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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

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

#if(_MSC_VER==1200)
#include <itkFixedCenterOfRotationAffineTransform.h>
#include <itkIndex.h>
#include <itkConceptChecking.h>
#endif
#include "mitkBoundingObjectCutter.h"
#include "mitkBoundingObjectCutter.txx"
#include "mitkTimeHelper.h"
#include "mitkImageAccessByItk.h"
#include "mitkBoundingObject.h"
#include "mitkGeometry3D.h"
//#include "itkImageRegionIteratorWithIndex.h"

namespace mitk
{

void BoundingObjectCutter::SetBoundingObject( const mitk::BoundingObject* boundingObject )
{
  m_BoundingObject = const_cast<mitk::BoundingObject*>(boundingObject);
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput(1,
    const_cast< mitk::BoundingObject * >( boundingObject ) );
}

const mitk::BoundingObject* BoundingObjectCutter::GetBoundingObject() const
{
  return m_BoundingObject.GetPointer();
}

BoundingObjectCutter::BoundingObjectCutter()
  : m_BoundingObject(NULL), m_InsideValue(1), m_OutsideValue(0), m_AutoOutsideValue(false),
    m_UseInsideValue(false), m_OutsidePixelCount(0), m_InsidePixelCount(0), m_UseWholeInputRegion(false)
{
  this->SetNumberOfInputs(2);
  this->SetNumberOfRequiredInputs(2);
  m_InputTimeSelector  = mitk::ImageTimeSelector::New();
  m_OutputTimeSelector = mitk::ImageTimeSelector::New();
}

BoundingObjectCutter::~BoundingObjectCutter()
{
}

const std::type_info& BoundingObjectCutter::GetOutputPixelType()
{
  return *this->GetInput()->GetPixelType().GetTypeId();
}

void BoundingObjectCutter::GenerateInputRequestedRegion()
{
  mitk::Image* output = this->GetOutput();
  if((output->IsInitialized()==false) || (m_BoundingObject.IsNull()) || (m_BoundingObject->GetTimeSlicedGeometry()->GetTimeSteps() == 0))
    return;
  // we have already calculated the spatial part of the
  // input-requested-region in m_InputRequestedRegion in
  // GenerateOutputInformation (which is called before
  // GenerateInputRequestedRegion).
  GenerateTimeInInputRegion(output, const_cast< mitk::Image * > ( this->GetInput() ));
  GenerateTimeInInputRegion(output, m_BoundingObject.GetPointer());
}

void BoundingObjectCutter::GenerateOutputInformation()
{
  mitk::Image::Pointer output = this->GetOutput();
  if ((output->IsInitialized()) && (output->GetPipelineMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
    return;

  mitk::Image::Pointer input = const_cast< mitk::Image * > ( this->GetInput() );

  itkDebugMacro(<<"GenerateOutputInformation()");

  if(input.IsNull())
    return;

  if((m_BoundingObject.IsNull()) || (m_BoundingObject->GetTimeSlicedGeometry()->GetTimeSteps() == 0))
    return;

  mitk::Geometry3D* boGeometry =  m_BoundingObject->GetGeometry();
  mitk::Geometry3D* inputImageGeometry = input->GetSlicedGeometry();
  // calculate bounding box of bounding-object relative to the geometry
  // of the input image. The result is in pixel coordinates of the input
  // image (because the m_IndexToWorldTransform includes the spacing).
  mitk::BoundingBox::Pointer boBoxRelativeToImage = boGeometry->CalculateBoundingBoxRelativeToTransform( inputImageGeometry->GetIndexToWorldTransform() );

  // PART I: initialize input requested region. We do this already here (and not
  // later when GenerateInputRequestedRegion() is called), because we
  // also need the information to setup the output.

  // pre-initialize input-requested-region to largest-possible-region
  // and correct time-region; spatial part will be cropped by
  // bounding-box of bounding-object below
  m_InputRequestedRegion = input->GetLargestPossibleRegion();

  // build region out of bounding-box of bounding-object
  mitk::SlicedData::IndexType  index=m_InputRequestedRegion.GetIndex(); //init times and channels
  mitk::BoundingBox::PointType min = boBoxRelativeToImage->GetMinimum();
  index[0] = (mitk::SlicedData::IndexType::IndexValueType)(min[0]+0.5);
  index[1] = (mitk::SlicedData::IndexType::IndexValueType)(min[1]+0.5);
  index[2] = (mitk::SlicedData::IndexType::IndexValueType)(min[2]+0.5);

  mitk::SlicedData::SizeType   size = m_InputRequestedRegion.GetSize(); //init times and channels
  mitk::BoundingBox::PointType max = boBoxRelativeToImage->GetMaximum();
  size[0] = (mitk::SlicedData::SizeType::SizeValueType)(max[0]+0.5)-index[0];
  size[1] = (mitk::SlicedData::SizeType::SizeValueType)(max[1]+0.5)-index[1];
  size[2] = (mitk::SlicedData::SizeType::SizeValueType)(max[2]+0.5)-index[2];

  mitk::SlicedData::RegionType boRegion(index, size);

  if(m_UseWholeInputRegion == false)
  {
	  // crop input-requested-region with region of bounding-object
	  if(m_InputRequestedRegion.Crop(boRegion)==false)
	  {
		// crop not possible => do nothing: set time size to 0.
		size.Fill(0);
		m_InputRequestedRegion.SetSize(size);
		boRegion.SetSize(size);
		m_BoundingObject->SetRequestedRegion(&boRegion);
		return;
	  }
  }

  // set input-requested-region, because we access it later in
  // GenerateInputRequestedRegion (there we just set the time)
  input->SetRequestedRegion(&m_InputRequestedRegion);

  // PART II: initialize output image

  unsigned int dimension = input->GetDimension();
  unsigned int *dimensions = new unsigned int [dimension];
  itk2vtk(m_InputRequestedRegion.GetSize(), dimensions);
  if(dimension>3)
    memcpy(dimensions+3, input->GetDimensions()+3, (dimension-3)*sizeof(unsigned int));
  output->Initialize(mitk::PixelType(GetOutputPixelType()), dimension, dimensions);
  delete [] dimensions;

  // now we have everything to initialize the transform of the output
  mitk::SlicedGeometry3D* slicedGeometry = output->GetSlicedGeometry();

  // set the transform: use the transform of the input;
  // the origin will be replaced afterwards
  AffineTransform3D::Pointer indexToWorldTransform = AffineTransform3D::New();
  indexToWorldTransform->SetParameters(input->GetSlicedGeometry()->GetIndexToWorldTransform()->GetParameters());
  slicedGeometry->SetIndexToWorldTransform(indexToWorldTransform);

  // Position the output Image to match the corresponding region of the input image
  const mitk::SlicedData::IndexType& start = m_InputRequestedRegion.GetIndex();
  mitk::Point3D origin; vtk2itk(start, origin);
  inputImageGeometry->IndexToWorld(origin, origin);
  slicedGeometry->SetOrigin(origin);

  mitk::TimeSlicedGeometry* timeSlicedGeometry = output->GetTimeSlicedGeometry();
  timeSlicedGeometry->InitializeEvenlyTimed(slicedGeometry, output->GetDimension(3));
  timeSlicedGeometry->CopyTimes(input->GetTimeSlicedGeometry());

  m_TimeOfHeaderInitialization.Modified();
}

void BoundingObjectCutter::ComputeData(mitk::Image* input3D, int boTimeStep)
{
  AccessFixedDimensionByItk_2(input3D, CutImage, 3, this, boTimeStep);
}

void BoundingObjectCutter::GenerateData()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if(input.IsNull())
    return;

  if((output->IsInitialized()==false) || (m_BoundingObject.IsNull()) || (m_BoundingObject->GetTimeSlicedGeometry()->GetTimeSteps() == 0))
    return;

  m_InputTimeSelector->SetInput(input);
  m_OutputTimeSelector->SetInput(this->GetOutput());

  mitk::Surface::RegionType outputRegion = output->GetRequestedRegion();
  const mitk::TimeSlicedGeometry *outputTimeGeometry = output->GetTimeSlicedGeometry();
  const mitk::TimeSlicedGeometry *inputTimeGeometry = input->GetTimeSlicedGeometry();
  const mitk::TimeSlicedGeometry *boundingObjectTimeGeometry = m_BoundingObject->GetTimeSlicedGeometry();
  ScalarType timeInMS;

  int timestep=0;
  int tstart=outputRegion.GetIndex(3);
  int tmax=tstart+outputRegion.GetSize(3);

  int t;
  for(t=tstart;t<tmax;++t)
  {
    timeInMS = outputTimeGeometry->TimeStepToMS( t );

    timestep = inputTimeGeometry->MSToTimeStep( timeInMS );

    m_InputTimeSelector->SetTimeNr(timestep);
    m_InputTimeSelector->UpdateLargestPossibleRegion();
    m_OutputTimeSelector->SetTimeNr(t);
    m_OutputTimeSelector->UpdateLargestPossibleRegion();

    timestep = boundingObjectTimeGeometry->MSToTimeStep( timeInMS );

    ComputeData(m_InputTimeSelector->GetOutput(), timestep);
  }

  m_TimeOfHeaderInitialization.Modified();
}

} // of namespace mitk
<commit_msg>COMP (#4724): leak indirectly detected by test of mitk::BoundingObjectCutter<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

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

#if(_MSC_VER==1200)
#include <itkFixedCenterOfRotationAffineTransform.h>
#include <itkIndex.h>
#include <itkConceptChecking.h>
#endif
#include "mitkBoundingObjectCutter.h"
#include "mitkBoundingObjectCutter.txx"
#include "mitkTimeHelper.h"
#include "mitkImageAccessByItk.h"
#include "mitkBoundingObject.h"
#include "mitkGeometry3D.h"
//#include "itkImageRegionIteratorWithIndex.h"

namespace mitk
{

void BoundingObjectCutter::SetBoundingObject( const mitk::BoundingObject* boundingObject )
{
  m_BoundingObject = const_cast<mitk::BoundingObject*>(boundingObject);
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput(1,
    const_cast< mitk::BoundingObject * >( boundingObject ) );
}

const mitk::BoundingObject* BoundingObjectCutter::GetBoundingObject() const
{
  return m_BoundingObject.GetPointer();
}

BoundingObjectCutter::BoundingObjectCutter()
  : m_BoundingObject(NULL), m_InsideValue(1), m_OutsideValue(0), m_AutoOutsideValue(false),
    m_UseInsideValue(false), m_OutsidePixelCount(0), m_InsidePixelCount(0), m_UseWholeInputRegion(false)
{
  this->SetNumberOfInputs(2);
  this->SetNumberOfRequiredInputs(2);
  m_InputTimeSelector  = mitk::ImageTimeSelector::New();
  m_OutputTimeSelector = mitk::ImageTimeSelector::New();
}

BoundingObjectCutter::~BoundingObjectCutter()
{
}

const std::type_info& BoundingObjectCutter::GetOutputPixelType()
{
  return *this->GetInput()->GetPixelType().GetTypeId();
}

void BoundingObjectCutter::GenerateInputRequestedRegion()
{
  mitk::Image* output = this->GetOutput();
  if((output->IsInitialized()==false) || (m_BoundingObject.IsNull()) || (m_BoundingObject->GetTimeSlicedGeometry()->GetTimeSteps() == 0))
    return;
  // we have already calculated the spatial part of the
  // input-requested-region in m_InputRequestedRegion in
  // GenerateOutputInformation (which is called before
  // GenerateInputRequestedRegion).
  GenerateTimeInInputRegion(output, const_cast< mitk::Image * > ( this->GetInput() ));
  GenerateTimeInInputRegion(output, m_BoundingObject.GetPointer());
}

void BoundingObjectCutter::GenerateOutputInformation()
{
  mitk::Image::Pointer output = this->GetOutput();
  if ((output->IsInitialized()) && (output->GetPipelineMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
    return;

  mitk::Image::Pointer input = const_cast< mitk::Image * > ( this->GetInput() );

  itkDebugMacro(<<"GenerateOutputInformation()");

  if(input.IsNull())
    return;

  if((m_BoundingObject.IsNull()) || (m_BoundingObject->GetTimeSlicedGeometry()->GetTimeSteps() == 0))
    return;

  mitk::Geometry3D* boGeometry =  m_BoundingObject->GetGeometry();
  mitk::Geometry3D* inputImageGeometry = input->GetSlicedGeometry();
  // calculate bounding box of bounding-object relative to the geometry
  // of the input image. The result is in pixel coordinates of the input
  // image (because the m_IndexToWorldTransform includes the spacing).
  mitk::BoundingBox::Pointer boBoxRelativeToImage = boGeometry->CalculateBoundingBoxRelativeToTransform( inputImageGeometry->GetIndexToWorldTransform() );

  // PART I: initialize input requested region. We do this already here (and not
  // later when GenerateInputRequestedRegion() is called), because we
  // also need the information to setup the output.

  // pre-initialize input-requested-region to largest-possible-region
  // and correct time-region; spatial part will be cropped by
  // bounding-box of bounding-object below
  m_InputRequestedRegion = input->GetLargestPossibleRegion();

  // build region out of bounding-box of bounding-object
  mitk::SlicedData::IndexType  index=m_InputRequestedRegion.GetIndex(); //init times and channels
  mitk::BoundingBox::PointType min = boBoxRelativeToImage->GetMinimum();
  index[0] = (mitk::SlicedData::IndexType::IndexValueType)(min[0]+0.5);
  index[1] = (mitk::SlicedData::IndexType::IndexValueType)(min[1]+0.5);
  index[2] = (mitk::SlicedData::IndexType::IndexValueType)(min[2]+0.5);

  mitk::SlicedData::SizeType   size = m_InputRequestedRegion.GetSize(); //init times and channels
  mitk::BoundingBox::PointType max = boBoxRelativeToImage->GetMaximum();
  size[0] = (mitk::SlicedData::SizeType::SizeValueType)(max[0]+0.5)-index[0];
  size[1] = (mitk::SlicedData::SizeType::SizeValueType)(max[1]+0.5)-index[1];
  size[2] = (mitk::SlicedData::SizeType::SizeValueType)(max[2]+0.5)-index[2];

  mitk::SlicedData::RegionType boRegion(index, size);

  if(m_UseWholeInputRegion == false)
  {
	  // crop input-requested-region with region of bounding-object
	  if(m_InputRequestedRegion.Crop(boRegion)==false)
	  {
		// crop not possible => do nothing: set time size to 0.
		size.Fill(0);
		m_InputRequestedRegion.SetSize(size);
		boRegion.SetSize(size);
		m_BoundingObject->SetRequestedRegion(&boRegion);
		return;
	  }
  }

  // set input-requested-region, because we access it later in
  // GenerateInputRequestedRegion (there we just set the time)
  input->SetRequestedRegion(&m_InputRequestedRegion);

  // PART II: initialize output image

  unsigned int dimension = input->GetDimension();
  unsigned int *dimensions = new unsigned int [dimension];
  itk2vtk(m_InputRequestedRegion.GetSize(), dimensions);
  if(dimension>3)
    memcpy(dimensions+3, input->GetDimensions()+3, (dimension-3)*sizeof(unsigned int));
  output->Initialize(mitk::PixelType(GetOutputPixelType()), dimension, dimensions);
  delete [] dimensions;

  // now we have everything to initialize the transform of the output
  mitk::SlicedGeometry3D* slicedGeometry = output->GetSlicedGeometry();

  // set the transform: use the transform of the input;
  // the origin will be replaced afterwards
  AffineTransform3D::Pointer indexToWorldTransform = AffineTransform3D::New();
  indexToWorldTransform->SetParameters(input->GetSlicedGeometry()->GetIndexToWorldTransform()->GetParameters());
  slicedGeometry->SetIndexToWorldTransform(indexToWorldTransform);

  // Position the output Image to match the corresponding region of the input image
  const mitk::SlicedData::IndexType& start = m_InputRequestedRegion.GetIndex();
  mitk::Point3D origin; vtk2itk(start, origin);
  inputImageGeometry->IndexToWorld(origin, origin);
  slicedGeometry->SetOrigin(origin);

  mitk::TimeSlicedGeometry* timeSlicedGeometry = output->GetTimeSlicedGeometry();
  timeSlicedGeometry->InitializeEvenlyTimed(slicedGeometry, output->GetDimension(3));
  timeSlicedGeometry->CopyTimes(input->GetTimeSlicedGeometry());

  m_TimeOfHeaderInitialization.Modified();
}

void BoundingObjectCutter::ComputeData(mitk::Image* input3D, int boTimeStep)
{
  AccessFixedDimensionByItk_2(input3D, CutImage, 3, this, boTimeStep);
}

void BoundingObjectCutter::GenerateData()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if(input.IsNull())
    return;

  if((output->IsInitialized()==false) || (m_BoundingObject.IsNull()) || (m_BoundingObject->GetTimeSlicedGeometry()->GetTimeSteps() == 0))
    return;

  m_InputTimeSelector->SetInput(input);
  m_OutputTimeSelector->SetInput(this->GetOutput());

  mitk::Surface::RegionType outputRegion = output->GetRequestedRegion();
  const mitk::TimeSlicedGeometry *outputTimeGeometry = output->GetTimeSlicedGeometry();
  const mitk::TimeSlicedGeometry *inputTimeGeometry = input->GetTimeSlicedGeometry();
  const mitk::TimeSlicedGeometry *boundingObjectTimeGeometry = m_BoundingObject->GetTimeSlicedGeometry();
  ScalarType timeInMS;

  int timestep=0;
  int tstart=outputRegion.GetIndex(3);
  int tmax=tstart+outputRegion.GetSize(3);

  int t;
  for(t=tstart;t<tmax;++t)
  {
    timeInMS = outputTimeGeometry->TimeStepToMS( t );

    timestep = inputTimeGeometry->MSToTimeStep( timeInMS );

    m_InputTimeSelector->SetTimeNr(timestep);
    m_InputTimeSelector->UpdateLargestPossibleRegion();
    m_OutputTimeSelector->SetTimeNr(t);
    m_OutputTimeSelector->UpdateLargestPossibleRegion();

    timestep = boundingObjectTimeGeometry->MSToTimeStep( timeInMS );

    ComputeData(m_InputTimeSelector->GetOutput(), timestep);
  }

  m_InputTimeSelector->SetInput(NULL);
  m_OutputTimeSelector->SetInput(NULL);

  m_TimeOfHeaderInitialization.Modified();
}

} // of namespace mitk
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

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

#include "mitkTestingMacros.h"

#include "mitkPlanarAngle.h"
#include "mitkPlanarCircle.h"
#include "mitkPlanarCross.h"
#include "mitkPlanarFourPointAngle.h"
#include "mitkPlanarLine.h"
#include "mitkPlanarPolygon.h"
#include "mitkPlanarRectangle.h"

#include "mitkPlanarFigureWriter.h"
#include "mitkPlanarFigureReader.h"

#include "mitkPlaneGeometry.h"

#include <Poco/Zip/ZipLocalFileHeader.h>

/** \brief Helper class for testing PlanarFigure reader and writer classes. */
class PlanarFigureIOTestClass
{
public:

  typedef std::list< mitk::PlanarFigure::Pointer > PlanarFigureList;

  static PlanarFigureList CreatePlanarFigures()
  {
    PlanarFigureList planarFigures;

    // Create PlaneGeometry on which to place the PlanarFigures
    mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
    planeGeometry->InitializeStandardPlane( 100.0, 100.0 );

    // Create a few sample points for PlanarFigure placement
    mitk::Point2D p0; p0[0] = 20.0; p0[1] = 20.0;
    mitk::Point2D p1; p1[0] = 80.0; p1[1] = 80.0;
    mitk::Point2D p2; p2[0] = 90.0; p2[1] = 10.0;
    mitk::Point2D p3; p3[0] = 10.0; p3[1] = 90.0;

    // Create PlanarAngle
    mitk::PlanarAngle::Pointer planarAngle = mitk::PlanarAngle::New();
    planarAngle->SetGeometry2D( planeGeometry );
    planarAngle->PlaceFigure( p0 );
    planarAngle->SetCurrentControlPoint( p1 );
    planarAngle->AddControlPoint( p2 );
    planarFigures.push_back( planarAngle.GetPointer() );

    // Create PlanarCircle
    mitk::PlanarCircle::Pointer planarCircle = mitk::PlanarCircle::New();
    planarCircle->SetGeometry2D( planeGeometry );
    planarCircle->PlaceFigure( p0 );
    planarCircle->SetCurrentControlPoint( p1 );
    planarFigures.push_back( planarCircle.GetPointer() );

    // Create PlanarCross
    mitk::PlanarCross::Pointer planarCross = mitk::PlanarCross::New();
    planarCross->SetSingleLineMode( false );
    planarCross->SetGeometry2D( planeGeometry );
    planarCross->PlaceFigure( p0 );
    planarCross->SetCurrentControlPoint( p1 );
    planarCross->AddControlPoint( p2 );
    planarCross->AddControlPoint( p3 );
    planarFigures.push_back( planarCross.GetPointer() );

    // Create PlanarFourPointAngle
    mitk::PlanarFourPointAngle::Pointer planarFourPointAngle = mitk::PlanarFourPointAngle::New();
    planarFourPointAngle->SetGeometry2D( planeGeometry );
    planarFourPointAngle->PlaceFigure( p0 );
    planarFourPointAngle->SetCurrentControlPoint( p1 );
    planarFourPointAngle->AddControlPoint( p2 );
    planarFourPointAngle->AddControlPoint( p3 );
    planarFigures.push_back( planarFourPointAngle.GetPointer() );

    // Create PlanarLine
    mitk::PlanarLine::Pointer planarLine = mitk::PlanarLine::New();
    planarLine->SetGeometry2D( planeGeometry );
    planarLine->PlaceFigure( p0 );
    planarLine->SetCurrentControlPoint( p1 );
    planarFigures.push_back( planarLine.GetPointer() );

    // Create PlanarPolygon
    mitk::PlanarPolygon::Pointer planarPolygon = mitk::PlanarPolygon::New();
    planarPolygon->SetClosed( false );
    planarPolygon->SetGeometry2D( planeGeometry );
    planarPolygon->PlaceFigure( p0 );
    planarPolygon->SetCurrentControlPoint( p1 );
    planarPolygon->AddControlPoint( p2 );
    planarPolygon->AddControlPoint( p3 );
    planarFigures.push_back( planarPolygon.GetPointer() );

    // Create PlanarRectangle
    mitk::PlanarRectangle::Pointer planarRectangle = mitk::PlanarRectangle::New();
    planarRectangle->SetGeometry2D( planeGeometry );
    planarRectangle->PlaceFigure( p0 );
    planarRectangle->SetCurrentControlPoint( p1 );
    planarFigures.push_back( planarRectangle.GetPointer() );

    return planarFigures;
  }

  static void VerifyPlanarFigures( PlanarFigureList &planarFigures1, PlanarFigureList &planarFigures2 )
  {
    PlanarFigureList::iterator it1, it2;

    for ( it1 = planarFigures1.begin(); it1 != planarFigures1.end(); ++it1 )
    {
      bool planarFigureFound = false;
      for ( it2 = planarFigures2.begin(); it2 != planarFigures2.end(); ++it2 )
      {
        // Compare PlanarFigures (returns false if different types)
        if ( ComparePlanarFigures( *it1, *it2 ) )
        {
          planarFigureFound = true;
        }
      }

      // Test if (at least) on PlanarFigure of the first type was found in the second list
      MITK_TEST_CONDITION_REQUIRED(
        planarFigureFound,
        "Testing if " << (*it1)->GetNameOfClass() << " has a counterpart" );
    }
  }

  static bool ComparePlanarFigures( mitk::PlanarFigure* figure1, mitk::PlanarFigure* figure2 )
  {
    // Test if PlanarFigures are of same type; otherwise return
    if ( strcmp( figure1->GetNameOfClass(), figure2->GetNameOfClass() ) != 0 )
    {
      return false;
    }

    const char* figureName = figure1->GetNameOfClass();

    // Test for equal number of control points
    MITK_TEST_CONDITION_REQUIRED(
      figure1->GetNumberOfControlPoints() == figure2->GetNumberOfControlPoints(),
      figureName << ": Testing number of control points" );

    // Test if all control points are equal
    for ( unsigned int i = 0; i < figure1->GetNumberOfControlPoints(); ++i )
    {
      mitk::Point2D& point1 = figure1->GetControlPoint( i );
      mitk::Point2D& point2 = figure2->GetControlPoint( i );

      MITK_TEST_CONDITION_REQUIRED(
        point1.EuclideanDistanceTo( point2 ) < mitk::eps,
        figureName << ": Testing equality of control point " << i );
    }

    // Test for equal number of properties
    typedef mitk::PropertyList::PropertyMap PropertyMap;
    const PropertyMap* properties1 = figure1->GetPropertyList()->GetMap();
    const PropertyMap* properties2 = figure2->GetPropertyList()->GetMap();

    MITK_TEST_CONDITION_REQUIRED(
      properties1->size() == properties2->size(),
      figureName << ": Testing number of properties" );

    // Test if all properties are equal
    MITK_TEST_CONDITION_REQUIRED(
      std::equal( properties1->begin(), properties1->end(), properties2->begin(), PropertyMapEntryCompare() ),
      figureName << ": Testing equality of properties");

    // Test if Geometry is equal
    const mitk::PlaneGeometry* planeGeometry1 = dynamic_cast<const mitk::PlaneGeometry*>(figure1->GetGeometry2D());
    const mitk::PlaneGeometry* planeGeometry2 = dynamic_cast<const mitk::PlaneGeometry*>(figure2->GetGeometry2D());

    // Test Geometry transform parameters
    bool parametersEqual = true;
    typedef mitk::AffineGeometryFrame3D::TransformType TransformType;
    const TransformType* affineGeometry1 = planeGeometry1->GetIndexToWorldTransform();
    const TransformType::ParametersType& parameters1 = affineGeometry1->GetParameters();
    const TransformType::ParametersType& parameters2 = planeGeometry2->GetIndexToWorldTransform()->GetParameters();
    for ( unsigned int i = 0; i < affineGeometry1->GetNumberOfParameters(); ++i )
    {
      if ( fabs(parameters1.GetElement( i ) - parameters2.GetElement( i )) > mitk::eps )
      {
        parametersEqual = false;
      }
    }

    MITK_TEST_CONDITION_REQUIRED(
      parametersEqual,
      figureName << ": Testing if Geometry transform parameters are equal");

    // Test Geometry bounds
    bool boundsEqual = true;
    typedef mitk::Geometry3D::BoundsArrayType BoundsArrayType;
    const BoundsArrayType& bounds1 = planeGeometry1->GetBounds();
    const BoundsArrayType& bounds2 = planeGeometry2->GetBounds();
    for ( unsigned int i = 0; i < 6; ++i )
    {
      if ( fabs(bounds1.GetElement( i ) - bounds2.GetElement( i )) > mitk::eps )
      {
        boundsEqual = false;
      };
    }

    MITK_TEST_CONDITION_REQUIRED(
      boundsEqual,
      figureName << ": Testing if Geometry bounds are equal");

    // Test Geometry spacing and origin
    mitk::Vector3D spacing1 = planeGeometry1->GetSpacing();
    mitk::Vector3D spacing2 = planeGeometry2->GetSpacing();

    MITK_TEST_CONDITION_REQUIRED(
      (spacing1 - spacing2).GetNorm() < mitk::eps,
      figureName << ": Testing if Geometry spacing is equal");

    mitk::Point3D origin1 = planeGeometry1->GetOrigin();
    mitk::Point3D origin2 = planeGeometry2->GetOrigin();

    MITK_TEST_CONDITION_REQUIRED(
      origin1.EuclideanDistanceTo( origin2 ) < mitk::eps,
      figureName << ": Testing if Geometry origin are equal");

    return true;
  }

  static void SerializePlanarFigures( PlanarFigureList &planarFigures, std::string& fileName )
  {
    //std::string  sceneFileName = Poco::Path::temp() + /*Poco::Path::separator() +*/ "scene.zip";
    std::cout << "File name: " << fileName << std::endl;

    mitk::PlanarFigureWriter::Pointer writer = mitk::PlanarFigureWriter::New();
    writer->SetFileName( fileName.c_str() );

    unsigned int i;
    PlanarFigureList::iterator it;
    for ( it = planarFigures.begin(), i = 0;
          it != planarFigures.end();
          ++it, ++i )
    {
      writer->SetInput( i, *it );
    }

    writer->Update();

    MITK_TEST_CONDITION_REQUIRED(
      writer->GetSuccess(),
      "Testing if writing was successful");
  }

  static PlanarFigureList DeserializePlanarFigures( std::string& fileName)
  {
    // Read in the planar figures
    mitk::PlanarFigureReader::Pointer reader = mitk::PlanarFigureReader::New();
    reader->SetFileName( fileName.c_str() );
    reader->Update();

    MITK_TEST_CONDITION_REQUIRED(
      reader->GetSuccess(),
      "Testing if reading was successful");

    // Store them in the list and return it
    PlanarFigureList planarFigures;
    for ( unsigned int i = 0; i < reader->GetNumberOfOutputs(); ++i )
    {
      mitk::PlanarFigure* figure = reader->GetOutput( i );
      planarFigures.push_back( figure );
    }

    return planarFigures;
  }

private:
  class PropertyMapEntryCompare
  {
  public:
    bool operator()(
      const mitk::PropertyList::PropertyMap::value_type &entry1,
      const mitk::PropertyList::PropertyMap::value_type &entry2 )
    {
      // Compare property objects contained in the map entries (see mitk::PropertyList)
      return *(entry1.second.first) == *(entry2.second.first);
    }
  };

}; // end test helper class

/** \brief Test for PlanarFigure reader and writer classes.
 *
 * The test works as follows:
 *
 * First, a number of PlanarFigure objects of different types are created and placed with
 * various control points. These objects are the serialized to file, read again from file, and
 * the retrieved objects are compared with their control points, properties, and geometry
 * information to the original PlanarFigure objects.
 */
int mitkPlanarFigureIOTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("PlanarFigureIO")

  // Create a number of PlanarFigure objects
  PlanarFigureIOTestClass::PlanarFigureList originalPlanarFigures =
    PlanarFigureIOTestClass::CreatePlanarFigures();

  // Write PlanarFigure objects into temp file
  std::string fileName = Poco::Path::temp() + "TestPlanarFigure.pf";
  PlanarFigureIOTestClass::SerializePlanarFigures( originalPlanarFigures, fileName );

  // Read PlanarFigure objects from temp file
  PlanarFigureIOTestClass::PlanarFigureList retrievedPlanarFigures =
    PlanarFigureIOTestClass::DeserializePlanarFigures( fileName );

  // Test if original and retrieved PlanarFigure objects are the same
  PlanarFigureIOTestClass::VerifyPlanarFigures( originalPlanarFigures, retrievedPlanarFigures );

  MITK_TEST_END()
}
<commit_msg>FIX (#4122): generate unique PlanarFigure file name<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

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

#include "mitkTestingMacros.h"

#include "mitkPlanarAngle.h"
#include "mitkPlanarCircle.h"
#include "mitkPlanarCross.h"
#include "mitkPlanarFourPointAngle.h"
#include "mitkPlanarLine.h"
#include "mitkPlanarPolygon.h"
#include "mitkPlanarRectangle.h"

#include "mitkPlanarFigureWriter.h"
#include "mitkPlanarFigureReader.h"

#include "mitkPlaneGeometry.h"

#include <Poco/Zip/ZipLocalFileHeader.h>
#include "Poco/TemporaryFile.h"

/** \brief Helper class for testing PlanarFigure reader and writer classes. */
class PlanarFigureIOTestClass
{
public:

  typedef std::list< mitk::PlanarFigure::Pointer > PlanarFigureList;

  static PlanarFigureList CreatePlanarFigures()
  {
    PlanarFigureList planarFigures;

    // Create PlaneGeometry on which to place the PlanarFigures
    mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
    planeGeometry->InitializeStandardPlane( 100.0, 100.0 );

    // Create a few sample points for PlanarFigure placement
    mitk::Point2D p0; p0[0] = 20.0; p0[1] = 20.0;
    mitk::Point2D p1; p1[0] = 80.0; p1[1] = 80.0;
    mitk::Point2D p2; p2[0] = 90.0; p2[1] = 10.0;
    mitk::Point2D p3; p3[0] = 10.0; p3[1] = 90.0;

    // Create PlanarAngle
    mitk::PlanarAngle::Pointer planarAngle = mitk::PlanarAngle::New();
    planarAngle->SetGeometry2D( planeGeometry );
    planarAngle->PlaceFigure( p0 );
    planarAngle->SetCurrentControlPoint( p1 );
    planarAngle->AddControlPoint( p2 );
    planarFigures.push_back( planarAngle.GetPointer() );

    // Create PlanarCircle
    mitk::PlanarCircle::Pointer planarCircle = mitk::PlanarCircle::New();
    planarCircle->SetGeometry2D( planeGeometry );
    planarCircle->PlaceFigure( p0 );
    planarCircle->SetCurrentControlPoint( p1 );
    planarFigures.push_back( planarCircle.GetPointer() );

    // Create PlanarCross
    mitk::PlanarCross::Pointer planarCross = mitk::PlanarCross::New();
    planarCross->SetSingleLineMode( false );
    planarCross->SetGeometry2D( planeGeometry );
    planarCross->PlaceFigure( p0 );
    planarCross->SetCurrentControlPoint( p1 );
    planarCross->AddControlPoint( p2 );
    planarCross->AddControlPoint( p3 );
    planarFigures.push_back( planarCross.GetPointer() );

    // Create PlanarFourPointAngle
    mitk::PlanarFourPointAngle::Pointer planarFourPointAngle = mitk::PlanarFourPointAngle::New();
    planarFourPointAngle->SetGeometry2D( planeGeometry );
    planarFourPointAngle->PlaceFigure( p0 );
    planarFourPointAngle->SetCurrentControlPoint( p1 );
    planarFourPointAngle->AddControlPoint( p2 );
    planarFourPointAngle->AddControlPoint( p3 );
    planarFigures.push_back( planarFourPointAngle.GetPointer() );

    // Create PlanarLine
    mitk::PlanarLine::Pointer planarLine = mitk::PlanarLine::New();
    planarLine->SetGeometry2D( planeGeometry );
    planarLine->PlaceFigure( p0 );
    planarLine->SetCurrentControlPoint( p1 );
    planarFigures.push_back( planarLine.GetPointer() );

    // Create PlanarPolygon
    mitk::PlanarPolygon::Pointer planarPolygon = mitk::PlanarPolygon::New();
    planarPolygon->SetClosed( false );
    planarPolygon->SetGeometry2D( planeGeometry );
    planarPolygon->PlaceFigure( p0 );
    planarPolygon->SetCurrentControlPoint( p1 );
    planarPolygon->AddControlPoint( p2 );
    planarPolygon->AddControlPoint( p3 );
    planarFigures.push_back( planarPolygon.GetPointer() );

    // Create PlanarRectangle
    mitk::PlanarRectangle::Pointer planarRectangle = mitk::PlanarRectangle::New();
    planarRectangle->SetGeometry2D( planeGeometry );
    planarRectangle->PlaceFigure( p0 );
    planarRectangle->SetCurrentControlPoint( p1 );
    planarFigures.push_back( planarRectangle.GetPointer() );

    return planarFigures;
  }

  static void VerifyPlanarFigures( PlanarFigureList &planarFigures1, PlanarFigureList &planarFigures2 )
  {
    PlanarFigureList::iterator it1, it2;

    for ( it1 = planarFigures1.begin(); it1 != planarFigures1.end(); ++it1 )
    {
      bool planarFigureFound = false;
      for ( it2 = planarFigures2.begin(); it2 != planarFigures2.end(); ++it2 )
      {
        // Compare PlanarFigures (returns false if different types)
        if ( ComparePlanarFigures( *it1, *it2 ) )
        {
          planarFigureFound = true;
        }
      }

      // Test if (at least) on PlanarFigure of the first type was found in the second list
      MITK_TEST_CONDITION_REQUIRED(
        planarFigureFound,
        "Testing if " << (*it1)->GetNameOfClass() << " has a counterpart" );
    }
  }

  static bool ComparePlanarFigures( mitk::PlanarFigure* figure1, mitk::PlanarFigure* figure2 )
  {
    // Test if PlanarFigures are of same type; otherwise return
    if ( strcmp( figure1->GetNameOfClass(), figure2->GetNameOfClass() ) != 0 )
    {
      return false;
    }

    const char* figureName = figure1->GetNameOfClass();

    // Test for equal number of control points
    MITK_TEST_CONDITION_REQUIRED(
      figure1->GetNumberOfControlPoints() == figure2->GetNumberOfControlPoints(),
      figureName << ": Testing number of control points" );

    // Test if all control points are equal
    for ( unsigned int i = 0; i < figure1->GetNumberOfControlPoints(); ++i )
    {
      mitk::Point2D& point1 = figure1->GetControlPoint( i );
      mitk::Point2D& point2 = figure2->GetControlPoint( i );

      MITK_TEST_CONDITION_REQUIRED(
        point1.EuclideanDistanceTo( point2 ) < mitk::eps,
        figureName << ": Testing equality of control point " << i );
    }

    // Test for equal number of properties
    typedef mitk::PropertyList::PropertyMap PropertyMap;
    const PropertyMap* properties1 = figure1->GetPropertyList()->GetMap();
    const PropertyMap* properties2 = figure2->GetPropertyList()->GetMap();

    MITK_TEST_CONDITION_REQUIRED(
      properties1->size() == properties2->size(),
      figureName << ": Testing number of properties" );

    // Test if all properties are equal
    MITK_TEST_CONDITION_REQUIRED(
      std::equal( properties1->begin(), properties1->end(), properties2->begin(), PropertyMapEntryCompare() ),
      figureName << ": Testing equality of properties");

    // Test if Geometry is equal
    const mitk::PlaneGeometry* planeGeometry1 = dynamic_cast<const mitk::PlaneGeometry*>(figure1->GetGeometry2D());
    const mitk::PlaneGeometry* planeGeometry2 = dynamic_cast<const mitk::PlaneGeometry*>(figure2->GetGeometry2D());

    // Test Geometry transform parameters
    bool parametersEqual = true;
    typedef mitk::AffineGeometryFrame3D::TransformType TransformType;
    const TransformType* affineGeometry1 = planeGeometry1->GetIndexToWorldTransform();
    const TransformType::ParametersType& parameters1 = affineGeometry1->GetParameters();
    const TransformType::ParametersType& parameters2 = planeGeometry2->GetIndexToWorldTransform()->GetParameters();
    for ( unsigned int i = 0; i < affineGeometry1->GetNumberOfParameters(); ++i )
    {
      if ( fabs(parameters1.GetElement( i ) - parameters2.GetElement( i )) > mitk::eps )
      {
        parametersEqual = false;
      }
    }

    MITK_TEST_CONDITION_REQUIRED(
      parametersEqual,
      figureName << ": Testing if Geometry transform parameters are equal");

    // Test Geometry bounds
    bool boundsEqual = true;
    typedef mitk::Geometry3D::BoundsArrayType BoundsArrayType;
    const BoundsArrayType& bounds1 = planeGeometry1->GetBounds();
    const BoundsArrayType& bounds2 = planeGeometry2->GetBounds();
    for ( unsigned int i = 0; i < 6; ++i )
    {
      if ( fabs(bounds1.GetElement( i ) - bounds2.GetElement( i )) > mitk::eps )
      {
        boundsEqual = false;
      };
    }

    MITK_TEST_CONDITION_REQUIRED(
      boundsEqual,
      figureName << ": Testing if Geometry bounds are equal");

    // Test Geometry spacing and origin
    mitk::Vector3D spacing1 = planeGeometry1->GetSpacing();
    mitk::Vector3D spacing2 = planeGeometry2->GetSpacing();

    MITK_TEST_CONDITION_REQUIRED(
      (spacing1 - spacing2).GetNorm() < mitk::eps,
      figureName << ": Testing if Geometry spacing is equal");

    mitk::Point3D origin1 = planeGeometry1->GetOrigin();
    mitk::Point3D origin2 = planeGeometry2->GetOrigin();

    MITK_TEST_CONDITION_REQUIRED(
      origin1.EuclideanDistanceTo( origin2 ) < mitk::eps,
      figureName << ": Testing if Geometry origin are equal");

    return true;
  }

  static void SerializePlanarFigures( PlanarFigureList &planarFigures, std::string& fileName )
  {
    //std::string  sceneFileName = Poco::Path::temp() + /*Poco::Path::separator() +*/ "scene.zip";
    std::cout << "File name: " << fileName << std::endl;

    mitk::PlanarFigureWriter::Pointer writer = mitk::PlanarFigureWriter::New();
    writer->SetFileName( fileName.c_str() );

    unsigned int i;
    PlanarFigureList::iterator it;
    for ( it = planarFigures.begin(), i = 0;
          it != planarFigures.end();
          ++it, ++i )
    {
      writer->SetInput( i, *it );
    }

    writer->Update();

    MITK_TEST_CONDITION_REQUIRED(
      writer->GetSuccess(),
      "Testing if writing was successful");
  }

  static PlanarFigureList DeserializePlanarFigures( std::string& fileName)
  {
    // Read in the planar figures
    mitk::PlanarFigureReader::Pointer reader = mitk::PlanarFigureReader::New();
    reader->SetFileName( fileName.c_str() );
    reader->Update();

    MITK_TEST_CONDITION_REQUIRED(
      reader->GetSuccess(),
      "Testing if reading was successful");

    // Store them in the list and return it
    PlanarFigureList planarFigures;
    for ( unsigned int i = 0; i < reader->GetNumberOfOutputs(); ++i )
    {
      mitk::PlanarFigure* figure = reader->GetOutput( i );
      planarFigures.push_back( figure );
    }

    return planarFigures;
  }

private:
  class PropertyMapEntryCompare
  {
  public:
    bool operator()(
      const mitk::PropertyList::PropertyMap::value_type &entry1,
      const mitk::PropertyList::PropertyMap::value_type &entry2 )
    {
      // Compare property objects contained in the map entries (see mitk::PropertyList)
      return *(entry1.second.first) == *(entry2.second.first);
    }
  };

}; // end test helper class

/** \brief Test for PlanarFigure reader and writer classes.
 *
 * The test works as follows:
 *
 * First, a number of PlanarFigure objects of different types are created and placed with
 * various control points. These objects are the serialized to file, read again from file, and
 * the retrieved objects are compared with their control points, properties, and geometry
 * information to the original PlanarFigure objects.
 */
int mitkPlanarFigureIOTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("PlanarFigureIO")

  // Create a number of PlanarFigure objects
  PlanarFigureIOTestClass::PlanarFigureList originalPlanarFigures =
    PlanarFigureIOTestClass::CreatePlanarFigures();

  // Write PlanarFigure objects into temp file
  Poco::Path newname( Poco::TemporaryFile::tempName() );
  std::string fileName = Poco::Path::temp() + newname.getFileName() + ".pf";
  PlanarFigureIOTestClass::SerializePlanarFigures( originalPlanarFigures, fileName );

  // Read PlanarFigure objects from temp file
  PlanarFigureIOTestClass::PlanarFigureList retrievedPlanarFigures =
    PlanarFigureIOTestClass::DeserializePlanarFigures( fileName );

  // Test if original and retrieved PlanarFigure objects are the same
  PlanarFigureIOTestClass::VerifyPlanarFigures( originalPlanarFigures, retrievedPlanarFigures );

  MITK_TEST_END()
}
<|endoftext|>


<commit_before>/// (c) Koheron

#include "base.hpp"

Base::Base(Klib::DevMem& dev_mem_)
: dev_mem(dev_mem_),
  xadc(dev_mem_),
  gpio(dev_mem_)
{
    dac_wfm_size = 0;
    status = CLOSED;
}

Base::~Base()
{
    Close();
}

# define MAP_SIZE 4096

# define LASER_ENABLE_PIN 5

int Base::Open(uint32_t dac_wfm_size_)
{
    // Reopening
    if(status == OPENED && dac_wfm_size_ != dac_wfm_size) {
        Close();
    }

    if(status == CLOSED) {
        dac_wfm_size = dac_wfm_size_;

        // Initializes memory maps
        config_map = dev_mem.AddMemoryMap(CONFIG_ADDR, MAP_SIZE);

        if(static_cast<int>(config_map) < 0) {
            status = FAILED;
            return -1;
        }

        status_map = dev_mem.AddMemoryMap(STATUS_ADDR, MAP_SIZE);

        if(static_cast<int>(status_map) < 0) {
            status = FAILED;
            return -1;
        }

        dac_map = dev_mem.AddMemoryMap(DAC_ADDR, dac_wfm_size*MAP_SIZE/1024);

        if(static_cast<int>(dac_map) < 0) {
            status = FAILED;
            return -1;
        }

        // Open core drivers
        xadc.Open();
        gpio.Open();

        status = OPENED;
        reset();
    }

    return 0;
}

void Base::Close()
{
    if(status == OPENED) {
        reset();

        dev_mem.RmMemoryMap(config_map);
        dev_mem.RmMemoryMap(status_map);
        dev_mem.RmMemoryMap(dac_map);

        xadc.Close();
        gpio.Close();

        status = CLOSED;
    }
}

void Base::reset()
{
    assert(status == OPENED);

    // XADC
    xadc.set_channel(LASER_POWER_CHANNEL, LASER_CURRENT_CHANNEL);
    xadc.enable_averaging();
    xadc.set_averaging(256);

    // GPIO
    gpio.set_as_output(LASER_ENABLE_PIN, 2);

    // Config
    //Klib::ClearBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 0);
    Klib::ClearBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 1);
    Klib::SetBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 0);

    stop_laser();
    set_laser_current(0.0);
}

uint32_t Base::get_laser_current()
{
    return xadc.read(LASER_CURRENT_CHANNEL);
}

uint32_t Base::get_laser_power()
{
    return xadc.read(LASER_POWER_CHANNEL);
}

std::tuple<uint32_t, uint32_t> Base::get_monitoring()
{
    return std::make_tuple(get_laser_current(), get_laser_power());
}

void Base::start_laser()
{
    gpio.clear_bit(LASER_ENABLE_PIN, 2); // Laser enable on pin DIO7_P
}

void Base::stop_laser()
{
    gpio.set_bit(LASER_ENABLE_PIN, 2); // Laser enable on pin DIO7_P
}

#define GAIN_LT1789 (1+200/10)
#define PWM_MAX_VOLTAGE 1.8
#define PWM_MAX_VALUE 1024
#define MILLIAMPS_TO_AMPS 0.001
#define CURRENT_TO_VOLTAGE(current) \
    (current * MILLIAMPS_TO_AMPS * PWM_MAX_VALUE * GAIN_LT1789 / PWM_MAX_VOLTAGE)

void Base::set_laser_current(float current)
{
    float current_;
    current > MAX_LASER_CURRENT ? current_ = MAX_LASER_CURRENT : current_ = current;
    uint32_t voltage = (uint32_t) CURRENT_TO_VOLTAGE(current_);
    Klib::WriteReg32(dev_mem.GetBaseAddr(config_map) + PWM3_OFF, voltage);
}

void Base::set_dac_buffer(const uint32_t *data, uint32_t len)
{
    for (uint32_t i=0; i<len; i++)
        Klib::WriteReg32(dev_mem.GetBaseAddr(dac_map)+sizeof(uint32_t)*i, data[i]);
}

std::array<uint32_t, BITSTREAM_ID_SIZE> Base::get_bitstream_id()
{
    for (uint32_t i=0; i<bitstream_id.size(); i++)
        bitstream_id[i] = Klib::ReadReg32(dev_mem.GetBaseAddr(config_map) + BITSTREAM_ID_OFF + 4*i);

    return bitstream_id;
}

void Base::set_led(uint32_t value)
{
    Klib::WriteReg32(dev_mem.GetBaseAddr(config_map) + LED_OFF, value);
}

void Base::reset_acquisition()
{
    Klib::ClearBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 1);
    Klib::SetBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 1);
}
<commit_msg>Fix map ref<commit_after>/// (c) Koheron

#include "base.hpp"

Base::Base(Klib::DevMem& dev_mem_)
: dev_mem(dev_mem_),
  xadc(dev_mem_),
  gpio(dev_mem_)
{
    dac_wfm_size = 0;
    status = CLOSED;
}

Base::~Base()
{
    Close();
}

# define MAP_SIZE 4096

# define LASER_ENABLE_PIN 5

int Base::Open(uint32_t dac_wfm_size_)
{
    // Reopening
    if(status == OPENED && dac_wfm_size_ != dac_wfm_size) {
        Close();
    }

    if(status == CLOSED) {
        dac_wfm_size = dac_wfm_size_;

        // Initializes memory maps
        config_map = dev_mem.AddMemoryMap(CONFIG_ADDR, MAP_SIZE);

        if(static_cast<int>(config_map) < 0) {
            status = FAILED;
            return -1;
        }

        status_map = dev_mem.AddMemoryMap(STATUS_ADDR, MAP_SIZE);

        if(static_cast<int>(status_map) < 0) {
            status = FAILED;
            return -1;
        }

        dac_map = dev_mem.AddMemoryMap(DAC_ADDR, dac_wfm_size*MAP_SIZE/1024);

        if(static_cast<int>(dac_map) < 0) {
            status = FAILED;
            return -1;
        }

        // Open core drivers
        xadc.Open();
        gpio.Open();

        status = OPENED;
        reset();
    }

    return 0;
}

void Base::Close()
{
    if(status == OPENED) {
        reset();

        dev_mem.RmMemoryMap(config_map);
        dev_mem.RmMemoryMap(status_map);
        dev_mem.RmMemoryMap(dac_map);

        xadc.Close();
        gpio.Close();

        status = CLOSED;
    }
}

void Base::reset()
{
    assert(status == OPENED);

    // XADC
    xadc.set_channel(LASER_POWER_CHANNEL, LASER_CURRENT_CHANNEL);
    xadc.enable_averaging();
    xadc.set_averaging(256);

    // GPIO
    gpio.set_as_output(LASER_ENABLE_PIN, 2);

    // Config
    //Klib::ClearBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 0);
    Klib::ClearBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 1);
    Klib::SetBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 0);

    stop_laser();
    set_laser_current(0.0);
}

uint32_t Base::get_laser_current()
{
    return xadc.read(LASER_CURRENT_CHANNEL);
}

uint32_t Base::get_laser_power()
{
    return xadc.read(LASER_POWER_CHANNEL);
}

std::tuple<uint32_t, uint32_t> Base::get_monitoring()
{
    return std::make_tuple(get_laser_current(), get_laser_power());
}

void Base::start_laser()
{
    gpio.clear_bit(LASER_ENABLE_PIN, 2); // Laser enable on pin DIO7_P
}

void Base::stop_laser()
{
    gpio.set_bit(LASER_ENABLE_PIN, 2); // Laser enable on pin DIO7_P
}

#define GAIN_LT1789 (1+200/10)
#define PWM_MAX_VOLTAGE 1.8
#define PWM_MAX_VALUE 1024
#define MILLIAMPS_TO_AMPS 0.001
#define CURRENT_TO_VOLTAGE(current) \
    (current * MILLIAMPS_TO_AMPS * PWM_MAX_VALUE * GAIN_LT1789 / PWM_MAX_VOLTAGE)

void Base::set_laser_current(float current)
{
    float current_;
    current > MAX_LASER_CURRENT ? current_ = MAX_LASER_CURRENT : current_ = current;
    uint32_t voltage = (uint32_t) CURRENT_TO_VOLTAGE(current_);
    Klib::WriteReg32(dev_mem.GetBaseAddr(config_map) + PWM3_OFF, voltage);
}

void Base::set_dac_buffer(const uint32_t *data, uint32_t len)
{
    for (uint32_t i=0; i<len; i++)
        Klib::WriteReg32(dev_mem.GetBaseAddr(dac_map)+sizeof(uint32_t)*i, data[i]);
}

std::array<uint32_t, BITSTREAM_ID_SIZE> Base::get_bitstream_id()
{
    for (uint32_t i=0; i<bitstream_id.size(); i++)
        bitstream_id[i] = Klib::ReadReg32(dev_mem.GetBaseAddr(status_map) + BITSTREAM_ID_OFF + 4*i);

    return bitstream_id;
}

void Base::set_led(uint32_t value)
{
    Klib::WriteReg32(dev_mem.GetBaseAddr(config_map) + LED_OFF, value);
}

void Base::reset_acquisition()
{
    Klib::ClearBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 1);
    Klib::SetBit(dev_mem.GetBaseAddr(config_map) + ADDR_OFF, 1);
}
<|endoftext|>


<commit_before>#include <math.h>

#include <tr1/functional>
#include <tr1/unordered_map>
using std::tr1::hash;
using std::tr1::unordered_map;

#include <boost/random.hpp>
using boost::variate_generator;
using boost::normal_distribution;
using boost::cauchy_distribution;

typedef boost::mt19937 base_generator_type;

extern "C" {
#include <cblas.h>

#define INDEX(row, column, num_rows) ((int)(row) + ((int)(num_rows) * (int)(column)))
#define ROUND_TO_INT(x) ((int)((x) + 0.5))

void propagation_kernel(int *graph_ind, double *probabilities, int num_nodes,
												int num_labels, int num_graphs, double w, int p,
												double *kernel_matrix)
{
	int i, *labels;
	double *random_offsets, *signatures, *feature_vectors;

	unordered_map<double, int, hash<double> > signature_hash;

	base_generator_type generator(0);

	normal_distribution<double> normal(0, 1);
	variate_generator<base_generator_type&, normal_distribution<double> >
		randn(generator, normal);

	cauchy_distribution<double> cauchy(0, 1);
	variate_generator<base_generator_type&, cauchy_distribution<double> >
		randc(generator, cauchy);

	labels = new int[num_nodes];
	signatures = new double[num_nodes]();

	random_offsets = new double[num_labels - 1];
	for (i = 0; i < num_labels - 1; i++)
		if (p == 1)
			random_offsets[i] = randc();
		else
			random_offsets[i] = randn();

	cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, num_nodes, 1, num_labels - 1, 1,
							probabilities, num_nodes, random_offsets, num_labels - 1, 1, signatures, num_nodes);

	for (i = 0; i < num_nodes; i++)
		signatures[i] = floor(signatures[i] / w);

	num_labels = 0;
	for (i = 0; i < num_nodes; i++) {
		if (signature_hash.count(signatures[i]) == 0) {
			num_labels++;
			labels[i] = num_labels;
			signature_hash[signatures[i]] = num_labels;
		}
		else
			labels[i] = signature_hash[signatures[i]];
	}

	feature_vectors = new double[num_graphs * num_labels]();
	for (i = 0; i < num_nodes; i++)
		feature_vectors[INDEX(graph_ind[i] - 1, labels[i] - 1, num_graphs)]++;

	cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, num_graphs, num_labels,
							1.0, feature_vectors, num_graphs, 0.0, kernel_matrix, num_graphs);

	delete[] labels;
	delete[] feature_vectors;
	delete[] random_offsets;
	delete[] signatures;
}

}
<commit_msg>major overhaul<commit_after>#include <math.h>

#include <tr1/functional>
#include <tr1/unordered_map>
using std::tr1::hash;
using std::tr1::unordered_map;

#include <boost/random.hpp>
using boost::variate_generator;
using boost::normal_distribution;
using boost::cauchy_distribution;
typedef boost::mt19937 base_generator_type;

#define INDEX(row, column, num_rows) ((int)(row) + ((int)(num_rows) * (int)(column)))

extern "C" {
#include <cblas.h>

	void calculate_propagation_kernel_contribution(double *probabilities,
																								 int *graph_ind,
																								 double w,
																								 int p,
																								 int num_nodes,
																								 int num_classes,
																								 int num_graphs,
																								 double *kernel_matrix)
	{
		int i, j, *labels;
		double *random_offsets, *signatures, *feature_vectors;
		bool use_cauchy = (p == 1);

		unordered_map<double, int, hash<double> > signature_hash;

		base_generator_type generator(0);

		normal_distribution<double> normal(0, 1);
		variate_generator<base_generator_type&, normal_distribution<double> >
			randn(generator, normal);

		cauchy_distribution<double> cauchy(0, 1);
		variate_generator<base_generator_type&, cauchy_distribution<double> >
			randc(generator, cauchy);

		labels = new int[num_nodes];
		signatures = new double[num_nodes]();

		random_offsets = new double[num_classes - 1];
		for (i = 0; i < num_classes - 1; i++)
			if (use_cauchy)
				random_offsets[i] = randc();
			else
				random_offsets[i] = randn();

		if (!use_cauchy)
			for (i = 0; i < num_nodes; i++)
				for (j = 0; j < num_classes - 1; j++)
					probabilities[INDEX(i, j, num_nodes)] = sqrt(probabilities[INDEX(i, j, num_nodes)]);

		cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, num_nodes, 1, num_classes - 1, 1,
								probabilities, num_nodes, random_offsets, num_classes - 1, 1, signatures, num_nodes);

		for (i = 0; i < num_nodes; i++)
			signatures[i] = floor(signatures[i] / w);

		num_classes = 0;
		for (i = 0; i < num_nodes; i++) {
			if (signature_hash.count(signatures[i]) == 0) {
				num_classes++;
				labels[i] = num_classes;
				signature_hash[signatures[i]] = num_classes;
			}
			else
				labels[i] = signature_hash[signatures[i]];
		}

		feature_vectors = new double[num_graphs * num_classes]();
		for (i = 0; i < num_nodes; i++)
			feature_vectors[INDEX(graph_ind[i] - 1, labels[i] - 1, num_graphs)]++;

		cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, num_graphs, num_classes,
								1.0, feature_vectors, num_graphs, 0.0, kernel_matrix, num_graphs);

		delete[] labels;
		delete[] feature_vectors;
		delete[] random_offsets;
		delete[] signatures;
	}

}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    qRegisterMetaType<StateForTimestep>("StateForTimestep&");

    ui->setupUi(this);
    modelController = new FieldModelController();
    udpServer = new UdpServer();
    modeManager = new ModeManager();
    recorder = new Recorder();
    player = new RecordPlayer();

    connect(udpServer, SIGNAL(messageRecieved(QString)),modelController, SLOT(updateState(QString)));

    connect(modelController, SIGNAL(updateScene(StateForTimestep&)),
            modeManager, SLOT(on_updateScene_live(StateForTimestep&)));

    connect(modeManager, SIGNAL(updateScene(StateForTimestep&)),
            ui->rosoFieldWdgt, SLOT(on_updateScene(StateForTimestep&)));

    connect(modelController,SIGNAL(updateScene(StateForTimestep&)),
            recorder, SLOT(on_updateScene(StateForTimestep&)));

    connect(recorder, SIGNAL(recordsUpdated()), this, SLOT(on_recordsUpdated()));

    connect(player,SIGNAL(updateScene(StateForTimestep&)),
            modeManager, SLOT(on_updateScene_replay(StateForTimestep&)));

    connect(player, SIGNAL(recordPlayingFinished()),this,SLOT(on_player_finished()));

    ui->record_ListView->setModel(&recordListModel);
    on_liveMode_radioButton_toggled(true);

    ui->record_ListView->setSelectionMode(QListView::SingleSelection);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionClear_triggered()
{
    modelController->clearScene();
}

void MainWindow::on_actionRotate_Clockwise_triggered()
{
    ui->rosoFieldWdgt->rotateScene(ui->rosoFieldWdgt->getRotate() + 90);
}

void MainWindow::on_actionAbout_Qt_triggered()
{
    QMessageBox::aboutQt(this);
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, "About Roso_Viz", "Author: Tianlan Shao
Contact: shaotianlan.de@gmail.com

Github: https://github.com/shaosHumbleAccount/roso_viz

Published under MIT licence.

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.");
}

void MainWindow::on_liveMode_radioButton_toggled(bool checked)
{
    if(checked)
    {
        modeManager->setMode(ModeManager::LIVE);
        ui->startRecording_BTN->setEnabled(true);
        ui->playRecord_BTN->setEnabled(false);
        ui->saveRecord_BTN->setEnabled(false);
    }
    else
    {
        if(recorder->getIsRecording())
        {
            on_startRecording_BTN_clicked();
        }
        modeManager->setMode(ModeManager::REPLAY);
        ui->startRecording_BTN->setEnabled(false);
        ui->playRecord_BTN->setEnabled(true);
        ui->saveRecord_BTN->setEnabled(true);
    }
}

void MainWindow::on_recordsUpdated()
{
    QStringList recordNames = recorder->getRecordNames();

    recordListModel.clear();
    foreach(QString name, recordNames)
    {
        QStandardItem* item = new QStandardItem(name);
        item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        QList<QStandardItem *> row;
        row.append(item);
        recordListModel.invisibleRootItem()->appendRow(row);
    }
}

void MainWindow::on_startRecording_BTN_clicked()
{
    if(recorder->getIsRecording())
    {
        recorder->on_stopRecording();
        ui->startRecording_BTN->setText("Start\n Recording");
    }
    else
    {
        recorder->on_startRecording();
        ui->startRecording_BTN->setText("Stop");
    }
}

void MainWindow::on_saveRecord_BTN_clicked()
{
    QMessageBox::information(this,"Not Implemented yet", "This function will be available soon.");
}

void MainWindow::on_playRecord_BTN_clicked()
{
    if(player->getIsPlaying())
    {
        player->stopPlaying();
        return;
    }
    QModelIndexList indeces = ui->record_ListView->selectionModel()->selectedIndexes();
    if(indeces.length() <= 0)
    {
        QMessageBox::information(this, "No Record is Selected","Please select a record first.");
        return;
    }
    player->setRecord(recorder->getRecordByName(recordListModel.itemFromIndex(indeces[0])->text()));
    player->startPlaying();
    ui->playRecord_BTN->setText("Stop");
}

void MainWindow::on_player_finished()
{
    ui->playRecord_BTN->setText("Play Record");
}

void MainWindow::on_removeRecord_BTN_clicked()
{
    QModelIndexList indeces = ui->record_ListView->selectionModel()->selectedIndexes();
    if(indeces.length() <= 0)
    {
        QMessageBox::information(this, "No Record is Selected","Please select a record first.");
        return;
    }
    QString name = recordListModel.itemFromIndex(indeces[0])->text();
    QMessageBox::StandardButton re = QMessageBox::information( this, "Confirm",
                                                               "Are you sure to remove Record: " + name + "",
                                                               QMessageBox::Ok, QMessageBox::Cancel);
    if(re == QMessageBox::Ok)
    {
        recorder->removeRecord(name);
    }
}
<commit_msg>clear scene before recording.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    qRegisterMetaType<StateForTimestep>("StateForTimestep&");

    ui->setupUi(this);
    modelController = new FieldModelController();
    udpServer = new UdpServer();
    modeManager = new ModeManager();
    recorder = new Recorder();
    player = new RecordPlayer();

    connect(udpServer, SIGNAL(messageRecieved(QString)),modelController, SLOT(updateState(QString)));

    connect(modelController, SIGNAL(updateScene(StateForTimestep&)),
            modeManager, SLOT(on_updateScene_live(StateForTimestep&)));

    connect(modeManager, SIGNAL(updateScene(StateForTimestep&)),
            ui->rosoFieldWdgt, SLOT(on_updateScene(StateForTimestep&)));

    connect(modelController,SIGNAL(updateScene(StateForTimestep&)),
            recorder, SLOT(on_updateScene(StateForTimestep&)));

    connect(recorder, SIGNAL(recordsUpdated()), this, SLOT(on_recordsUpdated()));

    connect(player,SIGNAL(updateScene(StateForTimestep&)),
            modeManager, SLOT(on_updateScene_replay(StateForTimestep&)));

    connect(player, SIGNAL(recordPlayingFinished()),this,SLOT(on_player_finished()));

    ui->record_ListView->setModel(&recordListModel);
    on_liveMode_radioButton_toggled(true);

    ui->record_ListView->setSelectionMode(QListView::SingleSelection);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionClear_triggered()
{
    modelController->clearScene();
}

void MainWindow::on_actionRotate_Clockwise_triggered()
{
    ui->rosoFieldWdgt->rotateScene(ui->rosoFieldWdgt->getRotate() + 90);
}

void MainWindow::on_actionAbout_Qt_triggered()
{
    QMessageBox::aboutQt(this);
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, "About Roso_Viz", "Author: Tianlan Shao
Contact: shaotianlan.de@gmail.com

Github: https://github.com/shaosHumbleAccount/roso_viz

Published under MIT licence.

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.");
}

void MainWindow::on_liveMode_radioButton_toggled(bool checked)
{
    if(checked)
    {
        modeManager->setMode(ModeManager::LIVE);
        ui->startRecording_BTN->setEnabled(true);
        ui->playRecord_BTN->setEnabled(false);
        ui->saveRecord_BTN->setEnabled(false);
    }
    else
    {
        if(recorder->getIsRecording())
        {
            on_startRecording_BTN_clicked();
        }
        modeManager->setMode(ModeManager::REPLAY);
        ui->startRecording_BTN->setEnabled(false);
        ui->playRecord_BTN->setEnabled(true);
        ui->saveRecord_BTN->setEnabled(true);
    }
}

void MainWindow::on_recordsUpdated()
{
    QStringList recordNames = recorder->getRecordNames();

    recordListModel.clear();
    foreach(QString name, recordNames)
    {
        QStandardItem* item = new QStandardItem(name);
        item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        QList<QStandardItem *> row;
        row.append(item);
        recordListModel.invisibleRootItem()->appendRow(row);
    }
}

void MainWindow::on_startRecording_BTN_clicked()
{
    if(recorder->getIsRecording())
    {
        recorder->on_stopRecording();
        ui->startRecording_BTN->setText("Start\n Recording");
    }
    else
    {
        modelController->clearScene();
        recorder->on_startRecording();
        ui->startRecording_BTN->setText("Stop");
    }
}

void MainWindow::on_saveRecord_BTN_clicked()
{
    QMessageBox::information(this,"Not Implemented yet", "This function will be available soon.");
}

void MainWindow::on_playRecord_BTN_clicked()
{
    if(player->getIsPlaying())
    {
        player->stopPlaying();
        return;
    }
    QModelIndexList indeces = ui->record_ListView->selectionModel()->selectedIndexes();
    if(indeces.length() <= 0)
    {
        QMessageBox::information(this, "No Record is Selected","Please select a record first.");
        return;
    }
    player->setRecord(recorder->getRecordByName(recordListModel.itemFromIndex(indeces[0])->text()));
    player->startPlaying();
    ui->playRecord_BTN->setText("Stop");
}

void MainWindow::on_player_finished()
{
    ui->playRecord_BTN->setText("Play Record");
}

void MainWindow::on_removeRecord_BTN_clicked()
{
    QModelIndexList indeces = ui->record_ListView->selectionModel()->selectedIndexes();
    if(indeces.length() <= 0)
    {
        QMessageBox::information(this, "No Record is Selected","Please select a record first.");
        return;
    }
    QString name = recordListModel.itemFromIndex(indeces[0])->text();
    QMessageBox::StandardButton re = QMessageBox::information( this, "Confirm",
                                                               "Are you sure to remove Record: " + name + "",
                                                               QMessageBox::Ok, QMessageBox::Cancel);
    if(re == QMessageBox::Ok)
    {
        recorder->removeRecord(name);
    }
}
<|endoftext|>


<commit_before>// $Id$

AliJetEmbeddingFromGenTask* AddTaskJetEmbeddingFromGen(
  Int_t           genType        = 0, //use Pythia as default
  Double_t        ptHardMin      = 50.,
  Double_t        ptHardMax      = 1000.,
  Double_t        ecms           = 2760.,
  const char     *tracksName     = "GenParticles",
  const char     *taskName       = "JetEmbeddingFromGenTask",
  const Double_t  minPt          = 0.15,
  const Double_t  maxPt          = 1000,
  const Double_t  minEta         = -0.9,
  const Double_t  maxEta         = 0.9,
  const Double_t  minPhi         = 0,
  const Double_t  maxPhi         = TMath::Pi() * 2,
  const Bool_t    copyArray      = kTRUE,
  const Bool_t    drawQA         = kTRUE,
  const char     *pythiaInfoName = "PythiaInfo",
  Float_t         ptWeight       = 0,
  Int_t           kTune          = 2,
  Int_t           kColorReco     = 1,
  Float_t         kQuench        = 4.4e6,
  Int_t           kAnglePyquen   = 2
)
{
  AliGenerator *genGen = NULL;
  if(genType==0) { //PYTHIA Perugia 2011
    gROOT->LoadMacro("$ALICE_PHYSICS/ANALYSIS/macros/train/AddMCGenPythia.C");
    genGen = AddMCGenPythia(ecms, ptHardMin, ptHardMax, kTune,kColorReco,ptWeight);
  }
  else if(genType==1 || genType==2) { //QPYTHIA and PYQUEN
    gROOT->LoadMacro("$ALICE_PHYSICS/ANALYSIS/macros/train/AddMCGenQuench.C");
    genGen = AddMCGenQuench(ecms, ptHardMin, ptHardMax, genType,kQuench,kAnglePyquen,ptWeight);
  }
  if(!genGen)   {
    ::Error("AddTaskJetEmbeddingFromGenTask", "Generator does not exist");
    return NULL;
  }

  AliJetEmbeddingFromGenTask *task = AddTaskJetEmbeddingFromGen(genGen,tracksName,taskName,minPt,maxPt,minEta,maxEta,minPhi,maxPhi,copyArray,drawQA,pythiaInfoName);

  return task;
}

AliJetEmbeddingFromGenTask* AddTaskJetEmbeddingFromGen(
  AliGenerator   *genGen,
  const char     *tracksName     = "GenParticles",
  const char     *taskName       = "JetEmbeddingFromGenTask",
  const Double_t  minPt          = 0.15,
  const Double_t  maxPt          = 1000,
  const Double_t  minEta         = -0.9,
  const Double_t  maxEta         = 0.9,
  const Double_t  minPhi         = 0,
  const Double_t  maxPhi         = TMath::Pi() * 2,
  const Bool_t    copyArray      = kTRUE,
  const Bool_t    drawQA         = kTRUE,
  const char     *pythiaInfoName = ""
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskJetEmbedding", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskJetEmbedding", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  AliJetEmbeddingFromGenTask *jetEmb = new AliJetEmbeddingFromGenTask(taskName,drawQA);
  // if pythia is used as a generator, tell it not to print the event history to the screen
  if(genGen) {
    if(TString(genGen->IsA()->GetName()).EqualTo("AliGenPythia")) genGen->AliGenPythia::SetEventListRange(-10, -10);
    jetEmb->SetGen(genGen);
  }
  jetEmb->SetTracksName(tracksName);
  jetEmb->SetPythiaInfoName(pythiaInfoName);
  jetEmb->SetEtaRange(minEta, maxEta);
  jetEmb->SetPhiRange(minPhi, maxPhi);
  jetEmb->SetPtRange(minPt, maxPt);
  jetEmb->SetCopyArray(copyArray);

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------

  mgr->AddTask(jetEmb);

  // Create containers for input/output
  mgr->ConnectInput (jetEmb, 0, mgr->GetCommonInputContainer() );

  if (drawQA) {
    TString contName = taskName;
    contName += "_histos";
    AliAnalysisDataContainer *outc = mgr->CreateContainer(contName,
                                                          TList::Class(),
                                                          AliAnalysisManager::kOutputContainer,
                                                          Form("%s",AliAnalysisManager::GetCommonFileName()));
    mgr->ConnectOutput(jetEmb, 1, outc);
  }

  return jetEmb;
}
<commit_msg>ANALYSIS still in ALICE_ROOT<commit_after>// $Id$

AliJetEmbeddingFromGenTask* AddTaskJetEmbeddingFromGen(
  Int_t           genType        = 0, //use Pythia as default
  Double_t        ptHardMin      = 50.,
  Double_t        ptHardMax      = 1000.,
  Double_t        ecms           = 2760.,
  const char     *tracksName     = "GenParticles",
  const char     *taskName       = "JetEmbeddingFromGenTask",
  const Double_t  minPt          = 0.15,
  const Double_t  maxPt          = 1000,
  const Double_t  minEta         = -0.9,
  const Double_t  maxEta         = 0.9,
  const Double_t  minPhi         = 0,
  const Double_t  maxPhi         = TMath::Pi() * 2,
  const Bool_t    copyArray      = kTRUE,
  const Bool_t    drawQA         = kTRUE,
  const char     *pythiaInfoName = "PythiaInfo",
  Float_t         ptWeight       = 0,
  Int_t           kTune          = 2,
  Int_t           kColorReco     = 1,
  Float_t         kQuench        = 4.4e6,
  Int_t           kAnglePyquen   = 2
)
{
  AliGenerator *genGen = NULL;
  if(genType==0) { //PYTHIA Perugia 2011
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/train/AddMCGenPythia.C");
    genGen = AddMCGenPythia(ecms, ptHardMin, ptHardMax, kTune,kColorReco,ptWeight);
  }
  else if(genType==1 || genType==2) { //QPYTHIA and PYQUEN
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/train/AddMCGenQuench.C");
    genGen = AddMCGenQuench(ecms, ptHardMin, ptHardMax, genType,kQuench,kAnglePyquen,ptWeight);
  }
  if(!genGen)   {
    ::Error("AddTaskJetEmbeddingFromGenTask", "Generator does not exist");
    return NULL;
  }

  AliJetEmbeddingFromGenTask *task = AddTaskJetEmbeddingFromGen(genGen,tracksName,taskName,minPt,maxPt,minEta,maxEta,minPhi,maxPhi,copyArray,drawQA,pythiaInfoName);

  return task;
}

AliJetEmbeddingFromGenTask* AddTaskJetEmbeddingFromGen(
  AliGenerator   *genGen,
  const char     *tracksName     = "GenParticles",
  const char     *taskName       = "JetEmbeddingFromGenTask",
  const Double_t  minPt          = 0.15,
  const Double_t  maxPt          = 1000,
  const Double_t  minEta         = -0.9,
  const Double_t  maxEta         = 0.9,
  const Double_t  minPhi         = 0,
  const Double_t  maxPhi         = TMath::Pi() * 2,
  const Bool_t    copyArray      = kTRUE,
  const Bool_t    drawQA         = kTRUE,
  const char     *pythiaInfoName = ""
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskJetEmbedding", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskJetEmbedding", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  AliJetEmbeddingFromGenTask *jetEmb = new AliJetEmbeddingFromGenTask(taskName,drawQA);
  // if pythia is used as a generator, tell it not to print the event history to the screen
  if(genGen) {
    if(TString(genGen->IsA()->GetName()).EqualTo("AliGenPythia")) genGen->AliGenPythia::SetEventListRange(-10, -10);
    jetEmb->SetGen(genGen);
  }
  jetEmb->SetTracksName(tracksName);
  jetEmb->SetPythiaInfoName(pythiaInfoName);
  jetEmb->SetEtaRange(minEta, maxEta);
  jetEmb->SetPhiRange(minPhi, maxPhi);
  jetEmb->SetPtRange(minPt, maxPt);
  jetEmb->SetCopyArray(copyArray);

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------

  mgr->AddTask(jetEmb);

  // Create containers for input/output
  mgr->ConnectInput (jetEmb, 0, mgr->GetCommonInputContainer() );

  if (drawQA) {
    TString contName = taskName;
    contName += "_histos";
    AliAnalysisDataContainer *outc = mgr->CreateContainer(contName,
                                                          TList::Class(),
                                                          AliAnalysisManager::kOutputContainer,
                                                          Form("%s",AliAnalysisManager::GetCommonFileName()));
    mgr->ConnectOutput(jetEmb, 1, outc);
  }

  return jetEmb;
}
<|endoftext|>


<commit_before><commit_msg>`check_and_report_if_some_string_matches`: added `const` modifier.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/assembler.h"
#include "vm/cpu.h"
#include "vm/heap.h"
#include "vm/memory_region.h"
#include "vm/utils.h"
#include "vm/zone.h"

namespace dart {

static uword NewContents(int capacity) {
  Zone* zone = Isolate::Current()->current_zone();
  uword result = zone->Allocate(capacity);
#if defined(DEBUG)
  // Initialize the buffer with kBreakPointInstruction to force a break
  // point if we ever execute an uninitialized part of the code buffer.
  Assembler::InitializeMemoryWithBreakpoints(result, capacity);
#endif
  return result;
}

#if defined(DEBUG)
AssemblerBuffer::EnsureCapacity::EnsureCapacity(AssemblerBuffer* buffer) {
  if (buffer->cursor() >= buffer->limit()) buffer->ExtendCapacity();
  // In debug mode, we save the assembler buffer along with the gap
  // size before we start emitting to the buffer. This allows us to
  // check that any single generated instruction doesn't overflow the
  // limit implied by the minimum gap size.
  buffer_ = buffer;
  gap_ = ComputeGap();
  // Make sure that extending the capacity leaves a big enough gap
  // for any kind of instruction.
  ASSERT(gap_ >= kMinimumGap);
  // Mark the buffer as having ensured the capacity.
  ASSERT(!buffer->HasEnsuredCapacity());  // Cannot nest.
  buffer->has_ensured_capacity_ = true;
}

AssemblerBuffer::EnsureCapacity::~EnsureCapacity() {
  // Unmark the buffer, so we cannot emit after this.
  buffer_->has_ensured_capacity_ = false;
  // Make sure the generated instruction doesn't take up more
  // space than the minimum gap.
  int delta = gap_ - ComputeGap();
  ASSERT(delta <= kMinimumGap);
}
#endif

AssemblerBuffer::AssemblerBuffer()
    : pointer_offsets_(new ZoneGrowableArray<int>(16)) {
  static const int kInitialBufferCapacity = 4 * KB;
  contents_ = NewContents(kInitialBufferCapacity);
  cursor_ = contents_;
  limit_ = ComputeLimit(contents_, kInitialBufferCapacity);
  fixup_ = NULL;
#if defined(DEBUG)
  has_ensured_capacity_ = false;
  fixups_processed_ = false;
#endif

  // Verify internal state.
  ASSERT(Capacity() == kInitialBufferCapacity);
  ASSERT(Size() == 0);
}

AssemblerBuffer::~AssemblerBuffer() {
}

void AssemblerBuffer::ProcessFixups(const MemoryRegion& region) {
  AssemblerFixup* fixup = fixup_;
  while (fixup != NULL) {
    fixup->Process(region, fixup->position());
    fixup = fixup->previous();
  }
}

void AssemblerBuffer::FinalizeInstructions(const MemoryRegion& instructions) {
  // Copy the instructions from the buffer.
  MemoryRegion from(reinterpret_cast<void*>(contents()), Size());
  instructions.CopyFrom(0, from);

  // Process fixups in the instructions.
  ProcessFixups(instructions);
#if defined(DEBUG)
  fixups_processed_ = true;
#endif
}

void AssemblerBuffer::ExtendCapacity() {
  int old_size = Size();
  int old_capacity = Capacity();
  int new_capacity = Utils::Minimum(old_capacity * 2, old_capacity + 1 * MB);

  // Allocate the new data area and copy contents of the old one to it.
  uword new_contents = NewContents(new_capacity);
  memmove(reinterpret_cast<void*>(new_contents),
          reinterpret_cast<void*>(contents_),
          old_size);

  // Compute the relocation delta and switch to the new contents area.
  intptr_t delta = new_contents - contents_;
  contents_ = new_contents;

  // Update the cursor and recompute the limit.
  cursor_ += delta;
  limit_ = ComputeLimit(new_contents, new_capacity);

  // Verify internal state.
  ASSERT(Capacity() == new_capacity);
  ASSERT(Size() == old_size);
}

class PatchCodeWithHandle : public AssemblerFixup {
 public:
  PatchCodeWithHandle(ZoneGrowableArray<int>* pointer_offsets,
                      const Object& object)
      : pointer_offsets_(pointer_offsets), object_(object) {
  }

  void Process(const MemoryRegion& region, int position) {
    // Patch the handle into the code. Once the instructions are installed into
    // a raw code object and the pointer offsets are setup, the handle is
    // resolved.
    region.Store<const Object*>(position, &object_);
    pointer_offsets_->Add(position);
  }

 private:
  ZoneGrowableArray<int>* pointer_offsets_;
  const Object& object_;
};

void AssemblerBuffer::EmitObject(const Object& object) {
  // Since we are going to store the handle as part of the fixup information
  // the handle needs to be a zone handle.
  ASSERT(object.IsZoneHandle());
  EmitFixup(new PatchCodeWithHandle(pointer_offsets_, object));
  cursor_ += kWordSize;  // Reserve space for pointer.
}

// Shared macros are implemented here.
void Assembler::Unimplemented(const char* message) {
  const char* format = "Unimplemented: %s";
  const intptr_t len = snprintf(NULL, 0, format, message);
  char* buffer = reinterpret_cast<char*>(malloc(len + 1));
  snprintf(buffer, len + 1, format, message);
  Stop(buffer);
}

void Assembler::Untested(const char* message) {
  const char* format = "Untested: %s";
  const intptr_t len = snprintf(NULL, 0, format, message);
  char* buffer = reinterpret_cast<char*>(malloc(len + 1));
  snprintf(buffer, len + 1, format, message);
  Stop(buffer);
}

void Assembler::Unreachable(const char* message) {
  const char* format = "Unreachable: %s";
  const intptr_t len = snprintf(NULL, 0, format, message);
  char* buffer = reinterpret_cast<char*>(malloc(len + 1));
  snprintf(buffer, len + 1, format, message);
  Stop(buffer);
}

}  // namespace dart
<commit_msg>Fix win32 build. Review URL: http://codereview.chromium.org//8853002<commit_after>// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/assembler.h"
#include "vm/cpu.h"
#include "vm/heap.h"
#include "vm/memory_region.h"
#include "vm/os.h"
#include "vm/utils.h"
#include "vm/zone.h"

namespace dart {

static uword NewContents(int capacity) {
  Zone* zone = Isolate::Current()->current_zone();
  uword result = zone->Allocate(capacity);
#if defined(DEBUG)
  // Initialize the buffer with kBreakPointInstruction to force a break
  // point if we ever execute an uninitialized part of the code buffer.
  Assembler::InitializeMemoryWithBreakpoints(result, capacity);
#endif
  return result;
}

#if defined(DEBUG)
AssemblerBuffer::EnsureCapacity::EnsureCapacity(AssemblerBuffer* buffer) {
  if (buffer->cursor() >= buffer->limit()) buffer->ExtendCapacity();
  // In debug mode, we save the assembler buffer along with the gap
  // size before we start emitting to the buffer. This allows us to
  // check that any single generated instruction doesn't overflow the
  // limit implied by the minimum gap size.
  buffer_ = buffer;
  gap_ = ComputeGap();
  // Make sure that extending the capacity leaves a big enough gap
  // for any kind of instruction.
  ASSERT(gap_ >= kMinimumGap);
  // Mark the buffer as having ensured the capacity.
  ASSERT(!buffer->HasEnsuredCapacity());  // Cannot nest.
  buffer->has_ensured_capacity_ = true;
}

AssemblerBuffer::EnsureCapacity::~EnsureCapacity() {
  // Unmark the buffer, so we cannot emit after this.
  buffer_->has_ensured_capacity_ = false;
  // Make sure the generated instruction doesn't take up more
  // space than the minimum gap.
  int delta = gap_ - ComputeGap();
  ASSERT(delta <= kMinimumGap);
}
#endif

AssemblerBuffer::AssemblerBuffer()
    : pointer_offsets_(new ZoneGrowableArray<int>(16)) {
  static const int kInitialBufferCapacity = 4 * KB;
  contents_ = NewContents(kInitialBufferCapacity);
  cursor_ = contents_;
  limit_ = ComputeLimit(contents_, kInitialBufferCapacity);
  fixup_ = NULL;
#if defined(DEBUG)
  has_ensured_capacity_ = false;
  fixups_processed_ = false;
#endif

  // Verify internal state.
  ASSERT(Capacity() == kInitialBufferCapacity);
  ASSERT(Size() == 0);
}

AssemblerBuffer::~AssemblerBuffer() {
}

void AssemblerBuffer::ProcessFixups(const MemoryRegion& region) {
  AssemblerFixup* fixup = fixup_;
  while (fixup != NULL) {
    fixup->Process(region, fixup->position());
    fixup = fixup->previous();
  }
}

void AssemblerBuffer::FinalizeInstructions(const MemoryRegion& instructions) {
  // Copy the instructions from the buffer.
  MemoryRegion from(reinterpret_cast<void*>(contents()), Size());
  instructions.CopyFrom(0, from);

  // Process fixups in the instructions.
  ProcessFixups(instructions);
#if defined(DEBUG)
  fixups_processed_ = true;
#endif
}

void AssemblerBuffer::ExtendCapacity() {
  int old_size = Size();
  int old_capacity = Capacity();
  int new_capacity = Utils::Minimum(old_capacity * 2, old_capacity + 1 * MB);

  // Allocate the new data area and copy contents of the old one to it.
  uword new_contents = NewContents(new_capacity);
  memmove(reinterpret_cast<void*>(new_contents),
          reinterpret_cast<void*>(contents_),
          old_size);

  // Compute the relocation delta and switch to the new contents area.
  intptr_t delta = new_contents - contents_;
  contents_ = new_contents;

  // Update the cursor and recompute the limit.
  cursor_ += delta;
  limit_ = ComputeLimit(new_contents, new_capacity);

  // Verify internal state.
  ASSERT(Capacity() == new_capacity);
  ASSERT(Size() == old_size);
}

class PatchCodeWithHandle : public AssemblerFixup {
 public:
  PatchCodeWithHandle(ZoneGrowableArray<int>* pointer_offsets,
                      const Object& object)
      : pointer_offsets_(pointer_offsets), object_(object) {
  }

  void Process(const MemoryRegion& region, int position) {
    // Patch the handle into the code. Once the instructions are installed into
    // a raw code object and the pointer offsets are setup, the handle is
    // resolved.
    region.Store<const Object*>(position, &object_);
    pointer_offsets_->Add(position);
  }

 private:
  ZoneGrowableArray<int>* pointer_offsets_;
  const Object& object_;
};

void AssemblerBuffer::EmitObject(const Object& object) {
  // Since we are going to store the handle as part of the fixup information
  // the handle needs to be a zone handle.
  ASSERT(object.IsZoneHandle());
  EmitFixup(new PatchCodeWithHandle(pointer_offsets_, object));
  cursor_ += kWordSize;  // Reserve space for pointer.
}

// Shared macros are implemented here.
void Assembler::Unimplemented(const char* message) {
  const char* format = "Unimplemented: %s";
  const intptr_t len = OS::SNPrint(NULL, 0, format, message);
  char* buffer = reinterpret_cast<char*>(malloc(len + 1));
  OS::SNPrint(buffer, len + 1, format, message);
  Stop(buffer);
}

void Assembler::Untested(const char* message) {
  const char* format = "Untested: %s";
  const intptr_t len = OS::SNPrint(NULL, 0, format, message);
  char* buffer = reinterpret_cast<char*>(malloc(len + 1));
  OS::SNPrint(buffer, len + 1, format, message);
  Stop(buffer);
}

void Assembler::Unreachable(const char* message) {
  const char* format = "Unreachable: %s";
  const intptr_t len = OS::SNPrint(NULL, 0, format, message);
  char* buffer = reinterpret_cast<char*>(malloc(len + 1));
  OS::SNPrint(buffer, len + 1, format, message);
  Stop(buffer);
}

}  // namespace dart
<|endoftext|>