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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    ImageRegistration14.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

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

// Software Guide : BeginLatex
//
//  This example illustrates how to do registration with a 2D Rigid Transform
//  and with the Normalized Mutual Information metric.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkImageRegistrationMethod.h"

#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredTransformInitializer.h"

#include "itkNormalizedMutualInformationHistogramImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkOnePlusOneEvolutionaryOptimizer.h"
#include "itkNormalVariateGenerator.h"

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"

//  The following section of code implements a Command observer
//  used to monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
  typedef  CommandIterationUpdate   Self;
  typedef  itk::Command             Superclass;
  typedef itk::SmartPointer<Self>  Pointer;
  itkNewMacro( Self );
protected:
  CommandIterationUpdate() {};
public:
  typedef itk::OnePlusOneEvolutionaryOptimizer     OptimizerType;
  typedef   const OptimizerType   *    OptimizerPointer;

  void Execute(itk::Object *caller, const itk::EventObject & event)
    {
      Execute( (const itk::Object *)caller, event);
    }

  void Execute(const itk::Object * object, const itk::EventObject & event)
    {
      OptimizerPointer optimizer =
        dynamic_cast< OptimizerPointer >( object );
      if( typeid( event ) != typeid( itk::IterationEvent ) )
        {
        return;
        }
      double currentValue = optimizer->GetValue();
      // Only print out when the Metric value changes
      if( fabs( m_LastMetricValue - currentValue ) > 1e-7 )
        {
        std::cout << optimizer->GetCurrentIteration() << "   ";
        std::cout << currentValue << "   ";
        std::cout << optimizer->GetCurrentPosition() << std::endl;
        m_LastMetricValue = currentValue;
        }
    }
private:
  double m_LastMetricValue;
};

int main( int argc, char *argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " fixedImageFile  movingImageFile ";
    std::cerr << "outputImagefile [differenceImage]" << std::endl;
    return 1;
    }

  const    unsigned int    Dimension = 2;
  typedef  unsigned char   PixelType;

  typedef itk::Image< PixelType, Dimension >  FixedImageType;
  typedef itk::Image< PixelType, Dimension >  MovingImageType;

  typedef itk::CenteredRigid2DTransform< double > TransformType;

  typedef itk::OnePlusOneEvolutionaryOptimizer       OptimizerType;
  typedef itk::LinearInterpolateImageFunction<
                                    MovingImageType,
                                    double             > InterpolatorType;
  typedef itk::ImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType    > RegistrationType;

  typedef itk::NormalizedMutualInformationHistogramImageToImageMetric<
                                          FixedImageType,
                                          MovingImageType >    MetricType;

  TransformType::Pointer      transform     = TransformType::New();
  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  RegistrationType::Pointer   registration  = RegistrationType::New();

  registration->SetOptimizer(     optimizer     );
  registration->SetTransform(     transform     );
  registration->SetInterpolator(  interpolator  );

  MetricType::Pointer metric = MetricType::New();
  registration->SetMetric( metric  );

  unsigned int numberOfBins = 32;
  MetricType::HistogramType::SizeType histogramSize;
  histogramSize[0] = numberOfBins;
  histogramSize[1] = numberOfBins;
  metric->SetHistogramSize( histogramSize );

  const unsigned int numberOfParameters = transform->GetNumberOfParameters();

  typedef MetricType::ScalesType ScalesType;
  ScalesType scales( numberOfParameters );

  scales.Fill( 1.0 );

  metric->SetDerivativeStepLengthScales(scales);

  typedef itk::ImageFileReader< FixedImageType  > FixedImageReaderType;
  typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;

  FixedImageReaderType::Pointer  fixedImageReader  = FixedImageReaderType::New();
  MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();

  fixedImageReader->SetFileName(  argv[1] );
  movingImageReader->SetFileName( argv[2] );

  registration->SetFixedImage(    fixedImageReader->GetOutput()    );
  registration->SetMovingImage(   movingImageReader->GetOutput()   );

  fixedImageReader->Update();

  registration->SetFixedImageRegion(
       fixedImageReader->GetOutput()->GetBufferedRegion() );

  typedef itk::CenteredTransformInitializer<
                                    TransformType,
                                    FixedImageType,
                                    MovingImageType >  TransformInitializerType;
  TransformInitializerType::Pointer initializer = TransformInitializerType::New();

  initializer->SetTransform(   transform );
  initializer->SetFixedImage(  fixedImageReader->GetOutput() );
  initializer->SetMovingImage( movingImageReader->GetOutput() );
  initializer->GeometryOn();
  initializer->InitializeTransform();

  transform->SetAngle( 0.0 );

  registration->SetInitialTransformParameters( transform->GetParameters() );

  std::cout << "Initial transform parameters = ";
  std::cout << transform->GetParameters() << std::endl;

  typedef OptimizerType::ScalesType       OptimizerScalesType;
  OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );

  const double translationScale = 1.0 / 100.0;

  optimizerScales[0] = 1.0;
  optimizerScales[1] = translationScale;
  optimizerScales[2] = translationScale;
  optimizerScales[3] = translationScale;
  optimizerScales[4] = translationScale;
  optimizer->SetScales( optimizerScales );

  typedef itk::Statistics::NormalVariateGenerator  GeneratorType;

  GeneratorType::Pointer generator = GeneratorType::New();
  generator->Initialize(12345);

  optimizer->MaximizeOn();

  optimizer->SetNormalVariateGenerator( generator );

  const double initialRadius = 0.05;

  optimizer->Initialize( initialRadius );
  optimizer->SetEpsilon( 0.001 );
  optimizer->SetMaximumIteration( 500 );

  // Create the Command observer and register it with the optimizer.
  //
  CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
  optimizer->AddObserver( itk::IterationEvent(), observer );

  try
    {
    registration->StartRegistration();
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return -1;
    }

  typedef RegistrationType::ParametersType ParametersType;

  ParametersType finalParameters = registration->GetLastTransformParameters();

  const double finalAngle           = finalParameters[0];
  const double finalRotationCenterX = finalParameters[1];
  const double finalRotationCenterY = finalParameters[2];
  const double finalTranslationX    = finalParameters[3];
  const double finalTranslationY    = finalParameters[4];

  unsigned int numberOfIterations = optimizer->GetCurrentIteration();

  double bestValue = optimizer->GetValue();

  // Print out results
  //

  const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0);

  std::cout << "Result = " << std::endl;
  std::cout << " Angle (radians) " << finalAngle  << std::endl;
  std::cout << " Angle (degrees) " << finalAngleInDegrees  << std::endl;
  std::cout << " Center X      = " << finalRotationCenterX  << std::endl;
  std::cout << " Center Y      = " << finalRotationCenterY  << std::endl;
  std::cout << " Translation X = " << finalTranslationX  << std::endl;
  std::cout << " Translation Y = " << finalTranslationY  << std::endl;
  std::cout << " Iterations    = " << numberOfIterations << std::endl;
  std::cout << " Metric value  = " << bestValue          << std::endl;

  typedef itk::ResampleImageFilter<
                            MovingImageType,
                            FixedImageType >    ResampleFilterType;

  TransformType::Pointer finalTransform = TransformType::New();

  finalTransform->SetParameters( finalParameters );

  ResampleFilterType::Pointer resample = ResampleFilterType::New();

  resample->SetTransform( finalTransform );
  resample->SetInput( movingImageReader->GetOutput() );

  FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();

  resample->SetSize(    fixedImage->GetLargestPossibleRegion().GetSize() );
  resample->SetOutputOrigin(  fixedImage->GetOrigin() );
  resample->SetOutputSpacing( fixedImage->GetSpacing() );
  resample->SetDefaultPixelValue( 100 );

  typedef itk::Image< PixelType, Dimension > OutputImageType;

  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  WriterType::Pointer      writer =  WriterType::New();

  writer->SetFileName( argv[3] );

  writer->SetInput( resample->GetOutput() );
  writer->Update();

// Software Guide : EndCodeSnippet

  return 0;
}

<commit_msg>FIX: UMR, m_LastMetricValue not initialized<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    ImageRegistration14.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

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

// Software Guide : BeginLatex
//
//  This example illustrates how to do registration with a 2D Rigid Transform
//  and with the Normalized Mutual Information metric.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkImageRegistrationMethod.h"

#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredTransformInitializer.h"

#include "itkNormalizedMutualInformationHistogramImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkOnePlusOneEvolutionaryOptimizer.h"
#include "itkNormalVariateGenerator.h"

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"

//  The following section of code implements a Command observer
//  used to monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
  typedef  CommandIterationUpdate   Self;
  typedef  itk::Command             Superclass;
  typedef itk::SmartPointer<Self>  Pointer;
  itkNewMacro( Self );
protected:
  CommandIterationUpdate() {m_LastMetricValue = 0;}
public:
  typedef itk::OnePlusOneEvolutionaryOptimizer     OptimizerType;
  typedef   const OptimizerType   *    OptimizerPointer;

  void Execute(itk::Object *caller, const itk::EventObject & event)
    {
      Execute( (const itk::Object *)caller, event);
    }

  void Execute(const itk::Object * object, const itk::EventObject & event)
    {
      OptimizerPointer optimizer =
        dynamic_cast< OptimizerPointer >( object );
      if( typeid( event ) != typeid( itk::IterationEvent ) )
        {
        return;
        }
      double currentValue = optimizer->GetValue();
      // Only print out when the Metric value changes
      if( fabs( m_LastMetricValue - currentValue ) > 1e-7 )
        {
        std::cout << optimizer->GetCurrentIteration() << "   ";
        std::cout << currentValue << "   ";
        std::cout << optimizer->GetCurrentPosition() << std::endl;
        m_LastMetricValue = currentValue;
        }
    }
private:
  double m_LastMetricValue;
};

int main( int argc, char *argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " fixedImageFile  movingImageFile ";
    std::cerr << "outputImagefile [differenceImage]" << std::endl;
    return 1;
    }

  const    unsigned int    Dimension = 2;
  typedef  unsigned char   PixelType;

  typedef itk::Image< PixelType, Dimension >  FixedImageType;
  typedef itk::Image< PixelType, Dimension >  MovingImageType;

  typedef itk::CenteredRigid2DTransform< double > TransformType;

  typedef itk::OnePlusOneEvolutionaryOptimizer       OptimizerType;
  typedef itk::LinearInterpolateImageFunction<
                                    MovingImageType,
                                    double             > InterpolatorType;
  typedef itk::ImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType    > RegistrationType;

  typedef itk::NormalizedMutualInformationHistogramImageToImageMetric<
                                          FixedImageType,
                                          MovingImageType >    MetricType;

  TransformType::Pointer      transform     = TransformType::New();
  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  RegistrationType::Pointer   registration  = RegistrationType::New();

  registration->SetOptimizer(     optimizer     );
  registration->SetTransform(     transform     );
  registration->SetInterpolator(  interpolator  );

  MetricType::Pointer metric = MetricType::New();
  registration->SetMetric( metric  );

  unsigned int numberOfBins = 32;
  MetricType::HistogramType::SizeType histogramSize;
  histogramSize[0] = numberOfBins;
  histogramSize[1] = numberOfBins;
  metric->SetHistogramSize( histogramSize );

  const unsigned int numberOfParameters = transform->GetNumberOfParameters();

  typedef MetricType::ScalesType ScalesType;
  ScalesType scales( numberOfParameters );

  scales.Fill( 1.0 );

  metric->SetDerivativeStepLengthScales(scales);

  typedef itk::ImageFileReader< FixedImageType  > FixedImageReaderType;
  typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;

  FixedImageReaderType::Pointer  fixedImageReader  = FixedImageReaderType::New();
  MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();

  fixedImageReader->SetFileName(  argv[1] );
  movingImageReader->SetFileName( argv[2] );

  registration->SetFixedImage(    fixedImageReader->GetOutput()    );
  registration->SetMovingImage(   movingImageReader->GetOutput()   );

  fixedImageReader->Update();

  registration->SetFixedImageRegion(
       fixedImageReader->GetOutput()->GetBufferedRegion() );

  typedef itk::CenteredTransformInitializer<
                                    TransformType,
                                    FixedImageType,
                                    MovingImageType >  TransformInitializerType;
  TransformInitializerType::Pointer initializer = TransformInitializerType::New();

  initializer->SetTransform(   transform );
  initializer->SetFixedImage(  fixedImageReader->GetOutput() );
  initializer->SetMovingImage( movingImageReader->GetOutput() );
  initializer->GeometryOn();
  initializer->InitializeTransform();

  transform->SetAngle( 0.0 );

  registration->SetInitialTransformParameters( transform->GetParameters() );

  std::cout << "Initial transform parameters = ";
  std::cout << transform->GetParameters() << std::endl;

  typedef OptimizerType::ScalesType       OptimizerScalesType;
  OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );

  const double translationScale = 1.0 / 100.0;

  optimizerScales[0] = 1.0;
  optimizerScales[1] = translationScale;
  optimizerScales[2] = translationScale;
  optimizerScales[3] = translationScale;
  optimizerScales[4] = translationScale;
  optimizer->SetScales( optimizerScales );

  typedef itk::Statistics::NormalVariateGenerator  GeneratorType;

  GeneratorType::Pointer generator = GeneratorType::New();
  generator->Initialize(12345);

  optimizer->MaximizeOn();

  optimizer->SetNormalVariateGenerator( generator );

  const double initialRadius = 0.05;

  optimizer->Initialize( initialRadius );
  optimizer->SetEpsilon( 0.001 );
  optimizer->SetMaximumIteration( 500 );

  // Create the Command observer and register it with the optimizer.
  //
  CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
  optimizer->AddObserver( itk::IterationEvent(), observer );

  try
    {
    registration->StartRegistration();
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return -1;
    }

  typedef RegistrationType::ParametersType ParametersType;

  ParametersType finalParameters = registration->GetLastTransformParameters();

  const double finalAngle           = finalParameters[0];
  const double finalRotationCenterX = finalParameters[1];
  const double finalRotationCenterY = finalParameters[2];
  const double finalTranslationX    = finalParameters[3];
  const double finalTranslationY    = finalParameters[4];

  unsigned int numberOfIterations = optimizer->GetCurrentIteration();

  double bestValue = optimizer->GetValue();

  // Print out results
  //

  const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0);

  std::cout << "Result = " << std::endl;
  std::cout << " Angle (radians) " << finalAngle  << std::endl;
  std::cout << " Angle (degrees) " << finalAngleInDegrees  << std::endl;
  std::cout << " Center X      = " << finalRotationCenterX  << std::endl;
  std::cout << " Center Y      = " << finalRotationCenterY  << std::endl;
  std::cout << " Translation X = " << finalTranslationX  << std::endl;
  std::cout << " Translation Y = " << finalTranslationY  << std::endl;
  std::cout << " Iterations    = " << numberOfIterations << std::endl;
  std::cout << " Metric value  = " << bestValue          << std::endl;

  typedef itk::ResampleImageFilter<
                            MovingImageType,
                            FixedImageType >    ResampleFilterType;

  TransformType::Pointer finalTransform = TransformType::New();

  finalTransform->SetParameters( finalParameters );

  ResampleFilterType::Pointer resample = ResampleFilterType::New();

  resample->SetTransform( finalTransform );
  resample->SetInput( movingImageReader->GetOutput() );

  FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();

  resample->SetSize(    fixedImage->GetLargestPossibleRegion().GetSize() );
  resample->SetOutputOrigin(  fixedImage->GetOrigin() );
  resample->SetOutputSpacing( fixedImage->GetSpacing() );
  resample->SetDefaultPixelValue( 100 );

  typedef itk::Image< PixelType, Dimension > OutputImageType;

  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  WriterType::Pointer      writer =  WriterType::New();

  writer->SetFileName( argv[3] );

  writer->SetInput( resample->GetOutput() );
  writer->Update();

// Software Guide : EndCodeSnippet

  return 0;
}

<|endoftext|>


<commit_before>// $Id$
/*
 * Plotting macro for comparing offline- and HLT- ESD trees from
 * HLT-OFFLINE-GLOBAL-comparison.root produced using $ALICE_ROOT/HLT/QA/tasks/AliAnalysisTaskHLT.*
 *
 * Usage: aliroot drawGlobalESDHistograms.C'("HLT-OFFLINE-GLOBAL-comparison.root")'
 *
 * It saves the canvas with the output histograms in a png file.
 *
 * @ingroup alihlt_qa
 * @author Camilla.Stokkevag@student.uib.no, Kalliopi.Kanaki@ift.uib.no
 */

void drawGlobalESDHistograms(const char* filename="HLT-OFFLINE-GLOBAL-comparison.root"){

 gROOT->SetStyle("Plain");
 gStyle->SetPalette(1);
 gStyle->SetOptStat(10);
 gStyle->SetTitleX(gStyle->GetPadLeftMargin());

 TFile *f1 = TFile::Open(filename);
 if(!f1 || f1->IsZombie()) {
    printf("file %s does not exist or there is an error opening it\n", filename);
    return;
 }

 TList *l1 = (TList*)f1->Get("global_histograms");
 if(!l1){
    printf("No list %s contained in your input file\n", l1->GetName());
    return;
 }

//=================================================================//
//--------------- READ HISTOGRAMS ---------------------------------//
//=================================================================//

 TH1F *h1 = l1->FindObject("fNcluster_hlt");
 TH1F *h2 = l1->FindObject("fNcluster_off");
 h1->SetTitle("cluster distribution");
 h1->GetXaxis()->SetTitle("TPC clusters per track");
 h2->SetLineColor(2);
 if(h1->GetMaximum() >= h2->GetMaximum())  h2->SetMaximum(1.1*h1->GetMaximum());
 else h1->SetMaximum(1.1*h2->GetMaximum());

 TH1F *h3  = l1->FindObject("fDCA_hlt");
 TH1F *h4  = l1->FindObject("fDCA_off");
 TH1F *hSG = l1->FindObject("fDCA_hltSG");
 h3->SetTitle("DCA between track and vertex on XY plane");
 h3->GetXaxis()->SetTitle("DCAr (cm)");
 h4->SetLineColor(2);
 hSG->SetLineColor(kBlue);
 if(h3->GetMaximum() >= h4->GetMaximum()) h4->SetMaximum(1.1*h3->GetMaximum());
 else h3->SetMaximum(1.1*h4->GetMaximum());

 TH1F *h5 = l1->FindObject("fMult_hlt");
 TH1F *h6 = l1->FindObject("fMult_off");
 h5->SetTitle("track multiplicity");
 h6->SetLineColor(2);
 if(h5->GetMaximum() > h6->GetMaximum()) h6->SetMaximum(1.1*h5->GetMaximum());
 else h5->SetMaximum(1.1*h6->GetMaximum());

 TH1F *h7 = l1->FindObject("fCharge_hlt");
 TH1F *h8 = l1->FindObject("fCharge_off");
 h7->GetXaxis()->SetTitle("polarity");
 h7->SetTitle("charge distribution");
 h8->SetLineColor(2);
 if(h7->GetMaximum() > h8->GetMaximum()) h8->SetMaximum(1.1*h7->GetMaximum());
 else h7->SetMaximum(1.1*h8->GetMaximum());

 TH1F *h9  = l1->FindObject("fMomentum_hlt");
 TH1F *h10 = l1->FindObject("fMomentum_off");
 h9->GetXaxis()->SetTitle("p_{t} (GeV/c)");
 h9->SetTitle("transverse momentum");
 h10->SetLineColor(2);
 if(h9->GetMaximum() > h10->GetMaximum()) h10->SetMaximum(1.1*h9->GetMaximum());
 else h9->SetMaximum(1.1*h10->GetMaximum());

 TH1F *h11 = l1->FindObject("fEta_hlt");
 TH1F *h12 = l1->FindObject("fEta_off");
 h11->SetTitle("pseudorapidity");
 h11->GetXaxis()->SetTitle("#eta");
 h12->SetLineColor(2);
 if(h11->GetMaximum() > h12->GetMaximum()) h12->SetMaximum(1.1*h11->GetMaximum());
 else h11->SetMaximum(1.1*h12->GetMaximum());

 TH1F *h13 = l1->FindObject("fXvertex_hlt");
 TH1F *h14 = l1->FindObject("fXvertex_off");
 h13->GetXaxis()->SetTitle("x (cm)");
 h13->SetTitle("x of primary vertex");
 h14->SetLineColor(2);
 if(h13->GetMaximum() > h14->GetMaximum()) h14->SetMaximum(1.1*h13->GetMaximum());
 else h13->SetMaximum(1.1*h14->GetMaximum());

 TH1F *h15 = l1->FindObject("fYvertex_hlt");
 TH1F *h16 = l1->FindObject("fYvertex_off");
 h15->GetXaxis()->SetTitle("y (cm)");
 h15->SetTitle("y of primary vertex");
 h16->SetLineColor(2);
 if(h15->GetMaximum() > h16->GetMaximum()) h16->SetMaximum(1.1*h15->GetMaximum());
 else h15->SetMaximum(1.1*h16->GetMaximum());

 TH1F *h17 = l1->FindObject("fZvertex_hlt");
 TH1F *h18 = l1->FindObject("fZvertex_off");
 h17->GetXaxis()->SetTitle("z (cm)");
 h17->SetTitle("z of primary vertex");
 h18->SetLineColor(2);
 if(h17->GetMaximum() > h18->GetMaximum()) h18->SetMaximum(1.1*h17->GetMaximum());
 else h17->SetMaximum(1.1*h18->GetMaximum());

//  TH2F *h15 = l1->FindObject("fXYvertex_off");
//  h15->GetXaxis()->SetTitle("X (cm)");
//  h15->GetYaxis()->SetTitle("Y (cm)");
//  h15->SetTitle("XY primary vertex Offline");
//
//  TH2F *h16 = l1->FindObject("fXYvertex_hlt");
//  h16->GetXaxis()->SetTitle("X (cm)");
//  h16->GetYaxis()->SetTitle("Y (cm)");
//  h16->SetTitle("XY of primary vertex HLT");

 TLegend *leg1 = new TLegend(0.6,0.6,0.8,0.8);
 leg1->SetFillColor(10);
 leg1->SetLineColor(10);
 leg1->AddEntry(h1,"HLT", "l");
 leg1->AddEntry(h2,"OFF", "l");

//=================================================================//
//--------------------- DRAW HISTOGRAMS ---------------------------//
//=================================================================//

 TCanvas *c1 = new TCanvas("c1","HLT vs offline",1300,800);
 c1->Divide(3,3);

 c1->cd(1);
 h1->Draw();
 h2->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st1 = (TPaveStats*)h1->FindObject("stats");
 st1->SetLineColor(0);

 gPad->Update();
 TPaveStats *st2 = (TPaveStats*)h2->FindObject("stats");
 st2->SetY1NDC(st1->GetY1NDC()-0.05);
 st2->SetY2NDC(st1->GetY2NDC()-0.05);
 st2->SetLineColor(0);
 st2->SetTextColor(h2->GetLineColor());
 st2->SetFillStyle(0);
 st2->Draw();

 //======================

 c1->cd(2)->SetLogy();
 h3->Draw();
 h4->Draw("sames");
 hSG->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st3 = (TPaveStats*)h3->FindObject("stats");
 st3->SetLineColor(0);

 gPad->Update();
 TPaveStats *st4 = (TPaveStats*)h4->FindObject("stats");
 st4->SetY1NDC(st3->GetY1NDC()-0.05);
 st4->SetY2NDC(st3->GetY2NDC()-0.05);
 st4->SetLineColor(0);
 st4->SetTextColor(h4->GetLineColor());
 st4->SetFillStyle(0);
 st4->Draw();

 gPad->Update();
 TPaveStats *stSG = (TPaveStats*)hSG->FindObject("stats");
 stSG->SetY1NDC(st4->GetY1NDC()-0.05);
 stSG->SetY2NDC(st4->GetY2NDC()-0.05);
 stSG->SetLineColor(0);
 stSG->SetTextColor(hSG->GetLineColor());
 stSG->SetFillStyle(0);
 stSG->Draw();

//======================

 c1->cd(3);
 h5->Draw();
 h6->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st5 = (TPaveStats*)h5->FindObject("stats");
 st5->SetLineColor(0);

 gPad->Update();
 TPaveStats *st6 = (TPaveStats*)h6->FindObject("stats");
 st6->SetY1NDC(st5->GetY1NDC()-0.05);
 st6->SetY2NDC(st5->GetY2NDC()-0.05);
 st6->SetLineColor(0);
 st6->SetTextColor(h6->GetLineColor());
 st6->SetFillStyle(0);
 st6->Draw();

//======================

 c1->cd(4);
 h7->Draw();
 h8->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st7 = (TPaveStats*)h7->FindObject("stats");
 st7->SetLineColor(0);

 gPad->Update();
 TPaveStats *st8 = (TPaveStats*)h8->FindObject("stats");
 st8->SetY1NDC(st7->GetY1NDC()-0.05);
 st8->SetY2NDC(st7->GetY2NDC()-0.05);
 st8->SetLineColor(0);
 st8->SetTextColor(h8->GetLineColor());
 st8->SetFillStyle(0);
 st8->Draw();

//======================

 c1->cd(5)->SetLogy();
 h9->Draw();
 h10->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st9 = (TPaveStats*)h9->FindObject("stats");
 st9->SetLineColor(0);

 gPad->Update();
 TPaveStats *st10 = (TPaveStats*)h10->FindObject("stats");
 st10->SetY1NDC(st9->GetY1NDC()-0.05);
 st10->SetY2NDC(st9->GetY2NDC()-0.05);
 st10->SetLineColor(0);
 st10->SetTextColor(h10->GetLineColor());
 st10->SetFillStyle(0);
 st10->Draw();

//======================

 c1->cd(6);
 h11->Draw();
 h12->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st11 = (TPaveStats*)h11->FindObject("stats");
 st11->SetLineColor(0);

 gPad->Update();
 TPaveStats *st12 = (TPaveStats*)h12->FindObject("stats");
 st12->SetY1NDC(st11->GetY1NDC()-0.05);
 st12->SetY2NDC(st11->GetY2NDC()-0.05);
 st12->SetLineColor(0);
 st12->SetTextColor(h12->GetLineColor());
 st12->SetFillStyle(0);
 st12->Draw();

//======================

 c1->cd(7);
 h13->Draw();
 h14->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st13 = (TPaveStats*)h13->FindObject("stats");
 st13->SetLineColor(0);

 gPad->Update();
 TPaveStats *st14 = (TPaveStats*)h14->FindObject("stats");
 st14->SetY1NDC(st13->GetY1NDC()-0.05);
 st14->SetY2NDC(st13->GetY2NDC()-0.05);
 st14->SetLineColor(0);
 st14->SetTextColor(h14->GetLineColor());
 st14->SetFillStyle(0);
 st14->Draw();

//======================

 c1->cd(8);
 h15->Draw();
 h16->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st15 = (TPaveStats*)h15->FindObject("stats");
 st15->SetLineColor(0);

 gPad->Update();
 TPaveStats *st16 = (TPaveStats*)h16->FindObject("stats");
 st16->SetY1NDC(st15->GetY1NDC()-0.05);
 st16->SetY2NDC(st15->GetY2NDC()-0.05);
 st16->SetLineColor(0);
 st16->SetTextColor(h16->GetLineColor());
 st16->SetFillStyle(0);
 st16->Draw();

//======================

 c1->cd(9);
 h17->Draw();
 h18->Draw("sames");
 leg1->Draw("same");

 gPad->Update();
 TPaveStats *st17 = (TPaveStats*)h17->FindObject("stats");
 st17->SetLineColor(0);

 gPad->Update();
 TPaveStats *st18 = (TPaveStats*)h18->FindObject("stats");
 st18->SetY1NDC(st17->GetY1NDC()-0.05);
 st18->SetY2NDC(st17->GetY2NDC()-0.05);
 st18->SetLineColor(0);
 st18->SetTextColor(h18->GetLineColor());
 st18->SetFillStyle(0);
 st18->Draw();

//======================

 c1->SaveAs("HLT-offline.png");
}
<commit_msg>- added functions to replace big parts of the macro that were being repeated - removed the DCA plot read from the HLTesdTree - saved a ROOT file in addition to the png output of the macro - can be run in compiled mode too<commit_after>// $Id$
/*
 * Plotting macro for comparing offline- and HLT- ESD trees from
 * HLT-OFFLINE-GLOBAL-comparison.root produced using $ALICE_ROOT/HLT/QA/tasks/AliAnalysisTaskHLT.*
 *
 * Usage: aliroot drawGlobalESDHistograms.C'("HLT-OFFLINE-GLOBAL-comparison.root")'
 *
 * or aliroot drawGlobalESDHistograms.C++ in compiled mode
 *
 * It saves the canvas with the output histograms in a png file.
 *
 * @ingroup alihlt_qa
 * @author Camilla.Stokkevag@student.uib.no, Kalliopi.Kanaki@ift.uib.no
 */

#if !defined(__CINT__) || defined(__MAKECINT__)
#include "TSystem.h"
#include "TROOT.h"
#include "TFile.h"
#include "TString.h"
#include "TList.h"
#include "TCanvas.h"
#include "TText.h"
#include "TPaveText.h"
#include "TPaveStats.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TLegend.h"
#include "TStyle.h"
#include "TPad.h"
#include <iostream>
#include <cstdlib>
using std::endl;
#endif

// --------------------- forward declerations --------------//

void printStats(TH1F *h1, TH1F *h2);
void plot(TH1F *h1, TH1F *h2);

//==========================================================//

void drawGlobalESDHistograms(const char* filename="HLT-OFFLINE-GLOBAL-comparison.root"){

 gROOT->SetStyle("Plain");
 gStyle->SetPalette(1);
 gStyle->SetOptStat("emr");
 gStyle->SetTitleX(gStyle->GetPadLeftMargin());

 TFile *f1 = TFile::Open(filename);
 if(!f1 || f1->IsZombie()) {
    printf("file %s does not exist or there is an error opening it\n", filename);
    return;
 }

 TList *l1 = (TList*)f1->Get("global_histograms");
 if(!l1){
    printf("No list %s contained in your input file\n", l1->GetName());
    return;
 }

 TCanvas *c1 = new TCanvas("c1","HLT vs. offline",1200,700);
 c1->Divide(3,3);
 TH1F *h1 = NULL;
 TH1F *h2 = NULL;

 h1 = (TH1F*)l1->FindObject("fNcluster_hlt"); if(!h1) { printf("Empty histogram fNcluster_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fNcluster_off"); if(!h2) { printf("Empty histogram fNcluster_off\n"); return; }
 h1->SetTitle("TPC cluster distribution");
 h1->GetXaxis()->SetTitle("TPC clusters per track");

 TLegend *leg1 = new TLegend(0.7,0.6,0.88,0.77);
 leg1->SetFillColor(10);
 leg1->SetLineColor(10);
 leg1->AddEntry(h1,"HLT", "l");
 leg1->AddEntry(h2,"OFF", "l");

 c1->cd(1);
 plot(h1,h2);
 leg1->Draw("same");

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fDCA_hlt"); if(!h1) { printf("Empty histogram fDCA_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fDCA_off"); if(!h2) { printf("Empty histogram fDCA_off\n"); return; }
 h1->SetTitle("DCA between track and vertex on XY plane");
 h1->SetXTitle("DCAr (cm)");

 c1->cd(2);
 plot(h1,h2);

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fMult_hlt"); if(!h1) { printf("Empty histogram fMult_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fMult_off"); if(!h2) { printf("Empty histogram fMult_off\n"); return; }
 h1->SetTitle("track multiplicity");

 c1->cd(3);
 plot(h1,h2);

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fCharge_hlt"); if(!h1) { printf("Empty histogram fCharge_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fCharge_off"); if(!h2) { printf("Empty histogram fCharge_off\n"); return; }
 h1->SetXTitle("polarity");
 h1->SetTitle("charge distribution");

 c1->cd(4);
 plot(h1,h2);

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fMomentum_hlt"); if(!h1) { printf("Empty histogram fMomentum_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fMomentum_off"); if(!h2) { printf("Empty histogram fMomentum_off\n"); return; }
 h1->SetXTitle("p_{t} (GeV/c)");
 h1->SetTitle("transverse momentum");

 c1->cd(5);
 plot(h1,h2);

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fEta_hlt"); if(!h1) { printf("Empty histogram fEta_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fEta_off"); if(!h2) { printf("Empty histogram fEta_off\n"); return; }
 h1->SetTitle("pseudorapidity");
 h1->SetXTitle("#eta");

 c1->cd(6);
 plot(h1,h2);

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fXvertex_hlt"); if(!h1) { printf("Empty histogram fXvertex_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fXvertex_off"); if(!h2) { printf("Empty histogram fXvertex_off\n"); return; }
 h1->SetXTitle("x (cm)");
 h1->SetTitle("x of primary vertex");

 c1->cd(7);
 plot(h1,h2);

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fYvertex_hlt"); if(!h1) { printf("Empty histogram fYvertex_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fYvertex_off"); if(!h2) { printf("Empty histogram fYvertex_off\n"); return; }
 h1->SetXTitle("y (cm)");
 h1->SetTitle("y of primary vertex");

 c1->cd(8);
 plot(h1,h2);

//-------------------------------------------------

 h1 = (TH1F*)l1->FindObject("fZvertex_hlt"); if(!h1) { printf("Empty histogram fZvertex_hlt\n"); return; }
 h2 = (TH1F*)l1->FindObject("fZvertex_off"); if(!h2) { printf("Empty histogram fZvertex_off\n"); return; }
 h1->SetXTitle("z (cm)");
 h1->SetTitle("z of primary vertex");

 c1->cd(9);
 plot(h1,h2);

//-------------------------------------------------

 c1->SaveAs("HLT-offline.png");
 c1->SaveAs("HLT-offline.root");
 return;
}

void printStats(TH1F* h1, TH1F* h2){

  gPad->Update();
  TPaveStats *st1 = (TPaveStats*)h1->FindObject("stats"); if(!st1) { printf("TPaveStats st1 is 0x0\n"); return; }
  st1->SetLineColor(0);

  gPad->Update();
  TPaveStats *st2 = (TPaveStats*)h2->FindObject("stats"); if(!st2) { printf("TPaveStats st2 is 0x0\n"); return; }
  st2->SetY2NDC(st1->GetY1NDC()-0.05);
  st2->SetY1NDC(st2->GetY2NDC()-TMath::Abs(st1->GetY1NDC()-st1->GetY2NDC()));
  st2->SetLineColor(0);
  st2->SetTextColor(h2->GetLineColor());
  st2->SetFillStyle(0);
  st2->Draw();
  return;
}

void plot(TH1F *h1, TH1F *h2){
  //Y axis
  if(h1->GetMaximum() > h2->GetMaximum()) h2->SetMaximum(1.1*h1->GetMaximum());
  else h1->SetMaximum(1.1*h2->GetMaximum());

  h1->SetMinimum(0);
  h2->SetMinimum(0);
  h2->SetLineColor(2);

  // X axis
  double xmin, xmax;
  if(h1->GetBinLowEdge(1) > h2->GetBinLowEdge(1)) xmin = h1->GetBinLowEdge(1);
  else xmin = h2->GetBinLowEdge(1);
  if(h1->GetBinLowEdge(h1->GetNbinsX()+1) > h2->GetBinLowEdge(h1->GetNbinsX()+1)) xmax = h1->GetBinLowEdge(h1->GetNbinsX()+1);
  else xmax = h2->GetBinLowEdge(h2->GetNbinsX()+1);

  h2->SetAxisRange(xmin, xmax, "X");
  printStats(h1,h2);

  h1->Draw();
  h2->Draw("sames");
  return;
}
<|endoftext|>


<commit_before><commit_msg>Fixing default argument for Q/pt-shift switch also in jet task<commit_after><|endoftext|>


<commit_before>AliAnalysisTaskSEImproveITS *AddTaskImproveITS(Bool_t isRunInVertexing=kFALSE, // set to kTRUE to run during AODvertexingHF creation
					       const char *resfileCurURI="$ALICE_ROOT/PWGHF/vertexingHF/macros/ITSgraphs_Current.root",
                                               const char *resfileUpgURI="$ALICE_ROOT/PWGHF/vertexingHF/macros/ITSgraphs_NewAll-X0.3-Res4um.root",
					       Int_t ndebug=0) {
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddAliAnalysisTaskSEImproveITS", "No analysis manager to connect to.");
    return 0;
  }

  AliAnalysisTaskSEImproveITS *task
    =new AliAnalysisTaskSEImproveITS("ITSImprover",
                                     resfileCurURI,
                                     resfileUpgURI,
                                     isRunInVertexing,
                                     ndebug);
  mgr->AddTask(task);

  TString outputFileName=AliAnalysisManager::GetCommonFileName();
  outputFileName+=":ITSImprover";
  AliAnalysisDataContainer *coutput
     =mgr->CreateContainer("debug",
                           TNtuple::Class(),
                           AliAnalysisManager::kOutputContainer,
                           outputFileName);

  mgr->ConnectInput (task,0,mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task,1,coutput);

  return task;
}

<commit_msg>changed path to resolution files<commit_after>AliAnalysisTaskSEImproveITS *AddTaskImproveITS(Bool_t isRunInVertexing=kFALSE, // set to kTRUE to run during AODvertexingHF creation
					       const char *resfileCurURI="$ALICE_ROOT/PWGHF/vertexingHF/upgrade/ITSgraphs_Current.root",
                                               const char *resfileUpgURI="$ALICE_ROOT/PWGHF/vertexingHF/upgrade/ITSgraphs_NewAll-X0.3-Res4um.root",
					       Int_t ndebug=0) {
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddAliAnalysisTaskSEImproveITS", "No analysis manager to connect to.");
    return 0;
  }

  AliAnalysisTaskSEImproveITS *task
    =new AliAnalysisTaskSEImproveITS("ITSImprover",
                                     resfileCurURI,
                                     resfileUpgURI,
                                     isRunInVertexing,
                                     ndebug);
  mgr->AddTask(task);

  TString outputFileName=AliAnalysisManager::GetCommonFileName();
  outputFileName+=":ITSImprover";
  AliAnalysisDataContainer *coutput
     =mgr->CreateContainer("debug",
                           TNtuple::Class(),
                           AliAnalysisManager::kOutputContainer,
                           outputFileName);

  mgr->ConnectInput (task,0,mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task,1,coutput);

  return task;
}

<|endoftext|>


<commit_before>AliEmcalJetTask* AddTaskEmcalJet(
  const char *nTracks                        = "usedefault",
  const char *nClusters                      = "usedefault",
  const AliJetContainer::EJetAlgo_t jetAlgo  = AliJetContainer::antikt_algorithm,
  const Double_t radius                      = 0.4,
  const AliJetContainer::EJetType_t jetType  = AliJetContainer::kFullJet,
  const Double_t minTrPt                     = 0.15,
  const Double_t minClPt                     = 0.30,
  const Double_t ghostArea                   = 0.005,
  const AliJetContainer::ERecoScheme_t reco  = AliJetContainer::pt_scheme,
  const char *tag                            = "Jet",
  const Double_t minJetPt                    = 0.,
  const Bool_t lockTask                      = kTRUE,
  const Bool_t bFillGhosts                   = kFALSE
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskEmcalJet", "No analysis manager to connect to.");
    return 0;
  }

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

  enum EDataType_t {
    kUnknown,
    kESD,
    kAOD,
    kMCgen
  };

  TString trackName(nTracks);
  TString clusName(nClusters);

  EDataType_t dataType = kUnknown;
  if (handler->InheritsFrom("AliESDInputHandler")) {
    dataType = kESD;
  }
  else if (handler->InheritsFrom("AliAODInputHandler")) {
    dataType = kAOD;
  } else if (handler->InheritsFrom("AliMCGenHandler")) {
    dataType = kMCgen;
  }

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

  if (trackName == "usedefault") {
    if (dataType == kESD) {
      trackName = "Tracks";
    }
    else if (dataType == kAOD) {
      trackName = "tracks";
    }
    else if (dataType == kMCgen) {
      trackName = "mcparticles";
    }
  }

  if (clusName == "usedefault") {
    if (dataType == kESD) {
      clusName = "CaloClusters";
    }
    else if (dataType == kAOD) {
      clusName = "caloClusters";
    }
    else {
      clusName = "";
    }
  }

  AliParticleContainer* partCont = 0;
  if (trackName == "mcparticles") {
    AliMCParticleContainer* mcpartCont = new AliMCParticleContainer(trackName);
    partCont = mcpartCont;
  }
  else if (trackName == "tracks" || trackName == "Tracks") {
    AliTrackContainer* trackCont = new AliTrackContainer(trackName);
    partCont = trackCont;
  }
  else if (!trackName.IsNull()) {
    partCont = new AliParticleContainer(trackName);
  }
  if (partCont) partCont->SetParticlePtCut(minTrPt);

  AliClusterContainer* clusCont = 0;
  if (!clusName.IsNull()) {
    clusCont = new AliClusterContainer(clusName);
    clusCont->SetClusECut(0.);
    clusCont->SetClusPtCut(0.);
    clusCont->SetClusHadCorrEnergyCut(minClPt);
    clusCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
  }

  switch (jetType) {
  case AliJetContainer::kChargedJet:
    if (partCont) partCont->SetCharge(AliParticleContainer::kCharged);
    break;
  case AliJetContainer::kNeutralJet:
    if (partCont) partCont->SetCharge(AliParticleContainer::kNeutral);
    break;
  default:
    break;
  }

  TString name = AliJetContainer::GenerateJetName(jetType, jetAlgo, reco, radius, partCont, clusCont, tag);

  Printf("Jet task name: %s", name.Data());

  AliEmcalJetTask* mgrTask = static_cast<AliEmcalJetTask *>(mgr->GetTask(name.Data()));
  if (mgrTask) return mgrTask;

  AliEmcalJetTask* jetTask = new AliEmcalJetTask(name);
  jetTask->SetJetType(jetType);
  jetTask->SetJetAlgo(jetAlgo);
  jetTask->SetRecombScheme(reco);
  jetTask->SetRadius(radius);
  if (partCont) jetTask->AdoptParticleContainer(partCont);
  if (clusCont) jetTask->AdoptClusterContainer(clusCont);
  jetTask->SetJetsName(tag);
  jetTask->SetMinJetPt(minJetPt);
  jetTask->SetGhostArea(ghostArea);

  if (bFillGhosts) jetTask->SetFillGhost();
  if (lockTask) jetTask->SetLocked();

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

  mgr->AddTask(jetTask);

  // Create containers for input/output
  AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
  mgr->ConnectInput(jetTask, 0, cinput);

  TObjArray* cnt = mgr->GetContainers();

  return jetTask;
}
<commit_msg>equire only Contains instead of == for matching particle containers<commit_after>AliEmcalJetTask* AddTaskEmcalJet(
  const char *nTracks                        = "usedefault",
  const char *nClusters                      = "usedefault",
  const AliJetContainer::EJetAlgo_t jetAlgo  = AliJetContainer::antikt_algorithm,
  const Double_t radius                      = 0.4,
  const AliJetContainer::EJetType_t jetType  = AliJetContainer::kFullJet,
  const Double_t minTrPt                     = 0.15,
  const Double_t minClPt                     = 0.30,
  const Double_t ghostArea                   = 0.005,
  const AliJetContainer::ERecoScheme_t reco  = AliJetContainer::pt_scheme,
  const char *tag                            = "Jet",
  const Double_t minJetPt                    = 0.,
  const Bool_t lockTask                      = kTRUE,
  const Bool_t bFillGhosts                   = kFALSE
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskEmcalJet", "No analysis manager to connect to.");
    return 0;
  }

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

  enum EDataType_t {
    kUnknown,
    kESD,
    kAOD,
    kMCgen
  };

  TString trackName(nTracks);
  TString clusName(nClusters);

  EDataType_t dataType = kUnknown;
  if (handler->InheritsFrom("AliESDInputHandler")) {
    dataType = kESD;
  }
  else if (handler->InheritsFrom("AliAODInputHandler")) {
    dataType = kAOD;
  } else if (handler->InheritsFrom("AliMCGenHandler")) {
    dataType = kMCgen;
  }

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

  if (trackName == "usedefault") {
    if (dataType == kESD) {
      trackName = "Tracks";
    }
    else if (dataType == kAOD) {
      trackName = "tracks";
    }
    else if (dataType == kMCgen) {
      trackName = "mcparticles";
    }
  }

  if (clusName == "usedefault") {
    if (dataType == kESD) {
      clusName = "CaloClusters";
    }
    else if (dataType == kAOD) {
      clusName = "caloClusters";
    }
    else {
      clusName = "";
    }
  }

  AliParticleContainer* partCont = 0;
  if (trackName.Contains("mcparticles")) {  // must be contains in order to allow for non-standard particle containers
    AliMCParticleContainer* mcpartCont = new AliMCParticleContainer(trackName);
    partCont = mcpartCont;
  }
  else if (trackName == "tracks" || trackName == "Tracks") {
    AliTrackContainer* trackCont = new AliTrackContainer(trackName);
    partCont = trackCont;
  }
  else if (!trackName.IsNull()) {
    partCont = new AliParticleContainer(trackName);
  }
  if (partCont) partCont->SetParticlePtCut(minTrPt);

  AliClusterContainer* clusCont = 0;
  if (!clusName.IsNull()) {
    clusCont = new AliClusterContainer(clusName);
    clusCont->SetClusECut(0.);
    clusCont->SetClusPtCut(0.);
    clusCont->SetClusHadCorrEnergyCut(minClPt);
    clusCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
  }

  switch (jetType) {
  case AliJetContainer::kChargedJet:
    if (partCont) partCont->SetCharge(AliParticleContainer::kCharged);
    break;
  case AliJetContainer::kNeutralJet:
    if (partCont) partCont->SetCharge(AliParticleContainer::kNeutral);
    break;
  default:
    break;
  }

  TString name = AliJetContainer::GenerateJetName(jetType, jetAlgo, reco, radius, partCont, clusCont, tag);

  Printf("Jet task name: %s", name.Data());

  AliEmcalJetTask* mgrTask = static_cast<AliEmcalJetTask *>(mgr->GetTask(name.Data()));
  if (mgrTask) return mgrTask;

  AliEmcalJetTask* jetTask = new AliEmcalJetTask(name);
  jetTask->SetJetType(jetType);
  jetTask->SetJetAlgo(jetAlgo);
  jetTask->SetRecombScheme(reco);
  jetTask->SetRadius(radius);
  if (partCont) jetTask->AdoptParticleContainer(partCont);
  if (clusCont) jetTask->AdoptClusterContainer(clusCont);
  jetTask->SetJetsName(tag);
  jetTask->SetMinJetPt(minJetPt);
  jetTask->SetGhostArea(ghostArea);

  if (bFillGhosts) jetTask->SetFillGhost();
  if (lockTask) jetTask->SetLocked();

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

  mgr->AddTask(jetTask);

  // Create containers for input/output
  AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
  mgr->ConnectInput(jetTask, 0, cinput);

  TObjArray* cnt = mgr->GetContainers();

  return jetTask;
}
<|endoftext|>


<commit_before>#include "CameraBase.h"
#include "sys/SysControl.h"
#include "HMDWrapper.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

#define CAMERA_BASE_CLAMP            89.9f

CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR)
{
	m_nFlush = 0;
    m_vPosition = Vec3_zero;
    m_fPhiAngle = 0.0f;
    m_fThetaAngle = 0.0f;
    m_pLastPlayer = NULL;
	m_nEnabelMouse = 1;
    SetRadius(1.0f);

	SetMinThetaAngle(-90.0f);
    SetMaxThetaAngle(90.0f);
    SetTurning(90.0f);

    SetViewDirection(vec3(0.0f,1.0f,0.0f));

    SetEnabled(0);
    SetHMDEnabled(1);
}

CCameraBase::~CCameraBase()
{
    Leave();
}

void CCameraBase::SetEnabled(int nEnable)
{
	if(nEnable)
	{
		m_pLastPlayer =  g_Engine.pGame->GetPlayer();
        CPlayer::SetEnabled(nEnable);
		g_Engine.pGame->SetPlayer(this);

	}
	else
	{
		if (m_pLastPlayer)
        {
            g_Engine.pGame->SetPlayer(m_pLastPlayer);
            CPlayer::SetEnabled(nEnable);
        }
	}
}

int CCameraBase::IsEnabled() const
{
    return CPlayer::IsEnabled();
}
void CCameraBase::SetHMDEnabled(int nEnable)
{
    m_nHMDEnable = nEnable;
}

int CCameraBase::IsHMDEnabled() const
{
    return m_nHMDEnable;
}

void CCameraBase::SetRadius(float r)
{
    m_fRadius = r;
}

float CCameraBase::GetRadius() const
{
    return m_fRadius;
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/

/*
 */<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "CameraBase.h"
#include "sys/SysControl.h"
#include "HMDWrapper.h"
#include "Engine.h"
#include "Game.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

#define CAMERA_BASE_CLAMP            89.9f

CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR)
{
	m_nFlush = 0;
    m_vPosition = Vec3_zero;
    m_fPhiAngle = 0.0f;
    m_fThetaAngle = 0.0f;
    m_pLastPlayer = NULL;
	m_nEnabelMouse = 1;
    SetRadius(1.0f);

	SetMinThetaAngle(-90.0f);
    SetMaxThetaAngle(90.0f);
    SetTurning(90.0f);

    SetViewDirection(vec3(0.0f,1.0f,0.0f));

    SetEnabled(0);
    SetHMDEnabled(1);
}

CCameraBase::~CCameraBase()
{
    Leave();
}

void CCameraBase::SetEnabled(int nEnable)
{
	if(nEnable)
	{
		m_pLastPlayer =  g_Engine.pGame->GetPlayer();
        CPlayer::SetEnabled(nEnable);
		g_Engine.pGame->SetPlayer(this);

	}
	else
	{
		if (m_pLastPlayer)
        {
            g_Engine.pGame->SetPlayer(m_pLastPlayer);
            CPlayer::SetEnabled(nEnable);
        }
	}
}

int CCameraBase::IsEnabled() const
{
    return CPlayer::IsEnabled();
}
void CCameraBase::SetHMDEnabled(int nEnable)
{
    m_nHMDEnable = nEnable;
}

int CCameraBase::IsHMDEnabled() const
{
    return m_nHMDEnable;
}

void CCameraBase::SetRadius(float r)
{
    m_fRadius = r;
}

float CCameraBase::GetRadius() const
{
    return m_fRadius;
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/

/*
 */<|endoftext|>


<commit_before>// -------------------------------------------------------------------
//
// hot_backup_test.cc
//
// Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.  You may obtain
// a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------

#include <fcntl.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "util/testharness.h"
#include "util/testutil.h"

#include "db/dbformat.h"
#include "db/db_impl.h"
#include "util/hot_backup.h"

/**
 * Execution routine
 */
int main(int argc, char** argv)
{
    int ret_val;

    ret_val=leveldb::test::RunAllTests();

    return(ret_val);
}   // main

namespace leveldb {

/**
 * Wrapper class for tests.  Holds working variables
 * and helper functions.
 */
class HotBackupTester : public HotBackup
{
public:
    std::string m_DBName;
    std::string m_Trigger;

    HotBackupTester()
    {
        m_DBName = test::TmpDir() + "/hot_backup";
        m_Trigger = test::TmpDir() + "/trigger";
    };

    ~HotBackupTester()
    {
    };

    virtual const char * GetTriggerPath() {return(m_Trigger.c_str());};

};  // class HotBackupTester

/**
 * Initial code used the existance of /etc/riak/hot_backup file
 *  as flag to start a backup.
 */
TEST(HotBackupTester, FileTriggerTest)
{
    char * dup_path, *path;
    int ret_val;
    bool ret_flag;
    uint64_t perf_before, perf_after;

    perf_before=gPerfCounters->Value(ePerfSyslogWrite);

    // cleanup anything existing, likely fails
    ///  hmm, should there be a way to move this trigger
    ///  to a "safe" area like /tmp?
    unlink(GetTriggerPath());

    // does parent path exist?
    //  bypass test if it does not ... Travis CI and
    //  other users might not be able to access /etc/riak
    dup_path=strdup(GetTriggerPath());
    path=dirname(dup_path);
    ret_val=access(path, R_OK | W_OK);
    ASSERT_TRUE(-1!=ret_val);

    // is a trigger seen (hope not)
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // make a trigger
    ret_val=open(GetTriggerPath(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    ASSERT_TRUE(-1!=ret_val);
    close(ret_val);

    // test the trigger
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(ret_flag);

    // pretend to be back process
    /// schedule twice
    HotBackup::HotBackupScheduled();
    HotBackup::HotBackupScheduled();

    // trigger still there?
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(ret_flag);

    // release one, trigger goes away
    HotBackup::HotBackupFinished();
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // did our simulation create a syslog entry?
    //  (bonus if you manually check /var/log/syslog for actual entries)
    perf_after=gPerfCounters->Value(ePerfSyslogWrite) - perf_before;
    ASSERT_TRUE( 1==perf_after );

    // clean up second count.
    HotBackup::HotBackupFinished();

    free(dup_path);
    dup_path=NULL;

}   // FileTriggerTest

}  // namespace leveldb

<commit_msg>add DirectoryRotationTest<commit_after>// -------------------------------------------------------------------
//
// hot_backup_test.cc
//
// Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.  You may obtain
// a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------

#include <fcntl.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "leveldb/db.h"
#include "util/testharness.h"
#include "util/testutil.h"

#include "db/dbformat.h"
#include "db/db_impl.h"
#include "db/filename.h"
#include "util/hot_backup.h"

/**
 * Execution routine
 */
int main(int argc, char** argv)
{
    int ret_val;

    ret_val=leveldb::test::RunAllTests();

    return(ret_val);
}   // main

namespace leveldb {

/**
 * Wrapper class for tests.  Holds working variables
 * and helper functions.
 */
class HotBackupTester : public HotBackup
{
public:
    std::string m_DBName;
    std::string m_Trigger;

    HotBackupTester()
    {
        m_DBName = test::TmpDir() + "/hot_backup";
        m_Trigger = test::TmpDir() + "/trigger";
    };

    ~HotBackupTester()
    {

    };

    virtual const char * GetTriggerPath() {return(m_Trigger.c_str());};

    void ClearAllBackups(
        Options & InOptions)
    {
        int loop;
        Options options;

        // clear old if exists
        for (loop=0; loop<=config::kNumBackups; ++loop)
        {
            options=InOptions;

            SetBackupPaths(options, loop);
            DestroyDB("", options);
        }   // if

        options.tiered_slow_level=4;
        options.tiered_fast_prefix=m_DBName + "/fast";
        options.tiered_slow_prefix=m_DBName + "/slow";
        DestroyDB("", options);
    }   // ClearAllBackups

};  // class HotBackupTester

/**
 * Initial code used the existance of /etc/riak/hot_backup file
 *  as flag to start a backup.
 */
TEST(HotBackupTester, FileTriggerTest)
{
    char * dup_path, *path;
    int ret_val;
    bool ret_flag;
    uint64_t perf_before, perf_after;

    perf_before=gPerfCounters->Value(ePerfSyslogWrite);

    // cleanup anything existing, likely fails
    ///  hmm, should there be a way to move this trigger
    ///  to a "safe" area like /tmp?
    unlink(GetTriggerPath());

    // does parent path exist?
    //  bypass test if it does not ... Travis CI and
    //  other users might not be able to access /etc/riak
    dup_path=strdup(GetTriggerPath());
    path=dirname(dup_path);
    ret_val=access(path, R_OK | W_OK);
    ASSERT_TRUE(-1!=ret_val);

    // is a trigger seen (hope not)
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // make a trigger
    ret_val=open(GetTriggerPath(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    ASSERT_TRUE(-1!=ret_val);
    close(ret_val);

    // test the trigger
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(ret_flag);

    // pretend to be back process
    /// schedule twice
    HotBackup::HotBackupScheduled();
    HotBackup::HotBackupScheduled();

    // trigger still there?
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(ret_flag);

    // release one, trigger goes away
    HotBackup::HotBackupFinished();
    ret_flag=HotBackup::IsTriggerSet();
    ASSERT_TRUE(!ret_flag);

    // did our simulation create a syslog entry?
    //  (bonus if you manually check /var/log/syslog for actual entries)
    perf_after=gPerfCounters->Value(ePerfSyslogWrite) - perf_before;
    ASSERT_TRUE( 1==perf_after );

    // clean up second count.
    HotBackupFinished();

    // clean up
    free(dup_path);
    dup_path=NULL;

}   // FileTriggerTest

/**
 * Verify that backup directories rotate
 */
TEST(HotBackupTester, DirectoryRotationTest)
{
    int ret_val, loop, inner_loop, offset, file_num;
    Options options, backup_options, inner_options;
    bool ret_flag, should_find, did_find;
    std::string table_file, backup_name;

    options.tiered_slow_level=4;
    options.tiered_fast_prefix=m_DBName + "/fast";
    options.tiered_slow_prefix=m_DBName + "/slow";
    ClearAllBackups(options);

    // manually create database directories
    ret_val=mkdir(m_DBName.c_str(), 0777);
    ret_val=mkdir(options.tiered_fast_prefix.c_str(), 0777);
    ASSERT_TRUE(0==ret_val);
    ret_val=mkdir(options.tiered_slow_prefix.c_str(), 0777);
    ASSERT_TRUE(0==ret_val);
    MakeLevelDirectories(Env::Default(), options);

    backup_options=options;
    SetBackupPaths(backup_options, 0);

    // this loop goes one higher than permitted retention
    //  to validate deletion of oldest
    for (loop=0; loop<=config::kNumBackups; ++loop)
    {
        // rotate directories
        ret_flag=PrepareDirectories(options);
        ASSERT_TRUE(ret_flag);

        // these files are to "mark" the backups, not
        //  pretending this is a true file link
        // make a file in fast tier ... 10 + backup iteration
        table_file=TableFileName(backup_options, 10+loop, 1);
        ret_val=open(table_file.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
        ASSERT_TRUE(-1!=ret_val);
        close(ret_val);

        // make a file in slow tier ... 20 + backup iteration
        table_file=TableFileName(backup_options, 20+loop, 5);
        ret_val=open(table_file.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
        ASSERT_TRUE(-1!=ret_val);
        close(ret_val);

        // test files
        for (inner_loop=config::kNumBackups+1; 0<=inner_loop; --inner_loop)
        {
            offset=(loop<config::kNumBackups) ? 0 : loop-config::kNumBackups +1;
            should_find=(inner_loop<=loop) && (offset<=inner_loop);

            inner_options=options;
            SetBackupPaths(inner_options, inner_loop-offset);

            file_num=loop - inner_loop + offset;

            table_file=TableFileName(inner_options, 10+file_num, 1);
            ret_val=access(table_file.c_str(), F_OK);
            ASSERT_TRUE( (0==ret_val) == should_find);

            table_file=TableFileName(inner_options, 20+file_num, 5);
            ret_val=access(table_file.c_str(), F_OK);
            ASSERT_TRUE( (0==ret_val) == should_find);
        }   // for
    }   // for

    ClearAllBackups(options);

    // clean up
    ret_val=rmdir(m_DBName.c_str());
    ASSERT_TRUE(0==ret_val);

}   // DirectoryRotationTest

}  // namespace leveldb

<|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include "Instructions.hpp"

void run_part_one() {
    std::string line;
    InstructionRunner runner;
    std::array<int,REGISTER_COUNT> registers = {0,0};
    while(std::getline(std::cin,line)) {
        runner.add_instruction(parse_instruction(line));
    }
    runner.run(registers);
    std::cout<<registers[1]<<std::endl;
}
void run_part_two() {
}

int main(int argc, char* argv[]) {
    if (argc > 1) {
        if (std::string(argv[1]) == "--part_two") {
            run_part_two();
        } else {
            std::cout << "Usage: day23 [--part_two]" << std::endl;
            return -1;
        }
    } else {
        run_part_one();
    }
}
<commit_msg>added runtime code for day 23 part two<commit_after>#include <iostream>
#include <string>

#include "Instructions.hpp"

void run_part_one() {
    std::string line;
    InstructionRunner runner;
    std::array<int,REGISTER_COUNT> registers = {0,0};
    while(std::getline(std::cin,line)) {
        runner.add_instruction(parse_instruction(line));
    }
    runner.run(registers);
    std::cout<<registers[1]<<std::endl;
}
void run_part_two() {
    std::string line;
    InstructionRunner runner;
    std::array<int,REGISTER_COUNT> registers = {1,0};
    while(std::getline(std::cin,line)) {
        runner.add_instruction(parse_instruction(line));
    }
    runner.run(registers);
    std::cout<<registers[1]<<std::endl;
}

int main(int argc, char* argv[]) {
    if (argc > 1) {
        if (std::string(argv[1]) == "--part_two") {
            run_part_two();
        } else {
            std::cout << "Usage: day23 [--part_two]" << std::endl;
            return -1;
        }
    } else {
        run_part_one();
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "utilities/ttl/db_ttl.h"
#include "include/utilities/utility_db.h"
#include "db/filename.h"
#include "util/coding.h"
#include "include/leveldb/env.h"
#include "include/leveldb/iterator.h"

namespace leveldb {

class TtlIterator : public Iterator {

 public:
  TtlIterator(Iterator* iter, int32_t ts_len)
    : iter_(iter),
      ts_len_(ts_len) {
    assert(iter_);
  }

  ~TtlIterator() {
    delete iter_;
  }

  bool Valid() const {
    return iter_->Valid();
  }

  void SeekToFirst() {
    iter_->SeekToFirst();
  }

  void SeekToLast() {
    iter_->SeekToLast();
  }

  void Seek(const Slice& target) {
    iter_->Seek(target);
  }

  void Next() {
    iter_->Next();
  }

  void Prev() {
    iter_->Prev();
  }

  Slice key() const {
    return iter_->key();
  }

  Slice value() const {
    assert(iter_->value().size() >= (unsigned)ts_len_);
    return std::string(iter_->value().data(), iter_->value().size() - ts_len_);
  }

  Status status() const {
    return iter_->status();
  }

 private:
  Iterator* iter_;
  int32_t ts_len_;
};

// Open the db inside DBWithTTL because options needs pointer to its ttl
DBWithTTL::DBWithTTL(const int32_t ttl,
                     const Options& options,
                     const std::string& dbname,
                     Status& st)
    : ttl_(ttl) {
  assert(options.CompactionFilter == nullptr);
  Options options_to_open = options;
  options_to_open.compaction_filter_args = &ttl_;
  options_to_open.CompactionFilter = DeleteByTS;
  st = DB::Open(options_to_open, dbname, &db_);
}

DBWithTTL::~DBWithTTL() {
  delete db_;
}

Status UtilityDB::OpenTtlDB(
    const Options& options,
    const std::string& dbname,
    DB** dbptr,
    int32_t ttl) {
  Status st;
  *dbptr = new DBWithTTL(ttl, options, dbname, st);
  if (!st.ok()) {
    delete dbptr;
  }
  return st;
}

// returns true(i.e. key-value to be deleted) if its TS has expired based on ttl
bool DBWithTTL::DeleteByTS(
    void* args,
    int level,
    const Slice& key,
    const Slice& old_val,
    std::string* new_val,
    bool* value_changed) {
  return IsStale(old_val, *(int32_t*)args);
}

// Gives back the current time
Status DBWithTTL::GetCurrentTime(int32_t& curtime) {
  return Env::Default()->GetCurrentTime((int64_t*)&curtime);
}

// Appends the current timestamp to the string.
// Returns false if could not get the current_time, true if append succeeds
Status DBWithTTL::AppendTS(const Slice& val, std::string& val_with_ts) {
  val_with_ts.reserve(kTSLength + val.size());
  char ts_string[kTSLength];
  int32_t curtime;
  Status st = GetCurrentTime(curtime);
  if (!st.ok()) {
    return st;
  }
  EncodeFixed32(ts_string, curtime);
  val_with_ts.append(val.data(), val.size());
  val_with_ts.append(ts_string, kTSLength);
  return st;
}

// Checks if the string is stale or not according to TTl provided
bool DBWithTTL::IsStale(const Slice& value, int32_t ttl) {
  if (ttl <= 0) { // Data is fresh if TTL is non-positive
    return false;
  }
  int32_t curtime;
  if (!GetCurrentTime(curtime).ok()) {
    return false; // Treat the data as fresh if could not get current time
  } else {
    int32_t timestamp_value =
      DecodeFixed32(value.data() + value.size() - kTSLength);
    if ((timestamp_value + ttl) < curtime) {
      return true; // Data is stale
    }
  }
  return false;
}

// Strips the TS from the end of the string
Status DBWithTTL::StripTS(std::string* str) {
  Status st;
  if (str->length() < (unsigned)kTSLength) {
    return Status::IOError("Error: value's length less than timestamp's\n");
  }
  // Erasing characters which hold the TS
  str->erase(str->length() - kTSLength, kTSLength);
  return st;
}

Status DBWithTTL::Put(
    const WriteOptions& o,
    const Slice& key,
    const Slice& val) {
  std::string value_with_ts;
  Status st = AppendTS(val, value_with_ts);
  if (!st.ok()) {
    return st;
  }
  return db_->Put(o, key, value_with_ts);
}

Status DBWithTTL::Get(const ReadOptions& options,
                      const Slice& key,
                      std::string* value) {
  Status st = db_->Get(options, key, value);
  if (!st.ok()) {
    return st;
  }
  return StripTS(value);
}

Status DBWithTTL::Delete(const WriteOptions& wopts, const Slice& key) {
  return db_->Delete(wopts, key);
}

Status DBWithTTL::Write(const WriteOptions& opts, WriteBatch* updates) {
  return db_->Write(opts, updates);
}

Iterator* DBWithTTL::NewIterator(const ReadOptions& opts) {
  return new TtlIterator(db_->NewIterator(opts), kTSLength);
}

const Snapshot* DBWithTTL::GetSnapshot() {
  return db_->GetSnapshot();
}

void DBWithTTL::ReleaseSnapshot(const Snapshot* snapshot) {
  db_->ReleaseSnapshot(snapshot);
}

bool DBWithTTL::GetProperty(const Slice& property, std::string* value) {
  return db_->GetProperty(property, value);
}

void DBWithTTL::GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  db_->GetApproximateSizes(r, n, sizes);
}

void DBWithTTL::CompactRange(const Slice* begin, const Slice* end) {
  db_->CompactRange(begin, end);
}

int DBWithTTL::NumberLevels() {
  return db_->NumberLevels();
}

int DBWithTTL::MaxMemCompactionLevel() {
  return db_->MaxMemCompactionLevel();
}

int DBWithTTL::Level0StopWriteTrigger() {
  return db_->Level0StopWriteTrigger();
}

Status DBWithTTL::Flush(const FlushOptions& fopts) {
  return db_->Flush(fopts);
}

Status DBWithTTL::DisableFileDeletions() {
  return db_->DisableFileDeletions();
}

Status DBWithTTL::EnableFileDeletions() {
  return db_->EnableFileDeletions();
}

Status DBWithTTL::GetLiveFiles(std::vector<std::string>& vec, uint64_t* mfs) {
  return db_->GetLiveFiles(vec, mfs);
}

SequenceNumber DBWithTTL::GetLatestSequenceNumber() {
  return db_->GetLatestSequenceNumber();
}

Status DBWithTTL::GetUpdatesSince(
    SequenceNumber seq_number,
    unique_ptr<TransactionLogIterator>* iter) {
  return db_->GetUpdatesSince(seq_number, iter);
}

void DBWithTTL::TEST_Destroy_DBWithTtl() {
  ((DBImpl*) db_)->TEST_Destroy_DBImpl();
}

}  // namespace leveldb
<commit_msg>Fix invalid-read to freed memory in ttl-iterator<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "utilities/ttl/db_ttl.h"
#include "include/utilities/utility_db.h"
#include "db/filename.h"
#include "util/coding.h"
#include "include/leveldb/env.h"
#include "include/leveldb/iterator.h"

namespace leveldb {

class TtlIterator : public Iterator {

 public:
  TtlIterator(Iterator* iter, int32_t ts_len)
    : iter_(iter),
      ts_len_(ts_len) {
    assert(iter_);
  }

  ~TtlIterator() {
    delete iter_;
  }

  bool Valid() const {
    return iter_->Valid();
  }

  void SeekToFirst() {
    iter_->SeekToFirst();
  }

  void SeekToLast() {
    iter_->SeekToLast();
  }

  void Seek(const Slice& target) {
    iter_->Seek(target);
  }

  void Next() {
    iter_->Next();
  }

  void Prev() {
    iter_->Prev();
  }

  Slice key() const {
    return iter_->key();
  }

  Slice value() const {
    assert(iter_->value().size() >= (unsigned)ts_len_);
    Slice trimmed_value = iter_->value();
    trimmed_value.size_ -= ts_len_;
    return trimmed_value;
  }

  Status status() const {
    return iter_->status();
  }

 private:
  Iterator* iter_;
  int32_t ts_len_;
};

// Open the db inside DBWithTTL because options needs pointer to its ttl
DBWithTTL::DBWithTTL(const int32_t ttl,
                     const Options& options,
                     const std::string& dbname,
                     Status& st)
    : ttl_(ttl) {
  assert(options.CompactionFilter == nullptr);
  Options options_to_open = options;
  options_to_open.compaction_filter_args = &ttl_;
  options_to_open.CompactionFilter = DeleteByTS;
  st = DB::Open(options_to_open, dbname, &db_);
}

DBWithTTL::~DBWithTTL() {
  delete db_;
}

Status UtilityDB::OpenTtlDB(
    const Options& options,
    const std::string& dbname,
    DB** dbptr,
    int32_t ttl) {
  Status st;
  *dbptr = new DBWithTTL(ttl, options, dbname, st);
  if (!st.ok()) {
    delete dbptr;
  }
  return st;
}

// returns true(i.e. key-value to be deleted) if its TS has expired based on ttl
bool DBWithTTL::DeleteByTS(
    void* args,
    int level,
    const Slice& key,
    const Slice& old_val,
    std::string* new_val,
    bool* value_changed) {
  return IsStale(old_val, *(int32_t*)args);
}

// Gives back the current time
Status DBWithTTL::GetCurrentTime(int32_t& curtime) {
  return Env::Default()->GetCurrentTime((int64_t*)&curtime);
}

// Appends the current timestamp to the string.
// Returns false if could not get the current_time, true if append succeeds
Status DBWithTTL::AppendTS(const Slice& val, std::string& val_with_ts) {
  val_with_ts.reserve(kTSLength + val.size());
  char ts_string[kTSLength];
  int32_t curtime;
  Status st = GetCurrentTime(curtime);
  if (!st.ok()) {
    return st;
  }
  EncodeFixed32(ts_string, curtime);
  val_with_ts.append(val.data(), val.size());
  val_with_ts.append(ts_string, kTSLength);
  return st;
}

// Checks if the string is stale or not according to TTl provided
bool DBWithTTL::IsStale(const Slice& value, int32_t ttl) {
  if (ttl <= 0) { // Data is fresh if TTL is non-positive
    return false;
  }
  int32_t curtime;
  if (!GetCurrentTime(curtime).ok()) {
    return false; // Treat the data as fresh if could not get current time
  } else {
    int32_t timestamp_value =
      DecodeFixed32(value.data() + value.size() - kTSLength);
    if ((timestamp_value + ttl) < curtime) {
      return true; // Data is stale
    }
  }
  return false;
}

// Strips the TS from the end of the string
Status DBWithTTL::StripTS(std::string* str) {
  Status st;
  if (str->length() < (unsigned)kTSLength) {
    return Status::IOError("Error: value's length less than timestamp's\n");
  }
  // Erasing characters which hold the TS
  str->erase(str->length() - kTSLength, kTSLength);
  return st;
}

Status DBWithTTL::Put(
    const WriteOptions& o,
    const Slice& key,
    const Slice& val) {
  std::string value_with_ts;
  Status st = AppendTS(val, value_with_ts);
  if (!st.ok()) {
    return st;
  }
  return db_->Put(o, key, value_with_ts);
}

Status DBWithTTL::Get(const ReadOptions& options,
                      const Slice& key,
                      std::string* value) {
  Status st = db_->Get(options, key, value);
  if (!st.ok()) {
    return st;
  }
  return StripTS(value);
}

Status DBWithTTL::Delete(const WriteOptions& wopts, const Slice& key) {
  return db_->Delete(wopts, key);
}

Status DBWithTTL::Write(const WriteOptions& opts, WriteBatch* updates) {
  return db_->Write(opts, updates);
}

Iterator* DBWithTTL::NewIterator(const ReadOptions& opts) {
  return new TtlIterator(db_->NewIterator(opts), kTSLength);
}

const Snapshot* DBWithTTL::GetSnapshot() {
  return db_->GetSnapshot();
}

void DBWithTTL::ReleaseSnapshot(const Snapshot* snapshot) {
  db_->ReleaseSnapshot(snapshot);
}

bool DBWithTTL::GetProperty(const Slice& property, std::string* value) {
  return db_->GetProperty(property, value);
}

void DBWithTTL::GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  db_->GetApproximateSizes(r, n, sizes);
}

void DBWithTTL::CompactRange(const Slice* begin, const Slice* end) {
  db_->CompactRange(begin, end);
}

int DBWithTTL::NumberLevels() {
  return db_->NumberLevels();
}

int DBWithTTL::MaxMemCompactionLevel() {
  return db_->MaxMemCompactionLevel();
}

int DBWithTTL::Level0StopWriteTrigger() {
  return db_->Level0StopWriteTrigger();
}

Status DBWithTTL::Flush(const FlushOptions& fopts) {
  return db_->Flush(fopts);
}

Status DBWithTTL::DisableFileDeletions() {
  return db_->DisableFileDeletions();
}

Status DBWithTTL::EnableFileDeletions() {
  return db_->EnableFileDeletions();
}

Status DBWithTTL::GetLiveFiles(std::vector<std::string>& vec, uint64_t* mfs) {
  return db_->GetLiveFiles(vec, mfs);
}

SequenceNumber DBWithTTL::GetLatestSequenceNumber() {
  return db_->GetLatestSequenceNumber();
}

Status DBWithTTL::GetUpdatesSince(
    SequenceNumber seq_number,
    unique_ptr<TransactionLogIterator>* iter) {
  return db_->GetUpdatesSince(seq_number, iter);
}

void DBWithTTL::TEST_Destroy_DBWithTtl() {
  ((DBImpl*) db_)->TEST_Destroy_DBImpl();
}

}  // namespace leveldb
<|endoftext|>


<commit_before>// The MIT License
//
// Copyright (c) 2011 daniperez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////
// roadef12
#include "roadef12-common/service/Service.hpp"
#include "roadef12-common/service/ProgramOptions.hpp"
#include "roadef12-common/service/ServiceExceptions.hpp"
#include "roadef12-common/util/Util.hpp"
///////////////////////////////////////////////////////////////////////////
// STD
#include <iostream>
///////////////////////////////////////////////////////////////////////////

class ExampleService : public ROADEF12COMMON::Service
{
    public:

        ExampleService ( const ROADEF12COMMON::ServiceInput& input )
            throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException )
            : ROADEF12COMMON::Service ( input )
        {
        }

        virtual void optimize ()
          throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException )
        {
            std::cout << "processes=" << params.processes.size()
                      << " machines=" << params.machines.size()
                      << " resources=" << params.resources.size()
                      << std::endl;

            if ( options.nullCopy )
            {
                firstAssignment.write ( options.solution.c_str() );
            }
            else if ( options.nullNull )
            {
                // Do not perform any optimization, no output is produced.
            }
            else
            {
                std::cout << "Your code goes here" << std::endl;

                // Don't forget to write a solution
                firstAssignment.write ( options.solution.c_str() );
            }
        }
};

int main ( int argc, char **argv )
{
    try
    {
        ROADEF12COMMON::ServiceInput input
            = ROADEF12COMMON::ProgramOptions::parseCommandLine ( argc, argv );

        ExampleService service ( input );

        std::cout << "Optimization started..." << std::endl;

        service.optimize();

        std::cout << "Optimization finished!" << std::endl;

        exit ( EXIT_SUCCESS );
    }
    catch ( ROADEF12COMMON::DoNotContinue& e )
    {
        exit ( EXIT_SUCCESS );
    }
    catch( ROADEF12COMMON::ParseException& e )
    {
        std::cerr << "Error while parsing: " << e.what() << std::endl;
    }
    catch ( ROADEF12COMMON::InvalidSolution& e )
    {
        std::cerr << "The produced solution is not valid" << std::endl;
    }
    catch ( std::exception& e )
    {
        std::cerr << e.what() << std::endl;
    }

    exit ( EXIT_FAILURE );
}
<commit_msg>Removed headers not really needed.<commit_after>// The MIT License
//
// Copyright (c) 2011 daniperez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////
// roadef12
#include <roadef12-common/service/Service.hpp>
#include <roadef12-common/service/ProgramOptions.hpp>
///////////////////////////////////////////////////////////////////////////
// STD
#include <iostream>
///////////////////////////////////////////////////////////////////////////

class ExampleService : public ROADEF12COMMON::Service
{
    public:

        ExampleService ( const ROADEF12COMMON::ServiceInput& input )
            throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException )
            : ROADEF12COMMON::Service ( input )
        {
        }

        virtual void optimize ()
          throw ( ROADEF12COMMON::IOException, ROADEF12COMMON::ParseException )
        {
            std::cout << "processes=" << params.processes.size()
                      << " machines=" << params.machines.size()
                      << " resources=" << params.resources.size()
                      << std::endl;

            if ( options.nullCopy )
            {
                firstAssignment.write ( options.solution.c_str() );
            }
            else if ( options.nullNull )
            {
                // Do not perform any optimization, no output is produced.
            }
            else
            {
                std::cout << "Your code goes here" << std::endl;

                // Don't forget to write a solution
                firstAssignment.write ( options.solution.c_str() );
            }
        }
};

int main ( int argc, char **argv )
{
    try
    {
        ROADEF12COMMON::ServiceInput input
            = ROADEF12COMMON::ProgramOptions::parseCommandLine ( argc, argv );

        ExampleService service ( input );

        std::cout << "Optimization started..." << std::endl;

        service.optimize();

        std::cout << "Optimization finished!" << std::endl;

        exit ( EXIT_SUCCESS );
    }
    catch ( ROADEF12COMMON::DoNotContinue& e )
    {
        exit ( EXIT_SUCCESS );
    }
    catch( ROADEF12COMMON::ParseException& e )
    {
        std::cerr << "Error while parsing: " << e.what() << std::endl;
    }
    catch ( ROADEF12COMMON::InvalidSolution& e )
    {
        std::cerr << "The produced solution is not valid" << std::endl;
    }
    catch ( std::exception& e )
    {
        std::cerr << e.what() << std::endl;
    }

    exit ( EXIT_FAILURE );
}
<|endoftext|>


<commit_before>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//

//
//   Demo code (advanced), about
//
//     - loading an Abaqus tetahedrom mesh
//     - apply a load to the mesh using an external tool,
//       say CFD or SPH (here simulated as a function in this .cpp file)
//       that is perform a cosimulation.

#include "chrono/geometry/ChTriangleMeshConnected.h"
#include "chrono/solver/ChSolverMINRES.h"
#include "chrono/physics/ChLoadContainer.h"
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChSystemDEM.h"

#include "chrono_irrlicht/ChIrrApp.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/DeformableTerrain.h"

using namespace chrono;
using namespace chrono::irrlicht;

using namespace irr;

int main(int argc, char* argv[]) {
    // Global parameter for tire:
    double tire_rad = 0.8;
    double tire_vel_z0 = -3;
    ChVector<> tire_center(0, 0.02+tire_rad, 0);
    ChMatrix33<> tire_alignment(Q_from_AngAxis(CH_C_PI, VECT_Y)); // create rotated 180 on y

    double tire_w0 = tire_vel_z0/tire_rad;

    // Create a Chrono::Engine physical system
    ChSystemDEM my_system;

    // Create the Irrlicht visualization (open the Irrlicht device,
    // bind a simple user interface, etc. etc.)
    ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true);

    // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
    application.AddTypicalLogo();
    application.AddTypicalSky();
    application.AddTypicalLights();
    application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0));
    application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512,
                                   video::SColorf(0.8f, 0.8f, 1.0f));

    std::shared_ptr<ChBody> mtruss (new ChBody);
    mtruss->SetBodyFixed(true);
    my_system.Add(mtruss);

    //
    // CREATE A RIGID BODY WITH A MESH
    //

    // Create also a rigid body with a rigid mesh that will be used for the cosimulation,
    // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we
    // will use the ChLoadBodyMesh class:

    std::shared_ptr<ChBody> mrigidbody (new ChBody);
    my_system.Add(mrigidbody);
    mrigidbody->SetMass(200);
    mrigidbody->SetInertiaXX(ChVector<>(20,20,20));
    mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0));

    std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape);
    mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj"));
    mrigidmesh->GetMesh().Transform(VNULL, Q_from_AngAxis(CH_C_PI, VECT_Y) );
    mrigidbody->AddAsset(mrigidmesh);

    mrigidbody->GetCollisionModel()->ClearModel();
    mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(), false, false, VNULL,
                                                     ChMatrix33<>(CH_C_PI, VECT_Y), 0.01);
    mrigidbody->GetCollisionModel()->BuildModel();
    mrigidbody->SetCollide(true);

    std::shared_ptr<ChColorAsset> mcol(new ChColorAsset);
    mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f));
    mrigidbody->AddAsset(mcol);

    std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine);
    myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM);
    myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED);
    if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) )
        mfun->Set_yconst(CH_C_PI / 4.0);
    myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y)));
    my_system.Add(myengine);

    //
    // THE DEFORMABLE TERRAIN
    //

    // Create the 'deformable terrain' object
    vehicle::DeformableTerrain mterrain(&my_system);

    // Optionally, displace/tilt/rotate the terrain reference plane:
    mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5)));

    // Initialize the geometry of the soil: use either a regular grid:
     mterrain.Initialize(0.2,1.5,5,100,200);
    // or use a height map:
    //mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3);

    // Set the soil terramechanical parameters:
    mterrain.SetSoilParametersSCM(1.2e6,  // Bekker Kphi
                                    0,   // Bekker Kc
                                    1.1, // Bekker n exponent
                                    0,   // Mohr cohesive limit (Pa)
                                    30,  // Mohr friction limit (degrees)
                                    0.01,// Janosi shear coefficient (m)
                                    5e7  // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi
                                    );
    mterrain.SetBulldozingFlow(true);    // inflate soil at the border of the rut
    mterrain.SetBulldozingParameters(40, // angle of frictionfor erosion of displaced material at the border of the rut
                                    1.6);// displaced material vs downward pressed material.

    // Set some visualization parameters: either with a texture, or with falsecolor plot, etc.
    //mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2);
    mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8);

    // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items
    application.AssetBindAll();

    // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets
    application.AssetUpdateAll();

    // Use shadows in realtime view
    application.AddShadowAll();

    // ==IMPORTANT!== Mark completion of system construction
    my_system.SetupInitial();

    //
    // THE SOFT-REAL-TIME CYCLE
    //

 /*
        // Change solver to embedded MINRES
        // NOTE! it is strongly advised that you compile the optional MKL module
        // if you need higher precision, and switch to its MKL solver - see demos for FEA & MKL.
    my_system.SetSolverType(ChSystem::SOLVER_MINRES);
    my_system.SetSolverWarmStarting(true);  // this helps a lot to speedup convergence in this class of problems
    my_system.SetMaxItersSolverSpeed(40);
    my_system.SetTolForce(1e-10);
  */

    application.SetTimestep(0.005);

    while (application.GetDevice()->run()) {
        application.BeginScene();

        application.DrawAll();

        application.DoStep();

        ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(),  1180);

        application.EndScene();
    }

    return 0;
}
<commit_msg>Updating the demo of SCM deformable soil to use the new mesh refinement<commit_after>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//

//
//   Demo code (advanced), about
//
//     - loading an Abaqus tetahedrom mesh
//     - apply a load to the mesh using an external tool,
//       say CFD or SPH (here simulated as a function in this .cpp file)
//       that is perform a cosimulation.

#include "chrono/geometry/ChTriangleMeshConnected.h"
#include "chrono/solver/ChSolverMINRES.h"
#include "chrono/physics/ChLoadContainer.h"
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChSystemDEM.h"

#include "chrono_irrlicht/ChIrrApp.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/DeformableTerrain.h"

using namespace chrono;
using namespace chrono::irrlicht;

using namespace irr;

int main(int argc, char* argv[]) {
    // Global parameter for tire:
    double tire_rad = 0.8;
    double tire_vel_z0 = -3;
    ChVector<> tire_center(0, 0.02+tire_rad, 0);
    ChMatrix33<> tire_alignment(Q_from_AngAxis(CH_C_PI, VECT_Y)); // create rotated 180 on y

    double tire_w0 = tire_vel_z0/tire_rad;

    // Create a Chrono::Engine physical system
    ChSystemDEM my_system;

    // Create the Irrlicht visualization (open the Irrlicht device,
    // bind a simple user interface, etc. etc.)
    ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true);

    // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
    application.AddTypicalLogo();
    application.AddTypicalSky();
    application.AddTypicalLights();
    application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0));
    application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512,
                                   video::SColorf(0.8f, 0.8f, 1.0f));

    std::shared_ptr<ChBody> mtruss (new ChBody);
    mtruss->SetBodyFixed(true);
    my_system.Add(mtruss);

    //
    // CREATE A RIGID BODY WITH A MESH
    //

    // Create also a rigid body with a rigid mesh that will be used for the cosimulation,
    // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we
    // will use the ChLoadBodyMesh class:

    std::shared_ptr<ChBody> mrigidbody (new ChBody);
    my_system.Add(mrigidbody);
    mrigidbody->SetMass(200);
    mrigidbody->SetInertiaXX(ChVector<>(20,20,20));
    mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0));

    std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape);
    mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj"));
    mrigidmesh->GetMesh().Transform(VNULL, Q_from_AngAxis(CH_C_PI, VECT_Y) );
    mrigidbody->AddAsset(mrigidmesh);

    mrigidbody->GetCollisionModel()->ClearModel();
    mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(), false, false, VNULL,
                                                     ChMatrix33<>(CH_C_PI, VECT_Y), 0.01);
    mrigidbody->GetCollisionModel()->BuildModel();
    mrigidbody->SetCollide(true);

    std::shared_ptr<ChColorAsset> mcol(new ChColorAsset);
    mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f));
    mrigidbody->AddAsset(mcol);

    std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine);
    myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM);
    myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED);
    if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) )
        mfun->Set_yconst(CH_C_PI / 4.0);
    myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y)));
    my_system.Add(myengine);

    //
    // THE DEFORMABLE TERRAIN
    //

    // Create the 'deformable terrain' object
    vehicle::DeformableTerrain mterrain(&my_system);

    // Optionally, displace/tilt/rotate the terrain reference plane:
    mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5)));

    // Initialize the geometry of the soil: use either a regular grid:
     mterrain.Initialize(0.2,1.5,5,20,60);
    // or use a height map:
    //mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3);

    // Set the soil terramechanical parameters:
    mterrain.SetSoilParametersSCM(1.2e6,  // Bekker Kphi
                                    0,   // Bekker Kc
                                    1.1, // Bekker n exponent
                                    0,   // Mohr cohesive limit (Pa)
                                    30,  // Mohr friction limit (degrees)
                                    0.01,// Janosi shear coefficient (m)
                                    5e7  // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi
                                    );
    mterrain.SetBulldozingFlow(false);    // inflate soil at the border of the rut
    mterrain.SetBulldozingParameters(40, // angle of frictionfor erosion of displaced material at the border of the rut
                                    1.6);// displaced material vs downward pressed material.
    // Turn on the automatic level of detail refinement, so a coarse terrain mesh
    // is automatically improved by adding more points under the wheel contact patch:
    mterrain.SetAutomaticRefinement(true);
    mterrain.SetAutomaticRefinementResolution(0.02);

    // Set some visualization parameters: either with a texture, or with falsecolor plot, etc.
    //mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2);
    mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8);
    //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8);

    // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items
    application.AssetBindAll();

    // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets
    application.AssetUpdateAll();

    // Use shadows in realtime view
    application.AddShadowAll();

    // ==IMPORTANT!== Mark completion of system construction
    my_system.SetupInitial();

    //
    // THE SOFT-REAL-TIME CYCLE
    //

 /*
        // Change solver to embedded MINRES
        // NOTE! it is strongly advised that you compile the optional MKL module
        // if you need higher precision, and switch to its MKL solver - see demos for FEA & MKL.
    my_system.SetSolverType(ChSystem::SOLVER_MINRES);
    my_system.SetSolverWarmStarting(true);  // this helps a lot to speedup convergence in this class of problems
    my_system.SetMaxItersSolverSpeed(40);
    my_system.SetTolForce(1e-10);
  */

    application.SetTimestep(0.005);

    while (application.GetDevice()->run()) {
        application.BeginScene();

        application.DrawAll();

        application.DoStep();

        ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(),  1180);

        application.EndScene();
    }

    return 0;
}
<|endoftext|>