<commit_before>#include "antsUtilities.h"
#include "antsAllocImage.h"
#include <algorithm>
#include "ReadWriteData.h"

#include "itkAffineTransform.h"
#include "itkCSVArray2DDataObject.h"
#include "itkCSVArray2DFileReader.h"
#include "itkCSVNumericObjectFileWriter.h"
#include "itkImage.h"
#include "itkLabelGeometryImageFilter.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkResampleImageFilter.h"
#include "itkTransformFileWriter.h"

#include "itkLabelPerimeterEstimationCalculator.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkShapeLabelMapFilter.h"
#include "itkShapeLabelObject.h"

#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>

namespace ants
{
template <unsigned int ImageDimension>
int LabelGeometryMeasures( int argc, char * argv[] )
{
  typedef unsigned int                          LabelType;
  typedef itk::Image<LabelType, ImageDimension> LabelImageType;

  typedef float                                RealType;
  typedef itk::Image<RealType, ImageDimension> RealImageType;

  typename LabelImageType::Pointer labelImage = LabelImageType::New();
  ReadImage<LabelImageType>( labelImage, argv[2] );

  typename RealImageType::Pointer intensityImage = RealImageType::New();
  bool intensityImageUsed = false;
  if( argc > 3 )
    {
    try
      {
      ReadImage<RealImageType>( intensityImage, argv[3] );
      intensityImageUsed = true;
      }
    catch( ... )
      {
      }
    }

  bool outputCSVFormat = false;
  if( argc > 4  )
    {
    outputCSVFormat = true;
    }

  typedef itk::LabelGeometryImageFilter<LabelImageType, RealImageType> FilterType;
  typename FilterType::Pointer filter = FilterType::New();
  filter->SetInput( labelImage );
  if( intensityImageUsed )
    {
    filter->SetIntensityInput( intensityImage );
    }
  filter->CalculatePixelIndicesOff();
  filter->CalculateOrientedBoundingBoxOff();
  filter->CalculateOrientedLabelRegionsOff();
  // These generate optional outputs.
//   filter->CalculatePixelIndicesOn();
//   filter->CalculateOrientedBoundingBoxOn();;
//   filter->CalculateOrientedLabelRegionsOn();
  filter->Update();

  typedef itk::ShapeLabelObject<LabelType, ImageDimension> LabelObjectType;
  typedef itk::LabelMap< LabelObjectType > LabelMapType;

  // convert the image in a collection of objects
  typedef itk::LabelImageToLabelMapFilter<LabelImageType, LabelMapType> ConverterType;
  typename ConverterType::Pointer converter = ConverterType::New();
  converter->SetInput( labelImage );

  typedef itk::ShapeLabelMapFilter< LabelMapType > ValuatorType;
  typename ValuatorType::Pointer valuator = ValuatorType::New();
  valuator->SetInput( converter->GetOutput() );

  valuator->Update();

  typename LabelMapType::Pointer labelMap = valuator->GetOutput();

//   typedef itk::LabelPerimeterEstimationCalculator<LabelImageType> AreaFilterType;
//   typename AreaFilterType::Pointer areafilter = AreaFilterType::New();
//   areafilter->SetImage( labelImage );
//   areafilter->SetFullyConnected( false );
//   areafilter->Compute();

  typename FilterType::LabelsType allLabels = filter->GetLabels();
  std::sort( allLabels.begin(), allLabels.end() );

  if( outputCSVFormat )
    {
    typename FilterType::LabelsType::iterator allLabelsIt;

    std::vector<std::string>   columnHeaders;

    columnHeaders.push_back( std::string( "Label" ) );
    columnHeaders.push_back( std::string( "VolumeInVoxels" ) );
    columnHeaders.push_back( std::string( "SurfaceAreaInMillimetersSquared" ) );
    columnHeaders.push_back( std::string( "Eccentricity" ) );
    columnHeaders.push_back( std::string( "Elongation" ) );
    columnHeaders.push_back( std::string( "Orientation" ) );
    columnHeaders.push_back( std::string( "Centroid_x" ) );
    columnHeaders.push_back( std::string( "Centroid_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "Centroid_z" ) );
      }
    columnHeaders.push_back( std::string( "AxesLength_x" ) );
    columnHeaders.push_back( std::string( "AxesLength_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "AxesLength_z" ) );
      }
    columnHeaders.push_back( std::string( "BoundingBoxLower_x" ) );
    columnHeaders.push_back( std::string( "BoundingBoxLower_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "BoundingBoxLower_z" ) );
      }
    columnHeaders.push_back( std::string( "BoundingBoxUpper_x" ) );
    columnHeaders.push_back( std::string( "BoundingBoxUpper_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "BoundingBoxUpper_z" ) );
      }

    if( filter->GetIntensityInput() )
      {
      columnHeaders.push_back( std::string( "IntegratedIntensity" ) );
      columnHeaders.push_back( std::string( "WeightedCentroid_x" ) );
      columnHeaders.push_back( std::string( "WeightedCentroid_y" ) );
      if( ImageDimension == 3 )
        {
        columnHeaders.push_back( std::string( "WeightedCentroid_z" ) );
        }
      }

    std::vector<std::string>   rowHeaders;
    std::ostringstream convert;// stream used for the conversion
    for( allLabelsIt = allLabels.begin(); allLabelsIt != allLabels.end(); allLabelsIt++ )
      {
      convert << *allLabelsIt;   // insert the textual representation of 'Number' in the characters in the stream
      rowHeaders.push_back( convert.str() ); // set 'Result' to the contents of the stream
      }

    vnl_matrix<double> measures( allLabels.size(), columnHeaders.size() - 1 );

    unsigned int rowIndex = 0;
    for( allLabelsIt = allLabels.begin(); allLabelsIt != allLabels.end(); allLabelsIt++ )
      {
      unsigned int columnIndex = 0;
      measures( rowIndex, columnIndex++ ) = filter->GetVolume( *allLabelsIt );

      const LabelObjectType * labelObject = labelMap->GetLabelObject( *allLabelsIt );

      measures( rowIndex, columnIndex++ ) = labelObject->GetPerimeter();
      measures( rowIndex, columnIndex++ ) = filter->GetEccentricity( *allLabelsIt );
      measures( rowIndex, columnIndex++ ) = filter->GetElongation( *allLabelsIt );
      measures( rowIndex, columnIndex++ ) = filter->GetOrientation( *allLabelsIt );
      measures( rowIndex, columnIndex++ ) = filter->GetCentroid( *allLabelsIt )[0];
      measures( rowIndex, columnIndex++ ) = filter->GetCentroid( *allLabelsIt )[1];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetCentroid( *allLabelsIt )[2];
        }
      measures( rowIndex, columnIndex++ ) = filter->GetAxesLength( *allLabelsIt )[0];
      measures( rowIndex, columnIndex++ ) = filter->GetAxesLength( *allLabelsIt )[1];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetAxesLength( *allLabelsIt )[2];
        }

      unsigned int arrayIndex = 0;

      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
        }
      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
        }

      if( filter->GetIntensityInput() )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetIntegratedIntensity( *allLabelsIt );
        measures( rowIndex, columnIndex++ ) = filter->GetWeightedCentroid( *allLabelsIt )[0];
        measures( rowIndex, columnIndex++ ) = filter->GetWeightedCentroid( *allLabelsIt )[1];
        if( ImageDimension == 3 )
          {
          measures( rowIndex, columnIndex++ ) = filter->GetWeightedCentroid( *allLabelsIt )[2];
          }
        }
      rowIndex++;
      }

    typedef itk::CSVNumericObjectFileWriter<double, 1, 1> WriterType;
    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName( argv[4] );
    writer->SetColumnHeaders( columnHeaders );
    writer->SetRowHeaders( rowHeaders );
    writer->SetInput( &measures );
    try
      {
      writer->Write();
      }
    catch( itk::ExceptionObject& exp )
      {
      std::cerr << "Exception caught!" << std::endl;
      std::cerr << exp << std::endl;
      return EXIT_FAILURE;
      }
    }
  else
    {
    typename FilterType::LabelsType::iterator allLabelsIt;
  //   std::cout << "Number of labels: " << labelGeometryFilter->GetNumberOfLabels() << std::endl;
  //   std::cout << "Label geometry measures." << std::endl;
    std::cout << std::left << std::setw( 7 ) << "Label"
             << std::left << std::setw( 10 ) << "Volume"
             << std::left << std::setw( 15 ) << "SurfArea(mm^2)"
             << std::left << std::setw( 15 ) << "Eccentricity"
             << std::left << std::setw( 15 ) << "Elongation"
             << std::left << std::setw( 15 ) << "Orientation"
             << std::left << std::setw( 30 ) << "Centroid"
             << std::left << std::setw( 30 ) << "Axes Length"
             << std::left << std::setw( 30 ) << "Bounding Box";
    if( filter->GetIntensityInput() )
      {
      std::cout << std::left << std::setw( 20 )  << "Integrated Int."
               << std::left << std::setw( 30 ) << "Weighted Centroid";
      }
    std::cout << std::endl;
    for( allLabelsIt = allLabels.begin(); allLabelsIt != allLabels.end(); allLabelsIt++ )
      {
      if( *allLabelsIt == 0 )
        {
        continue;
        }
      std::cout << std::setw( 7 ) << *allLabelsIt;
      std::cout << std::setw( 10 ) << filter->GetVolume( *allLabelsIt );

      const LabelObjectType * labelObject = labelMap->GetLabelObject( *allLabelsIt );

      std::cout << std::setw( 15 ) << labelObject->GetPerimeter();
      std::cout << std::setw( 15 ) << filter->GetEccentricity( *allLabelsIt );
      std::cout << std::setw( 15 ) << filter->GetElongation( *allLabelsIt );
      std::cout << std::setw( 15 ) << filter->GetOrientation( *allLabelsIt );

      std::stringstream oss;
      oss << filter->GetCentroid( *allLabelsIt );
      std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
      oss.str( "" );

      oss << filter->GetAxesLength( *allLabelsIt );
      std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
      oss.str( "" );

      oss << filter->GetBoundingBox( *allLabelsIt );
      std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
      oss.str( "" );

  //     std::cout << filter->GetMajorAxisLength( *allLabelsIt ) << "\t";
  //     std::cout << filter->GetMinorAxisLength( *allLabelsIt ) << "\t";
      if( filter->GetIntensityInput() )
        {
        oss << filter->GetIntegratedIntensity( *allLabelsIt );
        std::cout << std::setw( 20 ) << ( oss.str() ).c_str();
        oss.str( "" );

        oss << filter->GetWeightedCentroid( *allLabelsIt );
        std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
        oss.str( "" );
        }
      std::cout << std::endl;
      }
    }

  return EXIT_SUCCESS;
}

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int LabelGeometryMeasures( std::vector<std::string> args, std::ostream* itkNotUsed( out_stream ) )
{
  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle
  args.insert( args.begin(), "LabelGeometryMeasures" );

  int     argc = args.size();
  char* * argv = new char *[args.size() + 1];
  for( unsigned int i = 0; i < args.size(); ++i )
    {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy( argv[i], args[i].c_str(), args[i].length() );
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
    }
  argv[argc] = ITK_NULLPTR;
  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
public:
    Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
    {
    }

    ~Cleanup_argv()
    {
      for( unsigned int i = 0; i < argc_plus_one; ++i )
        {
        delete[] argv[i];
        }
      delete[] argv;
    }

private:
    char* *      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv( argv, argc + 1 );

  // antscout->set_stream( out_stream );

  if( argc < 3 )
    {
    std::cout << "Usage 1: " << argv[0] << " imageDimension labelImage [intensityImage=none] [csvFile]" << std::endl;
//     std::cout << "Usage 2: " << argv[0] << " X singleLabelImage outputTransform <doReflection=1> <scaleFactor=1>" << std::endl;

    if( argc >= 2 &&
        ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
      {
      return EXIT_SUCCESS;
      }
    return EXIT_FAILURE;
    }

  switch( atoi( argv[1] ) )
    {
    case 2:
      {
      LabelGeometryMeasures<2>( argc, argv );
      }
      break;
    case 3:
      {
      LabelGeometryMeasures<3>( argc, argv );
      }
      break;
    default:
      std::cout << "Unsupported dimension" << std::endl;
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
} // namespace ants
<commit_msg>BUG: in csv output - still not fixed completely<commit_after>#include "antsUtilities.h"
#include "antsAllocImage.h"
#include <algorithm>
#include "ReadWriteData.h"

#include "itkAffineTransform.h"
#include "itkCSVArray2DDataObject.h"
#include "itkCSVArray2DFileReader.h"
#include "itkCSVNumericObjectFileWriter.h"
#include "itkImage.h"
#include "itkLabelGeometryImageFilter.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkResampleImageFilter.h"
#include "itkTransformFileWriter.h"

#include "itkLabelPerimeterEstimationCalculator.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkShapeLabelMapFilter.h"
#include "itkShapeLabelObject.h"

#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>

namespace ants
{
template <unsigned int ImageDimension>
int LabelGeometryMeasures( int argc, char * argv[] )
{
  typedef unsigned int                          LabelType;
  typedef itk::Image<LabelType, ImageDimension> LabelImageType;

  typedef float                                RealType;
  typedef itk::Image<RealType, ImageDimension> RealImageType;

  typename LabelImageType::Pointer labelImage = LabelImageType::New();
  ReadImage<LabelImageType>( labelImage, argv[2] );

  typename RealImageType::Pointer intensityImage = RealImageType::New();
  bool intensityImageUsed = false;
  if( argc > 3 )
    {
    try
      {
      ReadImage<RealImageType>( intensityImage, argv[3] );
      intensityImageUsed = true;
      }
    catch( ... )
      {
      }
    }

  bool outputCSVFormat = false;
  if( argc > 4  )
    {
    outputCSVFormat = true;
    }
  typedef itk::LabelGeometryImageFilter<LabelImageType, RealImageType> FilterType;
  typename FilterType::Pointer filter = FilterType::New();
  filter->SetInput( labelImage );
  if( intensityImageUsed )
    {
    filter->SetIntensityInput( intensityImage );
    }
  filter->CalculatePixelIndicesOff();
  filter->CalculateOrientedBoundingBoxOff();
  filter->CalculateOrientedLabelRegionsOff();
  // These generate optional outputs.
//   filter->CalculatePixelIndicesOn();
//   filter->CalculateOrientedBoundingBoxOn();;
//   filter->CalculateOrientedLabelRegionsOn();

  filter->Update();

  typedef itk::ShapeLabelObject<LabelType, ImageDimension> LabelObjectType;
  typedef itk::LabelMap< LabelObjectType > LabelMapType;

  // convert the image in a collection of objects
  typedef itk::LabelImageToLabelMapFilter<LabelImageType, LabelMapType> ConverterType;
  typename ConverterType::Pointer converter = ConverterType::New();
  converter->SetInput( labelImage );

  typedef itk::ShapeLabelMapFilter< LabelMapType > ValuatorType;
  typename ValuatorType::Pointer valuator = ValuatorType::New();
  valuator->SetInput( converter->GetOutput() );

  valuator->Update();

  typename LabelMapType::Pointer labelMap = valuator->GetOutput();

//   typedef itk::LabelPerimeterEstimationCalculator<LabelImageType> AreaFilterType;
//   typename AreaFilterType::Pointer areafilter = AreaFilterType::New();
//   areafilter->SetImage( labelImage );
//   areafilter->SetFullyConnected( false );
//   areafilter->Compute();

  typename FilterType::LabelsType allLabels = filter->GetLabels();
  std::sort( allLabels.begin(), allLabels.end() );

  if( outputCSVFormat )
    {
    typename FilterType::LabelsType::iterator allLabelsIt;

    std::vector<std::string>   columnHeaders;

    columnHeaders.push_back( std::string( "Label" ) );
    columnHeaders.push_back( std::string( "VolumeInVoxels" ) );
    columnHeaders.push_back( std::string( "SurfaceAreaInMillimetersSquared" ) );
    columnHeaders.push_back( std::string( "Eccentricity" ) );
    columnHeaders.push_back( std::string( "Elongation" ) );
    columnHeaders.push_back( std::string( "Orientation" ) );
    columnHeaders.push_back( std::string( "Centroid_x" ) );
    columnHeaders.push_back( std::string( "Centroid_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "Centroid_z" ) );
      }
    columnHeaders.push_back( std::string( "AxesLength_x" ) );
    columnHeaders.push_back( std::string( "AxesLength_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "AxesLength_z" ) );
      }
    columnHeaders.push_back( std::string( "BoundingBoxLower_x" ) );
    columnHeaders.push_back( std::string( "BoundingBoxLower_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "BoundingBoxLower_z" ) );
      }
    columnHeaders.push_back( std::string( "BoundingBoxUpper_x" ) );
    columnHeaders.push_back( std::string( "BoundingBoxUpper_y" ) );
    if( ImageDimension == 3 )
      {
      columnHeaders.push_back( std::string( "BoundingBoxUpper_z" ) );
      }

    if( filter->GetIntensityInput() )
      {
      columnHeaders.push_back( std::string( "IntegratedIntensity" ) );
      columnHeaders.push_back( std::string( "WeightedCentroid_x" ) );
      columnHeaders.push_back( std::string( "WeightedCentroid_y" ) );
      if( ImageDimension == 3 )
        {
        columnHeaders.push_back( std::string( "WeightedCentroid_z" ) );
        }
      }

    std::vector<std::string>   rowHeaders;
    std::ostringstream convert;// stream used for the conversion
    for( allLabelsIt = allLabels.begin(); allLabelsIt != allLabels.end(); allLabelsIt++ )
      {
      if( *allLabelsIt == 0 )
        {
        continue;
        }
      convert << *allLabelsIt;   // insert the textual representation of 'Number' in the characters in the stream
      rowHeaders.push_back( convert.str() ); // set 'Result' to the contents of the stream
      }

    vnl_matrix<double> measures( allLabels.size() - 1, columnHeaders.size() - 1 );

    unsigned int rowIndex = 0;
    for( allLabelsIt = allLabels.begin(); allLabelsIt != allLabels.end(); allLabelsIt++ )
      {
      if( *allLabelsIt == 0 )
        {
        continue;
        }

      unsigned int columnIndex = 0;
//      measures( rowIndex, columnIndex ) = static_cast< double >( *allLabelsIt );
      measures( rowIndex, columnIndex++ ) = filter->GetVolume( *allLabelsIt );

      const LabelObjectType * labelObject = labelMap->GetLabelObject( *allLabelsIt );

      measures( rowIndex, columnIndex++ ) = labelObject->GetPerimeter();
      measures( rowIndex, columnIndex++ ) = filter->GetEccentricity( *allLabelsIt );
      measures( rowIndex, columnIndex++ ) = filter->GetElongation( *allLabelsIt );
      measures( rowIndex, columnIndex++ ) = filter->GetOrientation( *allLabelsIt );
      measures( rowIndex, columnIndex++ ) = filter->GetCentroid( *allLabelsIt )[0];
      measures( rowIndex, columnIndex++ ) = filter->GetCentroid( *allLabelsIt )[1];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetCentroid( *allLabelsIt )[2];
        }
      measures( rowIndex, columnIndex++ ) = filter->GetAxesLength( *allLabelsIt )[0];
      measures( rowIndex, columnIndex++ ) = filter->GetAxesLength( *allLabelsIt )[1];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetAxesLength( *allLabelsIt )[2];
        }

      unsigned int arrayIndex = 0;

      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
        }
      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
      if( ImageDimension == 3 )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetBoundingBox( *allLabelsIt )[arrayIndex++];
        }

      if( filter->GetIntensityInput() )
        {
        measures( rowIndex, columnIndex++ ) = filter->GetIntegratedIntensity( *allLabelsIt );
        measures( rowIndex, columnIndex++ ) = filter->GetWeightedCentroid( *allLabelsIt )[0];
        measures( rowIndex, columnIndex++ ) = filter->GetWeightedCentroid( *allLabelsIt )[1];
        if( ImageDimension == 3 )
          {
          measures( rowIndex, columnIndex++ ) = filter->GetWeightedCentroid( *allLabelsIt )[2];
          }
        }
      rowIndex++;
      }

    typedef itk::CSVNumericObjectFileWriter<double, 1, 1> WriterType;
    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName( argv[4] );
    writer->SetColumnHeaders( columnHeaders );
    writer->SetRowHeaders( rowHeaders );
    writer->SetInput( &measures );
    try
      {
      writer->Write();
      }
    catch( itk::ExceptionObject& exp )
      {
      std::cerr << "Exception caught!" << std::endl;
      std::cerr << exp << std::endl;
      return EXIT_FAILURE;
      }
    }
  else
    {
    typename FilterType::LabelsType::iterator allLabelsIt;
  //   std::cout << "Number of labels: " << labelGeometryFilter->GetNumberOfLabels() << std::endl;
  //   std::cout << "Label geometry measures." << std::endl;
    std::cout << std::left << std::setw( 7 ) << "Label"
             << std::left << std::setw( 10 ) << "Volume"
             << std::left << std::setw( 15 ) << "SurfArea(mm^2)"
             << std::left << std::setw( 15 ) << "Eccentricity"
             << std::left << std::setw( 15 ) << "Elongation"
             << std::left << std::setw( 15 ) << "Orientation"
             << std::left << std::setw( 30 ) << "Centroid"
             << std::left << std::setw( 30 ) << "Axes Length"
             << std::left << std::setw( 30 ) << "Bounding Box";
    if( filter->GetIntensityInput() )
      {
      std::cout << std::left << std::setw( 20 )  << "Integrated Int."
               << std::left << std::setw( 30 ) << "Weighted Centroid";
      }
    std::cout << std::endl;
    for( allLabelsIt = allLabels.begin(); allLabelsIt != allLabels.end(); allLabelsIt++ )
      {
      if( *allLabelsIt == 0 )
        {
        continue;
        }
      std::cout << std::setw( 7 ) << *allLabelsIt;
      std::cout << std::setw( 10 ) << filter->GetVolume( *allLabelsIt );

      const LabelObjectType * labelObject = labelMap->GetLabelObject( *allLabelsIt );

      std::cout << std::setw( 15 ) << labelObject->GetPerimeter();
      std::cout << std::setw( 15 ) << filter->GetEccentricity( *allLabelsIt );
      std::cout << std::setw( 15 ) << filter->GetElongation( *allLabelsIt );
      std::cout << std::setw( 15 ) << filter->GetOrientation( *allLabelsIt );

      std::stringstream oss;
      oss << filter->GetCentroid( *allLabelsIt );
      std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
      oss.str( "" );

      oss << filter->GetAxesLength( *allLabelsIt );
      std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
      oss.str( "" );

      oss << filter->GetBoundingBox( *allLabelsIt );
      std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
      oss.str( "" );

  //     std::cout << filter->GetMajorAxisLength( *allLabelsIt ) << "\t";
  //     std::cout << filter->GetMinorAxisLength( *allLabelsIt ) << "\t";
      if( filter->GetIntensityInput() )
        {
        oss << filter->GetIntegratedIntensity( *allLabelsIt );
        std::cout << std::setw( 20 ) << ( oss.str() ).c_str();
        oss.str( "" );

        oss << filter->GetWeightedCentroid( *allLabelsIt );
        std::cout << std::setw( 30 ) << ( oss.str() ).c_str();
        oss.str( "" );
        }
      std::cout << std::endl;
      }
    }

  return EXIT_SUCCESS;
}

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int LabelGeometryMeasures( std::vector<std::string> args, std::ostream* itkNotUsed( out_stream ) )
{
  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle
  args.insert( args.begin(), "LabelGeometryMeasures" );

  int     argc = args.size();
  char* * argv = new char *[args.size() + 1];
  for( unsigned int i = 0; i < args.size(); ++i )
    {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy( argv[i], args[i].c_str(), args[i].length() );
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
    }
  argv[argc] = ITK_NULLPTR;
  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
public:
    Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
    {
    }

    ~Cleanup_argv()
    {
      for( unsigned int i = 0; i < argc_plus_one; ++i )
        {
        delete[] argv[i];
        }
      delete[] argv;
    }

private:
    char* *      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv( argv, argc + 1 );

  // antscout->set_stream( out_stream );

  if( argc < 3 )
    {
    std::cout << "Usage 1: " << argv[0] << " imageDimension labelImage [intensityImage=none] [csvFile]" << std::endl;
//     std::cout << "Usage 2: " << argv[0] << " X singleLabelImage outputTransform <doReflection=1> <scaleFactor=1>" << std::endl;

    if( argc >= 2 &&
        ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
      {
      return EXIT_SUCCESS;
      }
    return EXIT_FAILURE;
    }

  switch( atoi( argv[1] ) )
    {
    case 2:
      {
      LabelGeometryMeasures<2>( argc, argv );
      }
      break;
    case 3:
      {
      LabelGeometryMeasures<3>( argc, argv );
      }
      break;
    default:
      std::cout << "Unsupported dimension" << std::endl;
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
} // namespace ants
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    finance.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 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.

=========================================================================*/
#include "vtkDataSet.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkGaussianSplatter.h"
#include "vtkContourFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkAxes.h"
#include "vtkTubeFilter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkPoints.h"
#include "vtkScalars.h"

static vtkDataSet *ReadFinancialData(const char *x, const char *y, const char *z, const char *s);
static int ParseFile(FILE *file, const char *tag, float *data);

int main( int argc, char *argv[] )
{
  float bounds[6];
  vtkDataSet *dataSet;

  // read data
  dataSet = ReadFinancialData("MONTHLY_PAYMENT","INTEREST_RATE",
                              "LOAN_AMOUNT","TIME_LATE");
  if ( ! dataSet ) exit(0);

  // construct pipeline for original population
  vtkGaussianSplatter *popSplatter = vtkGaussianSplatter::New();
    popSplatter->SetInput(dataSet);
    popSplatter->SetSampleDimensions(50,50,50);
    popSplatter->SetRadius(0.05);
    popSplatter->ScalarWarpingOff();
  vtkContourFilter *popSurface = vtkContourFilter::New();
    popSurface->SetInput(popSplatter->GetOutput());
    popSurface->SetValue(0,0.01);
  vtkPolyDataMapper *popMapper = vtkPolyDataMapper::New();
    popMapper->SetInput(popSurface->GetOutput());
    popMapper->ScalarVisibilityOff();
  vtkActor *popActor = vtkActor::New();
    popActor->SetMapper(popMapper);
    popActor->GetProperty()->SetOpacity(0.3);
    popActor->GetProperty()->SetColor(.9,.9,.9);

  // construct pipeline for delinquent population
  vtkGaussianSplatter *lateSplatter = vtkGaussianSplatter::New();
    lateSplatter->SetInput(dataSet);
    lateSplatter->SetSampleDimensions(50,50,50);
    lateSplatter->SetRadius(0.05);
    lateSplatter->SetScaleFactor(0.005);
  vtkContourFilter *lateSurface = vtkContourFilter::New();
    lateSurface->SetInput(lateSplatter->GetOutput());
    lateSurface->SetValue(0,0.01);
  vtkPolyDataMapper *lateMapper = vtkPolyDataMapper::New();
    lateMapper->SetInput(lateSurface->GetOutput());
    lateMapper->ScalarVisibilityOff();
  vtkActor *lateActor = vtkActor::New();
    lateActor->SetMapper(lateMapper);
    lateActor->GetProperty()->SetColor(1.0,0.0,0.0);

  // create axes
  popSplatter->Update();
  popSplatter->GetOutput()->GetBounds(bounds);
  vtkAxes *axes = vtkAxes::New();
    axes->SetOrigin(bounds[0], bounds[2], bounds[4]);
    axes->SetScaleFactor(popSplatter->GetOutput()->GetLength()/5);
  vtkTubeFilter *axesTubes = vtkTubeFilter::New();
    axesTubes->SetInput(axes->GetOutput());
    axesTubes->SetRadius(axes->GetScaleFactor()/25.0);
    axesTubes->SetNumberOfSides(6);
  vtkPolyDataMapper *axesMapper = vtkPolyDataMapper::New();
    axesMapper->SetInput(axesTubes->GetOutput());
  vtkActor *axesActor = vtkActor::New();
    axesActor->SetMapper(axesMapper);

  // graphics stuff
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // read data  //set up renderer
  renderer->AddActor(lateActor);
  renderer->AddActor(axesActor);
  renderer->AddActor(popActor);
  renderer->SetBackground(1,1,1);
  renWin->SetSize(300,300);

  // interact with data
  iren->Initialize();

  renWin->Render();
  iren->Start();

  // Clean up
  renderer->Delete();
  renWin->Delete();
  iren->Delete();
  popSplatter->Delete();
  popSurface->Delete();
  popMapper->Delete();
  popActor->Delete();
  lateSplatter->Delete();
  lateSurface->Delete();
  lateMapper->Delete();
  lateActor->Delete();
  axes->Delete();
  axesTubes->Delete();
  axesMapper->Delete();
  axesActor->Delete();
  dataSet->Delete();

  return 0;
}

static vtkDataSet *ReadFinancialData(const char *x, const char *y, const char *z, const char *s)
{
  float xyz[3];
  FILE *file;
  int i, npts;
  char tag[80];
  const char *temp=getenv("VTK_DATA_ROOT");
  char filename[2048];

  if ( ! temp )
    {
    cerr << "ERROR: Please define environment variable VTK_DATA_ROOT\n";
    return NULL;
    }
  strcpy(filename,temp);
  strcat(filename,"/Data/financial.txt");

  if ( (file = fopen(filename,"r")) == 0 )
    {
    cerr << "ERROR: Can't read file: " << filename << "\n";
    return NULL;
    }

  fscanf (file, "%s %d", tag, &npts); // read number of points

  vtkUnstructuredGrid *dataSet = vtkUnstructuredGrid::New();
  float *xV = new float[npts];
  float *yV = new float[npts];
  float *zV = new float[npts];
  float *sV = new float[npts];

  if ( ! ParseFile(file, x, xV) || ! ParseFile(file, y, yV) ||
  ! ParseFile(file, z, zV) || ! ParseFile(file, s, sV) )
    {
    cerr << "Couldn't read data!\n";
    delete [] xV;
    delete [] yV;
    delete [] zV;
    delete [] sV;
    dataSet->Delete();
    return NULL;
    }

  vtkPoints *newPts = vtkPoints::New();
  vtkFloatArray *newScalars = vtkFloatArray::New();

  for (i=0; i<npts; i++)
    {
    xyz[0] = xV[i]; xyz[1] = yV[i]; xyz[2] = zV[i];
    newPts->InsertPoint(i, xyz);
    newScalars->InsertValue(i, sV[i]);
    }

  dataSet->SetPoints(newPts);
  dataSet->GetPointData()->SetScalars(newScalars);

  newPts->Delete(); //reference counted - it's okay
  newScalars->Delete();

  return dataSet;
}

static int ParseFile(FILE *file, const char *label, float *data)
{
  char tag[80];
  int i, npts, readData=0;
  float min=VTK_LARGE_FLOAT;
  float max=(-VTK_LARGE_FLOAT);

  if ( file == NULL || label == NULL ) return 0;

  rewind(file);

  fscanf(file, "%s %d", tag, &npts);

  while ( !readData && fscanf(file, "%s", tag) == 1 )
    {
    if ( ! strcmp(tag,label) )
      {
      readData = 1;
      for (i=0; i<npts; i++)
        {
        fscanf(file, "%f", data+i);
        if ( data[i] < min ) min = data[i];
        if ( data[i] > min ) max = data[i];
        }
      // normalize data
      for (i=0; i<npts; i++) data[i] = min + data[i]/(max-min);
      }
    else
      {
      for (i=0; i<npts; i++) fscanf(file, "%*f");
      }
    }

  if ( ! readData ) return 0;
  else return 1;
}
<commit_msg>ERR:Bad include<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    finance.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 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.

=========================================================================*/
#include "vtkDataSet.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkGaussianSplatter.h"
#include "vtkContourFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkAxes.h"
#include "vtkTubeFilter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkPoints.h"
#include "vtkFloatArray.h"

static vtkDataSet *ReadFinancialData(const char *x, const char *y, const char *z, const char *s);
static int ParseFile(FILE *file, const char *tag, float *data);

int main( int argc, char *argv[] )
{
  float bounds[6];
  vtkDataSet *dataSet;

  // read data
  dataSet = ReadFinancialData("MONTHLY_PAYMENT","INTEREST_RATE",
                              "LOAN_AMOUNT","TIME_LATE");
  if ( ! dataSet ) exit(0);

  // construct pipeline for original population
  vtkGaussianSplatter *popSplatter = vtkGaussianSplatter::New();
    popSplatter->SetInput(dataSet);
    popSplatter->SetSampleDimensions(50,50,50);
    popSplatter->SetRadius(0.05);
    popSplatter->ScalarWarpingOff();
  vtkContourFilter *popSurface = vtkContourFilter::New();
    popSurface->SetInput(popSplatter->GetOutput());
    popSurface->SetValue(0,0.01);
  vtkPolyDataMapper *popMapper = vtkPolyDataMapper::New();
    popMapper->SetInput(popSurface->GetOutput());
    popMapper->ScalarVisibilityOff();
  vtkActor *popActor = vtkActor::New();
    popActor->SetMapper(popMapper);
    popActor->GetProperty()->SetOpacity(0.3);
    popActor->GetProperty()->SetColor(.9,.9,.9);

  // construct pipeline for delinquent population
  vtkGaussianSplatter *lateSplatter = vtkGaussianSplatter::New();
    lateSplatter->SetInput(dataSet);
    lateSplatter->SetSampleDimensions(50,50,50);
    lateSplatter->SetRadius(0.05);
    lateSplatter->SetScaleFactor(0.005);
  vtkContourFilter *lateSurface = vtkContourFilter::New();
    lateSurface->SetInput(lateSplatter->GetOutput());
    lateSurface->SetValue(0,0.01);
  vtkPolyDataMapper *lateMapper = vtkPolyDataMapper::New();
    lateMapper->SetInput(lateSurface->GetOutput());
    lateMapper->ScalarVisibilityOff();
  vtkActor *lateActor = vtkActor::New();
    lateActor->SetMapper(lateMapper);
    lateActor->GetProperty()->SetColor(1.0,0.0,0.0);

  // create axes
  popSplatter->Update();
  popSplatter->GetOutput()->GetBounds(bounds);
  vtkAxes *axes = vtkAxes::New();
    axes->SetOrigin(bounds[0], bounds[2], bounds[4]);
    axes->SetScaleFactor(popSplatter->GetOutput()->GetLength()/5);
  vtkTubeFilter *axesTubes = vtkTubeFilter::New();
    axesTubes->SetInput(axes->GetOutput());
    axesTubes->SetRadius(axes->GetScaleFactor()/25.0);
    axesTubes->SetNumberOfSides(6);
  vtkPolyDataMapper *axesMapper = vtkPolyDataMapper::New();
    axesMapper->SetInput(axesTubes->GetOutput());
  vtkActor *axesActor = vtkActor::New();
    axesActor->SetMapper(axesMapper);

  // graphics stuff
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // read data  //set up renderer
  renderer->AddActor(lateActor);
  renderer->AddActor(axesActor);
  renderer->AddActor(popActor);
  renderer->SetBackground(1,1,1);
  renWin->SetSize(300,300);

  // interact with data
  iren->Initialize();

  renWin->Render();
  iren->Start();

  // Clean up
  renderer->Delete();
  renWin->Delete();
  iren->Delete();
  popSplatter->Delete();
  popSurface->Delete();
  popMapper->Delete();
  popActor->Delete();
  lateSplatter->Delete();
  lateSurface->Delete();
  lateMapper->Delete();
  lateActor->Delete();
  axes->Delete();
  axesTubes->Delete();
  axesMapper->Delete();
  axesActor->Delete();
  dataSet->Delete();

  return 0;
}

static vtkDataSet *ReadFinancialData(const char *x, const char *y, const char *z, const char *s)
{
  float xyz[3];
  FILE *file;
  int i, npts;
  char tag[80];
  const char *temp=getenv("VTK_DATA_ROOT");
  char filename[2048];

  if ( ! temp )
    {
    cerr << "ERROR: Please define environment variable VTK_DATA_ROOT\n";
    return NULL;
    }
  strcpy(filename,temp);
  strcat(filename,"/Data/financial.txt");

  if ( (file = fopen(filename,"r")) == 0 )
    {
    cerr << "ERROR: Can't read file: " << filename << "\n";
    return NULL;
    }

  fscanf (file, "%s %d", tag, &npts); // read number of points

  vtkUnstructuredGrid *dataSet = vtkUnstructuredGrid::New();
  float *xV = new float[npts];
  float *yV = new float[npts];
  float *zV = new float[npts];
  float *sV = new float[npts];

  if ( ! ParseFile(file, x, xV) || ! ParseFile(file, y, yV) ||
  ! ParseFile(file, z, zV) || ! ParseFile(file, s, sV) )
    {
    cerr << "Couldn't read data!\n";
    delete [] xV;
    delete [] yV;
    delete [] zV;
    delete [] sV;
    dataSet->Delete();
    return NULL;
    }

  vtkPoints *newPts = vtkPoints::New();
  vtkFloatArray *newScalars = vtkFloatArray::New();

  for (i=0; i<npts; i++)
    {
    xyz[0] = xV[i]; xyz[1] = yV[i]; xyz[2] = zV[i];
    newPts->InsertPoint(i, xyz);
    newScalars->InsertValue(i, sV[i]);
    }

  dataSet->SetPoints(newPts);
  dataSet->GetPointData()->SetScalars(newScalars);

  newPts->Delete(); //reference counted - it's okay
  newScalars->Delete();

  return dataSet;
}

static int ParseFile(FILE *file, const char *label, float *data)
{
  char tag[80];
  int i, npts, readData=0;
  float min=VTK_LARGE_FLOAT;
  float max=(-VTK_LARGE_FLOAT);

  if ( file == NULL || label == NULL ) return 0;

  rewind(file);

  fscanf(file, "%s %d", tag, &npts);

  while ( !readData && fscanf(file, "%s", tag) == 1 )
    {
    if ( ! strcmp(tag,label) )
      {
      readData = 1;
      for (i=0; i<npts; i++)
        {
        fscanf(file, "%f", data+i);
        if ( data[i] < min ) min = data[i];
        if ( data[i] > min ) max = data[i];
        }
      // normalize data
      for (i=0; i<npts; i++) data[i] = min + data[i]/(max-min);
      }
    else
      {
      for (i=0; i<npts; i++) fscanf(file, "%*f");
      }
    }

  if ( ! readData ) return 0;
  else return 1;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2010, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/////////////////////////////////////////////////////////////
//
// Base class for cuts on AOD reconstructed heavy-flavour decay
//
// Author: A.Dainese, andrea.dainese@pd.infn.it
/////////////////////////////////////////////////////////////
#include <Riostream.h>

#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliVVertex.h"
#include "AliESDVertex.h"
#include "AliAODVertex.h"
#include "AliESDtrack.h"
#include "AliAODTrack.h"
#include "AliESDtrackCuts.h"
#include "AliAODRecoDecayHF.h"
#include "AliRDHFCuts.h"

ClassImp(AliRDHFCuts)

//--------------------------------------------------------------------------
AliRDHFCuts::AliRDHFCuts(const Char_t* name, const Char_t* title) :
AliAnalysisCuts(name,title),
fMinVtxType(3),
fMinVtxContr(1),
fMaxVtxRedChi2(1e6),
fMinSPDMultiplicity(0),
fTriggerMask(0),
fTrackCuts(0),
fnPtBins(1),
fnPtBinLimits(1),
fPtBinLimits(0),
fnVars(1),
fVarNames(0),
fnVarsForOpt(0),
fVarsForOpt(0),
fGlobalIndex(1),
fCutsRD(0),
fIsUpperCut(0)
{
  //
  // Default Constructor
  //
}
//--------------------------------------------------------------------------
AliRDHFCuts::AliRDHFCuts(const AliRDHFCuts &source) :
  AliAnalysisCuts(source),
  fMinVtxType(source.fMinVtxType),
  fMinVtxContr(source.fMinVtxContr),
  fMaxVtxRedChi2(source.fMaxVtxRedChi2),
  fMinSPDMultiplicity(source.fMinSPDMultiplicity),
  fTriggerMask(source.fTriggerMask),
  fTrackCuts(0),
  fnPtBins(source.fnPtBins),
  fnPtBinLimits(source.fnPtBinLimits),
  fPtBinLimits(0),
  fnVars(source.fnVars),
  fVarNames(0),
  fnVarsForOpt(source.fnVarsForOpt),
  fVarsForOpt(0),
  fGlobalIndex(source.fGlobalIndex),
  fCutsRD(0),
  fIsUpperCut(0)
{
  //
  // Copy constructor
  //
  cout<<"Copy constructor"<<endl;
  if(source.GetTrackCuts()) AddTrackCuts(source.GetTrackCuts());
  if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits);
  if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut);
  if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD);
  if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt);
  PrintAll();

}
//--------------------------------------------------------------------------
AliRDHFCuts &AliRDHFCuts::operator=(const AliRDHFCuts &source)
{
  //
  // assignment operator
  //
  if(&source == this) return *this;

  AliAnalysisCuts::operator=(source);

  fMinVtxType=source.fMinVtxType;
  fMinVtxContr=source.fMinVtxContr;
  fMaxVtxRedChi2=source.fMaxVtxRedChi2;
  fMinSPDMultiplicity=source.fMinSPDMultiplicity;
  fTriggerMask=source.fTriggerMask;
  fnPtBins=source.fnPtBins;
  fnVars=source.fnVars;
  fGlobalIndex=source.fGlobalIndex;
  fnVarsForOpt=source.fnVarsForOpt;

  if(source.GetTrackCuts()) AddTrackCuts(source.GetTrackCuts());
  if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits);
  if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut);
  if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD);
  if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt);
  PrintAll();

  return *this;
}
//--------------------------------------------------------------------------
AliRDHFCuts::~AliRDHFCuts() {
  //
  // Default Destructor
  //
  if(fPtBinLimits) {delete [] fPtBinLimits; fPtBinLimits=0;}
  if(fVarNames) {delete [] fVarNames; fVarNames=0;}
  if(fVarsForOpt) {delete [] fVarsForOpt; fVarsForOpt=0;}
  if(fCutsRD) {
    delete [] fCutsRD;
    fCutsRD=0;
  }
  if(fIsUpperCut) {delete [] fIsUpperCut; fIsUpperCut=0;}

}
//---------------------------------------------------------------------------
Bool_t AliRDHFCuts::IsEventSelected(AliVEvent *event) const {
  //
  // Event selection
  //
  //if(fTriggerMask && event->GetTriggerMask()!=fTriggerMask) return kFALSE;

  // multiplicity cuts no implemented yet

  const AliVVertex *vertex = event->GetPrimaryVertex();

  if(!vertex) return kFALSE;

  TString title=vertex->GetTitle();
  if(title.Contains("Z") && fMinVtxType>1) return kFALSE;
  if(title.Contains("3D") && fMinVtxType>2) return kFALSE;

  if(vertex->GetNContributors()<fMinVtxContr) return kFALSE;

  return kTRUE;
}
//---------------------------------------------------------------------------
Bool_t AliRDHFCuts::AreDaughtersSelected(AliAODRecoDecayHF *d) const {
  //
  // Daughter tracks selection
  //
  if(!fTrackCuts) return kTRUE;

  Int_t ndaughters = d->GetNDaughters();
  AliESDtrack* esdTrack=0;
  AliAODVertex *vAOD = d->GetPrimaryVtx();
  Double_t pos[3],cov[6];
  vAOD->GetXYZ(pos);
  vAOD->GetCovarianceMatrix(cov);
  const AliESDVertex *vESD = new AliESDVertex(pos,cov,100.,100);

  Bool_t retval=kTRUE;

  for(Int_t idg=0; idg<ndaughters; idg++) {
    AliAODTrack *dgTrack = (AliAODTrack*)d->GetDaughter(idg);
    if(!dgTrack) retval = kFALSE;
    //printf("charge %d\n",dgTrack->Charge());
    if(dgTrack->Charge()==0) continue; // it's not a track, but a V0
    // convert to ESD track here
    esdTrack=new AliESDtrack(dgTrack);
    // needed to calculate the impact parameters
    esdTrack->RelateToVertex(vESD,0.,3.);
    if(!fTrackCuts->IsSelected(esdTrack)) retval = kFALSE;
    delete esdTrack; esdTrack=0;
  }

  delete vESD; vESD=0;

  return retval;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetPtBins(Int_t nPtBinLimits,Float_t *ptBinLimits) {
  // Set the pt bins

  if(fPtBinLimits) {
    delete [] fPtBinLimits;
    fPtBinLimits = NULL;
    printf("Changing the pt bins\n");
  }

  if(nPtBinLimits != fnPtBins+1){
    cout<<"Warning: ptBinLimits dimention "<<nPtBinLimits<<" != nPtBins+1 ("<<fnPtBins+1<<")\nSetting nPtBins to "<<nPtBinLimits-1<<endl;
    SetNPtBins(nPtBinLimits-1);
  }

  fnPtBinLimits = nPtBinLimits;
  SetGlobalIndex();
  cout<<"Changing also Global Index -> "<<fGlobalIndex<<endl;
  fPtBinLimits = new Float_t[fnPtBinLimits];
  for(Int_t ib=0; ib<nPtBinLimits; ib++) fPtBinLimits[ib]=ptBinLimits[ib];

  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetVarNames(Int_t nVars,TString *varNames,Bool_t *isUpperCut){
  // Set the variable names

  if(fVarNames) {
    delete [] fVarNames;
    fVarNames = NULL;
    printf("Changing the variable names\n");
  }
  if(nVars!=fnVars){
    printf("Wrong number of variables: it has to be %d\n",fnVars);
    return;
  }
  //fnVars=nVars;
  fVarNames = new TString[nVars];
  fIsUpperCut = new Bool_t[nVars];
  for(Int_t iv=0; iv<nVars; iv++) {
    fVarNames[iv] = varNames[iv];
    fIsUpperCut[iv] = isUpperCut[iv];
  }

  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetVarsForOpt(Int_t nVars,Bool_t *forOpt) {
  // Set the variables to be used for cuts optimization

  if(fVarsForOpt) {
    delete [] fVarsForOpt;
    fVarsForOpt = NULL;
    printf("Changing the variables for cut optimization\n");
  }

  if(nVars==0){//!=fnVars) {
    printf("%d not accepted as number of variables: it has to be %d\n",nVars,fnVars);
    return;
  }

  fnVarsForOpt = 0;
  fVarsForOpt = new Bool_t[fnVars];
  for(Int_t iv=0; iv<fnVars; iv++) {
    fVarsForOpt[iv]=forOpt[iv];
    if(fVarsForOpt[iv]) fnVarsForOpt++;
  }

  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetCuts(Int_t nVars,Int_t nPtBins,Float_t **cutsRD) {
  //
  // store the cuts
  //
  if(nVars!=fnVars) {
    printf("Wrong number of variables: it has to be %d\n",fnVars);
    return;
  }
  if(nPtBins!=fnPtBins) {
    printf("Wrong number of pt bins: it has to be %d\n",fnPtBins);
    return;
  }

  if(!fCutsRD)  fCutsRD = new Float_t[fGlobalIndex];

  for(Int_t iv=0; iv<fnVars; iv++) {

    for(Int_t ib=0; ib<fnPtBins; ib++) {

      //check
      if(GetGlobalIndex(iv,ib)>=fGlobalIndex) {
	cout<<"Overflow, exit..."<<endl;
	return;
      }

      fCutsRD[GetGlobalIndex(iv,ib)] = cutsRD[iv][ib];

    }
  }
  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetCuts(Int_t glIndex,Float_t* cutsRDGlob){
  //
  // store the cuts
  //
  if(glIndex != fGlobalIndex){
    cout<<"Wrong array size: it has to be "<<fGlobalIndex<<endl;
    return;
  }
  if(!fCutsRD)  fCutsRD = new Float_t[fGlobalIndex];

  for(Int_t iGl=0;iGl<fGlobalIndex;iGl++){
    fCutsRD[iGl] = cutsRDGlob[iGl];
  }
  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::PrintAll() const {
  //
  // print all cuts values
  //
  if(fVarNames){
    cout<<"Array of variables"<<endl;
    for(Int_t iv=0;iv<fnVars;iv++){
      cout<<fVarNames[iv]<<"\t";
    }
    cout<<endl;
  }
  if(fVarsForOpt){
    cout<<"Array of optimization"<<endl;
    for(Int_t iv=0;iv<fnVars;iv++){
      cout<<fVarsForOpt[iv]<<"\t";
    }
    cout<<endl;
  }
  if(fIsUpperCut){
    cout<<"Array of upper/lower cut"<<endl;
   for(Int_t iv=0;iv<fnVars;iv++){
     cout<<fIsUpperCut[iv]<<"\t";
   }
   cout<<endl;
  }
  if(fPtBinLimits){
    cout<<"Array of ptbin limits"<<endl;
    for(Int_t ib=0;ib<fnPtBinLimits;ib++){
      cout<<fPtBinLimits[ib]<<"\t";
    }
    cout<<endl;
  }
  if(fCutsRD){
    cout<<"Matrix of cuts"<<endl;
   for(Int_t iv=0;iv<fnVars;iv++){
     for(Int_t ib=0;ib<fnPtBins;ib++){
       cout<<"fCutsRD["<<iv<<"]["<<ib<<"] = "<<fCutsRD[GetGlobalIndex(iv,ib)]<<"\t";
     }
     cout<<endl;
   }
   cout<<endl;
  }
  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::GetCuts(Float_t**& cutsRD) const{
  //
  // get the cuts
  //

  //cout<<"Give back a "<<fnVars<<"x"<<fnPtBins<<" matrix."<<endl;

  Int_t iv,ib;
  if(!cutsRD) {
    //cout<<"Initialization..."<<endl;
    cutsRD=new Float_t*[fnVars];
    for(iv=0; iv<fnVars; iv++) {
      cutsRD[iv] = new Float_t[fnPtBins];
    }
  }

  for(Int_t iGlobal=0; iGlobal<fGlobalIndex; iGlobal++) {
    GetVarPtIndex(iGlobal,iv,ib);
    cutsRD[iv][ib] = fCutsRD[iGlobal];
  }

  return;
}

//---------------------------------------------------------------------------
Int_t AliRDHFCuts::GetGlobalIndex(Int_t iVar,Int_t iPtBin) const{
  //
  // give the global index from variable and pt bin
  //
  return iPtBin*fnVars+iVar;
}

//---------------------------------------------------------------------------
void AliRDHFCuts::GetVarPtIndex(Int_t iGlob, Int_t& iVar, Int_t& iPtBin) const {
  //
  //give the index of the variable and of the pt bin from the global index
  //
  iPtBin=(Int_t)iGlob/fnVars;
  iVar=iGlob%fnVars;

  return;
}

//---------------------------------------------------------------------------
Int_t AliRDHFCuts::PtBin(Double_t pt) const {
  //
  //give the pt bin where the pt lies.
  //
  Int_t ptbin=0;
  for (Int_t i=0;i<fnPtBins;i++){
    if(pt<fPtBinLimits[i+1]) {
      ptbin=i;
      break;
    }
  }
  return ptbin;
}
//-------------------------------------------------------------------
Float_t AliRDHFCuts::GetCutValue(Int_t iVar,Int_t iPtBin) const {
  //
  // Give the value of cut set for the variable iVar and the pt bin iPtBin
  //
  if(!fCutsRD){
    cout<<"Cuts not iniziaisez yet"<<endl;
    return 0;
  }
  return fCutsRD[GetGlobalIndex(iVar,iPtBin)];
}

<commit_msg>Now PtBin() returns -1 if pt>maximum of all bins<commit_after>/**************************************************************************
 * Copyright(c) 1998-2010, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/////////////////////////////////////////////////////////////
//
// Base class for cuts on AOD reconstructed heavy-flavour decay
//
// Author: A.Dainese, andrea.dainese@pd.infn.it
/////////////////////////////////////////////////////////////
#include <Riostream.h>

#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliVVertex.h"
#include "AliESDVertex.h"
#include "AliAODVertex.h"
#include "AliESDtrack.h"
#include "AliAODTrack.h"
#include "AliESDtrackCuts.h"
#include "AliAODRecoDecayHF.h"
#include "AliRDHFCuts.h"

ClassImp(AliRDHFCuts)

//--------------------------------------------------------------------------
AliRDHFCuts::AliRDHFCuts(const Char_t* name, const Char_t* title) :
AliAnalysisCuts(name,title),
fMinVtxType(3),
fMinVtxContr(1),
fMaxVtxRedChi2(1e6),
fMinSPDMultiplicity(0),
fTriggerMask(0),
fTrackCuts(0),
fnPtBins(1),
fnPtBinLimits(1),
fPtBinLimits(0),
fnVars(1),
fVarNames(0),
fnVarsForOpt(0),
fVarsForOpt(0),
fGlobalIndex(1),
fCutsRD(0),
fIsUpperCut(0)
{
  //
  // Default Constructor
  //
}
//--------------------------------------------------------------------------
AliRDHFCuts::AliRDHFCuts(const AliRDHFCuts &source) :
  AliAnalysisCuts(source),
  fMinVtxType(source.fMinVtxType),
  fMinVtxContr(source.fMinVtxContr),
  fMaxVtxRedChi2(source.fMaxVtxRedChi2),
  fMinSPDMultiplicity(source.fMinSPDMultiplicity),
  fTriggerMask(source.fTriggerMask),
  fTrackCuts(0),
  fnPtBins(source.fnPtBins),
  fnPtBinLimits(source.fnPtBinLimits),
  fPtBinLimits(0),
  fnVars(source.fnVars),
  fVarNames(0),
  fnVarsForOpt(source.fnVarsForOpt),
  fVarsForOpt(0),
  fGlobalIndex(source.fGlobalIndex),
  fCutsRD(0),
  fIsUpperCut(0)
{
  //
  // Copy constructor
  //
  cout<<"Copy constructor"<<endl;
  if(source.GetTrackCuts()) AddTrackCuts(source.GetTrackCuts());
  if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits);
  if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut);
  if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD);
  if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt);
  PrintAll();

}
//--------------------------------------------------------------------------
AliRDHFCuts &AliRDHFCuts::operator=(const AliRDHFCuts &source)
{
  //
  // assignment operator
  //
  if(&source == this) return *this;

  AliAnalysisCuts::operator=(source);

  fMinVtxType=source.fMinVtxType;
  fMinVtxContr=source.fMinVtxContr;
  fMaxVtxRedChi2=source.fMaxVtxRedChi2;
  fMinSPDMultiplicity=source.fMinSPDMultiplicity;
  fTriggerMask=source.fTriggerMask;
  fnPtBins=source.fnPtBins;
  fnVars=source.fnVars;
  fGlobalIndex=source.fGlobalIndex;
  fnVarsForOpt=source.fnVarsForOpt;

  if(source.GetTrackCuts()) AddTrackCuts(source.GetTrackCuts());
  if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits);
  if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut);
  if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD);
  if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt);
  PrintAll();

  return *this;
}
//--------------------------------------------------------------------------
AliRDHFCuts::~AliRDHFCuts() {
  //
  // Default Destructor
  //
  if(fPtBinLimits) {delete [] fPtBinLimits; fPtBinLimits=0;}
  if(fVarNames) {delete [] fVarNames; fVarNames=0;}
  if(fVarsForOpt) {delete [] fVarsForOpt; fVarsForOpt=0;}
  if(fCutsRD) {
    delete [] fCutsRD;
    fCutsRD=0;
  }
  if(fIsUpperCut) {delete [] fIsUpperCut; fIsUpperCut=0;}

}
//---------------------------------------------------------------------------
Bool_t AliRDHFCuts::IsEventSelected(AliVEvent *event) const {
  //
  // Event selection
  //
  //if(fTriggerMask && event->GetTriggerMask()!=fTriggerMask) return kFALSE;

  // multiplicity cuts no implemented yet

  const AliVVertex *vertex = event->GetPrimaryVertex();

  if(!vertex) return kFALSE;

  TString title=vertex->GetTitle();
  if(title.Contains("Z") && fMinVtxType>1) return kFALSE;
  if(title.Contains("3D") && fMinVtxType>2) return kFALSE;

  if(vertex->GetNContributors()<fMinVtxContr) return kFALSE;

  return kTRUE;
}
//---------------------------------------------------------------------------
Bool_t AliRDHFCuts::AreDaughtersSelected(AliAODRecoDecayHF *d) const {
  //
  // Daughter tracks selection
  //
  if(!fTrackCuts) return kTRUE;

  Int_t ndaughters = d->GetNDaughters();
  AliESDtrack* esdTrack=0;
  AliAODVertex *vAOD = d->GetPrimaryVtx();
  Double_t pos[3],cov[6];
  vAOD->GetXYZ(pos);
  vAOD->GetCovarianceMatrix(cov);
  const AliESDVertex *vESD = new AliESDVertex(pos,cov,100.,100);

  Bool_t retval=kTRUE;

  for(Int_t idg=0; idg<ndaughters; idg++) {
    AliAODTrack *dgTrack = (AliAODTrack*)d->GetDaughter(idg);
    if(!dgTrack) retval = kFALSE;
    //printf("charge %d\n",dgTrack->Charge());
    if(dgTrack->Charge()==0) continue; // it's not a track, but a V0
    // convert to ESD track here
    esdTrack=new AliESDtrack(dgTrack);
    // needed to calculate the impact parameters
    esdTrack->RelateToVertex(vESD,0.,3.);
    if(!fTrackCuts->IsSelected(esdTrack)) retval = kFALSE;
    delete esdTrack; esdTrack=0;
  }

  delete vESD; vESD=0;

  return retval;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetPtBins(Int_t nPtBinLimits,Float_t *ptBinLimits) {
  // Set the pt bins

  if(fPtBinLimits) {
    delete [] fPtBinLimits;
    fPtBinLimits = NULL;
    printf("Changing the pt bins\n");
  }

  if(nPtBinLimits != fnPtBins+1){
    cout<<"Warning: ptBinLimits dimention "<<nPtBinLimits<<" != nPtBins+1 ("<<fnPtBins+1<<")\nSetting nPtBins to "<<nPtBinLimits-1<<endl;
    SetNPtBins(nPtBinLimits-1);
  }

  fnPtBinLimits = nPtBinLimits;
  SetGlobalIndex();
  cout<<"Changing also Global Index -> "<<fGlobalIndex<<endl;
  fPtBinLimits = new Float_t[fnPtBinLimits];
  for(Int_t ib=0; ib<nPtBinLimits; ib++) fPtBinLimits[ib]=ptBinLimits[ib];

  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetVarNames(Int_t nVars,TString *varNames,Bool_t *isUpperCut){
  // Set the variable names

  if(fVarNames) {
    delete [] fVarNames;
    fVarNames = NULL;
    printf("Changing the variable names\n");
  }
  if(nVars!=fnVars){
    printf("Wrong number of variables: it has to be %d\n",fnVars);
    return;
  }
  //fnVars=nVars;
  fVarNames = new TString[nVars];
  fIsUpperCut = new Bool_t[nVars];
  for(Int_t iv=0; iv<nVars; iv++) {
    fVarNames[iv] = varNames[iv];
    fIsUpperCut[iv] = isUpperCut[iv];
  }

  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetVarsForOpt(Int_t nVars,Bool_t *forOpt) {
  // Set the variables to be used for cuts optimization

  if(fVarsForOpt) {
    delete [] fVarsForOpt;
    fVarsForOpt = NULL;
    printf("Changing the variables for cut optimization\n");
  }

  if(nVars==0){//!=fnVars) {
    printf("%d not accepted as number of variables: it has to be %d\n",nVars,fnVars);
    return;
  }

  fnVarsForOpt = 0;
  fVarsForOpt = new Bool_t[fnVars];
  for(Int_t iv=0; iv<fnVars; iv++) {
    fVarsForOpt[iv]=forOpt[iv];
    if(fVarsForOpt[iv]) fnVarsForOpt++;
  }

  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetCuts(Int_t nVars,Int_t nPtBins,Float_t **cutsRD) {
  //
  // store the cuts
  //
  if(nVars!=fnVars) {
    printf("Wrong number of variables: it has to be %d\n",fnVars);
    return;
  }
  if(nPtBins!=fnPtBins) {
    printf("Wrong number of pt bins: it has to be %d\n",fnPtBins);
    return;
  }

  if(!fCutsRD)  fCutsRD = new Float_t[fGlobalIndex];

  for(Int_t iv=0; iv<fnVars; iv++) {

    for(Int_t ib=0; ib<fnPtBins; ib++) {

      //check
      if(GetGlobalIndex(iv,ib)>=fGlobalIndex) {
	cout<<"Overflow, exit..."<<endl;
	return;
      }

      fCutsRD[GetGlobalIndex(iv,ib)] = cutsRD[iv][ib];

    }
  }
  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::SetCuts(Int_t glIndex,Float_t* cutsRDGlob){
  //
  // store the cuts
  //
  if(glIndex != fGlobalIndex){
    cout<<"Wrong array size: it has to be "<<fGlobalIndex<<endl;
    return;
  }
  if(!fCutsRD)  fCutsRD = new Float_t[fGlobalIndex];

  for(Int_t iGl=0;iGl<fGlobalIndex;iGl++){
    fCutsRD[iGl] = cutsRDGlob[iGl];
  }
  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::PrintAll() const {
  //
  // print all cuts values
  //
  if(fVarNames){
    cout<<"Array of variables"<<endl;
    for(Int_t iv=0;iv<fnVars;iv++){
      cout<<fVarNames[iv]<<"\t";
    }
    cout<<endl;
  }
  if(fVarsForOpt){
    cout<<"Array of optimization"<<endl;
    for(Int_t iv=0;iv<fnVars;iv++){
      cout<<fVarsForOpt[iv]<<"\t";
    }
    cout<<endl;
  }
  if(fIsUpperCut){
    cout<<"Array of upper/lower cut"<<endl;
   for(Int_t iv=0;iv<fnVars;iv++){
     cout<<fIsUpperCut[iv]<<"\t";
   }
   cout<<endl;
  }
  if(fPtBinLimits){
    cout<<"Array of ptbin limits"<<endl;
    for(Int_t ib=0;ib<fnPtBinLimits;ib++){
      cout<<fPtBinLimits[ib]<<"\t";
    }
    cout<<endl;
  }
  if(fCutsRD){
    cout<<"Matrix of cuts"<<endl;
   for(Int_t iv=0;iv<fnVars;iv++){
     for(Int_t ib=0;ib<fnPtBins;ib++){
       cout<<"fCutsRD["<<iv<<"]["<<ib<<"] = "<<fCutsRD[GetGlobalIndex(iv,ib)]<<"\t";
     }
     cout<<endl;
   }
   cout<<endl;
  }
  return;
}
//---------------------------------------------------------------------------
void AliRDHFCuts::GetCuts(Float_t**& cutsRD) const{
  //
  // get the cuts
  //

  //cout<<"Give back a "<<fnVars<<"x"<<fnPtBins<<" matrix."<<endl;

  Int_t iv,ib;
  if(!cutsRD) {
    //cout<<"Initialization..."<<endl;
    cutsRD=new Float_t*[fnVars];
    for(iv=0; iv<fnVars; iv++) {
      cutsRD[iv] = new Float_t[fnPtBins];
    }
  }

  for(Int_t iGlobal=0; iGlobal<fGlobalIndex; iGlobal++) {
    GetVarPtIndex(iGlobal,iv,ib);
    cutsRD[iv][ib] = fCutsRD[iGlobal];
  }

  return;
}

//---------------------------------------------------------------------------
Int_t AliRDHFCuts::GetGlobalIndex(Int_t iVar,Int_t iPtBin) const{
  //
  // give the global index from variable and pt bin
  //
  return iPtBin*fnVars+iVar;
}

//---------------------------------------------------------------------------
void AliRDHFCuts::GetVarPtIndex(Int_t iGlob, Int_t& iVar, Int_t& iPtBin) const {
  //
  //give the index of the variable and of the pt bin from the global index
  //
  iPtBin=(Int_t)iGlob/fnVars;
  iVar=iGlob%fnVars;

  return;
}

//---------------------------------------------------------------------------
Int_t AliRDHFCuts::PtBin(Double_t pt) const {
  //
  //give the pt bin where the pt lies.
  //
  Int_t ptbin=-1;
  for (Int_t i=0;i<fnPtBins;i++){
    if(pt<fPtBinLimits[i+1]) {
      ptbin=i;
      break;
    }
  }
  return ptbin;
}
//-------------------------------------------------------------------
Float_t AliRDHFCuts::GetCutValue(Int_t iVar,Int_t iPtBin) const {
  //
  // Give the value of cut set for the variable iVar and the pt bin iPtBin
  //
  if(!fCutsRD){
    cout<<"Cuts not iniziaisez yet"<<endl;
    return 0;
  }
  return fCutsRD[GetGlobalIndex(iVar,iPtBin)];
}

<|endoftext|>


<commit_before>// Macro for analisys task of preselected-central-diffractive events
//------------------------------------------------------------------
// When there is no time to wait for legotrain results,
// please use this macro to run jobs on grid for preselected events
//------------------------------------------------------------------
// Author: Taesoo Kim, Beomkyu Kim
// email:  kimb@cern.ch
//

// good-run list of LHC10b period : 33, 7 TeV
const int LHC10bRuns[] = {117222,117220,117116,117112,117099,117063,117060,117059,117053,117052,117050,117048,116645,116643,116574,116571,116562,116403,116402,115521,115401,115399,115393,115345,115335,115193,115186,114931,114930,114924,114918,114798,114786};
// good-run list of LHC10c period : 31, 7 TeV
const int LHC10cRuns[] = {120829,120825,120824,120823,120822,120821,120820,120758,120750,120741,120671,120617,120616,120505,120503,120244,120079,120076,120073,120072,120069,120067,119849,119846,119845,119844,119842,119841,119163,119161,119159};
// good-run list of LHC10d period : 55, 7 TeV
const int LHC10dRuns[]= {126432,126425,126424,126422,126409,126408,126407,126406,126405,126404,126403,126359,126352,126351,126285,126284,126283,126168,126167,126160,126158,126097,126090,126088,126082,126081,126078,126073,126008,126007,126004,125855,125851,125850,125849,125848,125847,125844,125843,125842,125633,125632,125630,125628,125296,125295,125134,125100,125097,125085,125083,125023,124751,122375,122374};
// good-run list of LHC10e period : 113, 7 TeV
const int LHC10eRuns[] ={130850,130848,130847,130844,130842,130840,130834,130804,130803,130802,130799,130798,130795,130793,130704,130696,130628,130623,130621,130620,130609,130608,130601,130524,130520,130519,130517,130481,130480,130479,130375,130356,130354,130343,130342,130178,130172,130157,130151,130149,129966,129962,129961,129960,129959,129744,129742,129738,129736,129735,129734,129729,129726,129725,129723,129659,129653,129652,129651,129650,129647,129641,129639,129587,129586,129540,129536,129528,129527,129525,129524,129523,129521,129520,129514,129513,129512,129042,128913,128855,128853,128850,128843,128836,128835,128834,128833,128824,128823,128820,128819,128778,128777,128678,128677,128621,128615,128611,128609,128605,128596,128594,128592,128590,128582,128506,128504,128503,128498,128495,128494,128486,128366};
// good-run list of LHC15f period : 64, 13 TeV
const int LHC15fRuns[]={225011,225016,225026,225031,225035,225037,225041,225043,225050,225051,225052,225105,225106,225305,225307,225310,225313,225314,225315,225322,225576,225578,225579,225580,225582,225586,225587,225589,225709,225710,225716,225717,225763,225768,226062,226085,226170,226175,226176,226177,226183,226210,226225,226444,226445,226466,226468,226472,226495,226500,226532,226543,226551,226554,226569,226573,226591,226593,226596,226600,226602,226603,226605,226606};

class AliAnalysisGrid;
void runCD(
      const char *taskname = "CD"
    , const char *option = "LHC10b" // LHC10b or c or d or e or LHC15f
    , const char *gridmode = "full" // or "terminate" to merge
    )
{

    // add aliroot indlude path
    gROOT->ProcessLine(Form(".include %s/include",gSystem->ExpandPathName("$ROOTSYS")));
    gROOT->ProcessLine(Form(".include %s/include",gSystem->ExpandPathName("$ALICE_ROOT")));
    gROOT->ProcessLine(Form(".include %s/include",gSystem->ExpandPathName("$ALICE_PHYSICS")));

    // analysis manager
    AliAnalysisManager* mgr = new AliAnalysisManager(Form("%s%s",taskname,option));

    // create the alien handler and attach it to the manager
    AliAnalysisAlien *plugin = new AliAnalysisAlien();
    plugin->SetRunMode(gridmode);
    plugin->SetAPIVersion("V1.1x");
    plugin->SetAliPhysicsVersion("vAN-20160126-1");
    plugin->SetDropToShell(0);
    plugin->SetRunPrefix("000");
    plugin->SetNrunsPerMaster(1);
    plugin->SetOutputToRunNo();

    TString foption = option;
    if (foption.Contains("LHC10b")){
        for (int i=0; i<33; i++) plugin->AddRunNumber(LHC10bRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10b/out");
    }
    if (foption.Contains("LHC10c")){
        for (int i=0; i<31; i++) plugin->AddRunNumber(LHC10cRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10c/out");
    }
    if (foption.Contains("LHC10d")){
        for (int i=0; i<55; i++) plugin->AddRunNumber(LHC10dRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10d/out");
    }
    if (foption.Contains("LHC10e")){
        for (int i=0; i<113; i++) plugin->AddRunNumber(LHC10eRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10e/out");
    }
    if (foption.Contains("LHC15f")){
        for (int i=0; i<64; i++) plugin->AddRunNumber(LHC15fRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC15f/out");
    }
    plugin->SetDataPattern("*ESDs.root");

    plugin->SetGridWorkingDir(Form("%s%s",taskname,option));
    plugin->SetGridOutputDir("out");
    plugin->AddIncludePath("-I$ALICE_ROOT/include  -I$ALICE_ROOT/lib -I$ALICE_PHYSICS/include -I$ALICE_PHYSICS/lib -I$ALICE_PHYSICS/OADB/macros" );
    plugin->SetDefaultOutputs(kFALSE);
    plugin->SetOutputFiles("AnalysisResults.root tree.root");
    plugin->SetSplitMaxInputFileNumber(1000);
    plugin->SetMasterResubmitThreshold(90);

    // Optionally set time to live (default 30000 sec)
    plugin->SetTTL(10000);
    // Optionally set input format (default xml-single)
    plugin->SetInputFormat("xml-single");
    // Optionally modify the name of the generated JDL (default analysis.jdl)
    plugin->SetJDLName(Form("%s%s.jdl",taskname,option));
    // Optionally modify the executable name (default analysis.sh)
    plugin->SetExecutable(Form("%s%s.sh",taskname,option));
    // Optionally modify job price (default 1)
    plugin->SetPrice(1);
    // Optionally modify split mode (default 'se')
    plugin->SetSplitMode("se");

    mgr->SetGridHandler(plugin);
    AliInputEventHandler* esdH = new AliESDInputHandler();
    esdH->SetNeedField(1);
    mgr->SetInputEventHandler(esdH);

    // Add PID task manager if we use PID----------------------------------------
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
    AliAnalysisTaskPIDResponse *pidResponseTask = AddTaskPIDResponse(0);
    if(!pidResponseTask) { Printf("no pidResponseTask"); return; }
    //---------------------------------------------------------------------------

    AliAnalysisTaskSE *task;

    if (foption.Contains("LHC15f")){
        AliInputEventHandler* hdl = (AliInputEventHandler*)AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler();
        if (hdl) hdl->SetNeedField(kTRUE);
        task = AliAnalysisTaskCDPWA("ESD");
    } else {
        gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
        AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(0);
        if(!physSelTask) { Printf("no physSelTask"); return; }

        task = new AliAnalysisTaskCDTree("ESD");
        task->SelectCollisionCandidates(AliVEvent::kMB);
    }

    // Create containers for input/output
    AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
    AliAnalysisDataContainer *coutput = mgr->CreateContainer("output", TTree::Class(), AliAnalysisManager::kOutputContainer,"tree.root");
    AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("output2", TList::Class(), AliAnalysisManager::kOutputContainer,"AnalysisResults.root");

    mgr->AddTask(task);
    mgr->ConnectInput(task, 0, cinput);
    mgr->ConnectOutput(task, 1, coutput);
    mgr->ConnectOutput(task, 2, coutput2);

    // enable debug printouts
    mgr->SetDebugLevel(2);
    if (!mgr->InitAnalysis()) return;
    mgr->PrintStatus();

    // start analysis
    Printf("Starting Analysis....");
    mgr->StartAnalysis("grid",1234567890,0);
}
<commit_msg>max split number is changed and new operator added<commit_after>// Macro for analisys task of preselected-central-diffractive events
//------------------------------------------------------------------
// When there is no time to wait for legotrain results,
// please use this macro to run jobs on grid for preselected events
//------------------------------------------------------------------
// Author: Taesoo Kim, Beomkyu Kim
// email:  kimb@cern.ch
//

// good-run list of LHC10b period : 33, 7 TeV
const int LHC10bRuns[] = {117222,117220,117116,117112,117099,117063,117060,117059,117053,117052,117050,117048,116645,116643,116574,116571,116562,116403,116402,115521,115401,115399,115393,115345,115335,115193,115186,114931,114930,114924,114918,114798,114786};
// good-run list of LHC10c period : 31, 7 TeV
const int LHC10cRuns[] = {120829,120825,120824,120823,120822,120821,120820,120758,120750,120741,120671,120617,120616,120505,120503,120244,120079,120076,120073,120072,120069,120067,119849,119846,119845,119844,119842,119841,119163,119161,119159};
// good-run list of LHC10d period : 55, 7 TeV
const int LHC10dRuns[]= {126432,126425,126424,126422,126409,126408,126407,126406,126405,126404,126403,126359,126352,126351,126285,126284,126283,126168,126167,126160,126158,126097,126090,126088,126082,126081,126078,126073,126008,126007,126004,125855,125851,125850,125849,125848,125847,125844,125843,125842,125633,125632,125630,125628,125296,125295,125134,125100,125097,125085,125083,125023,124751,122375,122374};
// good-run list of LHC10e period : 113, 7 TeV
const int LHC10eRuns[] ={130850,130848,130847,130844,130842,130840,130834,130804,130803,130802,130799,130798,130795,130793,130704,130696,130628,130623,130621,130620,130609,130608,130601,130524,130520,130519,130517,130481,130480,130479,130375,130356,130354,130343,130342,130178,130172,130157,130151,130149,129966,129962,129961,129960,129959,129744,129742,129738,129736,129735,129734,129729,129726,129725,129723,129659,129653,129652,129651,129650,129647,129641,129639,129587,129586,129540,129536,129528,129527,129525,129524,129523,129521,129520,129514,129513,129512,129042,128913,128855,128853,128850,128843,128836,128835,128834,128833,128824,128823,128820,128819,128778,128777,128678,128677,128621,128615,128611,128609,128605,128596,128594,128592,128590,128582,128506,128504,128503,128498,128495,128494,128486,128366};
// good-run list of LHC15f period : 64, 13 TeV
const int LHC15fRuns[]={225011,225016,225026,225031,225035,225037,225041,225043,225050,225051,225052,225105,225106,225305,225307,225310,225313,225314,225315,225322,225576,225578,225579,225580,225582,225586,225587,225589,225709,225710,225716,225717,225763,225768,226062,226085,226170,226175,226176,226177,226183,226210,226225,226444,226445,226466,226468,226472,226495,226500,226532,226543,226551,226554,226569,226573,226591,226593,226596,226600,226602,226603,226605,226606};

class AliAnalysisGrid;
void runCD(
      const char *taskname = "CD"
    , const char *option = "LHC10b" // LHC10b or c or d or e or LHC15f
    , const char *gridmode = "full" // or "terminate" to merge
    )
{

    // add aliroot indlude path
    gROOT->ProcessLine(Form(".include %s/include",gSystem->ExpandPathName("$ROOTSYS")));
    gROOT->ProcessLine(Form(".include %s/include",gSystem->ExpandPathName("$ALICE_ROOT")));
    gROOT->ProcessLine(Form(".include %s/include",gSystem->ExpandPathName("$ALICE_PHYSICS")));

    // analysis manager
    AliAnalysisManager* mgr = new AliAnalysisManager(Form("%s%s",taskname,option));

    // create the alien handler and attach it to the manager
    AliAnalysisAlien *plugin = new AliAnalysisAlien();
    plugin->SetRunMode(gridmode);
    plugin->SetAPIVersion("V1.1x");
    plugin->SetAliPhysicsVersion("vAN-20160126-1");
    plugin->SetDropToShell(0);
    plugin->SetRunPrefix("000");
    plugin->SetNrunsPerMaster(1);
    plugin->SetOutputToRunNo();

    TString foption = option;
    if (foption.Contains("LHC10b")){
        for (int i=0; i<33; i++) plugin->AddRunNumber(LHC10bRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10b/out");
    }
    if (foption.Contains("LHC10c")){
        for (int i=0; i<31; i++) plugin->AddRunNumber(LHC10cRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10c/out");
    }
    if (foption.Contains("LHC10d")){
        for (int i=0; i<55; i++) plugin->AddRunNumber(LHC10dRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10d/out");
    }
    if (foption.Contains("LHC10e")){
        for (int i=0; i<113; i++) plugin->AddRunNumber(LHC10eRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC10e/out");
    }
    if (foption.Contains("LHC15f")){
        for (int i=0; i<64; i++) plugin->AddRunNumber(LHC15fRuns[i]);
        plugin->SetGridDataDir("/alice/cern.ch/user/k/kimb/PreselectionLHC15f/out");
    }
    plugin->SetDataPattern("*ESDs.root");

    plugin->SetGridWorkingDir(Form("%s%s",taskname,option));
    plugin->SetGridOutputDir("out");
    plugin->AddIncludePath("-I$ALICE_ROOT/include  -I$ALICE_ROOT/lib -I$ALICE_PHYSICS/include -I$ALICE_PHYSICS/lib -I$ALICE_PHYSICS/OADB/macros" );
    plugin->SetDefaultOutputs(kFALSE);
    plugin->SetOutputFiles("AnalysisResults.root tree.root");
    plugin->SetSplitMaxInputFileNumber(100);
    plugin->SetMasterResubmitThreshold(90);

    // Optionally set time to live (default 30000 sec)
    plugin->SetTTL(10000);
    // Optionally set input format (default xml-single)
    plugin->SetInputFormat("xml-single");
    // Optionally modify the name of the generated JDL (default analysis.jdl)
    plugin->SetJDLName(Form("%s%s.jdl",taskname,option));
    // Optionally modify the executable name (default analysis.sh)
    plugin->SetExecutable(Form("%s%s.sh",taskname,option));
    // Optionally modify job price (default 1)
    plugin->SetPrice(1);
    // Optionally modify split mode (default 'se')
    plugin->SetSplitMode("se");

    mgr->SetGridHandler(plugin);
    AliInputEventHandler* esdH = new AliESDInputHandler();
    esdH->SetNeedField(1);
    mgr->SetInputEventHandler(esdH);

    // Add PID task manager if we use PID----------------------------------------
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
    AliAnalysisTaskPIDResponse *pidResponseTask = AddTaskPIDResponse(0);
    if(!pidResponseTask) { Printf("no pidResponseTask"); return; }
    //---------------------------------------------------------------------------

    AliAnalysisTaskSE *task;

    if (foption.Contains("LHC15f")){
        AliInputEventHandler* hdl = (AliInputEventHandler*)AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler();
        if (hdl) hdl->SetNeedField(kTRUE);
        task = new AliAnalysisTaskCDPWA("ESD");
    } else {
        gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
        AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(0);
        if(!physSelTask) { Printf("no physSelTask"); return; }

        task = new AliAnalysisTaskCDTree("ESD");
        task->SelectCollisionCandidates(AliVEvent::kMB);
    }

    // Create containers for input/output
    AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
    AliAnalysisDataContainer *coutput = mgr->CreateContainer("output", TTree::Class(), AliAnalysisManager::kOutputContainer,"tree.root");
    AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("output2", TList::Class(), AliAnalysisManager::kOutputContainer,"AnalysisResults.root");

    mgr->AddTask(task);
    mgr->ConnectInput(task, 0, cinput);
    mgr->ConnectOutput(task, 1, coutput);
    mgr->ConnectOutput(task, 2, coutput2);

    // enable debug printouts
    mgr->SetDebugLevel(2);
    if (!mgr->InitAnalysis()) return;
    mgr->PrintStatus();

    // start analysis
    Printf("Starting Analysis....");
    mgr->StartAnalysis("grid",1234567890,0);
}
<|endoftext|>