<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestLabelPlacerExodus.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

// .NAME Test of vtkLabelPlacer
// .SECTION Description
// this program tests vtkLabelPlacer which uses a sophisticated algorithm to
// prune labels/icons preventing them from overlapping.

#include "vtkActor.h"
#include "vtkActor2D.h"
#include "vtkCamera.h"
#include "vtkCellCenters.h"
#include "vtkCellData.h"
#include "vtkClipDataSet.h"
#include "vtkContourFilter.h"
#include "vtkColorTransferFunction.h"
#include "vtkExodusReader.h"
#include "vtkGeometryFilter.h"
#include "vtkIntArray.h"
#include "vtkLabeledDataMapper.h"
#include "vtkLabelHierarchy.h"
#include "vtkLabelPlacer.h"
#include "vtkLabelSizeCalculator.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkPlane.h"
#include "vtkPointSetToLabelHierarchy.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTextProperty.h"
#include "vtkTIFFWriter.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkPolyData.h"
#include "vtkImageData.h"
#include "vtkSmartPointer.h"
#include "vtkSphereSource.h"
#include "vtkStructuredGrid.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"
#include "vtkWindowToImageFilter.h"

#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>

int TestLabelPlacerExodus(int argc, char *argv[])
  {
  int maxLevels = 5;
  int targetLabels = 32;
  double labelRatio = 0.05;
  char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref.ex2");
  //int iteratorType = vtkLabelHierarchy::FULL_SORT;
  int iteratorType = vtkLabelHierarchy::QUEUE;
  //int iteratorType = vtkLabelHierarchy::DEPTH_FIRST;
  bool showBounds = false;

  vtkSmartPointer<vtkLabelSizeCalculator> labelSizeCalculator =
    vtkSmartPointer<vtkLabelSizeCalculator>::New();
  vtkSmartPointer<vtkLabelHierarchy> labelHierarchy =
    vtkSmartPointer<vtkLabelHierarchy>::New();
  vtkSmartPointer<vtkLabelPlacer> labelPlacer =
    vtkSmartPointer<vtkLabelPlacer>::New();
  vtkSmartPointer<vtkPointSetToLabelHierarchy> pointSetToLabelHierarchy =
    vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
  vtkSmartPointer<vtkExodusReader> exoReader =
    vtkSmartPointer<vtkExodusReader>::New();

  vtkSmartPointer<vtkPlane> plane1 = vtkSmartPointer<vtkPlane>::New();
  vtkSmartPointer<vtkPlane> plane2 = vtkSmartPointer<vtkPlane>::New();
  vtkSmartPointer<vtkClipDataSet> clip1 = vtkSmartPointer<vtkClipDataSet>::New();
  vtkSmartPointer<vtkClipDataSet> clip2 = vtkSmartPointer<vtkClipDataSet>::New();

  plane1->SetNormal(0.874613683283037, 0.0, -0.484820487411659);
  plane2->SetNormal(-0.483077342911335, 0.875577684026794, 0.0);

  vtkSmartPointer<vtkContourFilter> contour = vtkSmartPointer<vtkContourFilter>::New();

  vtkSmartPointer<vtkColorTransferFunction> contourXfer = vtkSmartPointer<vtkColorTransferFunction>::New();
  vtkSmartPointer<vtkColorTransferFunction> modelXfer = vtkSmartPointer<vtkColorTransferFunction>::New();

  vtkSmartPointer<vtkPolyDataMapper> modelMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkPolyDataMapper> contourMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkActor> modelActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkActor> contourActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
  vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
  vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();

  vtkSmartPointer<vtkLabeledDataMapper> labeledMapper =
    vtkSmartPointer<vtkLabeledDataMapper>::New();
  vtkSmartPointer<vtkActor2D> textActor = vtkSmartPointer<vtkActor2D>::New();
  vtkSmartPointer<vtkCellCenters> cellCenters = vtkSmartPointer<vtkCellCenters>::New();
  vtkSmartPointer<vtkGeometryFilter> geometry1 = vtkSmartPointer<vtkGeometryFilter>::New();
  vtkSmartPointer<vtkGeometryFilter> geometry2 = vtkSmartPointer<vtkGeometryFilter>::New();

  vtkSmartPointer<vtkPolyDataNormals> normals1 = vtkSmartPointer<vtkPolyDataNormals>::New();
  vtkSmartPointer<vtkPolyDataNormals> normals2 = vtkSmartPointer<vtkPolyDataNormals>::New();

  normals1->SplittingOn();
  normals1->ConsistencyOn();
  normals1->NonManifoldTraversalOn();
  normals2->SplittingOn();
  normals2->ConsistencyOn();
  normals2->NonManifoldTraversalOn();

  //xmlPolyDataReader->SetFileName( fname );
  exoReader->SetFileName( fname );
  //exoReader->SetPointArrayStatus("Temp", 1);
  exoReader->SetAllPointArrayStatus(1);
  delete [] fname;

  contour->SetInputConnection(exoReader->GetOutputPort());
  contour->ComputeNormalsOn();
  contour->ComputeGradientsOn();
  contour->ComputeScalarsOn();
  contour->SetValue(0, 362);
  contour->SetValue(1, 500);
  contour->SetValue(2, 638);
  contour->SetValue(3, 775);
  contour->SetValue(4, 844);
  contour->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Temp");

  clip1->SetInputConnection(exoReader->GetOutputPort());
  clip1->SetClipFunction(plane1);
  clip1->InsideOutOn();
  geometry1->SetInputConnection(clip1->GetOutputPort());

  clip2->SetInputConnection(contour->GetOutputPort());
  clip2->SetClipFunction(plane2);
  geometry2->SetInputConnection(clip2->GetOutputPort());

  cellCenters->SetInputConnection(clip2->GetOutputPort());
  cellCenters->Update();
  //cellCenters->GetOutput()->Print(cout);

  //geometry2->Update();
  //geometry2->GetOutput()->Print(cout);

  int numTemps = cellCenters->GetOutput()->GetNumberOfPoints();

  vtkSmartPointer<vtkIntArray> priority = vtkSmartPointer<vtkIntArray>::New();
  priority->SetName("Priority");
  priority->SetNumberOfComponents(1);
  priority->SetNumberOfValues(numTemps);

  for(int i = 0; i < numTemps; i++)
    {
    priority->SetValue(i, static_cast<int>(vtkMath::Random(0.0, 5.0)));
    }

  geometry2->Update();
  vtkSmartPointer<vtkPolyData> temp = vtkSmartPointer<vtkPolyData>::New();
  temp->ShallowCopy(cellCenters->GetOutput());
  temp->GetPointData()->AddArray(priority);
  //temp->GetPointData()->AddArray(geometry2->GetOutput()->GetPointData()->GetArray("Temp"));
  //temp-
  //temp->Print(cout);

  /// Label ///

  labelSizeCalculator->SetInput(temp);
  labelSizeCalculator->GetFontProperty()->SetFontSize( 14 );
  labelSizeCalculator->GetFontProperty()->SetFontFamily( vtkTextProperty::GetFontFamilyFromString( "Arial" ) );
  labelSizeCalculator->GetFontProperty()->ShadowOn();
  labelSizeCalculator->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );

  pointSetToLabelHierarchy->AddInputConnection(labelSizeCalculator->GetOutputPort());
  pointSetToLabelHierarchy->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Priority" );
  pointSetToLabelHierarchy->SetInputArrayToProcess( 1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "LabelSize" );
  pointSetToLabelHierarchy->SetInputArrayToProcess( 2, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );
  pointSetToLabelHierarchy->SetMaximumDepth( maxLevels );
  pointSetToLabelHierarchy->SetTargetLabelCount( targetLabels );

  labelPlacer->SetInputConnection( pointSetToLabelHierarchy->GetOutputPort() );
  labelPlacer->SetIteratorType( iteratorType );
  labelPlacer->SetOutputTraversedBounds( showBounds );
  labelPlacer->SetRenderer( renderer );
  labelPlacer->SetMaximumLabelFraction( labelRatio );
  labelPlacer->UseDepthBufferOn();

  labeledMapper->SetInputConnection(labelPlacer->GetOutputPort());
  labeledMapper->SetLabelTextProperty(labelSizeCalculator->GetFontProperty());
  labeledMapper->SetFieldDataName("LabelText");
  labeledMapper->SetLabelModeToLabelFieldData();
  labeledMapper->GetLabelTextProperty()->SetColor(1.0, 1.0, 1.0);
  textActor->SetMapper(labeledMapper);

  /// End Label ///

  normals1->SetInputConnection(geometry1->GetOutputPort());

  modelXfer->SetColorSpaceToDiverging();
  modelXfer->AddRGBPoint(0.08, 0.138094, 0.241093, 0.709102);
  modelXfer->AddRGBPoint(0.18, 0.672801, 0.140795, 0.126604);
  modelXfer->SetScaleToLinear();
  modelXfer->Build();

  modelMapper->SetInputConnection(normals1->GetOutputPort());
  modelMapper->SelectColorArray("AsH3");
  modelMapper->ScalarVisibilityOn();
  modelMapper->SetLookupTable(modelXfer);
  modelMapper->UseLookupTableScalarRangeOn();
  modelMapper->SetColorModeToMapScalars();
  modelMapper->ScalarVisibilityOn();
  modelMapper->SetScalarModeToUsePointFieldData();

  modelActor->SetMapper(modelMapper);

  contourXfer->SetColorSpaceToRGB();
  contourXfer->AddRGBPoint(293.0, 0.0, 0.666667, 0.0);
  contourXfer->AddRGBPoint(913.5, 0.67451, 0.443137, 0.113725);
  contourXfer->SetScaleToLinear();
  contourXfer->Build();

  normals2->SetInputConnection(geometry2->GetOutputPort());

  contourMapper->SetInputConnection(normals2->GetOutputPort());
  contourMapper->SelectColorArray("Temp");
  contourMapper->ScalarVisibilityOn();
  contourMapper->SetLookupTable(contourXfer);
  contourMapper->UseLookupTableScalarRangeOn();
  contourMapper->SetColorModeToMapScalars();
  contourMapper->ScalarVisibilityOn();
  contourMapper->SetScalarModeToUsePointFieldData();

  contourActor->SetMapper(contourMapper);
  modelActor->SetPosition(0.05, -0.05, 0.0);

  renderer->AddActor(contourActor);
  renderer->AddActor(modelActor);
  renderer->AddActor(textActor);

  renWin->SetSize(600, 600);
  renWin->AddRenderer(renderer);
  renderer->SetBackground(1.0, 1.0, 1.0);
  iren->SetRenderWindow(renWin);

  renderer->GetActiveCamera()->SetFocalPoint(-9.25157, 7.70629, 3.69546);
  renderer->GetActiveCamera()->SetPosition(24.9979, -27.946, -4.03877);
  renderer->GetActiveCamera()->SetViewAngle(30);
  renderer->GetActiveCamera()->SetViewUp(0.248261, 0.427108, -8.869451);

  renWin->Render();
  renderer->ResetCamera();
  renderer->ResetCamera();
  renderer->ResetCamera();

  vtkSmartPointer<vtkWindowToImageFilter> capture = vtkSmartPointer<vtkWindowToImageFilter>::New();

  //capture->SetInput(renWin);
  //char buffer[1024];

  //vtkSmartPointer<vtkTIFFWriter> tiffWriter = vtkSmartPointer<vtkTIFFWriter>::New();
  //tiffWriter->SetInputConnection(capture->GetOutputPort());
  //tiffWriter->SetCompressionToNoCompression();

  int j = 0;

  /*for(j = 0; j < 20; j++)
  {
  renderer->GetActiveCamera()->Azimuth(-0.5);
  renWin->Render();

  capture->Modified();
  sprintf(buffer, "%04d.tiff", j );

  tiffWriter->SetFileName(buffer);
  tiffWriter->Write();
  }*/

  for(; j < 80; j++)
    {
    renderer->GetActiveCamera()->Zoom(1.01);
    renWin->Render();

    //capture->Modified();
    //sprintf(buffer, "%04d.tiff", j );

    //tiffWriter->SetFileName(buffer);
    //tiffWriter->Write();
    }

  for(; j < 400; j++)
    {
    renderer->GetActiveCamera()->Azimuth(-0.25);
    renWin->Render();

    //capture->Modified();
    //sprintf(buffer, "%04d.tiff", j );

    //tiffWriter->SetFileName(buffer);
    //tiffWriter->Write();
    }

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  return !retVal;
  }
<commit_msg>ENH: shrink size of test window.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestLabelPlacerExodus.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

// .NAME Test of vtkLabelPlacer
// .SECTION Description
// this program tests vtkLabelPlacer which uses a sophisticated algorithm to
// prune labels/icons preventing them from overlapping.

#include "vtkActor.h"
#include "vtkActor2D.h"
#include "vtkCamera.h"
#include "vtkCellCenters.h"
#include "vtkCellData.h"
#include "vtkClipDataSet.h"
#include "vtkContourFilter.h"
#include "vtkColorTransferFunction.h"
#include "vtkExodusReader.h"
#include "vtkGeometryFilter.h"
#include "vtkIntArray.h"
#include "vtkLabeledDataMapper.h"
#include "vtkLabelHierarchy.h"
#include "vtkLabelPlacer.h"
#include "vtkLabelSizeCalculator.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkPlane.h"
#include "vtkPointSetToLabelHierarchy.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTextProperty.h"
#include "vtkTIFFWriter.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkPolyData.h"
#include "vtkImageData.h"
#include "vtkSmartPointer.h"
#include "vtkSphereSource.h"
#include "vtkStructuredGrid.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"
#include "vtkWindowToImageFilter.h"

#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>

int TestLabelPlacerExodus(int argc, char *argv[])
  {
  int maxLevels = 5;
  int targetLabels = 32;
  double labelRatio = 0.05;
  char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref.ex2");
  //int iteratorType = vtkLabelHierarchy::FULL_SORT;
  int iteratorType = vtkLabelHierarchy::QUEUE;
  //int iteratorType = vtkLabelHierarchy::DEPTH_FIRST;
  bool showBounds = false;

  vtkSmartPointer<vtkLabelSizeCalculator> labelSizeCalculator =
    vtkSmartPointer<vtkLabelSizeCalculator>::New();
  vtkSmartPointer<vtkLabelHierarchy> labelHierarchy =
    vtkSmartPointer<vtkLabelHierarchy>::New();
  vtkSmartPointer<vtkLabelPlacer> labelPlacer =
    vtkSmartPointer<vtkLabelPlacer>::New();
  vtkSmartPointer<vtkPointSetToLabelHierarchy> pointSetToLabelHierarchy =
    vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
  vtkSmartPointer<vtkExodusReader> exoReader =
    vtkSmartPointer<vtkExodusReader>::New();

  vtkSmartPointer<vtkPlane> plane1 = vtkSmartPointer<vtkPlane>::New();
  vtkSmartPointer<vtkPlane> plane2 = vtkSmartPointer<vtkPlane>::New();
  vtkSmartPointer<vtkClipDataSet> clip1 = vtkSmartPointer<vtkClipDataSet>::New();
  vtkSmartPointer<vtkClipDataSet> clip2 = vtkSmartPointer<vtkClipDataSet>::New();

  plane1->SetNormal(0.874613683283037, 0.0, -0.484820487411659);
  plane2->SetNormal(-0.483077342911335, 0.875577684026794, 0.0);

  vtkSmartPointer<vtkContourFilter> contour = vtkSmartPointer<vtkContourFilter>::New();

  vtkSmartPointer<vtkColorTransferFunction> contourXfer = vtkSmartPointer<vtkColorTransferFunction>::New();
  vtkSmartPointer<vtkColorTransferFunction> modelXfer = vtkSmartPointer<vtkColorTransferFunction>::New();

  vtkSmartPointer<vtkPolyDataMapper> modelMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkPolyDataMapper> contourMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkActor> modelActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkActor> contourActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
  vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
  vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();

  vtkSmartPointer<vtkLabeledDataMapper> labeledMapper =
    vtkSmartPointer<vtkLabeledDataMapper>::New();
  vtkSmartPointer<vtkActor2D> textActor = vtkSmartPointer<vtkActor2D>::New();
  vtkSmartPointer<vtkCellCenters> cellCenters = vtkSmartPointer<vtkCellCenters>::New();
  vtkSmartPointer<vtkGeometryFilter> geometry1 = vtkSmartPointer<vtkGeometryFilter>::New();
  vtkSmartPointer<vtkGeometryFilter> geometry2 = vtkSmartPointer<vtkGeometryFilter>::New();

  vtkSmartPointer<vtkPolyDataNormals> normals1 = vtkSmartPointer<vtkPolyDataNormals>::New();
  vtkSmartPointer<vtkPolyDataNormals> normals2 = vtkSmartPointer<vtkPolyDataNormals>::New();

  normals1->SplittingOn();
  normals1->ConsistencyOn();
  normals1->NonManifoldTraversalOn();
  normals2->SplittingOn();
  normals2->ConsistencyOn();
  normals2->NonManifoldTraversalOn();

  //xmlPolyDataReader->SetFileName( fname );
  exoReader->SetFileName( fname );
  //exoReader->SetPointArrayStatus("Temp", 1);
  exoReader->SetAllPointArrayStatus(1);
  delete [] fname;

  contour->SetInputConnection(exoReader->GetOutputPort());
  contour->ComputeNormalsOn();
  contour->ComputeGradientsOn();
  contour->ComputeScalarsOn();
  contour->SetValue(0, 362);
  contour->SetValue(1, 500);
  contour->SetValue(2, 638);
  contour->SetValue(3, 775);
  contour->SetValue(4, 844);
  contour->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Temp");

  clip1->SetInputConnection(exoReader->GetOutputPort());
  clip1->SetClipFunction(plane1);
  clip1->InsideOutOn();
  geometry1->SetInputConnection(clip1->GetOutputPort());

  clip2->SetInputConnection(contour->GetOutputPort());
  clip2->SetClipFunction(plane2);
  geometry2->SetInputConnection(clip2->GetOutputPort());

  cellCenters->SetInputConnection(clip2->GetOutputPort());
  cellCenters->Update();
  //cellCenters->GetOutput()->Print(cout);

  //geometry2->Update();
  //geometry2->GetOutput()->Print(cout);

  int numTemps = cellCenters->GetOutput()->GetNumberOfPoints();

  vtkSmartPointer<vtkIntArray> priority = vtkSmartPointer<vtkIntArray>::New();
  priority->SetName("Priority");
  priority->SetNumberOfComponents(1);
  priority->SetNumberOfValues(numTemps);

  for(int i = 0; i < numTemps; i++)
    {
    priority->SetValue(i, static_cast<int>(vtkMath::Random(0.0, 5.0)));
    }

  geometry2->Update();
  vtkSmartPointer<vtkPolyData> temp = vtkSmartPointer<vtkPolyData>::New();
  temp->ShallowCopy(cellCenters->GetOutput());
  temp->GetPointData()->AddArray(priority);
  //temp->GetPointData()->AddArray(geometry2->GetOutput()->GetPointData()->GetArray("Temp"));
  //temp-
  //temp->Print(cout);

  /// Label ///

  labelSizeCalculator->SetInput(temp);
  labelSizeCalculator->GetFontProperty()->SetFontSize( 14 );
  labelSizeCalculator->GetFontProperty()->SetFontFamily( vtkTextProperty::GetFontFamilyFromString( "Arial" ) );
  labelSizeCalculator->GetFontProperty()->ShadowOn();
  labelSizeCalculator->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );

  pointSetToLabelHierarchy->AddInputConnection(labelSizeCalculator->GetOutputPort());
  pointSetToLabelHierarchy->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Priority" );
  pointSetToLabelHierarchy->SetInputArrayToProcess( 1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "LabelSize" );
  pointSetToLabelHierarchy->SetInputArrayToProcess( 2, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );
  pointSetToLabelHierarchy->SetMaximumDepth( maxLevels );
  pointSetToLabelHierarchy->SetTargetLabelCount( targetLabels );

  labelPlacer->SetInputConnection( pointSetToLabelHierarchy->GetOutputPort() );
  labelPlacer->SetIteratorType( iteratorType );
  labelPlacer->SetOutputTraversedBounds( showBounds );
  labelPlacer->SetRenderer( renderer );
  labelPlacer->SetMaximumLabelFraction( labelRatio );
  labelPlacer->UseDepthBufferOn();

  labeledMapper->SetInputConnection(labelPlacer->GetOutputPort());
  labeledMapper->SetLabelTextProperty(labelSizeCalculator->GetFontProperty());
  labeledMapper->SetFieldDataName("LabelText");
  labeledMapper->SetLabelModeToLabelFieldData();
  labeledMapper->GetLabelTextProperty()->SetColor(1.0, 1.0, 1.0);
  textActor->SetMapper(labeledMapper);

  /// End Label ///

  normals1->SetInputConnection(geometry1->GetOutputPort());

  modelXfer->SetColorSpaceToDiverging();
  modelXfer->AddRGBPoint(0.08, 0.138094, 0.241093, 0.709102);
  modelXfer->AddRGBPoint(0.18, 0.672801, 0.140795, 0.126604);
  modelXfer->SetScaleToLinear();
  modelXfer->Build();

  modelMapper->SetInputConnection(normals1->GetOutputPort());
  modelMapper->SelectColorArray("AsH3");
  modelMapper->ScalarVisibilityOn();
  modelMapper->SetLookupTable(modelXfer);
  modelMapper->UseLookupTableScalarRangeOn();
  modelMapper->SetColorModeToMapScalars();
  modelMapper->ScalarVisibilityOn();
  modelMapper->SetScalarModeToUsePointFieldData();

  modelActor->SetMapper(modelMapper);

  contourXfer->SetColorSpaceToRGB();
  contourXfer->AddRGBPoint(293.0, 0.0, 0.666667, 0.0);
  contourXfer->AddRGBPoint(913.5, 0.67451, 0.443137, 0.113725);
  contourXfer->SetScaleToLinear();
  contourXfer->Build();

  normals2->SetInputConnection(geometry2->GetOutputPort());

  contourMapper->SetInputConnection(normals2->GetOutputPort());
  contourMapper->SelectColorArray("Temp");
  contourMapper->ScalarVisibilityOn();
  contourMapper->SetLookupTable(contourXfer);
  contourMapper->UseLookupTableScalarRangeOn();
  contourMapper->SetColorModeToMapScalars();
  contourMapper->ScalarVisibilityOn();
  contourMapper->SetScalarModeToUsePointFieldData();

  contourActor->SetMapper(contourMapper);
  modelActor->SetPosition(0.05, -0.05, 0.0);

  renderer->AddActor(contourActor);
  renderer->AddActor(modelActor);
  renderer->AddActor(textActor);

  renWin->SetSize(300, 300);
  renWin->AddRenderer(renderer);
  renderer->SetBackground(1.0, 1.0, 1.0);
  iren->SetRenderWindow(renWin);

  renderer->GetActiveCamera()->SetFocalPoint(-9.25157, 7.70629, 3.69546);
  renderer->GetActiveCamera()->SetPosition(24.9979, -27.946, -4.03877);
  renderer->GetActiveCamera()->SetViewAngle(30);
  renderer->GetActiveCamera()->SetViewUp(0.248261, 0.427108, -8.869451);

  renWin->Render();
  renderer->ResetCamera();
  renderer->ResetCamera();
  renderer->ResetCamera();

  vtkSmartPointer<vtkWindowToImageFilter> capture = vtkSmartPointer<vtkWindowToImageFilter>::New();

  //capture->SetInput(renWin);
  //char buffer[1024];

  //vtkSmartPointer<vtkTIFFWriter> tiffWriter = vtkSmartPointer<vtkTIFFWriter>::New();
  //tiffWriter->SetInputConnection(capture->GetOutputPort());
  //tiffWriter->SetCompressionToNoCompression();

  int j = 0;

  /*for(j = 0; j < 20; j++)
  {
  renderer->GetActiveCamera()->Azimuth(-0.5);
  renWin->Render();

  capture->Modified();
  sprintf(buffer, "%04d.tiff", j );

  tiffWriter->SetFileName(buffer);
  tiffWriter->Write();
  }*/

  for(; j < 80; j++)
    {
    renderer->GetActiveCamera()->Zoom(1.01);
    renWin->Render();

    //capture->Modified();
    //sprintf(buffer, "%04d.tiff", j );

    //tiffWriter->SetFileName(buffer);
    //tiffWriter->Write();
    }

  for(; j < 400; j++)
    {
    renderer->GetActiveCamera()->Azimuth(-0.25);
    renWin->Render();

    //capture->Modified();
    //sprintf(buffer, "%04d.tiff", j );

    //tiffWriter->SetFileName(buffer);
    //tiffWriter->Write();
    }

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  return !retVal;
  }
<|endoftext|>


<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_ed
#include <boost/test/unit_test.hpp>
#include "ed/build_helper.h"
#include "type/type.h"
#include "tests/utils_test.h"
#include "time_tables/route_schedules.h"
//for more concice test
static pt::ptime d(std::string str) {
    return boost::posix_time::from_iso_string(str);
}
/*
    Wanted schedules:
            VJ1    VJ2    VJ3    VJ4
        A          8h00   8h05
        B          8h10   8h20   8h25
        C   8h05
        D   9h30                 9h35

        But the thermometer algorithm is buggy, is doesn't give the shorest common superstring..
        So, actually we have this schedule
            VJ1
        C
        D
        A   8h
        B   8h10
        D

With VJ1, and VJ2, we ensure that we are no more comparing the two first jpp of
each VJ, but we have a more human order.
VJ2 and VJ3, is a basic test.
The difficulty with VJ4 comes when we have to compare it to VJ1.
When comparing VJ1 and VJ4, we compare VJ1(stopC) with VJ4(stopD)
and when we compare VJ4 and VJ1, we compare VJ4(stopB) with VJ1(stopC).
*/
struct route_schedule_fixture {
    ed::builder b = {"20120614"};

    route_schedule_fixture() {
        const std::string a_name = "stopA",
                          b_name = "stopB",
                          c_name = "stopC",
                          d_name = "stopD";
        b.vj("A", "1111111", "", true, "1", "1", "JP1")(c_name, 8*3600 + 5*60)(d_name, 9*3600 + 30*60);
        b.vj("A", "1111111", "", true, "2", "2", "JP2")(a_name, 8*3600)(b_name, 8*3600 + 10*60);
        b.vj("A", "1111111", "", true, "3", "3", "JP2")(a_name, 8*3600 + 5*60)(b_name, 8*3600 + 20*60);
        b.vj("A", "1111111", "", true, "4", "4", "JP3")(b_name, 8*3600+25*60)(d_name, 9*3600 + 35*60);
        b.finish();
        b.data->pt_data->index();
        b.data->build_raptor();

        boost::gregorian::date begin = boost::gregorian::date_from_iso_string("20120613");
        boost::gregorian::date end = boost::gregorian::date_from_iso_string("20120630");

        b.data->meta->production_date = boost::gregorian::date_period(begin, end);
    }
};

BOOST_FIXTURE_TEST_CASE(test1, route_schedule_fixture) {

    pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", boost::optional<const std::string>(), {}, d("20120615T070000"), 86400, 100,
                                                                   1, 3, 10, 0, *(b.data), false, false);
    BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
    pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
    auto get_vj = [](pbnavitia::RouteSchedule r, int i) {
        return r.table().headers(i).pt_display_informations().uris().vehicle_journey();
    };
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 0), "1");
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 1), "2");
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 2), "3");
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 3), "4");
}

BOOST_FIXTURE_TEST_CASE(test_max_nb_stop_times, route_schedule_fixture) {
    pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", boost::optional<const std::string>(), {}, d("20120615T070000"), 86400, 0,
                                                                   1, 3, 10, 0, *(b.data), false, false);
    BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
    pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
    BOOST_REQUIRE_EQUAL(route_schedule.table().headers().size(), 0);
}

<commit_msg>Timetable: add unit test on calendar filter for route_schedules<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_ed
#include <boost/test/unit_test.hpp>
#include "ed/build_helper.h"
#include "type/type.h"
#include "tests/utils_test.h"
#include "time_tables/route_schedules.h"

struct logger_initialized {
    logger_initialized()   { init_logger(); }
};
BOOST_GLOBAL_FIXTURE( logger_initialized )

//for more concice test
static pt::ptime d(std::string str) {
    return boost::posix_time::from_iso_string(str);
}
/*
    Wanted schedules:
            VJ1    VJ2    VJ3    VJ4
        A          8h00   8h05
        B          8h10   8h20   8h25
        C   8h05
        D   9h30                 9h35

        But the thermometer algorithm is buggy, is doesn't give the shorest common superstring..
        So, actually we have this schedule
            VJ1
        C
        D
        A   8h
        B   8h10
        D

With VJ1, and VJ2, we ensure that we are no more comparing the two first jpp of
each VJ, but we have a more human order.
VJ2 and VJ3, is a basic test.
The difficulty with VJ4 comes when we have to compare it to VJ1.
When comparing VJ1 and VJ4, we compare VJ1(stopC) with VJ4(stopD)
and when we compare VJ4 and VJ1, we compare VJ4(stopB) with VJ1(stopC).
*/
struct route_schedule_fixture {
    ed::builder b = {"20120614"};

    route_schedule_fixture() {
        const std::string a_name = "stopA",
                          b_name = "stopB",
                          c_name = "stopC",
                          d_name = "stopD";
        b.vj("A", "1111111", "", true, "1", "1", "JP1")(c_name, 8*3600 + 5*60)(d_name, 9*3600 + 30*60);
        b.vj("A", "1111111", "", true, "2", "2", "JP2")(a_name, 8*3600)(b_name, 8*3600 + 10*60);
        b.vj("A", "1111111", "", true, "3", "3", "JP2")(a_name, 8*3600 + 5*60)(b_name, 8*3600 + 20*60);
        b.vj("A", "1111111", "", true, "4", "4", "JP3")(b_name, 8*3600+25*60)(d_name, 9*3600 + 35*60);
        b.finish();
        b.data->pt_data->index();
        b.data->build_raptor();

        boost::gregorian::date begin = boost::gregorian::date_from_iso_string("20120613");
        boost::gregorian::date end = boost::gregorian::date_from_iso_string("20120630");

        b.data->meta->production_date = boost::gregorian::date_period(begin, end);
    }
};

BOOST_FIXTURE_TEST_CASE(test1, route_schedule_fixture) {

    pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", {}, {}, d("20120615T070000"), 86400, 100,
                                                                   1, 3, 10, 0, *(b.data), false, false);
    BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
    pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
    auto get_vj = [](pbnavitia::RouteSchedule r, int i) {
        return r.table().headers(i).pt_display_informations().uris().vehicle_journey();
    };
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 0), "1");
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 1), "2");
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 2), "3");
    BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 3), "4");
}

BOOST_FIXTURE_TEST_CASE(test_max_nb_stop_times, route_schedule_fixture) {
    pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", {}, {}, d("20120615T070000"), 86400, 0,
                                                                   1, 3, 10, 0, *(b.data), false, false);
    BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
    pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
    BOOST_REQUIRE_EQUAL(route_schedule.table().headers().size(), 0);
}

/*
We have 3 vehicle journeys VJ5, VJ6, VJ7 and 3 stops S1, S2, S3 :
     VJ5     VJ6     VJ7
S1  10:00   11:00   13:00
S2  10:30   11:30   13:37
s3  11:00   12:00   14:00

We have 4 calendars, C1, C2, C3, C4 :
- C1 : week (monday to friday),
- C2 : week end,
- C3 : holiday (monday to sunday during holidays),
- C4 : random calendar nobody uses.

Each vehicle_journey has its respective meta_vj : MVJ5, MVJ6, MVJ7.
We have the following associations :
- MVJ5 => C1,C2
- MVJ6 => C2,C3
- MVJ7 => ∅
*/
struct route_schedule_calendar_fixture {
    ed::builder b = {"20120614"};
    navitia::type::Calendar *c1, *c2, *c3, *c4;
    navitia::type::VehicleJourney *vj5, *vj6, *vj7;

    route_schedule_calendar_fixture() {
        const std::string S1_name = "S1",
                          S2_name = "S2",
                          S3_name = "S3";
        boost::gregorian::date begin = boost::gregorian::date_from_iso_string("20120613");
        boost::gregorian::date end = boost::gregorian::date_from_iso_string("20120630");

        vj5 = b.vj("B", "1111111", "", true, "VJ5", "MVJ5", "JP4")(S1_name, 10*3600)(S2_name, 10*3600 + 30*60)(S3_name, 11*3600).vj;
        vj6 = b.vj("B", "1111111", "", true, "VJ6", "MVJ6", "JP4")(S1_name, 11*3600)(S2_name, 11*3600 + 30*60)(S3_name, 12*3600).vj;
        vj7 = b.vj("B", "1111111", "", true, "VJ7", "MVJ7", "JP4")(S1_name, 13*3600)(S2_name, 13*3600 + 37*60)(S3_name, 14*3600).vj;

        c1 = new navitia::type::Calendar(begin);
        c1->uri = "C1";
        c1->active_periods.push_back({begin, end});
        c1->week_pattern = std::bitset<7>("1111100");
        c2 = new navitia::type::Calendar(begin);
        c2->uri = "C2";
        c2->active_periods.push_back({begin, end});
        c2->week_pattern = std::bitset<7>("0000011");
        c3 = new navitia::type::Calendar(begin);
        c3->uri = "C3";
        c3->active_periods.push_back({begin, end});
        c3->week_pattern = std::bitset<7>("1111111");
        c4 = new navitia::type::Calendar(begin);
        c4->uri = "C4";
        c4->active_periods.push_back({begin, end});
        c4->week_pattern = std::bitset<7>("0000000");

        navitia::type::AssociatedCalendar a1;
        a1.calendar = c1;
        navitia::type::AssociatedCalendar a2;
        a1.calendar = c2;
        navitia::type::AssociatedCalendar a3;
        a1.calendar = c3;

        b.get_or_create_metavj("MVJ5")->associated_calendars.insert({c1->uri, &a1});
        b.get_or_create_metavj("MVJ5")->associated_calendars.insert({c2->uri, &a2});
        b.get_or_create_metavj("MVJ6")->associated_calendars.insert({c2->uri, &a2});
        b.get_or_create_metavj("MVJ6")->associated_calendars.insert({c3->uri, &a3});

        b.finish();
        b.data->pt_data->index();
        b.data->build_raptor();

        b.data->meta->production_date = boost::gregorian::date_period(begin, end);
    }

    std::string get_vj(pbnavitia::RouteSchedule r, int i) {
        return r.table().headers(i).pt_display_informations().uris().vehicle_journey();
    }

    void check_calendar_results(boost::optional<const std::string> calendar, std::vector<std::string> expected_vjs) {
        pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=B", calendar, {}, d("20120615T070000"), 86400, 100,
                                                                       1, 3, 10, 0, *(b.data), false, false);
        BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
        pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
        BOOST_REQUIRE_EQUAL(route_schedule.table().headers_size(), expected_vjs.size());
        for(int i = 0 ; i < route_schedule.table().headers_size() ; i++) {
            BOOST_REQUIRE_EQUAL(get_vj(route_schedule, i), expected_vjs[i]);
        }
    }
};

BOOST_FIXTURE_TEST_CASE(test_calendar_filter, route_schedule_calendar_fixture) {
    // No filter, all 3 VJs expected
    check_calendar_results({}, {vj5->uri, vj6->uri, vj7->uri});
    // For each calendar only the VJs explicitly linked to it expected
    check_calendar_results(c1->uri, {vj5->uri});
    check_calendar_results(c2->uri, {vj5->uri, vj6->uri});
    check_calendar_results(c3->uri, {vj6->uri});
    // No results for calendar C4
    check_calendar_results(c4->uri, {});
}
<|endoftext|>


<commit_before>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = CLOCKS_PER_SEC/10;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	cout << "resolution of cpu" << CLOCKS_PER_SEC << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			if(t == 0){
				t = 1;
			}
			else{
				t -=(1/resolution);
			}
			//Pulse(out1, sin((2PI/2) * abs(1/t)));
			//Wait(sin((PI/2) * abs(1/t)));
			cout << sin((2*PI)/t) << endl;
			cout << "this is t" << t << endl;
			Pulse(out1, 1/resolution);
			Wait(sin((2*PI)/t));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			for (double i = 0; i < 1; i += resolution) {
				Pulse(out1, 1/resolution);
				cout << sin(i)/resolution << endl;
				Wait(sin(i)/resolution);
			}
		}
	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1/resolution);
			Wait(4/resolution);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<commit_msg>Update pwm.cpp<commit_after>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = CLOCKS_PER_SEC/10;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	cout << "resolution of cpu" << CLOCKS_PER_SEC << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			if(t == 0){
				t = time_to_complete;
			}
			else{
				t -=;
			}
			//Pulse(out1, sin((2PI/2) * abs(1/t)));
			//Wait(sin((PI/2) * abs(1/t)));
			cout << sin((2*PI)/t) << endl;
			cout << "this is t" << t << endl;
			Pulse(out1, 1/resolution);
			Wait(sin((2*PI)/t));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			for (double i = 0; i < 1; i += resolution) {
				Pulse(out1, 1/resolution);
				cout << sin(i)/resolution << endl;
				Wait(sin(i)/resolution);
			}
		}
	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1/resolution);
			Wait(4/resolution);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<|endoftext|>


<commit_before><commit_msg>Revert "Fix n#653688"<commit_after><|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// runtime_state.cpp
//
// Identification: src/codegen/runtime_state.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/runtime_state.h"
#include "codegen/vector.h"

namespace peloton {
namespace codegen {

// Constructor
RuntimeState::RuntimeState() : constructed_type_(nullptr) {}

// Register some state of the given type and with the given name. The last
// argument indicates whether this state is local (i.e., lives on the stack) or
// whether the requesting operator wants to manage the memory.
RuntimeState::StateID RuntimeState::RegisterState(std::string name,
                                                  llvm::Type *type,
                                                  bool is_on_stack) {
  PL_ASSERT(constructed_type_ == nullptr);
  RuntimeState::StateID state_id = state_slots_.size();
  RuntimeState::StateInfo state_info;
  state_info.name = name;
  state_info.type = type;
  state_info.local = is_on_stack;
  state_slots_.push_back(state_info);
  return state_id;
}

llvm::Value *RuntimeState::LoadStatePtr(CodeGen &codegen,
                                        RuntimeState::StateID state_id) const {
  // At this point, the runtime state type must have been finalized. Otherwise,
  // it'd be impossible for us to index into it because the type would be
  // incomplete.
  PL_ASSERT(constructed_type_ != nullptr);
  PL_ASSERT(state_id < state_slots_.size());

  auto &state_info = state_slots_[state_id];

  PL_ASSERT(!state_info.local);

  // We index into the runtime state to get a pointer to the state
  std::string ptr_name{state_info.name + "Ptr"};
  llvm::Value *runtime_state = codegen.GetState();
  llvm::Value *state_ptr = codegen->CreateConstInBoundsGEP2_32(
      constructed_type_, runtime_state, 0, state_info.index, ptr_name);
  return state_ptr;
}

llvm::Value *RuntimeState::LoadStateValue(CodeGen &codegen,
                                          RuntimeState::StateID state_id) const {
  auto &state_info = state_slots_[state_id];
  if (state_info.local) {
    return state_info.val;
  }

  llvm::Value *state_ptr = LoadStatePtr(codegen, state_id);
  llvm::Value *state = codegen->CreateLoad(state_ptr);
#ifndef NDEBUG
  PL_ASSERT(state->getType() == state_info.type);
  if (state->getType()->isStructTy()) {
    PL_ASSERT(state_info.type->isStructTy());
    auto *our_type = llvm::cast<llvm::StructType>(state_info.type);
    auto *ret_type = llvm::cast<llvm::StructType>(state->getType());
    PL_ASSERT(ret_type->isLayoutIdentical(our_type));
  }
#endif
  return state;
}

llvm::Type *RuntimeState::FinalizeType(CodeGen &codegen) {
  // Check if we've already constructed the type
  if (constructed_type_ != nullptr) {
    return constructed_type_;
  }

  // Construct a type capturing all non-local state
  std::vector<llvm::Type *> types;
  for (uint32_t i = 0, index = 0; i < state_slots_.size(); i++) {
    if (!state_slots_[i].local) {
      // We set the index in the overall state where this instance is found
      state_slots_[i].index = index++;
      types.push_back(state_slots_[i].type);
    }
  }

  constructed_type_ =
      llvm::StructType::create(codegen.GetContext(), types, "RuntimeState");
  return constructed_type_;
}

void RuntimeState::CreateLocalState(CodeGen &codegen) {
  for (auto &state_info : state_slots_) {
    if (state_info.local) {
      if (auto *arr_type = llvm::dyn_cast<llvm::ArrayType>(state_info.type)) {
        // Do the stack allocation of the array
        llvm::AllocaInst *arr = codegen->CreateAlloca(
            arr_type->getArrayElementType(),
            codegen.Const32(arr_type->getArrayNumElements()));

        // Set the alignment
        arr->setAlignment(Vector::kDefaultVectorAlignment);

        // Zero-out the allocated space
        uint64_t sz = codegen.SizeOf(state_info.type);
        codegen->CreateMemSet(arr, codegen.Const8(0), sz, arr->getAlignment());

        state_info.val = arr;
      } else {
        state_info.val = codegen->CreateAlloca(state_info.type);
      }

      // Set the name of the local state to what the client wants
      state_info.val->setName(state_info.name);
    }
  }
}

}  // namespace codegen
}  // namespace peloton<commit_msg>Formatting<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// runtime_state.cpp
//
// Identification: src/codegen/runtime_state.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/runtime_state.h"
#include "codegen/vector.h"

namespace peloton {
namespace codegen {

// Constructor
RuntimeState::RuntimeState() : constructed_type_(nullptr) {}

// Register some state of the given type and with the given name. The last
// argument indicates whether this state is local (i.e., lives on the stack) or
// whether the requesting operator wants to manage the memory.
RuntimeState::StateID RuntimeState::RegisterState(std::string name,
                                                  llvm::Type *type,
                                                  bool is_on_stack) {
  PL_ASSERT(constructed_type_ == nullptr);
  RuntimeState::StateID state_id = state_slots_.size();
  RuntimeState::StateInfo state_info;
  state_info.name = name;
  state_info.type = type;
  state_info.local = is_on_stack;
  state_slots_.push_back(state_info);
  return state_id;
}

llvm::Value *RuntimeState::LoadStatePtr(CodeGen &codegen,
                                        RuntimeState::StateID state_id) const {
  // At this point, the runtime state type must have been finalized. Otherwise,
  // it'd be impossible for us to index into it because the type would be
  // incomplete.
  PL_ASSERT(constructed_type_ != nullptr);
  PL_ASSERT(state_id < state_slots_.size());

  auto &state_info = state_slots_[state_id];

  PL_ASSERT(!state_info.local);

  // We index into the runtime state to get a pointer to the state
  std::string ptr_name{state_info.name + "Ptr"};
  llvm::Value *runtime_state = codegen.GetState();
  llvm::Value *state_ptr = codegen->CreateConstInBoundsGEP2_32(
      constructed_type_, runtime_state, 0, state_info.index, ptr_name);
  return state_ptr;
}

llvm::Value *RuntimeState::LoadStateValue(
    CodeGen &codegen, RuntimeState::StateID state_id) const {
  auto &state_info = state_slots_[state_id];
  if (state_info.local) {
    return state_info.val;
  }

  llvm::Value *state_ptr = LoadStatePtr(codegen, state_id);
  llvm::Value *state = codegen->CreateLoad(state_ptr);
#ifndef NDEBUG
  PL_ASSERT(state->getType() == state_info.type);
  if (state->getType()->isStructTy()) {
    PL_ASSERT(state_info.type->isStructTy());
    auto *our_type = llvm::cast<llvm::StructType>(state_info.type);
    auto *ret_type = llvm::cast<llvm::StructType>(state->getType());
    PL_ASSERT(ret_type->isLayoutIdentical(our_type));
  }
#endif
  return state;
}

llvm::Type *RuntimeState::FinalizeType(CodeGen &codegen) {
  // Check if we've already constructed the type
  if (constructed_type_ != nullptr) {
    return constructed_type_;
  }

  // Construct a type capturing all non-local state
  std::vector<llvm::Type *> types;
  for (uint32_t i = 0, index = 0; i < state_slots_.size(); i++) {
    if (!state_slots_[i].local) {
      // We set the index in the overall state where this instance is found
      state_slots_[i].index = index++;
      types.push_back(state_slots_[i].type);
    }
  }

  constructed_type_ =
      llvm::StructType::create(codegen.GetContext(), types, "RuntimeState");
  return constructed_type_;
}

void RuntimeState::CreateLocalState(CodeGen &codegen) {
  for (auto &state_info : state_slots_) {
    if (state_info.local) {
      if (auto *arr_type = llvm::dyn_cast<llvm::ArrayType>(state_info.type)) {
        // Do the stack allocation of the array
        llvm::AllocaInst *arr = codegen->CreateAlloca(
            arr_type->getArrayElementType(),
            codegen.Const32(arr_type->getArrayNumElements()));

        // Set the alignment
        arr->setAlignment(Vector::kDefaultVectorAlignment);

        // Zero-out the allocated space
        uint64_t sz = codegen.SizeOf(state_info.type);
        codegen->CreateMemSet(arr, codegen.Const8(0), sz, arr->getAlignment());

        state_info.val = arr;
      } else {
        state_info.val = codegen->CreateAlloca(state_info.type);
      }

      // Set the name of the local state to what the client wants
      state_info.val->setName(state_info.name);
    }
  }
}

}  // namespace codegen
}  // namespace peloton<|endoftext|>


<commit_before>/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */
/* BSD 3-Clause License:
 * Copyright (c) 2013 - 2021, kazunobu watatsu.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.
 *    Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#if !defined(_LINEAR_OPT_)

using std::cerr;
using std::flush;

template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {
#if defined(_FLOAT_BITS_)
  static const auto epsilon(T(1) >> int64_t(mybits - 1));
#else
  static const auto epsilon(std::numeric_limits<T>::epsilon());
#endif
  assert(A.rows() == bl.size() && A.rows() == bu.size() &&
         0 < A.cols() && 0 < A.rows());
  // cout << A << endl << b << endl << c.transpose() << endl;
  cerr << " (" << A.rows() << ", " << A.cols() << ")";
  // bu - bb == A, bl - bb == - A <=> bu - bl == 2 A
  const auto bb(bu - (bu - bl) / T(2));
  const auto upper(bu - bb);
  SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);
  SimpleVector<T> one(AA.rows());
  std::vector<std::pair<T, int> > fidx;
  fidx.reserve(A.rows());
  for(int i = 0; i < A.rows(); i ++) {
    for(int j = 0; j < A.cols(); j ++)
      AA(i, j) = A(i, j);
    AA(i, A.cols()) = - bb[i];
    if(upper[i] == T(0)) {
      const auto n2(AA.row(i).dot(AA.row(i)));
      if(n2 != T(0)) {
        fidx.emplace_back(std::make_pair(- T(1), i));
        AA.row(i) /= sqrt(n2);
      }
    } else {
      AA.row(i) /= upper[i];
      AA(i, A.cols()) -= T(1);
    }
    one[i] = T(1);
    assert(isfinite(AA.row(i).dot(AA.row(i))));
    if(A.rows() - 1 <= i) break;
    AA.row(i + A.rows()) = - AA.row(i);
    one[i + A.rows()] = T(1);
  }
  SimpleMatrix<T> Pt(AA.cols(), AA.rows());
  for(int i = 0; i < Pt.rows(); i ++)
    for(int j = 0; j < Pt.cols(); j ++)
      Pt(i, j) = T(0);
  std::vector<int> residue;
  for(int i = 0; i < AA.cols(); i ++) {
    const auto Atrowi(AA.col(i));
    const auto work(Atrowi - Pt.projectionPt(Atrowi));
    const auto n2(work.dot(work));
    if(n2 <= epsilon) {
      residue.emplace_back(i);
      continue;
    }
    Pt.row(i) = work / sqrt(n2);
  }
  int ii(0);
  for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) {
    SimpleVector<T> ek(Pt.cols());
    for(int k = 0; k < Pt.cols(); k ++)
      ek[k] = j == k ? T(1) : T(0);
    ek -= Pt.projectionPt(ek);
    const auto n2(ek.dot(ek));
    if(n2 <= epsilon) continue;
    Pt.row(residue[ii ++]) = ek / sqrt(n2);
  }
  assert(residue.size() <= ii);
  cerr << "Q" << flush;
  const auto R(Pt * AA);
  cerr << "R" << flush;
  const auto on(Pt.projectionPt(- one));
  for(int i = 0; i < on.size(); i ++)
    if(T(0) < on[i])
      fidx.emplace_back(std::make_pair(on[i], i));
  std::sort(fidx.begin(), fidx.end());
  // worst case O(mn^2) over all in this function,
  // we can make this function better case it's O(n^3) but not now.
  for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {
    const auto& iidx(fidx[idx].second);
    const auto  orth(Pt.col(iidx));
    const auto  norm2orth(orth.dot(orth));
    // XXX error:
    if(norm2orth <= epsilon) {
      n_fixed --;
      continue;
    }
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
    for(int j = 0; j < Pt.cols(); j ++)
      Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) / norm2orth);
  }
  cerr << "G" << flush;
#if defined(_WITHOUT_EIGEN_)
  auto rvec(- R.solve(Pt * one));
#else
  auto rvec(- R.inverse() * (Pt * one));
#endif
  cerr << "I" << flush;
  SimpleVector<T> rrvec(rvec.size() - 1);
  // | [A, - bb == - upper] [x t] | <= epsilon 1.
  for(int i = 0; i < rrvec.size(); i ++)
    rrvec[i] = rvec[i] / rvec[rvec.size() - 1];
  return rrvec;
}

#define _LINEAR_OPT_
#endif

<commit_msg>sign fix with logic fix.<commit_after>/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */
/* BSD 3-Clause License:
 * Copyright (c) 2013 - 2021, kazunobu watatsu.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.
 *    Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#if !defined(_LINEAR_OPT_)

using std::cerr;
using std::flush;

template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {
#if defined(_FLOAT_BITS_)
  static const auto epsilon(T(1) >> int64_t(mybits - 1));
#else
  static const auto epsilon(std::numeric_limits<T>::epsilon());
#endif
  assert(A.rows() == bl.size() && A.rows() == bu.size() &&
         0 < A.cols() && 0 < A.rows());
  // cout << A << endl << b << endl << c.transpose() << endl;
  cerr << " (" << A.rows() << ", " << A.cols() << ")";
  // bu - bb == A, bl - bb == - A <=> bu - bl == 2 A
  const auto bb(bu - (bu - bl) / T(2));
  const auto upper(bu - bb);
  SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);
  SimpleVector<T> one(AA.rows());
  std::vector<std::pair<T, int> > fidx;
  fidx.reserve(A.rows());
  for(int i = 0; i < A.rows(); i ++) {
    for(int j = 0; j < A.cols(); j ++)
      AA(i, j) = A(i, j);
    AA(i, A.cols()) = bb[i];
    if(upper[i] == T(0)) {
      const auto n2(AA.row(i).dot(AA.row(i)));
      if(n2 != T(0)) {
        fidx.emplace_back(std::make_pair(- T(1), i));
        AA.row(i) /= sqrt(n2);
      }
    } else {
      AA.row(i) /= upper[i];
      // N.B. [A, [-b 1]] [x t] <= {0, 1}^m, t == 1 <=>
      //      bl - bb t <= Ax - bb t <= bu - bb t.
      AA(i, A.cols()) -= T(1);
    }
    one[i] = T(1);
    assert(isfinite(AA.row(i).dot(AA.row(i))));
    if(A.rows() - 1 <= i) break;
    AA.row(i + A.rows()) = - AA.row(i);
    one[i + A.rows()] = - T(1);
  }
  SimpleMatrix<T> Pt(AA.cols(), AA.rows());
  for(int i = 0; i < Pt.rows(); i ++)
    for(int j = 0; j < Pt.cols(); j ++)
      Pt(i, j) = T(0);
  std::vector<int> residue;
  for(int i = 0; i < AA.cols(); i ++) {
    const auto Atrowi(AA.col(i));
    const auto work(Atrowi - Pt.projectionPt(Atrowi));
    const auto n2(work.dot(work));
    if(n2 <= epsilon) {
      residue.emplace_back(i);
      continue;
    }
    Pt.row(i) = work / sqrt(n2);
  }
  int ii(0);
  for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) {
    SimpleVector<T> ek(Pt.cols());
    for(int k = 0; k < Pt.cols(); k ++)
      ek[k] = j == k ? T(1) : T(0);
    ek -= Pt.projectionPt(ek);
    const auto n2(ek.dot(ek));
    if(n2 <= epsilon) continue;
    Pt.row(residue[ii ++]) = ek / sqrt(n2);
  }
  assert(residue.size() <= ii);
  cerr << "Q" << flush;
  const auto R(Pt * AA);
  cerr << "R" << flush;
  const auto on(Pt.projectionPt(- one));
  for(int i = 0; i < on.size(); i ++)
    if(T(0) < on[i])
      fidx.emplace_back(std::make_pair(on[i], i));
  std::sort(fidx.begin(), fidx.end());
  // worst case O(mn^2) over all in this function,
  // we can make this function better case it's O(n^3) but not now.
  for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {
    const auto& iidx(fidx[idx].second);
    const auto  orth(Pt.col(iidx));
    const auto  norm2orth(orth.dot(orth));
    // XXX error:
    if(norm2orth <= epsilon) {
      n_fixed --;
      continue;
    }
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
    for(int j = 0; j < Pt.cols(); j ++)
      Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) / norm2orth);
  }
  cerr << "G" << flush;
#if defined(_WITHOUT_EIGEN_)
  auto rvec(- R.solve(Pt * one));
#else
  auto rvec(- R.inverse() * (Pt * one));
#endif
  cerr << "I" << flush;
  SimpleVector<T> rrvec(rvec.size() - 1);
  // | [A, - bb == - upper] [x t] | <= epsilon 1.
  for(int i = 0; i < rrvec.size(); i ++)
    rrvec[i] = rvec[i] / rvec[rvec.size() - 1];
  return rrvec;
}

#define _LINEAR_OPT_
#endif

<|endoftext|>


<commit_before>/*
    SWARM

    Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"
#include "db.h"
#include "threads.h"

static pthread_mutex_t scan_mutex;

static ThreadRunner * search_threads = nullptr;

struct search_data
{
  BYTE ** qtable;
  WORD ** qtable_w;

  BYTE * dprofile;
  WORD * dprofile_w;

  BYTE * hearray;

  uint64_t * dir_array;

  uint64_t target_count;
  uint64_t target_index;
};

static struct search_data * sd;
static uint64_t master_next;
static uint64_t master_length;
static uint64_t remainingchunks;
static uint64_t * master_targets;
static uint64_t * master_scores;
static uint64_t * master_diffs;
static uint64_t * master_alignlengths;
static int master_bits;
static uint64_t dirbufferbytes;

queryinfo_t query;
uint64_t longestdbsequence;

void search_alloc(struct search_data * sdp);
void search_free(struct search_data * sdp);
void search_init(struct search_data * sdp);
void search_chunk(struct search_data * sdp, int64_t bits);
auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool;
void search_worker_core(int64_t t);
auto search_worker(void * vp) -> void *;

void search_alloc(struct search_data * sdp)
{
  constexpr unsigned int one_kilobyte {1024};
  constexpr unsigned int nt_per_uint64 {32};
  constexpr unsigned int bytes_per_uint64 {8};

  dirbufferbytes =
    bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4;
  sdp->qtable = static_cast<BYTE**>
    (xmalloc(longestdbsequence * sizeof(BYTE*)));
  sdp->qtable_w = static_cast<WORD**>
    (xmalloc(longestdbsequence * sizeof(WORD*)));
  sdp->dprofile = static_cast<BYTE*>
    (xmalloc(2 * one_kilobyte));  // 4 * 16 * 32
  sdp->dprofile_w = static_cast<WORD*>
    (xmalloc(2 * one_kilobyte));  // 4 * 2 * 8 * 32
  sdp->hearray = static_cast<BYTE*>
    (xmalloc(longestdbsequence * nt_per_uint64));
  sdp->dir_array = static_cast<uint64_t *>
    (xmalloc(dirbufferbytes));

  memset(sdp->hearray, 0, longestdbsequence * nt_per_uint64);
  memset(sdp->dir_array, 0, dirbufferbytes);
}

void search_free(struct search_data * sdp)
{
  xfree(sdp->qtable);
  xfree(sdp->qtable_w);
  xfree(sdp->dprofile);
  xfree(sdp->dprofile_w);
  xfree(sdp->hearray);
  xfree(sdp->dir_array);
}

void search_init(struct search_data * sdp)
{
  constexpr int byte_multiplier {64};
  constexpr int word_multiplier {32};

  for(auto i = 0U; i < query.len; i++)
  {
    int nt_value {nt_extract(query.seq, i) + 1};   // 1,  2,   3, or   4
    int byte_offset {byte_multiplier * nt_value};  // 1, 64, 128, or 192
    int word_offset {word_multiplier * nt_value};  // 1, 32,  64, or 128

    sdp->qtable[i]   = sdp->dprofile   + byte_offset;
    sdp->qtable_w[i] = sdp->dprofile_w + word_offset;
  }
}

void search_chunk(struct search_data * sdp, int64_t bits)
{
  constexpr unsigned int bit_mode_16 {16};
  if (sdp->target_count == 0) {
    return;
  }

#if 0

  for(auto i = 0ULL; i < sdp->target_count; i++)
    {
    char * dseq;
    unsigned int dlen;
    char * nwalignment;

    uint64_t seqno = master_targets[sdp->target_index + i];
    db_getsequenceandlength(seqno, & dseq, & dlen);

    nw(dseq, dlen,
       query.seq, query.len,
       score_matrix_63,
       penalty_gapopen, penalty_gapextend,
       (int64_t *)(master_scores) + sdp->target_index + i,
       (int64_t *)(master_diffs) + sdp->target_index + i,
       (int64_t *)(master_alignlengths) + sdp->target_index + i,
       & nwalignment,
       (unsigned char *) sdp->dir_array,
       (int64_t *) sdp->hearray,
       query.qno, seqno);

#if 0
    printf("\nAlignment: %s\n", nwalignment);
#endif

    xfree(nwalignment);
  }

  return;

#endif

 if (bits == bit_mode_16)
   {
    search16(sdp->qtable_w,
             static_cast<WORD>(penalty_gapopen),
             static_cast<WORD>(penalty_gapextend),
             static_cast<WORD*>(score_matrix_16),
             sdp->dprofile_w,
             reinterpret_cast<WORD*>(sdp->hearray),
             sdp->target_count,
             master_targets + sdp->target_index,
             master_scores + sdp->target_index,
             master_diffs + sdp->target_index,
             master_alignlengths + sdp->target_index,
             static_cast<uint64_t>(query.len),
             dirbufferbytes / sizeof(uint64_t),
             sdp->dir_array);
   }
 else {
    search8(sdp->qtable,
            static_cast<BYTE>(penalty_gapopen),
            static_cast<BYTE>(penalty_gapextend),
            static_cast<BYTE*>(score_matrix_8),
            sdp->dprofile,
            sdp->hearray,
            sdp->target_count,
            master_targets + sdp->target_index,
            master_scores + sdp->target_index,
            master_diffs + sdp->target_index,
            master_alignlengths + sdp->target_index,
            static_cast<uint64_t>(query.len),
            dirbufferbytes / sizeof(uint64_t),
            sdp->dir_array);
 }
}

auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool
{
  // * countref = how many sequences to search
  // * firstref = index into master_targets/scores/diffs where thread should start

  bool status {false};

  pthread_mutex_lock(&scan_mutex);

  if (master_next < master_length)
    {
      uint64_t chunksize =
        ((master_length - master_next + remainingchunks - 1) / remainingchunks);

      * countref = chunksize;
      * firstref = master_next;

      master_next += chunksize;
      remainingchunks--;
      status = true;
    }

  pthread_mutex_unlock(&scan_mutex);

  return status;
}

#if 0

/* never used */

void master_dump()
{
  printf("master_dump\n");
  printf("   i    t    s    d\n");
  for(auto i = 0ULL; i < 1403; i++)
    {
      printf("%4" PRIu64 " %4" PRIu64 " %4" PRIu64 " %4" PRIu64 "\n",
             i, master_targets[i], master_scores[i], master_diffs[i]);
    }
}

#endif

void search_worker_core(int64_t t)
{
  search_init(sd + t);
  while(search_getwork(& sd[t].target_count, & sd[t].target_index)) {
    search_chunk(sd + t, master_bits);
  }
}

void search_do(uint64_t query_no,
               uint64_t listlength,
               uint64_t * targets,
               uint64_t * scores,
               uint64_t * diffs,
               uint64_t * alignlengths,
               int bits)
{
  // constexpr unsigned int bit_mode_16 {16};
  constexpr unsigned int channels_8 {8};
  constexpr unsigned int bit_mode_8 {8};
  constexpr unsigned int channels_16 {16};
  query.qno = query_no;
  unsigned int query_len = 0;
  db_getsequenceandlength(query_no, &query.seq, &query_len);
  query.len = query_len;

  master_next = 0;
  master_length = listlength;
  master_targets = targets;
  master_scores = scores;
  master_diffs = diffs;
  master_alignlengths = alignlengths;
  master_bits = bits;

  auto thr = static_cast<uint64_t>(opt_threads);

  if (bits == bit_mode_8)
    {
      if (master_length <= (channels_16 - 1) * thr) {
        thr = (master_length + channels_16 - 1) / channels_16;
      }
    }
  else
    {
      if (master_length <= (channels_8 - 1) * thr) {
        thr = (master_length + channels_8 - 1) / channels_8;
      }
    }

  remainingchunks = thr;

  if (thr == 1) {
    search_worker_core(0);
  }
  else {
    search_threads->run();
  }
}

void search_begin()
{
  longestdbsequence = db_getlongestsequence();

  sd = static_cast<struct search_data *>
    (xmalloc(sizeof(search_data) * static_cast<uint64_t>(opt_threads)));

  for(auto t = 0LL; t < opt_threads; t++) {
    search_alloc(sd+t);
  }

  pthread_mutex_init(& scan_mutex, nullptr);

  /* start threads */

  search_threads
    = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core);
}

void search_end()
{
  /* finish and clean up worker threads */

  delete search_threads;

  pthread_mutex_destroy(& scan_mutex);

  for(auto t = 0LL; t < opt_threads; t++) {
    search_free(sd+t);
  }
  xfree(sd);
}
<commit_msg>remove debugging function<commit_after>/*
    SWARM

    Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"
#include "db.h"
#include "threads.h"

static pthread_mutex_t scan_mutex;

static ThreadRunner * search_threads = nullptr;

struct search_data
{
  BYTE ** qtable;
  WORD ** qtable_w;

  BYTE * dprofile;
  WORD * dprofile_w;

  BYTE * hearray;

  uint64_t * dir_array;

  uint64_t target_count;
  uint64_t target_index;
};

static struct search_data * sd;
static uint64_t master_next;
static uint64_t master_length;
static uint64_t remainingchunks;
static uint64_t * master_targets;
static uint64_t * master_scores;
static uint64_t * master_diffs;
static uint64_t * master_alignlengths;
static int master_bits;
static uint64_t dirbufferbytes;

queryinfo_t query;
uint64_t longestdbsequence;

void search_alloc(struct search_data * sdp);
void search_free(struct search_data * sdp);
void search_init(struct search_data * sdp);
void search_chunk(struct search_data * sdp, int64_t bits);
auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool;
void search_worker_core(int64_t t);
auto search_worker(void * vp) -> void *;

void search_alloc(struct search_data * sdp)
{
  constexpr unsigned int one_kilobyte {1024};
  constexpr unsigned int nt_per_uint64 {32};
  constexpr unsigned int bytes_per_uint64 {8};

  dirbufferbytes =
    bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4;
  sdp->qtable = static_cast<BYTE**>
    (xmalloc(longestdbsequence * sizeof(BYTE*)));
  sdp->qtable_w = static_cast<WORD**>
    (xmalloc(longestdbsequence * sizeof(WORD*)));
  sdp->dprofile = static_cast<BYTE*>
    (xmalloc(2 * one_kilobyte));  // 4 * 16 * 32
  sdp->dprofile_w = static_cast<WORD*>
    (xmalloc(2 * one_kilobyte));  // 4 * 2 * 8 * 32
  sdp->hearray = static_cast<BYTE*>
    (xmalloc(longestdbsequence * nt_per_uint64));
  sdp->dir_array = static_cast<uint64_t *>
    (xmalloc(dirbufferbytes));

  memset(sdp->hearray, 0, longestdbsequence * nt_per_uint64);
  memset(sdp->dir_array, 0, dirbufferbytes);
}

void search_free(struct search_data * sdp)
{
  xfree(sdp->qtable);
  xfree(sdp->qtable_w);
  xfree(sdp->dprofile);
  xfree(sdp->dprofile_w);
  xfree(sdp->hearray);
  xfree(sdp->dir_array);
}

void search_init(struct search_data * sdp)
{
  constexpr int byte_multiplier {64};
  constexpr int word_multiplier {32};

  for(auto i = 0U; i < query.len; i++)
  {
    int nt_value {nt_extract(query.seq, i) + 1};   // 1,  2,   3, or   4
    int byte_offset {byte_multiplier * nt_value};  // 1, 64, 128, or 192
    int word_offset {word_multiplier * nt_value};  // 1, 32,  64, or 128

    sdp->qtable[i]   = sdp->dprofile   + byte_offset;
    sdp->qtable_w[i] = sdp->dprofile_w + word_offset;
  }
}

void search_chunk(struct search_data * sdp, int64_t bits)
{
  constexpr unsigned int bit_mode_16 {16};
  if (sdp->target_count == 0) {
    return;
  }

#if 0

  for(auto i = 0ULL; i < sdp->target_count; i++)
    {
    char * dseq;
    unsigned int dlen;
    char * nwalignment;

    uint64_t seqno = master_targets[sdp->target_index + i];
    db_getsequenceandlength(seqno, & dseq, & dlen);

    nw(dseq, dlen,
       query.seq, query.len,
       score_matrix_63,
       penalty_gapopen, penalty_gapextend,
       (int64_t *)(master_scores) + sdp->target_index + i,
       (int64_t *)(master_diffs) + sdp->target_index + i,
       (int64_t *)(master_alignlengths) + sdp->target_index + i,
       & nwalignment,
       (unsigned char *) sdp->dir_array,
       (int64_t *) sdp->hearray,
       query.qno, seqno);

#if 0
    printf("\nAlignment: %s\n", nwalignment);
#endif

    xfree(nwalignment);
  }

  return;

#endif

 if (bits == bit_mode_16)
   {
    search16(sdp->qtable_w,
             static_cast<WORD>(penalty_gapopen),
             static_cast<WORD>(penalty_gapextend),
             static_cast<WORD*>(score_matrix_16),
             sdp->dprofile_w,
             reinterpret_cast<WORD*>(sdp->hearray),
             sdp->target_count,
             master_targets + sdp->target_index,
             master_scores + sdp->target_index,
             master_diffs + sdp->target_index,
             master_alignlengths + sdp->target_index,
             static_cast<uint64_t>(query.len),
             dirbufferbytes / sizeof(uint64_t),
             sdp->dir_array);
   }
 else {
    search8(sdp->qtable,
            static_cast<BYTE>(penalty_gapopen),
            static_cast<BYTE>(penalty_gapextend),
            static_cast<BYTE*>(score_matrix_8),
            sdp->dprofile,
            sdp->hearray,
            sdp->target_count,
            master_targets + sdp->target_index,
            master_scores + sdp->target_index,
            master_diffs + sdp->target_index,
            master_alignlengths + sdp->target_index,
            static_cast<uint64_t>(query.len),
            dirbufferbytes / sizeof(uint64_t),
            sdp->dir_array);
 }
}

auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool
{
  // * countref = how many sequences to search
  // * firstref = index into master_targets/scores/diffs where thread should start

  bool status {false};

  pthread_mutex_lock(&scan_mutex);

  if (master_next < master_length)
    {
      uint64_t chunksize =
        ((master_length - master_next + remainingchunks - 1) / remainingchunks);

      * countref = chunksize;
      * firstref = master_next;

      master_next += chunksize;
      remainingchunks--;
      status = true;
    }

  pthread_mutex_unlock(&scan_mutex);

  return status;
}

void search_worker_core(int64_t t)
{
  search_init(sd + t);
  while(search_getwork(& sd[t].target_count, & sd[t].target_index)) {
    search_chunk(sd + t, master_bits);
  }
}

void search_do(uint64_t query_no,
               uint64_t listlength,
               uint64_t * targets,
               uint64_t * scores,
               uint64_t * diffs,
               uint64_t * alignlengths,
               int bits)
{
  // constexpr unsigned int bit_mode_16 {16};
  constexpr unsigned int channels_8 {8};
  constexpr unsigned int bit_mode_8 {8};
  constexpr unsigned int channels_16 {16};
  query.qno = query_no;
  unsigned int query_len = 0;
  db_getsequenceandlength(query_no, &query.seq, &query_len);
  query.len = query_len;

  master_next = 0;
  master_length = listlength;
  master_targets = targets;
  master_scores = scores;
  master_diffs = diffs;
  master_alignlengths = alignlengths;
  master_bits = bits;

  auto thr = static_cast<uint64_t>(opt_threads);

  if (bits == bit_mode_8)
    {
      if (master_length <= (channels_16 - 1) * thr) {
        thr = (master_length + channels_16 - 1) / channels_16;
      }
    }
  else
    {
      if (master_length <= (channels_8 - 1) * thr) {
        thr = (master_length + channels_8 - 1) / channels_8;
      }
    }

  remainingchunks = thr;

  if (thr == 1) {
    search_worker_core(0);
  }
  else {
    search_threads->run();
  }
}

void search_begin()
{
  longestdbsequence = db_getlongestsequence();

  sd = static_cast<struct search_data *>
    (xmalloc(sizeof(search_data) * static_cast<uint64_t>(opt_threads)));

  for(auto t = 0LL; t < opt_threads; t++) {
    search_alloc(sd+t);
  }

  pthread_mutex_init(& scan_mutex, nullptr);

  /* start threads */

  search_threads
    = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core);
}

void search_end()
{
  /* finish and clean up worker threads */

  delete search_threads;

  pthread_mutex_destroy(& scan_mutex);

  for(auto t = 0LL; t < opt_threads; t++) {
    search_free(sd+t);
  }
  xfree(sd);
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <sstream>
#include <stdlib.h>
#include <Context.h>
#include <ViewText.h>
#include <Date.h>
#include <main.h>
#include <i18n.h>
#include <text.h>
#include <CmdTimesheet.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdTimesheet::CmdTimesheet ()
{
  _keyword     = "timesheet";
  _usage       = "task          timesheet [weeks]";
  _description = STRING_CMD_TIMESHEET_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdTimesheet::execute (std::string& output)
{
  int rc = 0;

  // Scan the pending tasks.
  handleRecurrence ();
  std::vector <Task> all = context.tdb2.all_tasks ();

  // What day of the week does the user consider the first?
  int weekStart = Date::dayOfWeek (context.config.get ("weekstart"));
  if (weekStart != 0 && weekStart != 1)
    throw std::string (STRING_DATE_BAD_WEEKSTART);

  // Determine the date of the first day of the most recent report.
  Date today;
  Date start;
  start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;

  // Roll back to midnight.
  start = Date (start.month (), start.day (), start.year ());
  Date end = start + (7 * 86400);

  // Determine how many reports to run.
  int quantity = 1;
  std::vector <std::string> words = context.cli.getWords ();
  if (words.size () == 1)
    quantity = strtol (words[0].c_str (), NULL, 10);;

  std::stringstream out;
  for (int week = 0; week < quantity; ++week)
  {
    Date endString (end);
    endString -= 86400;

    std::string title = start.toString (context.config.get ("dateformat"))
                        + " - "
                        + endString.toString (context.config.get ("dateformat"));

    Color bold (Color::nocolor, Color::nocolor, false, true, false);
    out << "\n"
        << (context.color () ? bold.colorize (title) : title)
        << "\n";

    // Render the completed table.
    ViewText completed;
    completed.width (context.getWidth ());
    completed.add (Column::factory ("string",       "   "));
    completed.add (Column::factory ("string",       STRING_COLUMN_LABEL_PROJECT));
    completed.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
    completed.add (Column::factory ("string",       STRING_COLUMN_LABEL_DESC));

    Color label (context.config.get ("color.label"));
    completed.colorHeader (label);

    for (auto& task : all)
    {
      // If task completed within range.
      if (task.getStatus () == Task::completed)
      {
        Date compDate (task.get_date ("end"));
        if (compDate >= start && compDate < end)
        {
          Color c;
          if (context.color ())
            autoColorize (task, c);

          int row = completed.addRow ();
          std::string format = context.config.get ("dateformat.report");
          if (format == "")
            format = context.config.get ("dateformat");
          completed.set (row, 1, task.get ("project"), c);

          if(task.has ("due"))
          {
            Date dt (task.get_date ("due"));
            completed.set (row, 2, dt.toString (format));
          }

          std::string description = task.get ("description");
          int indent = context.config.getInteger ("indent.annotation");

          std::map <std::string, std::string> annotations;
          task.getAnnotations (annotations);
          for (auto& ann : annotations)
            description += "\n"
                         + std::string (indent, ' ')
                         + Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
                         + " "
                         + ann.second;

          completed.set (row, 3, description, c);
        }
      }
    }

    out << "  " << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << "\n";

    if (completed.rows ())
      out << completed.render ()
          << "\n";

    // Now render the started table.
    ViewText started;
    started.width (context.getWidth ());
    started.add (Column::factory ("string",       "   "));
    started.add (Column::factory ("string",       STRING_COLUMN_LABEL_PROJECT));
    started.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
    started.add (Column::factory ("string",       STRING_COLUMN_LABEL_DESC));
    started.colorHeader (label);

    for (auto& task : all)
    {
      // If task started within range, but not completed withing range.
      if (task.getStatus () == Task::pending &&
          task.has ("start"))
      {
        Date startDate (task.get_date ("start"));
        if (startDate >= start && startDate < end)
        {
          Color c;
          if (context.color ())
            autoColorize (task, c);

          int row = started.addRow ();
          std::string format = context.config.get ("dateformat.report");
          if (format == "")
            format = context.config.get ("dateformat");
          started.set (row, 1, task.get ("project"), c);

          if (task.has ("due"))
          {
            Date dt (task.get_date ("due"));
            started.set (row, 2, dt.toString (format));
          }

          std::string description = task.get ("description");
          int indent = context.config.getInteger ("indent.annotation");

          std::map <std::string, std::string> annotations;
          task.getAnnotations (annotations);
          for (auto& ann : annotations)
            description += "\n"
                         + std::string (indent, ' ')
                         + Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
                         + " "
                         + ann.second;

          started.set (row, 3, description, c);
        }
      }
    }

    out << "  " << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << "\n";

    if (started.rows ())
      out << started.render ()
          << "\n\n";

    // Prior week.
    start -= 7 * 86400;
    end   -= 7 * 86400;
  }

  output = out.str ();
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdTimesheet: Converted from CLI to CLI2<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <sstream>
#include <stdlib.h>
#include <Context.h>
#include <ViewText.h>
#include <Date.h>
#include <main.h>
#include <i18n.h>
#include <text.h>
#include <CmdTimesheet.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdTimesheet::CmdTimesheet ()
{
  _keyword     = "timesheet";
  _usage       = "task          timesheet [weeks]";
  _description = STRING_CMD_TIMESHEET_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdTimesheet::execute (std::string& output)
{
  int rc = 0;

  // Scan the pending tasks.
  handleRecurrence ();
  std::vector <Task> all = context.tdb2.all_tasks ();

  // What day of the week does the user consider the first?
  int weekStart = Date::dayOfWeek (context.config.get ("weekstart"));
  if (weekStart != 0 && weekStart != 1)
    throw std::string (STRING_DATE_BAD_WEEKSTART);

  // Determine the date of the first day of the most recent report.
  Date today;
  Date start;
  start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;

  // Roll back to midnight.
  start = Date (start.month (), start.day (), start.year ());
  Date end = start + (7 * 86400);

  // Determine how many reports to run.
  int quantity = 1;
  std::vector <std::string> words = context.cli2.getWords ();
  if (words.size () == 1)
    quantity = strtol (words[0].c_str (), NULL, 10);;

  std::stringstream out;
  for (int week = 0; week < quantity; ++week)
  {
    Date endString (end);
    endString -= 86400;

    std::string title = start.toString (context.config.get ("dateformat"))
                        + " - "
                        + endString.toString (context.config.get ("dateformat"));

    Color bold (Color::nocolor, Color::nocolor, false, true, false);
    out << "\n"
        << (context.color () ? bold.colorize (title) : title)
        << "\n";

    // Render the completed table.
    ViewText completed;
    completed.width (context.getWidth ());
    completed.add (Column::factory ("string",       "   "));
    completed.add (Column::factory ("string",       STRING_COLUMN_LABEL_PROJECT));
    completed.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
    completed.add (Column::factory ("string",       STRING_COLUMN_LABEL_DESC));

    Color label (context.config.get ("color.label"));
    completed.colorHeader (label);

    for (auto& task : all)
    {
      // If task completed within range.
      if (task.getStatus () == Task::completed)
      {
        Date compDate (task.get_date ("end"));
        if (compDate >= start && compDate < end)
        {
          Color c;
          if (context.color ())
            autoColorize (task, c);

          int row = completed.addRow ();
          std::string format = context.config.get ("dateformat.report");
          if (format == "")
            format = context.config.get ("dateformat");
          completed.set (row, 1, task.get ("project"), c);

          if(task.has ("due"))
          {
            Date dt (task.get_date ("due"));
            completed.set (row, 2, dt.toString (format));
          }

          std::string description = task.get ("description");
          int indent = context.config.getInteger ("indent.annotation");

          std::map <std::string, std::string> annotations;
          task.getAnnotations (annotations);
          for (auto& ann : annotations)
            description += "\n"
                         + std::string (indent, ' ')
                         + Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
                         + " "
                         + ann.second;

          completed.set (row, 3, description, c);
        }
      }
    }

    out << "  " << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << "\n";

    if (completed.rows ())
      out << completed.render ()
          << "\n";

    // Now render the started table.
    ViewText started;
    started.width (context.getWidth ());
    started.add (Column::factory ("string",       "   "));
    started.add (Column::factory ("string",       STRING_COLUMN_LABEL_PROJECT));
    started.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
    started.add (Column::factory ("string",       STRING_COLUMN_LABEL_DESC));
    started.colorHeader (label);

    for (auto& task : all)
    {
      // If task started within range, but not completed withing range.
      if (task.getStatus () == Task::pending &&
          task.has ("start"))
      {
        Date startDate (task.get_date ("start"));
        if (startDate >= start && startDate < end)
        {
          Color c;
          if (context.color ())
            autoColorize (task, c);

          int row = started.addRow ();
          std::string format = context.config.get ("dateformat.report");
          if (format == "")
            format = context.config.get ("dateformat");
          started.set (row, 1, task.get ("project"), c);

          if (task.has ("due"))
          {
            Date dt (task.get_date ("due"));
            started.set (row, 2, dt.toString (format));
          }

          std::string description = task.get ("description");
          int indent = context.config.getInteger ("indent.annotation");

          std::map <std::string, std::string> annotations;
          task.getAnnotations (annotations);
          for (auto& ann : annotations)
            description += "\n"
                         + std::string (indent, ' ')
                         + Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
                         + " "
                         + ann.second;

          started.set (row, 3, description, c);
        }
      }
    }

    out << "  " << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << "\n";

    if (started.rows ())
      out << started.render ()
          << "\n\n";

    // Prior week.
    start -= 7 * 86400;
    end   -= 7 * 86400;
  }

  output = out.str ();
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>