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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkInternalTrackingTool.h"

#include <itkMutexLockHolder.h>

typedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder;

mitk::InternalTrackingTool::InternalTrackingTool()
: TrackingTool(),
m_TrackingError(0.0f),
m_Enabled(true),
m_DataValid(false),
m_ToolTipSet(false)
{
  m_Position[0] = 0.0f;
  m_Position[1] = 0.0f;
  m_Position[2] = 0.0f;
  m_Orientation[0] = 0.0f;
  m_Orientation[1] = 0.0f;
  m_Orientation[2] = 0.0f;
  m_Orientation[3] = 0.0f;
  // this should not be necessary as the tools bring their own tooltip transformation
  m_ToolTip[0] = 0.0f;
  m_ToolTip[1] = 0.0f;
  m_ToolTip[2] = 0.0f;
  m_ToolTipRotation[0] = 0.0f;
  m_ToolTipRotation[1] = 0.0f;
  m_ToolTipRotation[2] = 0.0f;
  m_ToolTipRotation[3] = 1.0f;
}

mitk::InternalTrackingTool::~InternalTrackingTool()
{
}

void mitk::InternalTrackingTool::SetToolName(const char* _arg)
{
  itkDebugMacro("setting  m_ToolName to " << _arg);
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if ( _arg && (_arg == this->m_ToolName) )
  {
    return;
  }
  if (_arg)
  {
    this->m_ToolName= _arg;
  }
  else
  {
    this->m_ToolName= "";
  }
  this->Modified();
}

void mitk::InternalTrackingTool::SetToolName( const std::string _arg )
{
  this->SetToolName(_arg.c_str());
}

void mitk::InternalTrackingTool::GetPosition(mitk::Point3D& position) const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_ToolTipSet)
    {
    // Compute the position of tool tip in the coordinate frame of the
    // tracking device: Rotate the position of the tip into the tracking
    // device coordinate frame then add to the position of the tracking
    // sensor
    vnl_vector<float> pos_vnl = m_Position.Get_vnl_vector() + m_Orientation.rotate( m_ToolTip.Get_vnl_vector() ) ;
    position[0] = pos_vnl[0];
    position[1] = pos_vnl[1];
    position[2] = pos_vnl[2];
    }
  else
    {
    position[0] = m_Position[0];
    position[1] = m_Position[1];
    position[2] = m_Position[2];
    }
  this->Modified();
}

void mitk::InternalTrackingTool::SetPosition(mitk::Point3D position, mitk::ScalarType eps)
{
  itkDebugMacro("setting  m_Position to " << position);
  if (!Equal(m_Position, position, eps))
  {
    MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
    m_Position = position;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::GetOrientation(mitk::Quaternion& orientation) const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_ToolTipSet)
    {
    // Compute the orientation of the tool tip in the coordinate frame of
    // the tracking device.
    //
    //   * m_Orientation is the orientation of the sensor relative to the transmitter
    //   * m_ToolTipRotation is the orientation of the tool tip relative to the sensor
    orientation =  m_Orientation * m_ToolTipRotation;
    }
  else
    {
    orientation = m_Orientation;
    }
}

void mitk::InternalTrackingTool::SetToolTip(mitk::Point3D toolTipPosition,
                                            mitk::Quaternion orientation,
                                            mitk::ScalarType eps)
{
  if ( !Equal(m_ToolTip, toolTipPosition, eps) ||
       !Equal(m_ToolTipRotation, orientation, eps) )
  {
    if( (toolTipPosition[0] == 0) &&
        (toolTipPosition[1] == 0) &&
        (toolTipPosition[2] == 0) &&
        (orientation.x() == 0) &&
        (orientation.y() == 0) &&
        (orientation.z() == 0) &&
        (orientation.r() == 1))
    {
      m_ToolTipSet = false;
    }
    else
    {
      m_ToolTipSet = true;
    }
    m_ToolTip = toolTipPosition;
    m_ToolTipRotation = orientation;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::SetOrientation(mitk::Quaternion orientation, mitk::ScalarType eps)
{
  itkDebugMacro("setting  m_Orientation to " << orientation);
  if (!Equal(m_Orientation, orientation, eps))
  {
    MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
    m_Orientation = orientation;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::SetTrackingError(float error)
{
  itkDebugMacro("setting  m_TrackingError  to " << error);
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (error == m_TrackingError)
  {
    return;
  }
  m_TrackingError = error;
  this->Modified();
}

float mitk::InternalTrackingTool::GetTrackingError() const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  float r = m_TrackingError;
  return r;
}

bool mitk::InternalTrackingTool::Enable()
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_Enabled == false)
  {
    this->m_Enabled = true;
    this->Modified();
  }
  return true;
}

bool mitk::InternalTrackingTool::Disable()
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_Enabled == true)
  {
    this->m_Enabled = false;
    this->Modified();
  }
  return true;
}

bool mitk::InternalTrackingTool::IsEnabled() const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  return m_Enabled;
}

bool mitk::InternalTrackingTool::IsDataValid() const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  return m_DataValid;
}

void mitk::InternalTrackingTool::SetDataValid(bool _arg)
{
  itkDebugMacro("setting m_DataValid to " << _arg);
  if (this->m_DataValid != _arg)
  {
    MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
    this->m_DataValid = _arg;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::SetErrorMessage(const char* _arg)
{
  itkDebugMacro("setting  m_ErrorMessage  to " << _arg);
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if ((_arg == NULL) || (_arg == this->m_ErrorMessage))
    return;

  if (_arg != NULL)
    this->m_ErrorMessage = _arg;
  else
    this->m_ErrorMessage = "";
  this->Modified();
}
<commit_msg>Add mitk::InternalTrackingTool::PrintSelf<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkInternalTrackingTool.h"

#include <itkMutexLockHolder.h>

typedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder;

mitk::InternalTrackingTool::InternalTrackingTool()
: TrackingTool(),
m_TrackingError(0.0f),
m_Enabled(true),
m_DataValid(false),
m_ToolTipSet(false)
{
  m_Position[0] = 0.0f;
  m_Position[1] = 0.0f;
  m_Position[2] = 0.0f;
  m_Orientation[0] = 0.0f;
  m_Orientation[1] = 0.0f;
  m_Orientation[2] = 0.0f;
  m_Orientation[3] = 0.0f;
  // this should not be necessary as the tools bring their own tooltip transformation
  m_ToolTip[0] = 0.0f;
  m_ToolTip[1] = 0.0f;
  m_ToolTip[2] = 0.0f;
  m_ToolTipRotation[0] = 0.0f;
  m_ToolTipRotation[1] = 0.0f;
  m_ToolTipRotation[2] = 0.0f;
  m_ToolTipRotation[3] = 1.0f;
}

mitk::InternalTrackingTool::~InternalTrackingTool()
{
}

void mitk::InternalTrackingTool::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Position: " << m_Position << std::endl;
  os << indent << "Orientation: " << m_Orientation << std::endl;
  os << indent << "TrackingError: " << m_TrackingError << std::endl;
  os << indent << "Enabled: " << m_Enabled << std::endl;
  os << indent << "DataValid: " << m_DataValid << std::endl;
  os << indent << "ToolTip: " << m_ToolTip << std::endl;
  os << indent << "ToolTipRotation: " << m_ToolTipRotation << std::endl;
  os << indent << "ToolTipSet: " << m_ToolTipSet << std::endl;
}

void mitk::InternalTrackingTool::SetToolName(const char* _arg)
{
  itkDebugMacro("setting  m_ToolName to " << _arg);
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if ( _arg && (_arg == this->m_ToolName) )
  {
    return;
  }
  if (_arg)
  {
    this->m_ToolName= _arg;
  }
  else
  {
    this->m_ToolName= "";
  }
  this->Modified();
}

void mitk::InternalTrackingTool::SetToolName( const std::string _arg )
{
  this->SetToolName(_arg.c_str());
}

void mitk::InternalTrackingTool::GetPosition(mitk::Point3D& position) const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_ToolTipSet)
    {
    // Compute the position of tool tip in the coordinate frame of the
    // tracking device: Rotate the position of the tip into the tracking
    // device coordinate frame then add to the position of the tracking
    // sensor
    vnl_vector<float> pos_vnl = m_Position.Get_vnl_vector() + m_Orientation.rotate( m_ToolTip.Get_vnl_vector() ) ;
    position[0] = pos_vnl[0];
    position[1] = pos_vnl[1];
    position[2] = pos_vnl[2];
    }
  else
    {
    position[0] = m_Position[0];
    position[1] = m_Position[1];
    position[2] = m_Position[2];
    }
  this->Modified();
}

void mitk::InternalTrackingTool::SetPosition(mitk::Point3D position, mitk::ScalarType eps)
{
  itkDebugMacro("setting  m_Position to " << position);
  if (!Equal(m_Position, position, eps))
  {
    MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
    m_Position = position;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::GetOrientation(mitk::Quaternion& orientation) const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_ToolTipSet)
    {
    // Compute the orientation of the tool tip in the coordinate frame of
    // the tracking device.
    //
    //   * m_Orientation is the orientation of the sensor relative to the transmitter
    //   * m_ToolTipRotation is the orientation of the tool tip relative to the sensor
    orientation =  m_Orientation * m_ToolTipRotation;
    }
  else
    {
    orientation = m_Orientation;
    }
}

void mitk::InternalTrackingTool::SetToolTip(mitk::Point3D toolTipPosition,
                                            mitk::Quaternion orientation,
                                            mitk::ScalarType eps)
{
  if ( !Equal(m_ToolTip, toolTipPosition, eps) ||
       !Equal(m_ToolTipRotation, orientation, eps) )
  {
    if( (toolTipPosition[0] == 0) &&
        (toolTipPosition[1] == 0) &&
        (toolTipPosition[2] == 0) &&
        (orientation.x() == 0) &&
        (orientation.y() == 0) &&
        (orientation.z() == 0) &&
        (orientation.r() == 1))
    {
      m_ToolTipSet = false;
    }
    else
    {
      m_ToolTipSet = true;
    }
    m_ToolTip = toolTipPosition;
    m_ToolTipRotation = orientation;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::SetOrientation(mitk::Quaternion orientation, mitk::ScalarType eps)
{
  itkDebugMacro("setting  m_Orientation to " << orientation);
  if (!Equal(m_Orientation, orientation, eps))
  {
    MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
    m_Orientation = orientation;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::SetTrackingError(float error)
{
  itkDebugMacro("setting  m_TrackingError  to " << error);
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (error == m_TrackingError)
  {
    return;
  }
  m_TrackingError = error;
  this->Modified();
}

float mitk::InternalTrackingTool::GetTrackingError() const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  float r = m_TrackingError;
  return r;
}

bool mitk::InternalTrackingTool::Enable()
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_Enabled == false)
  {
    this->m_Enabled = true;
    this->Modified();
  }
  return true;
}

bool mitk::InternalTrackingTool::Disable()
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if (m_Enabled == true)
  {
    this->m_Enabled = false;
    this->Modified();
  }
  return true;
}

bool mitk::InternalTrackingTool::IsEnabled() const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  return m_Enabled;
}

bool mitk::InternalTrackingTool::IsDataValid() const
{
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  return m_DataValid;
}

void mitk::InternalTrackingTool::SetDataValid(bool _arg)
{
  itkDebugMacro("setting m_DataValid to " << _arg);
  if (this->m_DataValid != _arg)
  {
    MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
    this->m_DataValid = _arg;
    this->Modified();
  }
}

void mitk::InternalTrackingTool::SetErrorMessage(const char* _arg)
{
  itkDebugMacro("setting  m_ErrorMessage  to " << _arg);
  MutexLockHolder lock(*m_MyMutex); // lock and unlock the mutex
  if ((_arg == NULL) || (_arg == this->m_ErrorMessage))
    return;

  if (_arg != NULL)
    this->m_ErrorMessage = _arg;
  else
    this->m_ErrorMessage = "";
  this->Modified();
}
<|endoftext|>


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

#include <soa.h>

void print_soa_iis(const SoA<int, std::string, int> &soa_iis) {
  for (int i = 0; i < soa_iis.size(); ++i) {
    std::cout << "(" << i << "): " << soa_iis.get<0>(i) << ", \""
              << soa_iis.get<1>(i) << "\", "
              << soa_iis.get<2>(i) << std::endl;
  }
}

int main() {
  SoA<int, std::string, int> soa_iis;
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;

  soa_iis.push_back(22, "Kitty", 4);
  soa_iis.push_back(0, "Hi", 2);

  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Iterate the arrays and print out the elements.
  std::cout << "Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Swap the elements.
  soa_iis.swap(0, 1);
  std::cout << "Swapped first two elements. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Modify an element
  soa_iis.get<1>(0) = "I am changed!";
  std::cout << "Modified the 0th element. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Erase an element.
  soa_iis.erase(0);
  std::cout << "Erased 0th element. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Add two new elements...
  soa_iis.push_back(1, "Hi... for now...", 5);
  soa_iis.push_back(80, "I'll survive!'", 20);
  std::cout << "Added 2 new elements. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // And erase the first two.
  soa_iis.erase(0, 2);
  std::cout << "Erased first 2 elements. Arrays now contain:\n";
  print_soa_iis(soa_iis);

  // Kill the arrays via resize.
  soa_iis.resize(0);
  std::cout << "Resized to 0. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Resize to have some new elements.
  soa_iis.resize(5);
  std::cout << "Resized to 5. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Modify an element and insert an element.
  soa_iis.get<1>(3) = "Oh hai!";
  soa_iis.get<2>(3) = 11;
  soa_iis.get<0>(3) = 22;
  soa_iis.push_back(100, "I'm new!.", 20);
  std::cout
      << "Modified the 4th element and added a new one. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Get arrays and print them.
  std::cout << "Printing arrays individually:\n";
  int *ints0 = soa_iis.array<0>();
  std::string *strings = soa_iis.array<1>();
  int *ints1 = soa_iis.array<2>();
  for (int i = 0; i < soa_iis.size(); ++i) {
    std::cout << "Index: " << i << ": ";
    std::cout << ints0[i] << ", \"";
    std::cout << strings[i] << "\", ";
    std::cout << ints1[i] << std::endl;
  }
}
<commit_msg>Ran clang format on soa_example.cc<commit_after>#include <iostream>
#include <string>

#include <soa.h>

void print_soa_iis(const SoA<int, std::string, int>& soa_iis) {
  for (int i = 0; i < soa_iis.size(); ++i) {
    std::cout << "(" << i << "): " << soa_iis.get<0>(i) << ", \""
              << soa_iis.get<1>(i) << "\", " << soa_iis.get<2>(i) << std::endl;
  }
}

int main() {
  SoA<int, std::string, int> soa_iis;
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;

  soa_iis.push_back(22, "Kitty", 4);
  soa_iis.push_back(0, "Hi", 2);

  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Iterate the arrays and print out the elements.
  std::cout << "Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Swap the elements.
  soa_iis.swap(0, 1);
  std::cout << "Swapped first two elements. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Modify an element
  soa_iis.get<1>(0) = "I am changed!";
  std::cout << "Modified the 0th element. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Erase an element.
  soa_iis.erase(0);
  std::cout << "Erased 0th element. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // Add two new elements...
  soa_iis.push_back(1, "Hi... for now...", 5);
  soa_iis.push_back(80, "I'll survive!'", 20);
  std::cout << "Added 2 new elements. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << std::endl;

  // And erase the first two.
  soa_iis.erase(0, 2);
  std::cout << "Erased first 2 elements. Arrays now contain:\n";
  print_soa_iis(soa_iis);

  // Kill the arrays via resize.
  soa_iis.resize(0);
  std::cout << "Resized to 0. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Resize to have some new elements.
  soa_iis.resize(5);
  std::cout << "Resized to 5. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Modify an element and insert an element.
  soa_iis.get<1>(3) = "Oh hai!";
  soa_iis.get<2>(3) = 11;
  soa_iis.get<0>(3) = 22;
  soa_iis.push_back(100, "I'm new!.", 20);
  std::cout
      << "Modified the 4th element and added a new one. Arrays now contain:\n";
  print_soa_iis(soa_iis);
  std::cout << "size: " << soa_iis.size() << std::endl;
  std::cout << "empty: " << soa_iis.empty() << std::endl;
  std::cout << std::endl;

  // Get arrays and print them.
  std::cout << "Printing arrays individually:\n";
  int* ints0 = soa_iis.array<0>();
  std::string* strings = soa_iis.array<1>();
  int* ints1 = soa_iis.array<2>();
  for (int i = 0; i < soa_iis.size(); ++i) {
    std::cout << "Index: " << i << ": ";
    std::cout << ints0[i] << ", \"";
    std::cout << strings[i] << "\", ";
    std::cout << ints1[i] << std::endl;
  }
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbCvRTreesWrapper.h"
#include <algorithm>
#include <functional>

namespace otb
{

CvRTreesWrapper::CvRTreesWrapper()
{
#ifdef OTB_OPENCV_3
  m_Impl = cv::ml::RTrees::create();
#endif
}

CvRTreesWrapper::~CvRTreesWrapper()
{
}

void CvRTreesWrapper::get_votes(const cv::Mat& sample,
                                const cv::Mat& missing,
                                CvRTreesWrapper::VotesVectorType& vote_count) const
{
#ifdef OTB_OPENCV_3
  (void) sample;
  (void) missing;
  (void) vote_count;
  // TODO
#else
  vote_count.resize(nclasses);
  for( int k = 0; k < ntrees; k++ )
    {
    CvDTreeNode* predicted_node = trees[k]->predict( sample, missing );
    int class_idx = predicted_node->class_idx;
    CV_Assert( 0 <= class_idx && class_idx < nclasses );
    ++vote_count[class_idx];
    }
#endif
}

float CvRTreesWrapper::predict_margin(const cv::Mat& sample,
                                      const cv::Mat& missing) const
{
#ifdef OTB_OPENCV_3
  (void) sample;
  (void) missing;
  // TODO
  return 0.;
#else
  // Sanity check (division by ntrees later on)
  if(ntrees == 0)
    {
    return 0.;
    }
  std::vector<unsigned int> classVotes;
  this->get_votes(sample, missing, classVotes);
// We only sort the 2 greatest elements
  std::nth_element(classVotes.begin(), classVotes.begin()+1,
                   classVotes.end(), std::greater<unsigned int>());
  float margin = static_cast<float>(classVotes[0]-classVotes[1])/ntrees;
  return margin;
#endif
}

float CvRTreesWrapper::predict_confidence(const cv::Mat& sample,
                                  const cv::Mat& missing) const
{
#ifdef OTB_OPENCV_3
  (void) sample;
  (void) missing;
  // TODO
  return 0.;
#else
  // Sanity check (division by ntrees later on)
  if(ntrees == 0)
    {
    return 0.;
    }
  std::vector<unsigned int> classVotes;
  this->get_votes(sample, missing, classVotes);
  unsigned int max_votes = *(std::max_element(classVotes.begin(),
                                              classVotes.end()));
  float confidence = static_cast<float>(max_votes)/ntrees;
  return confidence;
#endif
}

#ifdef OTB_OPENCV_3
#define OTB_CV_WRAP_IMPL(type,name) \
type CvRTreesWrapper::get##name() const \
{ return m_Impl->get##name(); } \
void CvRTreesWrapper::set##name(type val) \
{ m_Impl->set##name(val); }

#define OTB_CV_WRAP_IMPL_REF(type,name) \
type CvRTreesWrapper::get##name() const \
{ return m_Impl->get##name(); } \
void CvRTreesWrapper::set##name(const type &val) \
{ m_Impl->set##name(val); }

#define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \
const type& CvRTreesWrapper::get##name() const \
{ return m_Impl->get##name(); }

// TODO : wrap all method used
OTB_CV_WRAP_IMPL(int, MaxCategories)
OTB_CV_WRAP_IMPL(int, MaxDepth)
OTB_CV_WRAP_IMPL(int, MinSampleCount)
OTB_CV_WRAP_IMPL(bool, UseSurrogates)
OTB_CV_WRAP_IMPL(int, CVFolds)
OTB_CV_WRAP_IMPL(bool, Use1SERule)
OTB_CV_WRAP_IMPL(bool,TruncatePrunedTree)
OTB_CV_WRAP_IMPL(float, RegressionAccuracy)
OTB_CV_WRAP_IMPL(bool, CalculateVarImportance)
OTB_CV_WRAP_IMPL(int, ActiveVarCount)
OTB_CV_WRAP_IMPL_REF(cv::Mat, Priors)
OTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria)

OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots)
OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes)
OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits)
OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets)

int CvRTreesWrapper::getVarCount() const
{
  return m_Impl->getVarCount();
}

bool CvRTreesWrapper::isTrained() const
{
  return m_Impl->isTrained();
}

bool CvRTreesWrapper::isClassifier() const
{
  return m_Impl->isClassifier();
}

cv::Mat CvRTreesWrapper::getVarImportance() const
{
  return m_Impl->getVarImportance();
}

cv::String CvRTreesWrapper::getDefaultName () const
{
  return m_Impl->getDefaultName();
}

void CvRTreesWrapper::read (const cv::FileNode &fn)
{
  m_Impl->read(fn);
}

void CvRTreesWrapper::write (cv::FileStorage &fs) const
{
  m_Impl->write(fs);
}

void CvRTreesWrapper::save (const cv::String &filename) const
{
  m_Impl->save(filename);
}

bool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses)
{
  return m_Impl->train(samples,layout, responses);
}

bool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags )
{
  return m_Impl->train(trainData, flags);
}

float CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const
{
  return m_Impl->predict(samples, results, flags);
}

cv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create()
  {
  return cv::makePtr<CvRTreesWrapper>();
  }

#undef OTB_CV_WRAP_IMPL
#undef OTB_CV_WRAP_IMPL_REF
#undef OTB_CV_WRAP_IMPL_CSTREF_GET
#endif

}
<commit_msg>ENH: implement margin and confidence prediction for CvRTreesWrapper<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbCvRTreesWrapper.h"
#include <algorithm>
#include <functional>

namespace otb
{

CvRTreesWrapper::CvRTreesWrapper()
{
#ifdef OTB_OPENCV_3
  m_Impl = cv::ml::RTrees::create();
#endif
}

CvRTreesWrapper::~CvRTreesWrapper()
{
}

void CvRTreesWrapper::get_votes(const cv::Mat& sample,
                                const cv::Mat& missing,
                                CvRTreesWrapper::VotesVectorType& vote_count) const
{
#ifdef OTB_OPENCV_3
  // missing samples not implemented yet
  (void) missing;

  // Here we have to re-implement a basic "predict_tree()" since the function is
  // not exposed anymore
  const std::vector< cv::ml::DTrees::Node > &nodes = m_Impl->getNodes();
  const std::vector< cv::ml::DTrees::Split > &splits = m_Impl->getSplits();
  const std::vector<int> &roots = m_Impl->getRoots();
  int ntrees = roots.size();
  int nodeIdx, prevNodeIdx;
  int predictedClass = -1;
  const float* samplePtr = sample.ptr<float>();
  std::map<int, unsigned int> votes;

  for (int t=0; t<ntrees ; t++)
    {
    nodeIdx = roots[t];
    prevNodeIdx = nodeIdx;
    while(1)
      {
      prevNodeIdx = nodeIdx;
      const cv::ml::DTrees::Node &curNode = nodes[nodeIdx];
      // test if this node is a leaf
      if (curNode.split < 0)
        break;
      const cv::ml::DTrees::Split& split = splits[curNode.split];
      int varIdx = split.varIdx;
      float val = samplePtr[varIdx];
      nodeIdx = val <= split.c ? curNode.left : curNode.right;
      }
    predictedClass = nodes[prevNodeIdx].classIdx;
    votes[predictedClass] += 1;
    }

  vote_count.resize(votes.size());
  int pos=0;
  for (std::map<int, unsigned int>::const_iterator it=votes.begin() ;
       it != votes.end() ;
       ++it)
    {
    vote_count[pos] = it->second;
    pos++;
    }

  if (vote_count.size() == 1)
    {
    // give at least 2 classes
    vote_count.push_back(0);
    }
#else
  vote_count.resize(nclasses);
  for( int k = 0; k < ntrees; k++ )
    {
    CvDTreeNode* predicted_node = trees[k]->predict( sample, missing );
    int class_idx = predicted_node->class_idx;
    CV_Assert( 0 <= class_idx && class_idx < nclasses );
    ++vote_count[class_idx];
    }
#endif
}

float CvRTreesWrapper::predict_margin(const cv::Mat& sample,
                                      const cv::Mat& missing) const
{
#ifdef OTB_OPENCV_3
  int ntrees = m_Impl->getRoots().size();
#endif
  // Sanity check (division by ntrees later on)
  if(ntrees == 0)
    {
    return 0.;
    }
  std::vector<unsigned int> classVotes;
  this->get_votes(sample, missing, classVotes);
// We only sort the 2 greatest elements
  std::nth_element(classVotes.begin(), classVotes.begin()+1,
                   classVotes.end(), std::greater<unsigned int>());
  float margin = static_cast<float>(classVotes[0]-classVotes[1])/ntrees;
  return margin;
}

float CvRTreesWrapper::predict_confidence(const cv::Mat& sample,
                                  const cv::Mat& missing) const
{
#ifdef OTB_OPENCV_3
  int ntrees = m_Impl->getRoots().size();
#endif
  // Sanity check (division by ntrees later on)
  if(ntrees == 0)
    {
    return 0.;
    }
  std::vector<unsigned int> classVotes;
  this->get_votes(sample, missing, classVotes);
  unsigned int max_votes = *(std::max_element(classVotes.begin(),
                                              classVotes.end()));
  float confidence = static_cast<float>(max_votes)/ntrees;
  return confidence;
}

#ifdef OTB_OPENCV_3
#define OTB_CV_WRAP_IMPL(type,name) \
type CvRTreesWrapper::get##name() const \
{ return m_Impl->get##name(); } \
void CvRTreesWrapper::set##name(type val) \
{ m_Impl->set##name(val); }

#define OTB_CV_WRAP_IMPL_REF(type,name) \
type CvRTreesWrapper::get##name() const \
{ return m_Impl->get##name(); } \
void CvRTreesWrapper::set##name(const type &val) \
{ m_Impl->set##name(val); }

#define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \
const type& CvRTreesWrapper::get##name() const \
{ return m_Impl->get##name(); }

// TODO : wrap all method used
OTB_CV_WRAP_IMPL(int, MaxCategories)
OTB_CV_WRAP_IMPL(int, MaxDepth)
OTB_CV_WRAP_IMPL(int, MinSampleCount)
OTB_CV_WRAP_IMPL(bool, UseSurrogates)
OTB_CV_WRAP_IMPL(int, CVFolds)
OTB_CV_WRAP_IMPL(bool, Use1SERule)
OTB_CV_WRAP_IMPL(bool,TruncatePrunedTree)
OTB_CV_WRAP_IMPL(float, RegressionAccuracy)
OTB_CV_WRAP_IMPL(bool, CalculateVarImportance)
OTB_CV_WRAP_IMPL(int, ActiveVarCount)
OTB_CV_WRAP_IMPL_REF(cv::Mat, Priors)
OTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria)

OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots)
OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes)
OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits)
OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets)

int CvRTreesWrapper::getVarCount() const
{
  return m_Impl->getVarCount();
}

bool CvRTreesWrapper::isTrained() const
{
  return m_Impl->isTrained();
}

bool CvRTreesWrapper::isClassifier() const
{
  return m_Impl->isClassifier();
}

cv::Mat CvRTreesWrapper::getVarImportance() const
{
  return m_Impl->getVarImportance();
}

cv::String CvRTreesWrapper::getDefaultName () const
{
  return m_Impl->getDefaultName();
}

void CvRTreesWrapper::read (const cv::FileNode &fn)
{
  m_Impl->read(fn);
}

void CvRTreesWrapper::write (cv::FileStorage &fs) const
{
  m_Impl->write(fs);
}

void CvRTreesWrapper::save (const cv::String &filename) const
{
  m_Impl->save(filename);
}

bool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses)
{
  return m_Impl->train(samples,layout, responses);
}

bool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags )
{
  return m_Impl->train(trainData, flags);
}

float CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const
{
  return m_Impl->predict(samples, results, flags);
}

cv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create()
  {
  return cv::makePtr<CvRTreesWrapper>();
  }

#undef OTB_CV_WRAP_IMPL
#undef OTB_CV_WRAP_IMPL_REF
#undef OTB_CV_WRAP_IMPL_CSTREF_GET
#endif

}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright David Doria 2012 daviddoria@gmail.com
 *
 *  Licensed 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.txt
 *
 *  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.
 *
 *=========================================================================*/

#ifndef LinearSearchBestStrategySelection_HPP
#define LinearSearchBestStrategySelection_HPP

#include "HistogramDifference.hpp"

#include <Utilities/Histogram/HistogramHelpers.hpp>
#include <Utilities/Histogram/HistogramDifferences.hpp>

#include <Utilities/PatchHelpers.h>

/**
   * This function template is similar to std::min_element but can be used when the comparison
   * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the
   * the element in the range [first,last) which has the "smallest" distance (of course, both the
   * distance metric and comparison can be overriden to perform something other than the canonical
   * Euclidean distance and less-than comparison, which would yield the element with minimum distance).
   * \tparam DistanceValueType The value-type for the distance measures.
   * \tparam DistanceFunctionType The functor type to compute the distance measure.
   * \tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering).
   */
template <typename PropertyMapType, typename TImage>
class LinearSearchBestStrategySelection
{
  PropertyMapType PropertyMap;
  TImage* Image;
  Mask* MaskImage;

  unsigned int Iteration;

public:
  /** Constructor. This class requires the property map, an image, and a mask. */
  LinearSearchBestStrategySelection(PropertyMapType propertyMap, TImage* const image, Mask* const mask) :
    PropertyMap(propertyMap), Image(image), MaskImage(mask), Iteration(0)
  {}

  /**
    * \param first Start of the range in which to search.
    * \param last One element past the last element in the range in which to search.
    * \param query The element to compare to.
    * \return The iterator to the best element in the range (best is defined as the one which would compare favorably to all
    *         the elements in the range with respect to the distance metric).
    */
  template <typename TIterator>
  typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query)
  {
    std::cout << "LinearSearchBestStrategySelection iteration: " << this->Iteration << std::endl;

    // If the input element range is empty, there is nothing to do.
    if(first == last)
    {
      std::cerr << "LinearSearchBestStrategySelection: Nothing to do..." << std::endl;
      return *last;
    }

    PatchHelpers::WriteTopPatches(this->Image, this->PropertyMap, first, last, "BestPatches", this->Iteration);

    typedef float BinValueType;
    typedef QuadrantHistogramProperties<typename TImage::PixelType> QuadrantHistogramPropertiesType;
    typedef MaskedHistogramGenerator<BinValueType, QuadrantHistogramPropertiesType> MaskedHistogramGeneratorType;
    typedef typename MaskedHistogramGeneratorType::QuadrantHistogramType QuadrantHistogramType;

    itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion();

     // We must construct the bounds using the pixels from the entire valid region, otherwise the quadrant histogram
     // bins will not correspond to each other!
     bool useProvidedRanges = true;

     typename TImage::PixelType minValue = 0;

     typename TImage::PixelType maxValue = 255;

     // Use the range of the valid region of the target patch for the histograms. This is not necessarily the right thing
     // to do, because we might have a pretty solid "sky" patch that has more white in one of the quadrants than blue so
     // these quadrant histograms would match poorly even though the whole valid region was "sky" without any hard lines.
//     typename TImage::PixelType minValue;
//     MaskOperations::FindMinimumValueInMaskedRegion(this->Image, this->MaskImage,
//                                                    queryRegion, this->MaskImage->GetValidValue(), minValue);

//     typename TImage::PixelType maxValue;
//     MaskOperations::FindMaximumValueInMaskedRegion(this->Image, this->MaskImage,
//                                                    queryRegion, this->MaskImage->GetValidValue(), maxValue);

     QuadrantHistogramProperties<typename TImage::PixelType> quadrantHistogramProperties;

     quadrantHistogramProperties.SetAllMinRanges(minValue);
     quadrantHistogramProperties.SetAllMaxRanges(maxValue);

     QuadrantHistogramType targetQuadrantHistogram =
         MaskedHistogramGeneratorType::ComputeQuadrantMaskedImage1DHistogramAdaptive(this->Image, queryRegion,
           this->MaskImage, queryRegion, quadrantHistogramProperties,
           useProvidedRanges, this->MaskImage->GetValidValue());

     targetQuadrantHistogram.NormalizeHistograms();

     std::vector<float> distances;

     for(unsigned int i = 0; i < 4; ++i)
     {
       if(!targetQuadrantHistogram.Properties.Valid[i])
       {
         continue;
       }

       for(unsigned int j = 0; j < 4; ++j)
       {
         if(i == j)
         {
           continue;
         }

         if(!targetQuadrantHistogram.Properties.Valid[j])
         {
           continue;
         }

         typedef typename MaskedHistogramGeneratorType::HistogramType HistogramType;

         float distance = HistogramDifferences::HistogramDifference(targetQuadrantHistogram.Histograms[i], targetQuadrantHistogram.Histograms[j]);
//         std::cout << "distance " << i << " " << j << " " << distance << std::endl;
         distances.push_back(distance);
       }
     }

     std::string logFileName = "StrategySelection.txt";
     std::ofstream fout(logFileName.c_str(), std::ios::app);

     // If there were no valid histograms to compare, just use the best SSD patch
     if(distances.size() == 0)
     {
       std::cout << "Using best SSD patch (not enough valid histogram quadrants)..." << std::endl;
       fout << "F " << Helpers::ZeroPad(this->Iteration, 3) << std::endl; // 'F'ail
       fout.close();
       this->Iteration++;
       return *first;
     }

     float maxDistance = Helpers::Max(distances);

     std::cout << "maxDistance: " << maxDistance << std::endl;
     bool useHistogramComparison = false;

     if(maxDistance < 0.5f)
     {
       useHistogramComparison = true;
     }

     if(useHistogramComparison)
     {
       std::cout << "Using histogram comparison with minValue: " << minValue
                 << " maxValue: " << maxValue << std::endl;
//       LinearSearchBestHistogramDifference<PropertyMapType, TImage, TIterator>
//           histogramCheck(this->PropertyMap, this->Image, this->MaskImage);
       LinearSearchBestDualHistogramDifference<PropertyMapType, TImage, TIterator>
           histogramCheck(this->PropertyMap, this->Image, this->MaskImage);
       histogramCheck.SetRangeMin(minValue);
       histogramCheck.SetRangeMax(maxValue);
       histogramCheck.SetNumberOfBinsPerDimension(30);

       fout << "H " << Helpers::ZeroPad(this->Iteration, 3)
            << " " << maxDistance << " : " << distances << std::endl; // 'H'istogram
       fout.close();
       this->Iteration++;
       return histogramCheck(first, last, query);
     }
     else // Just use the best SSD match
     {
       std::cout << "Using best SSD patch..." << std::endl;
       fout << "S " << Helpers::ZeroPad(this->Iteration, 3)
            << " " << maxDistance << " : " << distances << std::endl; // 'S'SD
       fout.close();
       this->Iteration++;
       return *first;
     }

  }

}; // end class

#endif
<commit_msg>Breakout histogram similarity test in preparation for adding more strategies.<commit_after>/*=========================================================================
 *
 *  Copyright David Doria 2012 daviddoria@gmail.com
 *
 *  Licensed 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.txt
 *
 *  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.
 *
 *=========================================================================*/

#ifndef LinearSearchBestStrategySelection_HPP
#define LinearSearchBestStrategySelection_HPP

#include "HistogramDifference.hpp"

#include <Utilities/Histogram/HistogramHelpers.hpp>
#include <Utilities/Histogram/HistogramDifferences.hpp>

#include <Utilities/PatchHelpers.h>

/**
   * This function template is similar to std::min_element but can be used when the comparison
   * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the
   * the element in the range [first,last) which has the "smallest" distance (of course, both the
   * distance metric and comparison can be overriden to perform something other than the canonical
   * Euclidean distance and less-than comparison, which would yield the element with minimum distance).
   * \tparam DistanceValueType The value-type for the distance measures.
   * \tparam DistanceFunctionType The functor type to compute the distance measure.
   * \tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering).
   */
template <typename PropertyMapType, typename TImage>
class LinearSearchBestStrategySelection
{
  PropertyMapType PropertyMap;
  TImage* Image;
  Mask* MaskImage;

  unsigned int Iteration;

public:
  /** Constructor. This class requires the property map, an image, and a mask. */
  LinearSearchBestStrategySelection(PropertyMapType propertyMap, TImage* const image, Mask* const mask) :
    PropertyMap(propertyMap), Image(image), MaskImage(mask), Iteration(0)
  {}

  typedef QuadrantHistogramProperties<typename TImage::PixelType> QuadrantHistogramPropertiesType;
  typedef std::pair<bool, QuadrantHistogramPropertiesType> UseHistogramReturnPairType;

  UseHistogramReturnPairType UseHistogramComparison(const itk::ImageRegion<2>& queryRegion)
  {
    typedef float BinValueType;

    typedef MaskedHistogramGenerator<BinValueType, QuadrantHistogramPropertiesType> MaskedHistogramGeneratorType;
    typedef typename MaskedHistogramGeneratorType::QuadrantHistogramType QuadrantHistogramType;

    // We must construct the bounds using the pixels from the entire valid region, otherwise the quadrant histogram
    // bins will not correspond to each other!
    bool useProvidedRanges = true;

    typename TImage::PixelType minValue = 0;

    typename TImage::PixelType maxValue = 255;

     // Use the range of the valid region of the target patch for the histograms. This is not necessarily the right thing
     // to do, because we might have a pretty solid "sky" patch that has more white in one of the quadrants than blue so
     // these quadrant histograms would match poorly even though the whole valid region was "sky" without any hard lines.
//     typename TImage::PixelType minValue;
//     MaskOperations::FindMinimumValueInMaskedRegion(this->Image, this->MaskImage,
//                                                    queryRegion, this->MaskImage->GetValidValue(), minValue);

//     typename TImage::PixelType maxValue;
//     MaskOperations::FindMaximumValueInMaskedRegion(this->Image, this->MaskImage,
//                                                    queryRegion, this->MaskImage->GetValidValue(), maxValue);

    QuadrantHistogramPropertiesType quadrantHistogramProperties;

    quadrantHistogramProperties.SetAllMinRanges(minValue);
    quadrantHistogramProperties.SetAllMaxRanges(maxValue);

    QuadrantHistogramType targetQuadrantHistogram =
        MaskedHistogramGeneratorType::ComputeQuadrantMaskedImage1DHistogramAdaptive(this->Image, queryRegion,
                                                                                this->MaskImage, queryRegion, quadrantHistogramProperties,
                                                                                useProvidedRanges, this->MaskImage->GetValidValue());

    targetQuadrantHistogram.NormalizeHistograms();

    std::vector<float> distances;

    for(unsigned int i = 0; i < 4; ++i)
    {
      if(!targetQuadrantHistogram.Properties.Valid[i])
      {
        continue;
      }

      for(unsigned int j = 0; j < 4; ++j)
      {
        if(i == j)
        {
          continue;
        }

        if(!targetQuadrantHistogram.Properties.Valid[j])
        {
          continue;
        }

        typedef typename MaskedHistogramGeneratorType::HistogramType HistogramType;

        float distance = HistogramDifferences::HistogramDifference(targetQuadrantHistogram.Histograms[i], targetQuadrantHistogram.Histograms[j]);
        //         std::cout << "distance " << i << " " << j << " " << distance << std::endl;
        distances.push_back(distance);
      }
    }

    std::string logFileName = "StrategySelection.txt";
    std::ofstream fout(logFileName.c_str(), std::ios::app);

    // If there were no valid histograms to compare, just use the best SSD patch
    if(distances.size() == 0)
    {
      std::cout << "Using best SSD patch (not enough valid histogram quadrants)..." << std::endl;
      fout << "F " << Helpers::ZeroPad(this->Iteration, 3) << std::endl; // 'F'ail
      fout.close();
      this->Iteration++;
      return UseHistogramReturnPairType(false, quadrantHistogramProperties);
    }

    float maxDistance = Helpers::Max(distances);

    std::cout << "maxDistance: " << maxDistance << std::endl;

    if(maxDistance < 0.5f)
    {
      std::cout << "Using histogram comparison with minValue: " << minValue
                << " maxValue: " << maxValue << std::endl;
      return UseHistogramReturnPairType(true, quadrantHistogramProperties);
    }
    else
    {
      return UseHistogramReturnPairType(false, quadrantHistogramProperties);
    }

  }

  /**
    * \param first Start of the range in which to search.
    * \param last One element past the last element in the range in which to search.
    * \param query The element to compare to.
    * \return The iterator to the best element in the range (best is defined as the one which would compare favorably to all
    *         the elements in the range with respect to the distance metric).
    */
  template <typename TIterator>
  typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query)
  {
    std::cout << "LinearSearchBestStrategySelection iteration: " << this->Iteration << std::endl;

    // If the input element range is empty, there is nothing to do.
    if(first == last)
    {
      std::cerr << "LinearSearchBestStrategySelection: Nothing to do..." << std::endl;
      return *last;
    }

    PatchHelpers::WriteTopPatches(this->Image, this->PropertyMap, first, last, "BestPatches", this->Iteration);

    itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion();

    UseHistogramReturnPairType useHistogramComparison = UseHistogramComparison(queryRegion);

    QuadrantHistogramPropertiesType quadrantHistogramProperties = useHistogramComparison.second;

    if(useHistogramComparison.first)
    {
      //       LinearSearchBestHistogramDifference<PropertyMapType, TImage, TIterator>
      //           histogramCheck(this->PropertyMap, this->Image, this->MaskImage);
      LinearSearchBestDualHistogramDifference<PropertyMapType, TImage, TIterator>
          histogramCheck(this->PropertyMap, this->Image, this->MaskImage);

      // This is a single histogram comparison, so we use the ranges of the 0th quadrant of the quadrant histogram. This is
      // only reasonable as long as the same range is used for each quadrant (which it is in UseHistogramComparison()).
      histogramCheck.SetRangeMin(quadrantHistogramProperties.QuadrantMinRanges[0]);
      histogramCheck.SetRangeMax(quadrantHistogramProperties.QuadrantMaxRanges[0]);
      histogramCheck.SetNumberOfBinsPerDimension(30);

//      fout << "H " << Helpers::ZeroPad(this->Iteration, 3)
//           << " " << maxDistance << " : " << distances << std::endl; // 'H'istogram
//      fout.close();
      this->Iteration++;
      return histogramCheck(first, last, query);
    }
    else // Just use the best SSD match
    {
//      std::cout << "Using best SSD patch..." << std::endl;
//      fout << "S " << Helpers::ZeroPad(this->Iteration, 3)
//           << " " << maxDistance << " : " << distances << std::endl; // 'S'SD
//      fout.close();
      this->Iteration++;
      return *first;
    }

  }

}; // end class

#endif
<|endoftext|>


<commit_before>/* $Id$ */

// Script to create calibration parameters and store them into CDB
// Two sets of calibration parameters can be created:
// 1) equal parameters
// 2) randomly distributed parameters for decalibrated detector silumations

#if !defined(__CINT__)
#include "TControlBar.h"
#include "TString.h"
#include "TRandom.h"
#include "TH2F.h"
#include "TCanvas.h"

#include "AliRun.h"
#include "AliPHOSCalibData.h"
#include "AliCDBMetaData.h"
#include "AliCDBId.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#endif

static const Int_t nMod =  5;
static const Int_t nCol = 56;
static const Int_t nRow = 64;

void AliPHOSSetCDB()
{
  TControlBar *menu = new TControlBar("vertical","PHOS CDB");
  menu->AddButton("Help to run PHOS CDB","Help()",
		  "Explains how to use PHOS CDS menus");
  menu->AddButton("Equal CC","SetCC(0)",
		  "Set equal calibration coefficients");
  menu->AddButton("Decalibrate","SetCC(1)",
		  "Set random decalibration calibration coefficients");
  menu->AddButton("Set calibration equal to invers decalibration coefficients","SetCC(2)",
		  "Set calibration coefficients inverse to decalibration ones");
  menu->AddButton("Residual calibration","SetCC(3)",
		  "Set residual decalibration calibration coefficients");

  menu->AddButton("Read equal CC","GetCC(0)",
		  "Read initial equal calibration coefficients");
  menu->AddButton("Read random CC","GetCC(1)",
		  "Read random decalibration calibration coefficients");
  menu->AddButton("Read inverse CC","GetCC(2)",
		  "Read calibration coefficients inverse to decalibration ones");
  menu->AddButton("Read residual CC","GetCC(3)",
		  "Read residial calibration coefficients");
  menu->Show();
}

//------------------------------------------------------------------------
void Help()
{
  char *string =
    "\nSet calibration parameters and write them into ALICE CDB.
Press button \"Equal CC\" to create equal pedestals and gain factors.
Press button \"Decalibrate\" to create random pedestals and gain factors to imitate decalibrated detector\n";
  printf(string);
}

//------------------------------------------------------------------------
void SetCC(Int_t flag=0)
{
  // Writing calibration coefficients into the Calibration DB
  // Arguments:
  //   flag=0: all calibration coefficients are equal
  //   flag=1: decalibration coefficients
  //   flag=2: calibration coefficients equal to inverse decalibration ones
  // Author: Boris Polishchuk (Boris.Polichtchouk at cern.ch)

  TString DBFolder;
  Int_t firstRun   =  0;
  Int_t lastRun    =  0;
  Int_t beamPeriod =  1;
  char* objFormat  = "";

  AliPHOSCalibData* cdb = 0;

  if      (flag == 0) {
    DBFolder  ="local://InitCalibDB";
    firstRun  =  0;
    lastRun   =  999999;
    objFormat = "PHOS initial pedestals and ADC gain factors (5x64x56)";
    cdb = new AliPHOSCalibData();
    cdb->CreateNew();
  }

  else if (flag == 1) {
    DBFolder  ="local://DeCalibDB";
    firstRun  =  0;
    lastRun   =  999999;
    objFormat = "PHOS decalibration pedestals and ADC gain factors (5x64x56)";

    cdb = new AliPHOSCalibData();
    cdb->RandomEmc();
    cdb->RandomCpv();
  }

  else if (flag == 2) {
    // First read decalibration DB
    AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT");
    AliCDBManager::Instance()->SetSpecificStorage("PHOS/*","local://DeCalibDB");
    AliPHOSCalibData* cdbDecalib = new AliPHOSCalibData(100);

    DBFolder  ="local://InverseCalibDB";
    firstRun  = 0;
    lastRun   = 999999;
    objFormat = "PHOS calibration parameters equal to inverse decalibration ones (5x64x56)";
    cdb = new AliPHOSCalibData();

    // Read EMC decalibration parameters and put inverse values to a new artificial CDB

    for (Int_t module=1; module<=nMod; module++) {
      for (Int_t column=1; column<=nCol; column++) {
	for (Int_t row=1; row<=nRow; row++) {
	  Float_t valueGain = cdbDecalib->GetADCchannelEmc (module,column,row);
	  Float_t valuePed  = cdbDecalib->GetADCpedestalEmc(module,column,row);
	  cdb->SetADCchannelEmc(module,column,row,1./valueGain);
	  cdb->SetADCpedestalEmc(module,column,row,valuePed);
	}
      }
    }

    // Read CPV decalibration parameters and put inverse values to a new artificial CDB

    for (Int_t module=1; module<=nMod; module++) {
      for (Int_t column=1; column<=nCol*2; column++) {
	for (Int_t row=1; row<=nRow; row++) {
	  Float_t valueGain = cdbDecalib->GetADCchannelCpv (module,column,row);
	  Float_t valuePed  = cdbDecalib->GetADCpedestalCpv(module,column,row);
	  cdb->SetADCchannelCpv(module,column,row,1./valueGain);
	  cdb->SetADCpedestalCpv(module,column,row,valuePed);
	}
      }
    }
  }
  else if (flag == 3) {
    DBFolder  ="local://ResidualCalibDB";
    firstRun  =  0;
    lastRun   =  999999;
    objFormat = "PHOS residual ADC gain factors (5x64x56)";

    cdb = new AliPHOSCalibData();
    cdb->RandomEmc(0.98,1.02);
    cdb->RandomCpv(0.00115,0.00125);
  }

  //Store calibration data into database

  AliCDBMetaData md;
  md.SetComment(objFormat);
  md.SetBeamPeriod(beamPeriod);
  md.SetResponsible("Boris Polichtchouk");

  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT");
  AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data());

  cdb->WriteEmc(firstRun,lastRun,&md);
  cdb->WriteCpv(firstRun,lastRun,&md);

}

//------------------------------------------------------------------------
void GetCC(Int_t flag=0)
{
  // Read calibration coefficients into the Calibration DB
  // Arguments:
  //   flag=0: all calibration coefficients are equal
  //   flag=1: decalibration coefficients
  //   flag=2: calibration coefficients equal to inverse decalibration ones
  // Author: Yuri.Kharlov at cern.ch

  TString DBFolder;
  Int_t runNumber;

  if      (flag == 0) {
    DBFolder  ="local://InitCalibDB";
    runNumber = 0;
  }
  else if (flag == 1) {
    DBFolder  ="local://DeCalibDB";
    runNumber = 100;
  }
  else if (flag == 2) {
    DBFolder  ="local://InverseCalibDB";
    runNumber = 200;
  }
  else if (flag == 2) {
    DBFolder  ="local://ResidualCalibDB";
    runNumber = 0;
  }

  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT");
  AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data());

  AliPHOSCalibData* clb  = new AliPHOSCalibData(runNumber);

  TH2::AddDirectory(kFALSE);

  TH2F* hPed[5];
  TH2F* hGain[5];

  TCanvas *cPed  = new TCanvas("cPed" ,"PHOS EMC Pedestals"   , 10,10,400,800);
  TCanvas *cGain = new TCanvas("cGain","PHOS EMC Gain factors",410,10,400,800);
  cPed ->Divide(1,5);
  cGain->Divide(1,5);

  for (Int_t module=1; module<=nMod; module++) {
    TString namePed="hPed";
    namePed+=module;
    TString titlePed="Pedestals in module ";
    titlePed+=module;
    hPed[module-1] = new TH2F(namePed.Data(),titlePed.Data(),
			    nCol,1.,1.*nCol,nRow,1.,1.*nRow);

    TString nameGain="hGain";
    nameGain+=module;
    TString titleGain="Gain factors in module ";
    titleGain+=module;
    hGain[module-1] = new TH2F(nameGain.Data(),titleGain.Data(),
			    nCol,1.,1.*nCol,nRow,1.,1.*nRow);

    for (Int_t column=1; column<=nCol; column++) {
      for (Int_t row=1; row<=nRow; row++) {
	Float_t ped  = clb->GetADCpedestalEmc(module,column,row);
	Float_t gain = clb->GetADCchannelEmc (module,column,row);
	hPed[module-1]->SetBinContent(column,row,ped);
	hGain[module-1]->SetBinContent(column,row,gain);
      }
    }
    cPed ->cd(module);
    hPed[module-1]->Draw("lego2");
    cGain->cd(module);
    hGain[module-1]->Draw("lego2");
  }
  cPed ->Print("pedestals.eps");
  cGain->Print("gains.eps");
}
<commit_msg>New ideal set of calibration parameters and bad channel map, along with a script creating them<commit_after>/* $Id$ */

// Script to create calibration parameters and store them into CDB
// Two sets of calibration parameters can be created:
// 1) equal parameters
// 2) randomly distributed parameters for decalibrated detector silumations

#if !defined(__CINT__)
#include "TControlBar.h"
#include "TString.h"
#include "TRandom.h"
#include "TH2F.h"
#include "TCanvas.h"

#include "AliRun.h"
#include "AliPHOSCalibData.h"
#include "AliCDBMetaData.h"
#include "AliCDBId.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#endif

static const Int_t nMod =  5;
static const Int_t nCol = 56;
static const Int_t nRow = 64;

void AliPHOSSetCDB()
{
  TControlBar *menu = new TControlBar("vertical","PHOS CDB");
  menu->AddButton("Help to run PHOS CDB","Help()",
		  "Explains how to use PHOS CDB menus");
  menu->AddButton("Equal CC","SetCC(0)",
		  "Set equal CC");
  menu->AddButton("Full decalibration","SetCC(1)",
		  "Set random decalibration CC");
  menu->AddButton("Residual decalibration","SetCC(2)",
		  "Set residual decalibration calibration coefficients");

  menu->AddButton("Read equal CC","GetCC(0)",
		  "Read equal calibration coefficients");
  menu->AddButton("Read random CC","GetCC(1)",
		  "Read random decalibration calibration coefficients");
  menu->AddButton("Read residual CC","GetCC(2)",
		  "Read residial calibration coefficients");
  menu->AddButton("Exit","gApplication->Terminate(0)","Quit aliroot session");
  menu->Show();
}

//------------------------------------------------------------------------
void Help()
{
  TString string="\nSet calibration parameters and write them into ALICE OCDB:";
  string += "\n\tPress button \"Equal CC\" to create equal calibration coefficients;";
  string += "\n\tPress button \"Full decalibration\" to create \n\t random calibration coefficients with 20\% spread \n\t to imitate fully decalibrated detector;";
  string += "\n\tPress button \"Residual decalibration\" to create \n\t random calibration coefficients with +-2\% spread\n\t to imitate decalibrated detector after initial calibration.\n";
  printf("%s",string.Data());
}

//------------------------------------------------------------------------
void SetCC(Int_t flag=0)
{
  // Writing calibration coefficients into the Calibration DB
  // Arguments:
  //   flag=0: all calibration coefficients are equal
  //   flag=1: decalibration coefficients
  //   flag=2: calibration coefficients equal to inverse decalibration ones
  // Author: Boris Polishchuk (Boris.Polichtchouk at cern.ch)

  TString DBFolder;
  Int_t firstRun   =  0;
  Int_t lastRun    =  0;
  Int_t beamPeriod =  1;
  char* objFormat  = "";

  AliPHOSCalibData* cdb = 0;

  if      (flag == 0) {
    DBFolder  ="local://InitCalibDB";
    firstRun  =  0;
    lastRun   =  999999;
    objFormat = "PHOS initial pedestals and ADC gain factors (5x64x56)";
    cdb = new AliPHOSCalibData();
    cdb->CreateNew();
  }

  else if (flag == 1) {
    DBFolder  ="local://FullDecalibDB";
    firstRun  =  0;
    lastRun   =  999999;
    objFormat = "PHOS fully decalibrated calibration coefficients (5x64x56)";

    cdb = new AliPHOSCalibData();
    cdb->RandomEmc(0.8,1.2);
    cdb->RandomCpv(0.0008,0.0016);
  }

  else if (flag == 2) {
    DBFolder  ="local://ResidualCalibDB";
    firstRun  =  0;
    lastRun   =  999999;
    objFormat = "PHOS residual calibration coefficients (5x64x56)";

    cdb = new AliPHOSCalibData();
    cdb->RandomEmc(0.98,1.02);
    cdb->RandomCpv(0.00115,0.00125);
  }

  //Store calibration data into database

  AliCDBMetaData md;
  md.SetComment(objFormat);
  md.SetBeamPeriod(beamPeriod);
  md.SetResponsible("Boris Polichtchouk");

  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT");
  if(gSystem->Getenv("STORAGE")){
    cout << "Setting specific storage" << endl;
    AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data());
  }

  cdb->WriteEmc(firstRun,lastRun,&md);
  cdb->WriteCpv(firstRun,lastRun,&md);
  cdb->WriteEmcBadChannelsMap(firstRun,lastRun,&md);

}

//------------------------------------------------------------------------
void GetCC(Int_t flag=0)
{
  // Read calibration coefficients into the Calibration DB
  // Arguments:
  //   flag=0: all calibration coefficients are equal
  //   flag=1: decalibration coefficients
  //   flag=2: calibration coefficients equal to inverse decalibration ones
  // Author: Yuri.Kharlov at cern.ch

  gStyle->SetPalette(1);
  gStyle->SetOptStat(0);
  TString DBFolder;
  Int_t runNumber;

  if      (flag == 0) {
    DBFolder  ="local://InitCalibDB";
    runNumber = 0;
  }
  else if (flag == 1) {
    DBFolder  ="local://FullDecalibDB";
    runNumber = 0;
  }
  else if (flag == 2) {
    DBFolder  ="local://ResidualCalibDB";
    runNumber = 0;
  }

  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT");
  if(gSystem->Getenv("STORAGE")){
    cout << "Setting specific storage" << endl;
    AliCDBManager::Instance()->SetSpecificStorage("PHOS/*",DBFolder.Data());
  }

  AliPHOSCalibData* clb  = new AliPHOSCalibData(runNumber);

  TH2::AddDirectory(kFALSE);

  TH2F* hGain[5];

  TCanvas *cGain = new TCanvas("cGain","PHOS EMC Gain factors",10,10,700,500);
  cGain->Divide(3,2);

  for (Int_t module=1; module<=nMod; module++) {
    TString nameGain="hGain";
    nameGain+=module;
    TString titleGain="Gain factors in module ";
    titleGain+=module;
    hGain[module-1] = new TH2F(nameGain.Data(),titleGain.Data(),
			    nCol,1.,1.*nCol,nRow,1.,1.*nRow);

    for (Int_t column=1; column<=nCol; column++) {
      for (Int_t row=1; row<=nRow; row++) {
        Float_t gain = clb->GetADCchannelEmc (module,column,row);
	hGain[module-1]->SetBinContent(column,row,gain);
      }
    }
    cGain->cd(module);
    hGain[module-1]->SetMinimum(0);
    hGain[module-1]->Draw("colz");
  }
  cGain->Print("gains.eps");
}
<|endoftext|>


<commit_before>
void ProofEnableAliRoot(const char* location = "/usr/local/grid/AliRoot/v4-05-Release")
{
  // enables a locally deployed AliRoot in a PROOF cluster

  printf("Load libraries: %s \n",location);
  gProof->Exec(Form("TString str(gSystem->ExpandPathName(\"%s\")); gSystem->Setenv(\"ALICE_ROOT\", str);", location), kTRUE);

  gProof->AddIncludePath(Form("%s/include", location));
  gProof->AddIncludePath(Form("%s/TPC", location));
  gProof->AddIncludePath(Form("%s/PWG0", location));
  gProof->AddIncludePath(Form("%s/PWG0/dNdPt", location));
  gProof->AddIncludePath(Form("%s/ANALYSIS", location));

  gProof->AddDynamicPath(Form("%s/lib/tgt_linuxx8664gcc", location));

  // load all libraries
  gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/PWG0/dNdPt/macros/LoadMyLibs.C\")",kTRUE);
}

<commit_msg>small correction<commit_after>
void ProofEnableAliRootGSI(const char* location = "/usr/local/grid/AliRoot/v4-05-Release")
{
  // enables a locally deployed AliRoot in a PROOF cluster

  printf("Load libraries: %s \n",location);
  gProof->Exec(Form("TString str(gSystem->ExpandPathName(\"%s\")); gSystem->Setenv(\"ALICE_ROOT\", str);", location), kTRUE);

  gProof->AddIncludePath(Form("%s/include", location));
  gProof->AddIncludePath(Form("%s/TPC", location));
  gProof->AddIncludePath(Form("%s/PWG0", location));
  gProof->AddIncludePath(Form("%s/PWG0/dNdPt", location));
  gProof->AddIncludePath(Form("%s/ANALYSIS", location));

  gProof->AddDynamicPath(Form("%s/lib/tgt_linuxx8664gcc", location));

  // load all libraries
  gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/PWG0/dNdPt/macros/LoadMyLibs.C\")",kTRUE);
}

<|endoftext|>


<commit_before>AliFourPion *AddTaskFourPion(
			         Bool_t MCcase=kFALSE,
			         Bool_t TabulatePairs=kFALSE,
				 Int_t CentBinLowLimit=0,
				 Int_t CentBinHighLimit=1,
				 TString StWeightName="alien:///alice/cern.ch/user/d/dgangadh/WeightFile_FourPion.root",
				 TString StMomResName="alien:///alice/cern.ch/user/d/dgangadh/MomResFile_FourPion.root",
				 TString StKName="alien:///alice/cern.ch/user/d/dgangadh/KFile_FourPion.root",
				 TString StMuonName="alien:///alice/cern.ch/user/d/dgangadh/MuonCorrection_FourPion.root",
				 TString StEAName="alien:///alice/cern.ch/user/d/dgangadh/c3EAfile.root"
			     ) {

  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskFourPion", "No analysis manager to connect to.");
    return NULL;
  }

  //____________________________________________//
  // Create task
  AliFourPion *FourPionTask = new AliFourPion("FourPionTask");
  if(!FourPionTask) return NULL;
  FourPionTask->SetLEGOCase(kTRUE);
  FourPionTask->SetMCdecision(MCcase);
  FourPionTask->SetCollisionType(0);
  FourPionTask->SetGenerateSignal(kFALSE);
  FourPionTask->SetTabulatePairs(TabulatePairs);
  FourPionTask->SetInterpolationType(kFALSE);
  FourPionTask->SetCentBinRange(CentBinLowLimit, CentBinHighLimit);
  FourPionTask->SetRMax(11);
  FourPionTask->SetfcSq(0.7);
  FourPionTask->SetFilterBit(7);
  FourPionTask->SetMaxChi2NDF(10);
  FourPionTask->SetMinTPCncls(0);
  FourPionTask->SetPairSeparationCutEta(0.02);
  FourPionTask->SetPairSeparationCutPhi(0.045);
  FourPionTask->SetNsigmaTPC(2.0);
  FourPionTask->SetNsigmaTOF(2.0);
  //
  FourPionTask->SetMixedChargeCut(kFALSE);
  FourPionTask->SetMinPt(0.16);
  FourPionTask->SetMaxPt(1.0);
  FourPionTask->SetKT3transition(0.3);
  FourPionTask->SetKT4transition(0.3);
  mgr->AddTask(FourPionTask);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGCF.outputFourPionAnalysis.root";
  AliAnalysisDataContainer *coutFourPion = mgr->CreateContainer("FourPionOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  mgr->ConnectInput(FourPionTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(FourPionTask, 1, coutFourPion);

  TFile *inputFileWeight = 0;
  TFile *inputFileMomRes = 0;
  TFile *inputFileFSI = 0;
  TFile *inputFileMuon = 0;
  TFile *inputFileEA = 0;

  if(!TabulatePairs){
    inputFileWeight = TFile::Open(StWeightName,"OLD");
    if (!inputFileWeight){
      cout << "Requested file:" << inputFileWeight << " was not opened. ABORT." << endl;
      return NULL;
    }
    ////////////////////////////////////////////////////
    // C2 Weight File
    const Int_t ktbins_temp = FourPionTask->GetNumKtBins();
    const Int_t cbins_temp = FourPionTask->GetNumCentBins();
    const Int_t ktbins = ktbins_temp;
    const Int_t cbins = cbins_temp;

    TH3F *weightHisto[ktbins][cbins];
    for(Int_t i=0; i<ktbins; i++){
      for(Int_t j=0; j<cbins; j++){
	TString name = "Weight_Kt_";
	name += i;
	name += "_Ky_0_M_";
	name += j;
	name += "_ED_0";

	weightHisto[i][j] = (TH3F*)inputFileWeight->Get(name);
      }
    }
    FourPionTask->SetWeightArrays( kTRUE, weightHisto );
    //
    //
    inputFileEA = TFile::Open(StEAName,"OLD");
    if (!inputFileEA){
      cout << "Requested file:" << inputFileEA << " was not opened. ABORT." << endl;
      return NULL;
    }
    TH3D *PbPbEA = 0;
    TH3D *pPbEA = 0;
    TH3D *ppEA = 0;
    PbPbEA = (TH3D*)inputFileEA->Get("PbPbEA");
    pPbEA = (TH3D*)inputFileEA->Get("pPbEA");
    ppEA = (TH3D*)inputFileEA->Get("ppEA");
    FourPionTask->Setc3FitEAs( kTRUE, PbPbEA, pPbEA, ppEA );
    ////////////////////////////////////////////////////
  }// TabulatePairs check

  if(!MCcase && !TabulatePairs){

    inputFileMomRes = TFile::Open(StMomResName,"OLD");
    if (!inputFileMomRes){
      cout << "Requested file:" << inputFileMomRes << " was not opened. ABORT." << endl;
      return NULL;
    }
    ////////////////////////////////////////////////////
    // Momentum Resolution File
    TH2D *momResHisto2DSC = 0;
    TH2D *momResHisto2DMC = 0;
    momResHisto2DSC = (TH2D*)inputFileMomRes->Get("MRC_C2_SC");
    momResHisto2DMC = (TH2D*)inputFileMomRes->Get("MRC_C2_MC");
    FourPionTask->SetMomResCorrections( kTRUE, momResHisto2DSC, momResHisto2DMC );
    ////////////////////////////////////////////////////

    // Muon corrections
    inputFileMuon = TFile::Open(StMuonName,"OLD");
    if (!inputFileMuon){
      cout << "Requested file:" << inputFileMuon << " was not opened. ABORT." << endl;
      return NULL;
    }
    TH2D *muonHisto2D = 0;
    muonHisto2D = (TH2D*)inputFileMuon->Get("WeightmuonCorrection");
    FourPionTask->SetMuonCorrections( kTRUE, muonHisto2D);

  }// MCcase and TabulatePairs check

  ////////////////////////////////////////////////////
  // FSI File
  inputFileFSI = TFile::Open(StKName,"OLD");
  if (!inputFileFSI){
    cout << "Requested file:" << inputFileFSI << " was not opened. ABORT." << endl;
    return NULL;
  }
  TH1D *FSIss[12];
  TH1D *FSIos[12];
  for(Int_t index=0; index<12; index++) {
    TString *nameSS=new TString("K2ss_");
    *nameSS += index;
    FSIss[index] = (TH1D*)inputFileFSI->Get(nameSS->Data());
    TString *nameOS=new TString("K2os_");
    *nameOS += index;
    FSIos[index] = (TH1D*)inputFileFSI->Get(nameOS->Data());
    //
    FSIss[index]->SetDirectory(0);
    FSIos[index]->SetDirectory(0);
  }
  //
  FourPionTask->SetFSICorrelations( kTRUE, FSIss, FSIos );
  ////////////////////////////////////////////////////

  // Return the task pointer
  return FourPionTask;
}
<commit_msg>Include extra FSI bin for pp and pPb<commit_after>AliFourPion *AddTaskFourPion(
			         Bool_t MCcase=kFALSE,
			         Bool_t TabulatePairs=kFALSE,
				 Int_t CentBinLowLimit=0,
				 Int_t CentBinHighLimit=1,
				 TString StWeightName="alien:///alice/cern.ch/user/d/dgangadh/WeightFile_FourPion.root",
				 TString StMomResName="alien:///alice/cern.ch/user/d/dgangadh/MomResFile_FourPion.root",
				 TString StKName="alien:///alice/cern.ch/user/d/dgangadh/KFile_FourPion.root",
				 TString StMuonName="alien:///alice/cern.ch/user/d/dgangadh/MuonCorrection_FourPion.root",
				 TString StEAName="alien:///alice/cern.ch/user/d/dgangadh/c3EAfile.root"
			     ) {

  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskFourPion", "No analysis manager to connect to.");
    return NULL;
  }

  //____________________________________________//
  // Create task
  AliFourPion *FourPionTask = new AliFourPion("FourPionTask");
  if(!FourPionTask) return NULL;
  FourPionTask->SetLEGOCase(kTRUE);
  FourPionTask->SetMCdecision(MCcase);
  FourPionTask->SetCollisionType(0);
  FourPionTask->SetGenerateSignal(kFALSE);
  FourPionTask->SetTabulatePairs(TabulatePairs);
  FourPionTask->SetInterpolationType(kFALSE);
  FourPionTask->SetCentBinRange(CentBinLowLimit, CentBinHighLimit);
  FourPionTask->SetRMax(11);
  FourPionTask->SetfcSq(0.7);
  FourPionTask->SetFilterBit(7);
  FourPionTask->SetMaxChi2NDF(10);
  FourPionTask->SetMinTPCncls(0);
  FourPionTask->SetPairSeparationCutEta(0.02);
  FourPionTask->SetPairSeparationCutPhi(0.045);
  FourPionTask->SetNsigmaTPC(2.0);
  FourPionTask->SetNsigmaTOF(2.0);
  //
  FourPionTask->SetMixedChargeCut(kFALSE);
  FourPionTask->SetMinPt(0.16);
  FourPionTask->SetMaxPt(1.0);
  FourPionTask->SetKT3transition(0.3);
  FourPionTask->SetKT4transition(0.3);
  mgr->AddTask(FourPionTask);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGCF.outputFourPionAnalysis.root";
  AliAnalysisDataContainer *coutFourPion = mgr->CreateContainer("FourPionOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  mgr->ConnectInput(FourPionTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(FourPionTask, 1, coutFourPion);

  TFile *inputFileWeight = 0;
  TFile *inputFileMomRes = 0;
  TFile *inputFileFSI = 0;
  TFile *inputFileMuon = 0;
  TFile *inputFileEA = 0;

  if(!TabulatePairs){
    inputFileWeight = TFile::Open(StWeightName,"OLD");
    if (!inputFileWeight){
      cout << "Requested file:" << inputFileWeight << " was not opened. ABORT." << endl;
      return NULL;
    }
    ////////////////////////////////////////////////////
    // C2 Weight File
    const Int_t ktbins_temp = FourPionTask->GetNumKtBins();
    const Int_t cbins_temp = FourPionTask->GetNumCentBins();
    const Int_t ktbins = ktbins_temp;
    const Int_t cbins = cbins_temp;

    TH3F *weightHisto[ktbins][cbins];
    for(Int_t i=0; i<ktbins; i++){
      for(Int_t j=0; j<cbins; j++){
	TString name = "Weight_Kt_";
	name += i;
	name += "_Ky_0_M_";
	name += j;
	name += "_ED_0";

	weightHisto[i][j] = (TH3F*)inputFileWeight->Get(name);
      }
    }
    FourPionTask->SetWeightArrays( kTRUE, weightHisto );
    //
    //
    inputFileEA = TFile::Open(StEAName,"OLD");
    if (!inputFileEA){
      cout << "Requested file:" << inputFileEA << " was not opened. ABORT." << endl;
      return NULL;
    }
    TH3D *PbPbEA = 0;
    TH3D *pPbEA = 0;
    TH3D *ppEA = 0;
    PbPbEA = (TH3D*)inputFileEA->Get("PbPbEA");
    pPbEA = (TH3D*)inputFileEA->Get("pPbEA");
    ppEA = (TH3D*)inputFileEA->Get("ppEA");
    FourPionTask->Setc3FitEAs( kTRUE, PbPbEA, pPbEA, ppEA );
    ////////////////////////////////////////////////////
  }// TabulatePairs check

  if(!MCcase && !TabulatePairs){

    inputFileMomRes = TFile::Open(StMomResName,"OLD");
    if (!inputFileMomRes){
      cout << "Requested file:" << inputFileMomRes << " was not opened. ABORT." << endl;
      return NULL;
    }
    ////////////////////////////////////////////////////
    // Momentum Resolution File
    TH2D *momResHisto2DSC = 0;
    TH2D *momResHisto2DMC = 0;
    momResHisto2DSC = (TH2D*)inputFileMomRes->Get("MRC_C2_SC");
    momResHisto2DMC = (TH2D*)inputFileMomRes->Get("MRC_C2_MC");
    FourPionTask->SetMomResCorrections( kTRUE, momResHisto2DSC, momResHisto2DMC );
    ////////////////////////////////////////////////////

    // Muon corrections
    inputFileMuon = TFile::Open(StMuonName,"OLD");
    if (!inputFileMuon){
      cout << "Requested file:" << inputFileMuon << " was not opened. ABORT." << endl;
      return NULL;
    }
    TH2D *muonHisto2D = 0;
    muonHisto2D = (TH2D*)inputFileMuon->Get("WeightmuonCorrection");
    FourPionTask->SetMuonCorrections( kTRUE, muonHisto2D);

  }// MCcase and TabulatePairs check

  ////////////////////////////////////////////////////
  // FSI File
  inputFileFSI = TFile::Open(StKName,"OLD");
  if (!inputFileFSI){
    cout << "Requested file:" << inputFileFSI << " was not opened. ABORT." << endl;
    return NULL;
  }
  TH1D *FSIss[13];
  TH1D *FSIos[13];
  for(Int_t index=0; index<13; index++) {
    TString *nameSS=new TString("K2ss_");
    *nameSS += index;
    FSIss[index] = (TH1D*)inputFileFSI->Get(nameSS->Data());
    TString *nameOS=new TString("K2os_");
    *nameOS += index;
    FSIos[index] = (TH1D*)inputFileFSI->Get(nameOS->Data());
    //
    FSIss[index]->SetDirectory(0);
    FSIos[index]->SetDirectory(0);
  }
  //
  FourPionTask->SetFSICorrelations( kTRUE, FSIss, FSIos );
  ////////////////////////////////////////////////////

  // Return the task pointer
  return FourPionTask;
}
<|endoftext|>


<commit_before>/*
 * File:   Scene.hpp
 * Author: Benedikt Vogler
 *
 * Created on 8. Juli 2014, 18:54
 */

#ifndef SCENE_HPP
#define	SCENE_HPP

#include "Material.hpp"
#include "Camera.hpp"
#include "LightPoint.hpp"
#include "RenderObject.hpp"
#include <map>

struct Scene {
    std::map<std::string, Material> materials;
    std::map<std::string, LightPoint> lights;
    std::map<std::string, std::shared_ptr<RenderObject>> renderObjects;
    Camera camera;
    std::string camname;
    int resX;
    int resY;
    std::string outputFile;
    Color amb;
    int antialiase;
    bool random;

//    //manual destructor needed?
//    ~Scene(){
//        for (auto itr=materials.begin(); itr !=materials.end();++itr) {
//            materials.erase(itr);
//        }
//        for (auto itr=lights.begin(); itr !=lights.end();++itr) {
//            lights.erase(itr);
//        }
//        for (auto itr=renderObjects.begin(); itr !=renderObjects.end();++itr) {
//            renderObjects.erase(itr);
//        }
//    }
};

#endif	/* SCENE_HPP */

<commit_msg>Compatible with VS<commit_after>/*
 * File:   Scene.hpp
 * Author: Benedikt Vogler
 *
 * Created on 8. Juli 2014, 18:54
 */

#ifndef SCENE_HPP
#define	SCENE_HPP

#include "Material.hpp"
#include "Camera.hpp"
#include "LightPoint.hpp"
#include "RenderObject.hpp"
#include <map>
#include <memory>

struct Scene {
    std::map<std::string, Material> materials;
    std::map<std::string, LightPoint> lights;
    std::map<std::string, std::shared_ptr<RenderObject>> renderObjects;
    Camera camera;
    std::string camname;
    int resX;
    int resY;
    std::string outputFile;
    Color amb;
    int antialiase;
    bool random;

//    //manual destructor needed?
//    ~Scene(){
//        for (auto itr=materials.begin(); itr !=materials.end();++itr) {
//            materials.erase(itr);
//        }
//        for (auto itr=lights.begin(); itr !=lights.end();++itr) {
//            lights.erase(itr);
//        }
//        for (auto itr=renderObjects.begin(); itr !=renderObjects.end();++itr) {
//            renderObjects.erase(itr);
//        }
//    }
};

#endif	/* SCENE_HPP */

<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "swissknife_lease_curl.h"

#include "cvmfs_config.h"

size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) {
  CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp);

  if (size * nmemb < 1) {
    return 0;
  }

  my_buffer->data = static_cast<char*>(buffer);

  return my_buffer->data.size();
}

CURL* PrepareCurl(const char* method) {
  const char* user_agent_string = "cvmfs/" VERSION;

  CURL* h_curl = curl_easy_init();

  if (h_curl) {
    curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);
    curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string);
    curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);
    curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method);
    curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  }

  return h_curl;
}

bool MakeAcquireRequest(const std::string& user_name,
                        const std::string& repo_path,
                        const std::string& repo_service_url,
                        CurlBuffer* buffer) {
  CURLcode ret = static_cast<CURLcode>(0);

  CURL* h_curl = PrepareCurl("POST");
  if (!h_curl) {
    return false;
  }

  // Make request to acquire lease from repo services
  curl_easy_setopt(h_curl, CURLOPT_URL,
                   (repo_service_url + REPO_SERVICES_API_ROOT +
                    "/leases?user=" + user_name + "&path=" + repo_path)
                       .c_str());
  curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
                   static_cast<curl_off_t>(0));
  curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
  curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);

  ret = curl_easy_perform(h_curl);

  curl_easy_cleanup(h_curl);
  h_curl = NULL;

  return !ret;
}

bool MakeDeleteRequest(const std::string& session_token,
                       const std::string& repo_service_url,
                       CurlBuffer* buffer) {
  CURLcode ret = static_cast<CURLcode>(0);

  CURL* h_curl = PrepareCurl("DELETE");
  if (!h_curl) {
    return false;
  }
  curl_easy_setopt(
      h_curl, CURLOPT_URL,
      (repo_service_url + REPO_SERVICES_API_ROOT + "/leases/" + session_token)
          .c_str());
  curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
                   static_cast<curl_off_t>(0));
  curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, 0);
  curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
  curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);

  ret = curl_easy_perform(h_curl);

  curl_easy_cleanup(h_curl);
  h_curl = NULL;

  return !ret;
}
<commit_msg>cvmfs_swissknife lease - modify MakeAcquireRequest to use JSON body<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "swissknife_lease_curl.h"

#include "cvmfs_config.h"

size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) {
  CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp);

  if (size * nmemb < 1) {
    return 0;
  }

  my_buffer->data = static_cast<char*>(buffer);

  return my_buffer->data.size();
}

CURL* PrepareCurl(const char* method) {
  const char* user_agent_string = "cvmfs/" VERSION;

  CURL* h_curl = curl_easy_init();

  if (h_curl) {
    curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);
    curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string);
    curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);
    curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method);
    curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  }

  return h_curl;
}

bool MakeAcquireRequest(const std::string& user_name,
                        const std::string& repo_path,
                        const std::string& repo_service_url,
                        CurlBuffer* buffer) {
  CURLcode ret = static_cast<CURLcode>(0);

  CURL* h_curl = PrepareCurl("POST");
  if (!h_curl) {
    return false;
  }

  // Prepare payload
  const std::string payload =
      "{\"user\" : \"" + user_name + "\", \"path\" : \"" + repo_path + "\"}";

  // Make request to acquire lease from repo services
  curl_easy_setopt(
      h_curl, CURLOPT_URL,
      (repo_service_url + REPO_SERVICES_API_ROOT + "/leases").c_str());
  curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
                   static_cast<curl_off_t>(payload.length()));
  curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, payload.c_str());
  curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
  curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);

  ret = curl_easy_perform(h_curl);

  curl_easy_cleanup(h_curl);
  h_curl = NULL;

  return !ret;
}

bool MakeDeleteRequest(const std::string& session_token,
                       const std::string& repo_service_url,
                       CurlBuffer* buffer) {
  CURLcode ret = static_cast<CURLcode>(0);

  CURL* h_curl = PrepareCurl("DELETE");
  if (!h_curl) {
    return false;
  }
  curl_easy_setopt(
      h_curl, CURLOPT_URL,
      (repo_service_url + REPO_SERVICES_API_ROOT + "/leases/" + session_token)
          .c_str());
  curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
                   static_cast<curl_off_t>(0));
  curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, 0);
  curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
  curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);

  ret = curl_easy_perform(h_curl);

  curl_easy_cleanup(h_curl);
  h_curl = NULL;

  return !ret;
}
<|endoftext|>