<commit_before>#include "time.h"

#include <strstream>
#include <RegisterWindow.h>
#include <FL/fl_file_chooser.H>

RegisterWindow::RegisterWindow()
{
  m_FixedImageViewer = ImageViewerType::New() ;
  m_MovingImageViewer = ImageViewerType::New() ;
  m_RegisteredImageViewer = ImageViewerType::New() ;
  m_MixedChannelViewer = MixedChannelViewerType::New() ;

  m_FixedImageViewer->SetLabel( "Fixed Image" ) ;
  m_MovingImageViewer->SetLabel( "Moving Image" ) ;
  m_RegisteredImageViewer->SetLabel( "Registered Image" ) ;
  m_MixedChannelViewer->SetLabel( "Mixed Channel View" ) ;

  m_DebugViewer = ImageViewerType::New() ;
  m_DebugViewer->SetLabel( "Debug" ) ;

  m_ChannelSources[0] = fixed ;
  m_ChannelSources[1] = registered ;
  m_ChannelSources[2] = none ;

  m_FixedImageViewer->imageViewer->
    SetSelectionCallBack((void*) this,
                         RegisterWindow::SelectionCallBackWrapper) ;
  buStartRegistration->deactivate() ;
  buSaveRegisteredImage->deactivate() ;
  buShowDisplay->deactivate() ;
  lsDisplay->deactivate() ;
  menuFixedImageDisplay->deactivate() ;
  menuMovingImageDisplay->deactivate() ;
  menuRegisteredImageDisplay->deactivate() ;
  menuMixedChannel->deactivate() ;

  m_IterationObserver = IterationObserverType::New();
  m_IterationObserver->SetOptimizer( m_Registrator->GetOptimizer() );
  m_IterationObserver->SetBrowser( iterationsBrowser );

  this->ShowStatus("Let's start by loading an image...");
}

RegisterWindow::~RegisterWindow()
{
}

void RegisterWindow::LoadMovingImage(void)
{
  const char * filename =
    fl_file_chooser("Moving Image filename","*.*","");
  if( !filename )
    {
      return;
    }

  m_MovingImageFileName = filename ;

  this->ShowStatus("Loading moving image file...");

  try
    {
      RegisterApplication::LoadMovingImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuMovingImageDisplay->activate() ;

  this->ShowStatus("Moving Image Loaded");
}

void RegisterWindow::LoadFixedImage(void)
{
  const char * filename =
    fl_file_chooser("Fixed Image filename","*.*","");

  if( !filename )
    {
      return;
    }

  m_FixedImageFileName = filename ;

  this->ShowStatus("Loading fixed image file...");

  try
    {
      RegisterApplication::LoadFixedImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  m_TempBox.X1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[0] ;
  m_TempBox.Y1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[1] ;
  m_TempBox.X2 = m_TempBox.X1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  m_TempBox.Y2 = m_TempBox.Y1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  outSelectedRegionBeginX->value(m_TempBox.X1) ;
  outSelectedRegionBeginY->value(m_TempBox.Y1) ;
  outSelectedRegionEndX->value(m_TempBox.X2) ;
  outSelectedRegionEndY->value(m_TempBox.Y2) ;

  m_FixedImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuFixedImageDisplay->activate() ;
  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  this->ShowStatus("Fixed Image Loaded");
}

void RegisterWindow::Show()
{
  winMain->show() ;
}

void RegisterWindow::Hide()
{
  winMain->hide();
  m_FixedImageViewer->Hide();
  m_MovingImageViewer->Hide();
  m_RegisteredImageViewer->Hide();
  m_MixedChannelViewer->Hide() ;
}

void RegisterWindow::Quit(void)
{
  this->Hide() ;
}

void RegisterWindow::ShowStatus(const char * text)
{
  outStatus->value( text );
  Fl::check();
}

void RegisterWindow::ShowFixedImage(void)
{
  if( !m_FixedImageLoaded )
    {
      return;
    }

  m_FixedImageViewer->SetImage( m_FixedImage );
  m_FixedImageViewer->Show();
}

void RegisterWindow::ShowMovingImage(void)
{
  if( !m_MovingImageLoaded )
    {
      return;
    }

  m_MovingImageViewer->SetImage( m_MovingImage );
  m_MovingImageViewer->Show();

  if (m_FixedImage != 0)
    {
      m_TempBox.X1 = (int) outSelectedRegionBeginX->value() ;
      m_TempBox.Y1 = (int) outSelectedRegionBeginY->value() ;
      m_TempBox.X2 = (int) outSelectedRegionEndX->value() ;
      m_TempBox.Y2 = (int) outSelectedRegionEndY->value() ;
      m_MovingImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
    }
}

void RegisterWindow::ShowRegisteredImage(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }

  m_RegisteredImageViewer->SetImage( m_RegisteredImage );
  m_RegisteredImageViewer->Show();
}

void RegisterWindow::ShowMixedChannel(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }
  int sizeX = m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  int sizeY = m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  if (m_ChannelSources[0] == fixed)
    {
      m_MixedChannelViewer->SetRedChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      m_MixedChannelViewer->SetRedChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(0, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      m_MixedChannelViewer->SetGreenChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      m_MixedChannelViewer->SetGreenChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(1, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      m_MixedChannelViewer->SetBlueChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      m_MixedChannelViewer->SetBlueChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(2, 0, sizeX, sizeY) ;
    }

  m_MixedChannelViewer->Show();
}

void RegisterWindow::Execute(void)
{

  iterationsWindow->show();
  Fl::check();

  clock_t time_begin ;
  clock_t time_end ;

  this->ShowStatus("Registering Moving Image against Fixed Image ...");
  grpControls->deactivate() ;
  this->UpdateParameters() ;

  time_begin = clock() ;
  RegisterApplication::Execute();
  time_end = clock() ;

  menuRegisteredImageDisplay->activate() ;
  menuMixedChannel->activate() ;
  buSaveRegisteredImage->activate() ;
  grpControls->activate() ;
  std::ostrstream message ;
  message
    << "Registration done in " <<
    double(time_end - time_begin) / CLOCKS_PER_SEC << "seconds."
    << std::endl ;
  message << "angle = "
    << m_Registrator->GetTransformParameters()[0] << ", x offset = "
    << m_Registrator->GetTransformParameters()[1] << ", y offset = "
    << m_Registrator->GetTransformParameters()[2] << std::ends;
  this->ShowStatus(message.str());

//    m_MovingImage->SetRequestedRegion(m_SelectedRegion) ;
//    m_DebugViewer->SetImage(m_MovingImage) ;
//    m_DebugViewer->Show() ;
//    m_MovingImage->SetRequestedRegionToLargestPossibleRegion() ;
}

void RegisterWindow::UpdateParameters(void)
{

  m_RegionBegin.resize(ImageDimension) ;
  m_RegionEnd.resize(ImageDimension) ;

  m_RegionBegin[0] = (int) outSelectedRegionBeginX->value() ;
  m_RegionBegin[1] = (int) outSelectedRegionBeginY->value() ;
  m_RegionEnd[0] = (int) outSelectedRegionEndX->value() ;
  m_RegionEnd[1] = (int) outSelectedRegionEndY->value() ;

  int i ;
  // crop images from original image using selected region
  for (i = 0 ; i < ImageDimension ; i++)
    {
      if (m_RegionEnd[i] > m_RegionBegin[i])
        {
          m_SelectedSize[i] = m_RegionEnd[i] - m_RegionBegin[i] ;
          m_SelectedIndex[i] = m_RegionBegin[i] ;
        }
      else
        {
          m_SelectedSize[i] = m_RegionBegin[i] - m_RegionEnd[i] ;
          m_SelectedIndex[i] = m_RegionEnd[i] ;
        }
    }

  m_SelectedRegion.SetIndex(m_SelectedIndex) ;
  m_SelectedRegion.SetSize(m_SelectedSize) ;

}

void RegisterWindow::ShowAdvancedOptionsWindow()
{
  winAdvancedOptions->show() ;
  inTranslationScale->value(m_TranslationScale) ;
  inRotationScale->value(m_RotationScale) ;
  inLearningRate->value(m_LearningRate) ;
  inNumberOfIterations->value(m_NumberOfIterations) ;

  if (m_ChannelSources[0] == fixed)
    {
      buRedFixedImage->setonly() ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      buRedRegisteredImage->setonly() ;
    }
  else
    {
      buRedNone->setonly() ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      buGreenFixedImage->setonly() ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      buGreenRegisteredImage->setonly() ;
    }
  else
    {
      buGreenNone->setonly() ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      buBlueFixedImage->setonly() ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      buBlueRegisteredImage->setonly() ;
    }
  else
    {
      buBlueNone->setonly() ;
    }
}

void RegisterWindow::UpdateAdvancedOptions(void)
{
  m_TranslationScale = inTranslationScale->value() ;
  m_RotationScale = inRotationScale->value() ;
  m_LearningRate = inLearningRate->value() ;
  m_NumberOfIterations = (int) inNumberOfIterations->value() ;

  if (buRedFixedImage->value() == 1)
    {
      m_ChannelSources[0] = fixed ;
    }
  else if (buRedRegisteredImage->value() == 1)
    {
      m_ChannelSources[0] = registered ;
    }
  else
    {
      m_ChannelSources[0] = none ;
    }

  if (buGreenFixedImage->value() == 1)
    {
      m_ChannelSources[1] = fixed ;
    }
  else if (buGreenRegisteredImage->value() == 1)
    {
      m_ChannelSources[1] = registered ;
    }
  else
    {
      m_ChannelSources[1] = none ;
    }

  if (buBlueFixedImage->value() == 1)
    {
      m_ChannelSources[2] = fixed ;
    }
  else if (buBlueRegisteredImage->value() == 1)
    {
      m_ChannelSources[2] = registered ;
    }
  else
    {
      m_ChannelSources[2] = none ;
    }

  winAdvancedOptions->hide() ;
}

void RegisterWindow::CloseAdvancedOptionsWindow(void)
{
  winAdvancedOptions->hide() ;
}

void RegisterWindow::SaveRegisteredImage( void )
{

  const char * filename =
    fl_file_chooser("Registered Image filename","*.*","");

  if( !filename )
    {
      return;
    }

  this->ShowStatus("Saving registered image file...");

  try
    {
      RegisterApplication::SaveRegisteredImage( filename );
    }
  catch( ... )
    {
      this->ShowStatus("Problems saving file format");
      return;
    }

  this->ShowStatus("Registered Image Saved");
}

void RegisterWindow
::SelectionCallBackWrapper(void* ptrSelf,
                           fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  RegisterWindow* self = (RegisterWindow*) ptrSelf ;
  self->UpdateSelectedRegion(box) ;
}

void RegisterWindow
::UpdateSelectedRegion(fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  outSelectedRegionBeginX->value(box->X1) ;
  outSelectedRegionBeginY->value(box->Y1) ;
  outSelectedRegionEndX->value(box->X2) ;
  outSelectedRegionEndY->value(box->Y2) ;
  m_MovingImageViewer->imageViewer->SetSelectionBox(box) ;
}

<commit_msg>BUG: old library strstream is replaced by sstream<commit_after>#include "time.h"

#include <sstream>
#include <RegisterWindow.h>
#include <FL/fl_file_chooser.H>

RegisterWindow::RegisterWindow()
{
  m_FixedImageViewer = ImageViewerType::New() ;
  m_MovingImageViewer = ImageViewerType::New() ;
  m_RegisteredImageViewer = ImageViewerType::New() ;
  m_MixedChannelViewer = MixedChannelViewerType::New() ;

  m_FixedImageViewer->SetLabel( "Fixed Image" ) ;
  m_MovingImageViewer->SetLabel( "Moving Image" ) ;
  m_RegisteredImageViewer->SetLabel( "Registered Image" ) ;
  m_MixedChannelViewer->SetLabel( "Mixed Channel View" ) ;

  m_DebugViewer = ImageViewerType::New() ;
  m_DebugViewer->SetLabel( "Debug" ) ;

  m_ChannelSources[0] = fixed ;
  m_ChannelSources[1] = registered ;
  m_ChannelSources[2] = none ;

  m_FixedImageViewer->imageViewer->
    SetSelectionCallBack((void*) this,
                         RegisterWindow::SelectionCallBackWrapper) ;
  buStartRegistration->deactivate() ;
  buSaveRegisteredImage->deactivate() ;
  buShowDisplay->deactivate() ;
  lsDisplay->deactivate() ;
  menuFixedImageDisplay->deactivate() ;
  menuMovingImageDisplay->deactivate() ;
  menuRegisteredImageDisplay->deactivate() ;
  menuMixedChannel->deactivate() ;

  m_IterationObserver = IterationObserverType::New();
  m_IterationObserver->SetOptimizer( m_Registrator->GetOptimizer() );
  m_IterationObserver->SetBrowser( iterationsBrowser );

  this->ShowStatus("Let's start by loading an image...");
}

RegisterWindow::~RegisterWindow()
{
}

void RegisterWindow::LoadMovingImage(void)
{
  const char * filename =
    fl_file_chooser("Moving Image filename","*.*","");
  if( !filename )
    {
      return;
    }

  m_MovingImageFileName = filename ;

  this->ShowStatus("Loading moving image file...");

  try
    {
      RegisterApplication::LoadMovingImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuMovingImageDisplay->activate() ;

  this->ShowStatus("Moving Image Loaded");
}

void RegisterWindow::LoadFixedImage(void)
{
  const char * filename =
    fl_file_chooser("Fixed Image filename","*.*","");

  if( !filename )
    {
      return;
    }

  m_FixedImageFileName = filename ;

  this->ShowStatus("Loading fixed image file...");

  try
    {
      RegisterApplication::LoadFixedImage();
    }
  catch( ... )
    {
      this->ShowStatus("Problems reading file format");
      return;
    }

  m_TempBox.X1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[0] ;
  m_TempBox.Y1 = m_FixedImage->GetLargestPossibleRegion().GetIndex()[1] ;
  m_TempBox.X2 = m_TempBox.X1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  m_TempBox.Y2 = m_TempBox.Y1 +
    m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  outSelectedRegionBeginX->value(m_TempBox.X1) ;
  outSelectedRegionBeginY->value(m_TempBox.Y1) ;
  outSelectedRegionEndX->value(m_TempBox.X2) ;
  outSelectedRegionEndY->value(m_TempBox.Y2) ;

  m_FixedImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;

  lsDisplay->activate() ;
  buShowDisplay->activate() ;
  menuFixedImageDisplay->activate() ;
  if (m_FixedImage != 0 && m_MovingImage != 0)
    {
      buStartRegistration->activate() ;
    }

  this->ShowStatus("Fixed Image Loaded");
}

void RegisterWindow::Show()
{
  winMain->show() ;
}

void RegisterWindow::Hide()
{
  winMain->hide();
  m_FixedImageViewer->Hide();
  m_MovingImageViewer->Hide();
  m_RegisteredImageViewer->Hide();
  m_MixedChannelViewer->Hide() ;
}

void RegisterWindow::Quit(void)
{
  this->Hide() ;
}

void RegisterWindow::ShowStatus(const char * text)
{
  outStatus->value( text );
  Fl::check();
}

void RegisterWindow::ShowFixedImage(void)
{
  if( !m_FixedImageLoaded )
    {
      return;
    }

  m_FixedImageViewer->SetImage( m_FixedImage );
  m_FixedImageViewer->Show();
}

void RegisterWindow::ShowMovingImage(void)
{
  if( !m_MovingImageLoaded )
    {
      return;
    }

  m_MovingImageViewer->SetImage( m_MovingImage );
  m_MovingImageViewer->Show();

  if (m_FixedImage != 0)
    {
      m_TempBox.X1 = (int) outSelectedRegionBeginX->value() ;
      m_TempBox.Y1 = (int) outSelectedRegionBeginY->value() ;
      m_TempBox.X2 = (int) outSelectedRegionEndX->value() ;
      m_TempBox.Y2 = (int) outSelectedRegionEndY->value() ;
      m_MovingImageViewer->imageViewer->SetSelectionBox(&m_TempBox) ;
    }
}

void RegisterWindow::ShowRegisteredImage(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }

  m_RegisteredImageViewer->SetImage( m_RegisteredImage );
  m_RegisteredImageViewer->Show();
}

void RegisterWindow::ShowMixedChannel(void)
{
  if( !m_RegisteredImageAvailable )
    {
      return;
    }
  int sizeX = m_FixedImage->GetLargestPossibleRegion().GetSize()[0] ;
  int sizeY = m_FixedImage->GetLargestPossibleRegion().GetSize()[1] ;

  if (m_ChannelSources[0] == fixed)
    {
      m_MixedChannelViewer->SetRedChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      m_MixedChannelViewer->SetRedChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(0, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      m_MixedChannelViewer->SetGreenChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      m_MixedChannelViewer->SetGreenChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(1, 0, sizeX, sizeY) ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      m_MixedChannelViewer->SetBlueChannel( m_FixedImage) ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      m_MixedChannelViewer->SetBlueChannel( m_RegisteredImage ) ;
    }
  else
    {
      m_MixedChannelViewer->FillChannel(2, 0, sizeX, sizeY) ;
    }

  m_MixedChannelViewer->Show();
}

void RegisterWindow::Execute(void)
{

  iterationsWindow->show();
  Fl::check();

  clock_t time_begin ;
  clock_t time_end ;

  this->ShowStatus("Registering Moving Image against Fixed Image ...");
  grpControls->deactivate() ;
  this->UpdateParameters() ;

  time_begin = clock() ;
  RegisterApplication::Execute();
  time_end = clock() ;

  menuRegisteredImageDisplay->activate() ;
  menuMixedChannel->activate() ;
  buSaveRegisteredImage->activate() ;
  grpControls->activate() ;
  std::ostrstream message ;
  message
    << "Registration done in " <<
    double(time_end - time_begin) / CLOCKS_PER_SEC << "seconds."
    << std::endl ;
  message << "angle = "
    << m_Registrator->GetTransformParameters()[0] << ", x offset = "
    << m_Registrator->GetTransformParameters()[1] << ", y offset = "
    << m_Registrator->GetTransformParameters()[2] << std::ends;
  this->ShowStatus(message.str());

//    m_MovingImage->SetRequestedRegion(m_SelectedRegion) ;
//    m_DebugViewer->SetImage(m_MovingImage) ;
//    m_DebugViewer->Show() ;
//    m_MovingImage->SetRequestedRegionToLargestPossibleRegion() ;
}

void RegisterWindow::UpdateParameters(void)
{

  m_RegionBegin.resize(ImageDimension) ;
  m_RegionEnd.resize(ImageDimension) ;

  m_RegionBegin[0] = (int) outSelectedRegionBeginX->value() ;
  m_RegionBegin[1] = (int) outSelectedRegionBeginY->value() ;
  m_RegionEnd[0] = (int) outSelectedRegionEndX->value() ;
  m_RegionEnd[1] = (int) outSelectedRegionEndY->value() ;

  int i ;
  // crop images from original image using selected region
  for (i = 0 ; i < ImageDimension ; i++)
    {
      if (m_RegionEnd[i] > m_RegionBegin[i])
        {
          m_SelectedSize[i] = m_RegionEnd[i] - m_RegionBegin[i] ;
          m_SelectedIndex[i] = m_RegionBegin[i] ;
        }
      else
        {
          m_SelectedSize[i] = m_RegionBegin[i] - m_RegionEnd[i] ;
          m_SelectedIndex[i] = m_RegionEnd[i] ;
        }
    }

  m_SelectedRegion.SetIndex(m_SelectedIndex) ;
  m_SelectedRegion.SetSize(m_SelectedSize) ;

}

void RegisterWindow::ShowAdvancedOptionsWindow()
{
  winAdvancedOptions->show() ;
  inTranslationScale->value(m_TranslationScale) ;
  inRotationScale->value(m_RotationScale) ;
  inLearningRate->value(m_LearningRate) ;
  inNumberOfIterations->value(m_NumberOfIterations) ;

  if (m_ChannelSources[0] == fixed)
    {
      buRedFixedImage->setonly() ;
    }
  else if (m_ChannelSources[0] == registered)
    {
      buRedRegisteredImage->setonly() ;
    }
  else
    {
      buRedNone->setonly() ;
    }

  if (m_ChannelSources[1] == fixed)
    {
      buGreenFixedImage->setonly() ;
    }
  else if (m_ChannelSources[1] == registered)
    {
      buGreenRegisteredImage->setonly() ;
    }
  else
    {
      buGreenNone->setonly() ;
    }

  if (m_ChannelSources[2] == fixed)
    {
      buBlueFixedImage->setonly() ;
    }
  else if (m_ChannelSources[2] == registered)
    {
      buBlueRegisteredImage->setonly() ;
    }
  else
    {
      buBlueNone->setonly() ;
    }
}

void RegisterWindow::UpdateAdvancedOptions(void)
{
  m_TranslationScale = inTranslationScale->value() ;
  m_RotationScale = inRotationScale->value() ;
  m_LearningRate = inLearningRate->value() ;
  m_NumberOfIterations = (int) inNumberOfIterations->value() ;

  if (buRedFixedImage->value() == 1)
    {
      m_ChannelSources[0] = fixed ;
    }
  else if (buRedRegisteredImage->value() == 1)
    {
      m_ChannelSources[0] = registered ;
    }
  else
    {
      m_ChannelSources[0] = none ;
    }

  if (buGreenFixedImage->value() == 1)
    {
      m_ChannelSources[1] = fixed ;
    }
  else if (buGreenRegisteredImage->value() == 1)
    {
      m_ChannelSources[1] = registered ;
    }
  else
    {
      m_ChannelSources[1] = none ;
    }

  if (buBlueFixedImage->value() == 1)
    {
      m_ChannelSources[2] = fixed ;
    }
  else if (buBlueRegisteredImage->value() == 1)
    {
      m_ChannelSources[2] = registered ;
    }
  else
    {
      m_ChannelSources[2] = none ;
    }

  winAdvancedOptions->hide() ;
}

void RegisterWindow::CloseAdvancedOptionsWindow(void)
{
  winAdvancedOptions->hide() ;
}

void RegisterWindow::SaveRegisteredImage( void )
{

  const char * filename =
    fl_file_chooser("Registered Image filename","*.*","");

  if( !filename )
    {
      return;
    }

  this->ShowStatus("Saving registered image file...");

  try
    {
      RegisterApplication::SaveRegisteredImage( filename );
    }
  catch( ... )
    {
      this->ShowStatus("Problems saving file format");
      return;
    }

  this->ShowStatus("Registered Image Saved");
}

void RegisterWindow
::SelectionCallBackWrapper(void* ptrSelf,
                           fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  RegisterWindow* self = (RegisterWindow*) ptrSelf ;
  self->UpdateSelectedRegion(box) ;
}

void RegisterWindow
::UpdateSelectedRegion(fltk::Image2DViewerWindow::SelectionBoxType* box)
{
  outSelectedRegionBeginX->value(box->X1) ;
  outSelectedRegionBeginY->value(box->Y1) ;
  outSelectedRegionEndX->value(box->X2) ;
  outSelectedRegionEndY->value(box->Y2) ;
  m_MovingImageViewer->imageViewer->SetSelectionBox(box) ;
}

<|endoftext|>


<commit_before>/******************************************************************************
    font.cpp

    SDL-based Font Rendering API

  Copyright (c) 2013 Jeffrey Carpenter

******************************************************************************/
#include "font.h"

Font::Font ( void )
{
  #ifdef DEBUG_FONT_OBJ
    std::cout << "Font::Font (): " << "Hello, world!" << "\n" << std::endl;
  #endif

  this->font = NULL;

  if ( TTF_Init () == -1 )
  {
    #ifdef DEBUG_FONT
      std::cout << "ERR in Font::Font (): " << TTF_GetError() << std::endl;
    #endif
    exit ( EXIT_FAILURE ); // TODO: Reconsider
  }

  this->text_color = { 0, 0, 0 };
  this->coords = { 0, 0, 0, 0 };
}

Font::~Font ( void )
{
  #ifdef DEBUG_FONT_OBJ
    std::cout << "Font::~Font (): " << "Goodbye cruel world!" << "\n" << std::endl;
  #endif

  if ( this->font != NULL )
  {
    TTF_CloseFont ( this->font );
    this->font = NULL;
  }

  TTF_Quit ();
}

unsigned int Font::GetTextWidth ( void )
{
  return this->coords.w;
}

unsigned int Font::GetTextHeight ( void )
{
  return this->coords.h;
}

std::string Font::GetTextBuffer ( void )
{
  return this->text_buffer;
}

void Font::SetTextBuffer ( std::string text )
{
  signed int width, height = 0;

/*
TODO: Finish ERR checks:

  if ( text.length() > 0 )
*/
    if ( TTF_SizeText ( this->font, text.c_str(), &width, &height ) != -1 )
    {
      this->coords.w = width;
      this->coords.h = height;
      this->text_buffer = text;
    }
}

SDL_Color Font::GetTextColor ( void )
{
  return this->text_color;
}

void Font::SetTextColor ( unsigned r, unsigned g, unsigned b )
{
  this->text_color.r = r;
  this->text_color.g = g;
  this->text_color.b = b;
}

bool Font::LoadTTF ( std::string filename, unsigned int font_size )
{
  this->font = TTF_OpenFont ( filename.c_str(), font_size );

  if ( this->font == NULL )
  {
    #ifdef DEBUG_FONT
      std::cout << "ERR: " << TTF_GetError() << std::endl;
    #endif
    return false;
  }

  return true;
}

bool Font::DrawText ( Gfx *engine, unsigned int x, unsigned int y )
{
  SDL_Surface *video_buffer = NULL;
  this->coords.x = x;
  this->coords.y = y;

  if ( this->GetTextBuffer().c_str() != NULL )
  {
    video_buffer = TTF_RenderText_Solid ( this->font, this->GetTextBuffer().c_str(), this->text_color );
  }
  else
  {
    std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;

    SDL_FreeSurface ( video_buffer );
    video_buffer = NULL;

    return false;
  }

  if ( video_buffer != NULL )
  {
    if ( engine->DrawSurface ( video_buffer, x, y ) == false )
    {
      std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;
    }

    SDL_FreeSurface ( video_buffer );
    video_buffer = NULL;

    return false;
  }

  SDL_FreeSurface ( video_buffer );
  video_buffer = NULL;

  return true;
}
<commit_msg>Compile Time ERR Fix<commit_after>/******************************************************************************
    font.cpp

    SDL-based Font Rendering API

  Copyright (c) 2013 Jeffrey Carpenter

******************************************************************************/
#include "font.h"

Font::Font ( void )
{
  #ifdef DEBUG_FONT_OBJ
    std::cout << "Font::Font (): " << "Hello, world!" << "\n" << std::endl;
  #endif

  this->font = NULL;

  if ( TTF_Init () == -1 )
  {
    #ifdef DEBUG_FONT
      std::cout << "ERR in Font::Font (): " << TTF_GetError() << std::endl;
    #endif
    exit ( EXIT_FAILURE ); // TODO: Reconsider
  }
}

Font::~Font ( void )
{
  #ifdef DEBUG_FONT_OBJ
    std::cout << "Font::~Font (): " << "Goodbye cruel world!" << "\n" << std::endl;
  #endif

  if ( this->font != NULL )
  {
    TTF_CloseFont ( this->font );
    this->font = NULL;
  }

  TTF_Quit ();
}

unsigned int Font::GetTextWidth ( void )
{
  return this->coords.w;
}

unsigned int Font::GetTextHeight ( void )
{
  return this->coords.h;
}

std::string Font::GetTextBuffer ( void )
{
  return this->text_buffer;
}

void Font::SetTextBuffer ( std::string text )
{
  signed int width, height = 0;

/*
TODO: Finish ERR checks:

  if ( text.length() > 0 )
*/
    if ( TTF_SizeText ( this->font, text.c_str(), &width, &height ) != -1 )
    {
      this->coords.w = width;
      this->coords.h = height;
      this->text_buffer = text;
    }
}

SDL_Color Font::GetTextColor ( void )
{
  return this->text_color;
}

void Font::SetTextColor ( unsigned r, unsigned g, unsigned b )
{
  this->text_color.r = r;
  this->text_color.g = g;
  this->text_color.b = b;
}

bool Font::LoadTTF ( std::string filename, unsigned int font_size )
{
  this->font = TTF_OpenFont ( filename.c_str(), font_size );

  if ( this->font == NULL )
  {
    #ifdef DEBUG_FONT
      std::cout << "ERR: " << TTF_GetError() << std::endl;
    #endif
    return false;
  }

  return true;
}

bool Font::DrawText ( Gfx *engine, unsigned int x, unsigned int y )
{
  SDL_Surface *video_buffer = NULL;
  this->coords.x = x;
  this->coords.y = y;

  if ( this->GetTextBuffer().c_str() != NULL )
  {
    video_buffer = TTF_RenderText_Solid ( this->font, this->GetTextBuffer().c_str(), this->text_color );
  }
  else
  {
    std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;

    SDL_FreeSurface ( video_buffer );
    video_buffer = NULL;

    return false;
  }

  if ( video_buffer != NULL )
  {
    if ( engine->DrawSurface ( video_buffer, x, y ) == false )
    {
      std::cout << "ERR in Font::DrawText(): " << SDL_GetError() << std::endl;
    }

    SDL_FreeSurface ( video_buffer );
    video_buffer = NULL;

    return false;
  }

  SDL_FreeSurface ( video_buffer );
  video_buffer = NULL;

  return true;
}
<|endoftext|>


<commit_before>/*
 * GPIO handler for Dragonboard
 * Author: Kenny Yokoyama & Mike Lara
 */
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ros/ros.h"
#include "std_msgs/Int32.h"

#define GPIO_EXPORT_PATH    "/sys/class/gpio/export"
#define GPIO_UNEXPORT_PATH  "/sys/class/gpio/unexport"
#define GPIO_DIR_PATH       "/sys/class/gpio/gpio%d/direction"
#define GPIO_VALUE_PATH     "/sys/class/gpio/gpio%d/value"

#define GPIO_HIGH   1
#define GPIO_LOW    0
#define GPIO_IN     "in"
#define GPIO_OUT    "out"

enum GPIO_PINS { GPIO_1=6, GPIO_2=7, GPIO_3=206, GPIO_4=207,
    GPIO_5=186, GPIO_6=189, GPIO_7=22, GPIO_8=23};
int PIN_VALUES[5];

class GPIOPin
{
    private:
        // Mike:
        int hwPinId;
        int fileDesc;

    public:
        GPIOPin(GPIO_PINS pin, const char* pinIO);
        ~GPIOPin();
        // Kenny:
        void setPin(int state);
        // Mike:
        void writeFile(int value);
};

GPIOPin::GPIOPin(GPIO_PINS pin, const char* pinIO)
{
    char path[256];

    hwPinId = pin;
    // setup export
    fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
    memset(path, 0, sizeof(path));
    snprintf(path, sizeof(path), "%d", hwPinId);
    write(fileDesc, path, strlen(path));
    close(fileDesc);
    // setup signal direction
    memset(path, 0, sizeof(path));
    snprintf(path, sizeof(path), GPIO_DIR_PATH, hwPinId);
    fileDesc = open(path, O_WRONLY);
    write(fileDesc, pinIO, sizeof(const char*));
    close(fileDesc);
    // open descriptor to value
    memset(path, 0, sizeof(path));
    snprintf(path, sizeof(path), GPIO_VALUE_PATH, hwPinId);
    fileDesc = open(path, O_RDWR);
}

GPIOPin::~GPIOPin()
{
    close(fileDesc);
    //fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
    //write(fileDesc, hwPinId, sizeof(hwPinId));
    //close(fileDesc);
}

void GPIOPin::setPin(int state)
{
    char buffer[4];
    memset(buffer, 0, sizeof(buffer));
    snprintf(buffer, sizeof(buffer), "%d", state);
    ROS_INFO("Setting pin %d to %s", hwPinId, buffer);
    lseek(fileDesc, 0, SEEK_SET);
    write(fileDesc, buffer, strlen(buffer));
}

void pinCallback(const std_msgs::Int32::ConstPtr& msg)
{
    memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));
    if (!(msg->data < 0 || msg->data > sizeof(PIN_VALUES)/sizeof(int))) {
        PIN_VALUES[msg->data] = GPIO_HIGH;
        ROS_INFO("%d is now on", msg->data);
    }
}

// Mike:
int main (int argc, char *argv[])
{
    ros::init(argc, argv, "gpio_controller");
    ros::NodeHandle n;
    ros::Subscriber gpio_sub = n.subscribe<std_msgs::Int32>("/gpio_ctl", 10, &pinCallback);

    ros::Rate loop_rate(1);

    memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));

    // create pins
    GPIOPin pin1(GPIO_1, GPIO_OUT);
    GPIOPin pin2(GPIO_2, GPIO_OUT);
    GPIOPin pin3(GPIO_3, GPIO_OUT);
    GPIOPin pin4(GPIO_4, GPIO_OUT);
    GPIOPin pin7(GPIO_7, GPIO_OUT);

    while (ros::ok()) {
        pin1.setPin(PIN_VALUES[0]);
        pin2.setPin(PIN_VALUES[1]);
        pin3.setPin(PIN_VALUES[2]);
        pin4.setPin(PIN_VALUES[3]);
        pin7.setPin(PIN_VALUES[4]);
        ros::spinOnce();
        loop_rate.sleep();
    }
    return 0;
}
<commit_msg>Updated GPIO code. Corrected the LED lightup order<commit_after>/*
 * GPIO handler for Dragonboard
 * Author: Kenny Yokoyama & Mike Lara
 */
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ros/ros.h"
#include "std_msgs/Int32.h"

#define GPIO_EXPORT_PATH    "/sys/class/gpio/export"
#define GPIO_UNEXPORT_PATH  "/sys/class/gpio/unexport"
#define GPIO_DIR_PATH       "/sys/class/gpio/gpio%d/direction"
#define GPIO_VALUE_PATH     "/sys/class/gpio/gpio%d/value"

#define GPIO_HIGH   1
#define GPIO_LOW    0
#define GPIO_IN     "in"
#define GPIO_OUT    "out"

enum GPIO_PINS { GPIO_1=6, GPIO_2=7, GPIO_3=206, GPIO_4=207,
    GPIO_5=186, GPIO_6=189, GPIO_7=22, GPIO_8=23};
int PIN_VALUES[5];

class GPIOPin
{
    private:
        // Mike:
        int hwPinId;
        int fileDesc;

    public:
        GPIOPin(GPIO_PINS pin, const char* pinIO);
        ~GPIOPin();
        // Kenny:
        void setPin(int state);
        // Mike:
        void writeFile(int value);
};

GPIOPin::GPIOPin(GPIO_PINS pin, const char* pinIO)
{
    char path[256];

    hwPinId = pin;
    // setup export
    fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
    memset(path, 0, sizeof(path));
    snprintf(path, sizeof(path), "%d", hwPinId);
    write(fileDesc, path, strlen(path));
    close(fileDesc);
    // setup signal direction
    memset(path, 0, sizeof(path));
    snprintf(path, sizeof(path), GPIO_DIR_PATH, hwPinId);
    fileDesc = open(path, O_WRONLY);
    write(fileDesc, pinIO, sizeof(const char*));
    close(fileDesc);
    // open descriptor to value
    memset(path, 0, sizeof(path));
    snprintf(path, sizeof(path), GPIO_VALUE_PATH, hwPinId);
    fileDesc = open(path, O_RDWR);
}

GPIOPin::~GPIOPin()
{
    close(fileDesc);
    //fileDesc = open(GPIO_EXPORT_PATH, O_WRONLY);
    //write(fileDesc, hwPinId, sizeof(hwPinId));
    //close(fileDesc);
}

void GPIOPin::setPin(int state)
{
    char buffer[4];
    memset(buffer, 0, sizeof(buffer));
    snprintf(buffer, sizeof(buffer), "%d", state);
    ROS_INFO("Setting pin %d to %s", hwPinId, buffer);
    lseek(fileDesc, 0, SEEK_SET);
    write(fileDesc, buffer, strlen(buffer));
}

void pinCallback(const std_msgs::Int32::ConstPtr& msg)
{
    memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));
    if (!(msg->data < 0 || msg->data > sizeof(PIN_VALUES)/sizeof(int))) {
        PIN_VALUES[msg->data] = GPIO_HIGH;
        ROS_INFO("%d is now on", msg->data);
    }
}

// Mike:
int main (int argc, char *argv[])
{
    ros::init(argc, argv, "gpio_controller");
    ros::NodeHandle n;
    ros::Subscriber gpio_sub = n.subscribe<std_msgs::Int32>("/gpio_ctl", 10, &pinCallback);

    ros::Rate loop_rate(1);

    memset(PIN_VALUES, GPIO_LOW, sizeof(PIN_VALUES));

    // create pins
    GPIOPin pin1(GPIO_1, GPIO_OUT);
    GPIOPin pin2(GPIO_2, GPIO_OUT);
    GPIOPin pin3(GPIO_3, GPIO_OUT);
    GPIOPin pin4(GPIO_4, GPIO_OUT);
    GPIOPin pin7(GPIO_7, GPIO_OUT);

    while (ros::ok()) {
        pin1.setPin(PIN_VALUES[1]);
        pin2.setPin(PIN_VALUES[0]);
        pin3.setPin(PIN_VALUES[3]);
        pin4.setPin(PIN_VALUES[2]);
        pin7.setPin(PIN_VALUES[4]);
        ros::spinOnce();
        loop_rate.sleep();
    }
    return 0;
}
<|endoftext|>


<commit_before>//! @file
//! @copyright See LICENSE.txt.

#pragma once

#include "coordinates.hpp"

#include "reg.hpp"
#include "utility/reference.hpp"

#include <array>
#include <iostream>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <unordered_set>

namespace ql {
	struct light_source;

	//! An rhomboid section of hexes in a region.
	struct section {
		//! Generates a new section.
		//! @param region_id The ID of the region containing this section.
		//! @param coords The coordinates of the section within its region.
		section(id region_id, section_hex::point coords);

		//! The hex coordinates of this section within its region's sections.
		auto section_coords() const;

		//! The coordinates of this section's center tile.
		auto center_coords() const -> tile_hex::point;

		//! A map in this section of tile coordinates to occupying entities.
		auto entity_id_map() const -> std::unordered_map<tile_hex::point, id> const&;

		//! The ID of the entity at @p tile_coords or nullopt if there is none.
		auto entity_id_at(tile_hex::point tile_coords) const -> std::optional<id>;

		//! Tries to add the given entity to the section. Returns true on success or false if there is already an entity
		//! at the entity's coordinates.
		[[nodiscard]] auto try_add(id being_id) -> bool;

		//! Removes the being at the given region tile coordinates, if present.
		auto remove_at(tile_hex::point coords) -> void;

		//! Removes the entity with ID @p entity_id from this section, if present.
		auto remove(id entity_id) -> void;

		//! The ID of the tile at @p coords in this section.
		//! @note Behavior is undefined if @p coords is not within this section.
		auto tile_id_at(tile_hex::point coords) const -> id;

	private:
		//! A q-major array of tiles, representing a rhomboid section of tiles centered on this section's hex coordinates.
		std::array<std::array<id, section_diameter.value>, section_diameter.value> _tile_ids;

		std::unordered_map<tile_hex::point, id> _entity_id_map;

		//! The hex coordinates of this section within its region.
		section_hex::point _coords;

		//! The array indices of the tile at @p coords.
		//! @note Behavior is undefined if @p coords is not within this section.
		auto indices(tile_hex::point coords) const -> std::tuple<size_t, size_t>;
	};
}
<commit_msg>Removed unused includes.<commit_after>//! @file
//! @copyright See LICENSE.txt.

#pragma once

#include "coordinates.hpp"

#include "reg.hpp"
#include "utility/reference.hpp"

#include <array>
#include <optional>
#include <unordered_map>

namespace ql {
	struct light_source;

	//! An rhomboid section of hexes in a region.
	struct section {
		//! Generates a new section.
		//! @param region_id The ID of the region containing this section.
		//! @param coords The coordinates of the section within its region.
		section(id region_id, section_hex::point coords);

		//! The hex coordinates of this section within its region's sections.
		auto section_coords() const;

		//! The coordinates of this section's center tile.
		auto center_coords() const -> tile_hex::point;

		//! A map in this section of tile coordinates to occupying entities.
		auto entity_id_map() const -> std::unordered_map<tile_hex::point, id> const&;

		//! The ID of the entity at @p tile_coords or nullopt if there is none.
		auto entity_id_at(tile_hex::point tile_coords) const -> std::optional<id>;

		//! Tries to add the given entity to the section. Returns true on success or false if there is already an entity
		//! at the entity's coordinates.
		[[nodiscard]] auto try_add(id being_id) -> bool;

		//! Removes the being at the given region tile coordinates, if present.
		auto remove_at(tile_hex::point coords) -> void;

		//! Removes the entity with ID @p entity_id from this section, if present.
		auto remove(id entity_id) -> void;

		//! The ID of the tile at @p coords in this section.
		//! @note Behavior is undefined if @p coords is not within this section.
		auto tile_id_at(tile_hex::point coords) const -> id;

	private:
		//! A q-major array of tiles, representing a rhomboid section of tiles centered on this section's hex coordinates.
		std::array<std::array<id, section_diameter.value>, section_diameter.value> _tile_ids;

		std::unordered_map<tile_hex::point, id> _entity_id_map;

		//! The hex coordinates of this section within its region.
		section_hex::point _coords;

		//! The array indices of the tile at @p coords.
		//! @note Behavior is undefined if @p coords is not within this section.
		auto indices(tile_hex::point coords) const -> std::tuple<size_t, size_t>;
	};
}
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct EquivStructWorker
{
	Module *module;
	SigMap sigmap;
	SigMap equiv_bits;
	bool mode_nortl;
	int merge_count;

	dict<IdString, pool<IdString>> cells_by_type;

	void handle_cell_pair(Cell *cell_a, Cell *cell_b)
	{
		if (cell_a->parameters != cell_b->parameters)
			return;

		bool merge_this_cells = false;
		vector<SigSpec> inputs_a, inputs_b;

		for (auto &port_a : cell_a->connections())
		{
			SigSpec bits_a = equiv_bits(port_a.second);
			SigSpec bits_b = equiv_bits(cell_b->getPort(port_a.first));

			if (GetSize(bits_a) != GetSize(bits_b))
				return;

			if (cell_a->output(port_a.first)) {
				for (int i = 0; i < GetSize(bits_a); i++)
					if (bits_a[i] == bits_b[i])
						merge_this_cells = true;
			} else {
				SigSpec diff_bits_a, diff_bits_b;
				for (int i = 0; i < GetSize(bits_a); i++)
					if (bits_a[i] != bits_b[i]) {
						diff_bits_a.append(bits_a[i]);
						diff_bits_b.append(bits_b[i]);
					}
				if (!diff_bits_a.empty()) {
					inputs_a.push_back(diff_bits_a);
					inputs_b.push_back(diff_bits_b);
				}
			}
		}

		if (merge_this_cells)
		{
			SigMap merged_map;

			log("      Merging cells %s and %s.\n", log_id(cell_a),  log_id(cell_b));
			merge_count++;

			for (int i = 0; i < GetSize(inputs_a); i++) {
				SigSpec &sig_a = inputs_a[i], &sig_b = inputs_b[i];
				SigSpec sig_y = module->addWire(NEW_ID, GetSize(sig_a));
				log("        A: %s, B: %s, Y: %s\n", log_signal(sig_a),  log_signal(sig_b), log_signal(sig_y));
				module->addEquiv(NEW_ID, sig_a, sig_b, sig_y);
				merged_map.add(sig_a, sig_y);
				merged_map.add(sig_b, sig_y);
			}

			std::vector<IdString> outport_names, inport_names;

			for (auto &port_a : cell_a->connections())
				if (cell_a->output(port_a.first))
					outport_names.push_back(port_a.first);
				else
					inport_names.push_back(port_a.first);

			for (auto &pn : inport_names)
				cell_a->setPort(pn, merged_map(equiv_bits(cell_a->getPort(pn))));

			for (auto &pn : outport_names) {
				SigSpec sig_a = cell_a->getPort(pn);
				SigSpec sig_b = cell_b->getPort(pn);
				module->connect(sig_b, sig_a);
				sigmap.add(sig_b, sig_a);
				equiv_bits.add(sig_b, sig_a);
			}

			module->remove(cell_b);
		}
	}

	EquivStructWorker(Module *module, bool mode_nortl) :
			module(module), sigmap(module), equiv_bits(module), mode_nortl(mode_nortl), merge_count(0)
	{
		log("  Starting new iteration.\n");

		for (auto cell : module->selected_cells())
			if (cell->type == "$equiv") {
				equiv_bits.add(sigmap(cell->getPort("\\A")), sigmap(cell->getPort("\\B")));
			} else
			if (module->design->selected(module, cell)) {
				if (!mode_nortl || module->design->module(cell->type))
					cells_by_type[cell->type].insert(cell->name);
			}

		for (auto &it : cells_by_type)
		{
			if (it.second.size() <= 1)
				continue;

			log("    Merging %s cells..\n", log_id(it.first));

			// FIXME: O(n^2)
			for (auto cell_name_a : it.second)
			for (auto cell_name_b : it.second)
				if (cell_name_a < cell_name_b) {
					Cell *cell_a = module->cell(cell_name_a);
					Cell *cell_b = module->cell(cell_name_b);
					if (cell_a && cell_b)
						handle_cell_pair(cell_a, cell_b);
				}
		}
	}
};

struct EquivStructPass : public Pass {
	EquivStructPass() : Pass("equiv_struct", "structural equivalence checking") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    equiv_struct [options] [selection]\n");
		log("\n");
		log("This command adds additional $equiv cells based on the assumption that the\n");
		log("gold and gate circuit are structurally equivalent. Note that this can introduce\n");
		log("bad $equiv cells in cases where the netlists are not structurally equivalent,\n");
		log("for example when analyzing circuits with cells with commutative inputs.\n");
		log("\n");
		log("    -nortl\n");
		log("        only operate on 'blackbox' cells and hierarchical module instantiations\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, Design *design)
	{
		bool mode_nortl = false;

		log_header("Executing EQUIV_STRUCT pass.\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			if (args[argidx] == "-bb") {
				mode_nortl = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules()) {
			log("Running equiv_struct on module %s:", log_id(module));
			while (1) {
				EquivStructWorker worker(module, mode_nortl);
				if (worker.merge_count == 0)
					break;
			}
		}
	}
} EquivStructPass;

PRIVATE_NAMESPACE_END
<commit_msg>Improvements in equiv_struct<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct EquivStructWorker
{
	Module *module;
	SigMap sigmap;
	SigMap equiv_bits;
	bool mode_icells;
	int merge_count;

	dict<IdString, pool<IdString>> cells_by_type;

	void handle_cell_pair(Cell *cell_a, Cell *cell_b)
	{
		if (cell_a->parameters != cell_b->parameters)
			return;

		bool merge_this_cells = false;
		bool found_diff_inputs = false;
		vector<SigSpec> inputs_a, inputs_b;

		for (auto &port_a : cell_a->connections())
		{
			SigSpec bits_a = equiv_bits(port_a.second);
			SigSpec bits_b = equiv_bits(cell_b->getPort(port_a.first));

			if (GetSize(bits_a) != GetSize(bits_b))
				return;

			if (cell_a->output(port_a.first)) {
				for (int i = 0; i < GetSize(bits_a); i++)
					if (bits_a[i] == bits_b[i])
						merge_this_cells = true;
			} else {
				SigSpec diff_bits_a, diff_bits_b;
				for (int i = 0; i < GetSize(bits_a); i++)
					if (bits_a[i] != bits_b[i]) {
						diff_bits_a.append(bits_a[i]);
						diff_bits_b.append(bits_b[i]);
					}
				if (!diff_bits_a.empty()) {
					inputs_a.push_back(diff_bits_a);
					inputs_b.push_back(diff_bits_b);
					found_diff_inputs = true;
				}
			}
		}

		if (!found_diff_inputs)
			merge_this_cells = true;

		if (merge_this_cells)
		{
			SigMap merged_map;

			log("      Merging cells %s and %s.\n", log_id(cell_a),  log_id(cell_b));
			merge_count++;

			for (int i = 0; i < GetSize(inputs_a); i++) {
				SigSpec &sig_a = inputs_a[i], &sig_b = inputs_b[i];
				SigSpec sig_y = module->addWire(NEW_ID, GetSize(sig_a));
				log("        A: %s, B: %s, Y: %s\n", log_signal(sig_a),  log_signal(sig_b), log_signal(sig_y));
				module->addEquiv(NEW_ID, sig_a, sig_b, sig_y);
				merged_map.add(sig_a, sig_y);
				merged_map.add(sig_b, sig_y);
			}

			std::vector<IdString> outport_names, inport_names;

			for (auto &port_a : cell_a->connections())
				if (cell_a->output(port_a.first))
					outport_names.push_back(port_a.first);
				else
					inport_names.push_back(port_a.first);

			for (auto &pn : inport_names)
				cell_a->setPort(pn, merged_map(equiv_bits(cell_a->getPort(pn))));

			for (auto &pn : outport_names) {
				SigSpec sig_a = cell_a->getPort(pn);
				SigSpec sig_b = cell_b->getPort(pn);
				module->connect(sig_b, sig_a);
				sigmap.add(sig_b, sig_a);
				equiv_bits.add(sig_b, sig_a);
			}

			module->remove(cell_b);
		}
	}

	EquivStructWorker(Module *module, bool mode_icells) :
			module(module), sigmap(module), equiv_bits(module), mode_icells(mode_icells), merge_count(0)
	{
		log("  Starting new iteration.\n");

		for (auto cell : module->selected_cells())
			if (cell->type == "$equiv") {
				equiv_bits.add(sigmap(cell->getPort("\\A")), sigmap(cell->getPort("\\B")));
			} else
			if (module->design->selected(module, cell)) {
				if (mode_icells || module->design->module(cell->type))
					cells_by_type[cell->type].insert(cell->name);
			}

		for (auto &it : cells_by_type)
		{
			if (it.second.size() <= 1)
				continue;

			log("    Merging %s cells..\n", log_id(it.first));

			// FIXME: O(n^2)
			for (auto cell_name_a : it.second)
			for (auto cell_name_b : it.second)
				if (cell_name_a < cell_name_b) {
					Cell *cell_a = module->cell(cell_name_a);
					Cell *cell_b = module->cell(cell_name_b);
					if (cell_a && cell_b)
						handle_cell_pair(cell_a, cell_b);
				}
		}
	}
};

struct EquivStructPass : public Pass {
	EquivStructPass() : Pass("equiv_struct", "structural equivalence checking") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    equiv_struct [options] [selection]\n");
		log("\n");
		log("This command adds additional $equiv cells based on the assumption that the\n");
		log("gold and gate circuit are structurally equivalent. Note that this can introduce\n");
		log("bad $equiv cells in cases where the netlists are not structurally equivalent,\n");
		log("for example when analyzing circuits with cells with commutative inputs. This\n");
		log("command will also de-duplicate gates.\n");
		log("\n");
		log("    -icells\n");
		log("        by default, the internal RTL and gate cell types are ignored. add\n");
		log("        this option to also process those cell types with this command.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, Design *design)
	{
		bool mode_icells = false;

		log_header("Executing EQUIV_STRUCT pass.\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			if (args[argidx] == "-icells") {
				mode_icells = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules()) {
			log("Running equiv_struct on module %s:", log_id(module));
			while (1) {
				EquivStructWorker worker(module, mode_icells);
				if (worker.merge_count == 0)
					break;
			}
		}
	}
} EquivStructPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>AliAnalysisTask *AddTask_slehner_ElectronEfficiency(Bool_t hasITS = kTRUE,
                                                     Int_t trackCut=1,
                                                     Int_t evCut=1,
                                                     TString directoryBaseName = "slehner",
                                                     Char_t* outputFileName="LMEE_output.root",
                                                     Bool_t deactivateTree=kFALSE, // enabling this has priority over 'writeTree'! (needed for LEGO trains)
                                                     TString resolutionfile = "" //Resolution_pp_16l_eta.root
                                                     )
{

	//get the current analysis manager
	AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
	if(!mgr){

		Error("AddTask_slehner_ElectronEfficiency", "No analysis manager found.");
		return 0;
	}

	//Base Directory for GRID / LEGO Train
	TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";

        TString configLMEECutLib("LMEECutLib_slehner.C");
        TString configLMEECutLibPath(configBasePath+configLMEECutLib);

	std::cout << "Configpath:  " << configFilePath << std::endl;

        //LOAD CUTLIB
        if(gSystem->Exec(Form("ls %s", configLMEECutLibPath.Data()))==0){

		std::cout << "loading LMEECutLib: " << configLMEECutLibPath.Data() << std::endl;
		gROOT->LoadMacro(configLMEECutLibPath.Data());
	}
	else{
		std::cout << "LMEECutLib not found: " << configLMEECutLibPath.Data() << std::endl;
		return 0; // if return is not called, the job will fail instead of running wihout this task... (good for local tests, bad for train)
	}

	//Do we have an MC handler?
	Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler() != 0x0);
	std::cout << "hasMC = " << hasMC << std::endl;

      LMEECutLib* cutlib = new LMEECutLib();

      AliAnalysisTaskMLTreeMaker *task = new AliAnalysisTaskMLTreeMaker(taskname);

      task->SelectCollisionCandidates(AliVEvent::kINT7);
      task->SetTrackCuts(cutlib->GetTrackSelectionAna(trackCut));
      task->SetEventCuts(cutlib->GetEventCuts(evCut));

  mgr->AddTask(taskESD);

  TString outputFileName = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *coutESD = mgr->CreateContainer("output", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  mgr->ConnectInput(taskESD, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskESD, 1, coutESD);

 return taskESD;

}
<commit_msg>rename function<commit_after>AliAnalysisTask *AddTask_slehner_TreeMakeWCutLib(Bool_t hasITS = kTRUE,
                                                     Int_t trackCut=1,
                                                     Int_t evCut=1,
                                                     TString directoryBaseName = "slehner",
                                                     Char_t* outputFileName="LMEE_output.root",
                                                     Bool_t deactivateTree=kFALSE, // enabling this has priority over 'writeTree'! (needed for LEGO trains)
                                                     TString resolutionfile = "" //Resolution_pp_16l_eta.root
                                                     )
{

	//get the current analysis manager
	AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
	if(!mgr){

		Error("AddTask_slehner_TreeMakeWCutLib", "No analysis manager found.");
		return 0;
	}

	//Base Directory for GRID / LEGO Train
	TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";

        TString configLMEECutLib("LMEECutLib_slehner.C");
        TString configLMEECutLibPath(configBasePath+configLMEECutLib);

	std::cout << "Configpath:  " << configFilePath << std::endl;

        //LOAD CUTLIB
        if(gSystem->Exec(Form("ls %s", configLMEECutLibPath.Data()))==0){

		std::cout << "loading LMEECutLib: " << configLMEECutLibPath.Data() << std::endl;
		gROOT->LoadMacro(configLMEECutLibPath.Data());
	}
	else{
		std::cout << "LMEECutLib not found: " << configLMEECutLibPath.Data() << std::endl;
		return 0; // if return is not called, the job will fail instead of running wihout this task... (good for local tests, bad for train)
	}

	//Do we have an MC handler?
	Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler() != 0x0);
	std::cout << "hasMC = " << hasMC << std::endl;

      LMEECutLib* cutlib = new LMEECutLib();

      AliAnalysisTaskMLTreeMaker *task = new AliAnalysisTaskMLTreeMaker(taskname);

      task->SelectCollisionCandidates(AliVEvent::kINT7);
      task->SetTrackCuts(cutlib->GetTrackSelectionAna(trackCut));
      task->SetEventCuts(cutlib->GetEventCuts(evCut));

  mgr->AddTask(taskESD);

  TString outputFileName = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *coutESD = mgr->CreateContainer("output", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  mgr->ConnectInput(taskESD, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskESD, 1, coutESD);

 return taskESD;

}
<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
   #include <TMath.h>
   #include <TROOT.h>
   #include <Riostream.h>
   #include <TCanvas.h>

   #include <TString.h>

   #include <TFile.h>
   #include <TList.h>
   #include <TH1F.h>
   #include <TH1D.h>
   #include <TF2.h>
   #include <TFitResult.h>
   #include <TFitResultPtr.h>
   #include <TH2F.h>
   #include <TH3F.h>
#endif

   Double_t xbins[]={
   0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,
   1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,
   2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,
   4.5,5.0,5.5,6.5,8.0,10.0,12.0
   };
   Int_t nb=sizeof(xbins)/sizeof(Double_t);
   Int_t nb1=nb-1;

TFile *fAss;
TFile *fGen;
TFile *fRaw;

void Generated();
void Efficiencies(Float_t cMin, Float_t cMax, TString centr);
void RawYields(Float_t cMin, Float_t cMax, TString centr);
void Spectra(TString centr);

void SpectraV0CutVariations(Float_t cMin, Float_t cMax, TString centr) {

  fRaw=TFile::Open((centr+"/AliV0CutVariations.root").Data());
  fAss=TFile::Open((centr+"/AliV0CutVariationsMC.root").Data());
  fGen=TFile::Open("Generated.root");
  if (!fGen) {
     Generated();
     fGen=TFile::Open("Generated.root");
  }

  Efficiencies(cMin,cMax,centr);
  RawYields(cMin,cMax,centr);
  Spectra(centr);

  fAss->Close();
  fGen->Close();
  fRaw->Close();
}

TH1 *GetEfficiency(Float_t, Float_t, const Char_t *, const Char_t *);

void Efficiencies(Float_t cmin, Float_t cmax, TString centr) {

  TString name;

  TH1 *effK0s=
  GetEfficiency(cmin, cmax, "fK0sAs","f3dHistPrimRawPtVsYVsMultK0Short");
  name="eff_K0s_";
  name+=centr;
  effK0s->SetName(name.Data());

  TH1 *effLambda=
  GetEfficiency(cmin, cmax, "fLambdaAs","f3dHistPrimRawPtVsYVsMultLambda");
  name="eff_Lambda_";
  name+=centr;
  effLambda->SetName(name.Data());

  TH1 *effLambdaBar=
  GetEfficiency(cmin,cmax,"fLambdaBarAs","f3dHistPrimRawPtVsYVsMultAntiLambda");
  name="eff_LambdaBar_";
  name+=centr;
  effLambdaBar->SetName(name.Data());

  TFile *f=TFile::Open("SpectraFromTrees.root","update");
    effK0s->Write();
    effLambda->Write();
    effLambdaBar->Write();
  f->Close();
}

TH1 *GetEfficiency(Float_t cMin, Float_t cMax,
		   const Char_t *chis, const Char_t *znam) {
  // Numerator
  fAss->cd();
  TH2F *f2d=(TH2F*)gDirectory->Get(chis); f2d->Sumw2();
  TH1D *hAs=f2d->ProjectionX("hAs",0,-1,"e");

  // Denominator
  fGen->cd();
  TH3F *f3d = (TH3F*)gDirectory->Get(znam);
  f3d->Sumw2();

  TH1D *fpt = f3d->ProjectionX("fpt",
                  f3d->GetYaxis()->FindBin(-0.5+1e-2),
                  f3d->GetYaxis()->FindBin(+0.5-1e-2),
                  f3d->GetZaxis()->FindBin(cMin),
                  f3d->GetZaxis()->FindBin(cMax)
              );
   TH1 *hMc=fpt->Rebin(nb1,"hMc",xbins);

  //Efficiency
  TH1 *eff = (TH1*)hAs->Clone();
  eff->Divide(hAs,hMc,1,1,"b");

  return eff;
}

void RawYields(Float_t cMin, Float_t cMax, TString centr) {
  TString name;
  TH2F *f2d=0;

  //+++ Number of events for normalisation
  TFile *file=TFile::Open("Merged.root");
    TList *v0list=(TList *)gFile->Get("PWGLFExtractV0_PP/clistV0");
    TH1F *fMult=(TH1F*)v0list->FindObject("fHistMultiplicity");
    Int_t i1=fMult->GetXaxis()->FindBin(cMin+1e-2);
    Int_t i2=fMult->GetXaxis()->FindBin(cMax+1e-2);
    Float_t nEvents=fMult->Integral(i1,i2);
  file->Close();

  fRaw->cd();

  name="raw_K0s_";
  name+=centr;
  f2d=(TH2F*)gDirectory->Get("fK0sSi"); f2d->Sumw2();
  TH1D *rawK0s=f2d->ProjectionX(name,0,-1,"e");
  rawK0s->Scale(1/nEvents,"width");

  name="raw_Lambda_";
  name+=centr;
  f2d=(TH2F*)gDirectory->Get("fLambdaSi"); f2d->Sumw2();
  TH1D *rawLambda=f2d->ProjectionX(name,0,-1,"e");
  rawLambda->Scale(1/nEvents,"width");

  name="raw_LambdaBar_";
  name+=centr;
  f2d=(TH2F*)gDirectory->Get("fLambdaBarSi"); f2d->Sumw2();
  TH1D *rawLambdaBar=f2d->ProjectionX(name,0,-1,"e");
  rawLambdaBar->Scale(1/nEvents,"width");

  TFile *f=TFile::Open("SpectraFromTrees.root","update");
    rawK0s->Write();
    rawLambda->Write();
    rawLambdaBar->Write();
  f->Close();
}

void Spectra(TString centr) {
  TString name;
  TH1 *eff=0;
  TH1D *raw=0;
  TH1D *spe=0;

  TFile *f=TFile::Open("SpectraFromTrees.root","update");
    name="eff_K0s_";
    name+=centr;
    eff = (TH1*)gDirectory->Get(name.Data());
    name="raw_K0s_";
    name+=centr;
    raw = (TH1D*)gDirectory->Get(name.Data());
    spe = new TH1D(*raw);
    spe->Divide(eff);
    name="K0s_";
    name+=centr;
    spe->SetName(name.Data());
    spe->Write();

    name="eff_Lambda_";
    name+=centr;
    eff = (TH1*)gDirectory->Get(name.Data());
    name="raw_Lambda_";
    name+=centr;
    raw = (TH1D*)gDirectory->Get(name.Data());
    spe = new TH1D(*raw);
    spe->Divide(eff);
    name="Lambda_";
    name+=centr;
    spe->SetName(name.Data());
    spe->Write();

    name="eff_LambdaBar_";
    name+=centr;
    eff = (TH1*)gDirectory->Get(name.Data());
    name="raw_LambdaBar_";
    name+=centr;
    raw = (TH1D*)gDirectory->Get(name.Data());
    spe = new TH1D(*raw);
    spe->Divide(eff);
    name="LambdaBar_";
    name+=centr;
    spe->SetName(name.Data());
    spe->Write();
  f->Close();
}

void Generated() {
  TList *v0listMC=0;
  TH3F *h3=0;
  //
  TFile::Open("LHC11a10b_plus/Merged.root");
  v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");

  TH3F *k0s =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
  TH3F *k0s_nonInj =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");

  TH3F *lam =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
  TH3F *lam_nonInj =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");

  TH3F *alam =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
  TH3F *alam_nonInj =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");

  //
  TFile::Open("LHC11a10b_bis/Merged.root");
  v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");

  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
  k0s->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");
  k0s_nonInj->Add(h3);

  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
  lam->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");
  lam_nonInj->Add(h3);

  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
  alam->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");
  alam_nonInj->Add(h3);

  //
  TFile::Open("LHC11a10a_bis/Merged.root");
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
  k0s_nonInj->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
  lam_nonInj->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
  alam_nonInj->Add(h3);

  TFile *f=TFile::Open("Generated.root","new");
  k0s->Write(); k0s_nonInj->Write();
  lam->Write(); lam_nonInj->Write();
  alam->Write(); alam_nonInj->Write();
  f->Close();
}
<commit_msg>More convenient file names<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
   #include <TMath.h>
   #include <TROOT.h>
   #include <Riostream.h>
   #include <TCanvas.h>

   #include <TString.h>

   #include <TFile.h>
   #include <TList.h>
   #include <TH1F.h>
   #include <TH1D.h>
   #include <TF2.h>
   #include <TFitResult.h>
   #include <TFitResultPtr.h>
   #include <TH2F.h>
   #include <TH3F.h>
#endif

   Double_t xbins[]={
   0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,
   1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,
   2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,
   4.5,5.0,5.5,6.5,8.0,10.0,12.0
   };
   Int_t nb=sizeof(xbins)/sizeof(Double_t);
   Int_t nb1=nb-1;

TFile *fAss;
TFile *fGen;
TFile *fRaw;

void Generated();
void Efficiencies(Float_t cMin, Float_t cMax, TString centr);
void RawYields(Float_t cMin, Float_t cMax, TString centr);
void Spectra(TString centr);

void SpectraV0CutVariations(Float_t cMin, Float_t cMax, TString centr) {

  fRaw=TFile::Open((centr+"/AliV0CutVariations.root").Data());
  fAss=TFile::Open((centr+"/AliV0CutVariationsMC.root").Data());
  fGen=TFile::Open("Generated.root");
  if (!fGen) {
     Generated();
     fGen=TFile::Open("Generated.root");
  }

  Efficiencies(cMin,cMax,centr);
  RawYields(cMin,cMax,centr);
  Spectra(centr);

  fAss->Close();
  fGen->Close();
  fRaw->Close();
}

TH1 *GetEfficiency(Float_t, Float_t, const Char_t *, const Char_t *);

void Efficiencies(Float_t cmin, Float_t cmax, TString centr) {

  TString name;

  TH1 *effK0s=
  GetEfficiency(cmin, cmax, "fK0sAs","f3dHistPrimRawPtVsYVsMultK0Short");
  name="eff_K0s_";
  name+=centr;
  effK0s->SetName(name.Data());

  TH1 *effLambda=
  GetEfficiency(cmin, cmax, "fLambdaAs","f3dHistPrimRawPtVsYVsMultLambda");
  name="eff_Lambda_";
  name+=centr;
  effLambda->SetName(name.Data());

  TH1 *effLambdaBar=
  GetEfficiency(cmin,cmax,"fLambdaBarAs","f3dHistPrimRawPtVsYVsMultAntiLambda");
  name="eff_LambdaBar_";
  name+=centr;
  effLambdaBar->SetName(name.Data());

  TFile *f=TFile::Open("SpectraV0CutVariations.root","update");
    effK0s->Write();
    effLambda->Write();
    effLambdaBar->Write();
  f->Close();
}

TH1 *GetEfficiency(Float_t cMin, Float_t cMax,
		   const Char_t *chis, const Char_t *znam) {
  // Numerator
  fAss->cd();
  TH2F *f2d=(TH2F*)gDirectory->Get(chis); f2d->Sumw2();
  TH1D *hAs=f2d->ProjectionX("hAs",0,-1,"e");

  // Denominator
  fGen->cd();
  TH3F *f3d = (TH3F*)gDirectory->Get(znam);
  f3d->Sumw2();

  TH1D *fpt = f3d->ProjectionX("fpt",
                  f3d->GetYaxis()->FindBin(-0.5+1e-2),
                  f3d->GetYaxis()->FindBin(+0.5-1e-2),
                  f3d->GetZaxis()->FindBin(cMin),
                  f3d->GetZaxis()->FindBin(cMax)
              );
   TH1 *hMc=fpt->Rebin(nb1,"hMc",xbins);

  //Efficiency
  TH1 *eff = (TH1*)hAs->Clone();
  eff->Divide(hAs,hMc,1,1,"b");

  return eff;
}

void RawYields(Float_t cMin, Float_t cMax, TString centr) {
  TString name;
  TH2F *f2d=0;

  //+++ Number of events for normalisation
  TFile *file=TFile::Open("LHC10h_pass2/Merged.root");
    TList *v0list=(TList *)gFile->Get("PWGLFExtractV0_PP/clistV0");
    TH1F *fMult=(TH1F*)v0list->FindObject("fHistMultiplicity");
    Int_t i1=fMult->GetXaxis()->FindBin(cMin+1e-2);
    Int_t i2=fMult->GetXaxis()->FindBin(cMax+1e-2);
    Float_t nEvents=fMult->Integral(i1,i2);
  file->Close();

  fRaw->cd();

  name="raw_K0s_";
  name+=centr;
  f2d=(TH2F*)gDirectory->Get("fK0sSi"); f2d->Sumw2();
  TH1D *rawK0s=f2d->ProjectionX(name,0,-1,"e");
  rawK0s->Scale(1/nEvents,"width");

  name="raw_Lambda_";
  name+=centr;
  f2d=(TH2F*)gDirectory->Get("fLambdaSi"); f2d->Sumw2();
  TH1D *rawLambda=f2d->ProjectionX(name,0,-1,"e");
  rawLambda->Scale(1/nEvents,"width");

  name="raw_LambdaBar_";
  name+=centr;
  f2d=(TH2F*)gDirectory->Get("fLambdaBarSi"); f2d->Sumw2();
  TH1D *rawLambdaBar=f2d->ProjectionX(name,0,-1,"e");
  rawLambdaBar->Scale(1/nEvents,"width");

  TFile *f=TFile::Open("SpectraV0CutVariations.root","update");
    rawK0s->Write();
    rawLambda->Write();
    rawLambdaBar->Write();
  f->Close();
}

void Spectra(TString centr) {
  TString name;
  TH1 *eff=0;
  TH1D *raw=0;
  TH1D *spe=0;

  TFile *f=TFile::Open("SpectraV0CutVariations.root","update");
    name="eff_K0s_";
    name+=centr;
    eff = (TH1*)gDirectory->Get(name.Data());
    name="raw_K0s_";
    name+=centr;
    raw = (TH1D*)gDirectory->Get(name.Data());
    spe = new TH1D(*raw);
    spe->Divide(eff);
    name="K0s_";
    name+=centr;
    spe->SetName(name.Data());
    spe->Write();

    name="eff_Lambda_";
    name+=centr;
    eff = (TH1*)gDirectory->Get(name.Data());
    name="raw_Lambda_";
    name+=centr;
    raw = (TH1D*)gDirectory->Get(name.Data());
    spe = new TH1D(*raw);
    spe->Divide(eff);
    name="Lambda_";
    name+=centr;
    spe->SetName(name.Data());
    spe->Write();

    name="eff_LambdaBar_";
    name+=centr;
    eff = (TH1*)gDirectory->Get(name.Data());
    name="raw_LambdaBar_";
    name+=centr;
    raw = (TH1D*)gDirectory->Get(name.Data());
    spe = new TH1D(*raw);
    spe->Divide(eff);
    name="LambdaBar_";
    name+=centr;
    spe->SetName(name.Data());
    spe->Write();
  f->Close();
}

void Generated() {
  TList *v0listMC=0;
  TH3F *h3=0;
  //
  TFile::Open("LHC11a10b_plus/Merged.root");
  v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");

  TH3F *k0s =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
  TH3F *k0s_nonInj =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");

  TH3F *lam =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
  TH3F *lam_nonInj =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");

  TH3F *alam =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
  TH3F *alam_nonInj =
    (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");

  //
  TFile::Open("LHC11a10b_bis/Merged.root");
  v0listMC=(TList *)gFile->Get("PWGLFExtractPerformanceV0_PP_MC/clistV0MC");

  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
  k0s->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjK0Short");
  k0s_nonInj->Add(h3);

  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
  lam->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjLambda");
  lam_nonInj->Add(h3);

  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
  alam->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultNonInjAntiLambda");
  alam_nonInj->Add(h3);

  //
  TFile::Open("LHC11a10a_bis/Merged.root");
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultK0Short");
  k0s_nonInj->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultLambda");
  lam_nonInj->Add(h3);
  h3 = (TH3F*)v0listMC->FindObject("f3dHistPrimRawPtVsYVsMultAntiLambda");
  alam_nonInj->Add(h3);

  TFile *f=TFile::Open("Generated.root","new");
  k0s->Write(); k0s_nonInj->Write();
  lam->Write(); lam_nonInj->Write();
  alam->Write(); alam_nonInj->Write();
  f->Close();
}

<|endoftext|>


<commit_before>#include <limits>
#include <boost/math/special_functions/fpclassify.hpp>
#include <stan/agrad/rev/functions/abs.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>

TEST(AgradRev,abs_var) {
  AVAR a = 0.68;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(0.68, f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(1.0, g[0]);
}

TEST(AgradRev,abs_var_2) {
  AVAR a = -0.68;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(0.68, f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(-1.0, g[0]);
}

TEST(AgradRev,abs_var_3) {
  AVAR a = 0.0;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(0.0, f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_EQ(1U,g.size());
  EXPECT_FLOAT_EQ(0.0, g[0]);
}

TEST(AgradRev,abs_inf) {
  double inf = std::numeric_limits<double>::infinity();
  AVAR a = inf;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(inf,f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(1.0,g[0]);
}

TEST(AgradRev,abs_neg_inf) {
  double inf = std::numeric_limits<double>::infinity();
  AVAR a = -inf;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(inf,f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(-1.0,g[0]);
}

TEST(AgradRev,abs_NaN) {
  AVAR a = std::numeric_limits<double>::quiet_NaN();
  AVAR f = abs(a);

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);

  EXPECT_TRUE(boost::math::isnan(f.val()));
  ASSERT_EQ(1U,g.size());
  EXPECT_TRUE(boost::math::isnan(g[0]));
}
<commit_msg>update nan test for agrad/rev/abs<commit_after>#include <limits>
#include <stan/agrad/rev/functions/abs.hpp>
#include <test/unit/agrad/util.hpp>
#include <test/unit-agrad-rev/nan_util.hpp>
#include <gtest/gtest.h>

TEST(AgradRev,abs_var) {
  AVAR a = 0.68;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(0.68, f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(1.0, g[0]);
}

TEST(AgradRev,abs_var_2) {
  AVAR a = -0.68;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(0.68, f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(-1.0, g[0]);
}

TEST(AgradRev,abs_var_3) {
  AVAR a = 0.0;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(0.0, f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_EQ(1U,g.size());
  EXPECT_FLOAT_EQ(0.0, g[0]);
}

TEST(AgradRev,abs_inf) {
  double inf = std::numeric_limits<double>::infinity();
  AVAR a = inf;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(inf,f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(1.0,g[0]);
}

TEST(AgradRev,abs_neg_inf) {
  double inf = std::numeric_limits<double>::infinity();
  AVAR a = -inf;
  AVAR f = abs(a);
  EXPECT_FLOAT_EQ(inf,f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(-1.0,g[0]);
}

struct abs_fun {
  template <typename T0>
  inline T0
  operator()(const T0& arg1) const {
    return abs(arg1);
  }
};

TEST(AgradRev,abs_NaN) {
  abs_fun abs_;
  test_nan(abs_,false,true);
}
<|endoftext|>


<commit_before>#include "RhoFile.h"
#include "common/StringConverter.h"

namespace rho{
namespace common{

class CFileInputStream : public InputStream
{
    CRhoFile& m_oFile;
public:
    CFileInputStream(CRhoFile& oFile) : m_oFile(oFile){}

    virtual  int available(){ return m_oFile.size(); }
    virtual  int read(){ return m_oFile.readByte(); }
    virtual  int read(void* buffer, int bufOffset, int bytesToRead){ return m_oFile.readData(buffer, bufOffset, bytesToRead); }
    virtual  void reset(){ m_oFile.movePosToStart(); }
};

bool CRhoFile::isOpened(){
    return m_file!=0;
}

bool CRhoFile::open( const char* szFilePath, EOpenModes eMode ){
    m_strPath = szFilePath;
    if ( eMode == OpenForAppend || eMode == OpenForReadWrite ){
        m_file = fopen(szFilePath,"r+b");

        if ( eMode == OpenForAppend )
            movePosToEnd();

        if ( !m_file && !isFileExist(szFilePath) )
            m_file = fopen(szFilePath,"wb");
    }else if ( eMode == OpenReadOnly )
        m_file = fopen(szFilePath,"rb");
    else if ( eMode == OpenForWrite )
        m_file = fopen(szFilePath,"wb");

    return isOpened();
}

unsigned int CRhoFile::write( const void* data, unsigned int len ){
    if ( !isOpened() )
        return 0;

    return static_cast<unsigned int>( fwrite(data,1, len, m_file) );
}

int CRhoFile::readByte()
{
    unsigned char buf[1];
    int nSize = fread(buf, 1, 1, m_file);

    return nSize > 0 ? buf[0] : -1;
}

int CRhoFile::readData(void* buffer, int bufOffset, int bytesToRead)
{
    int nSize = fread(((char*)buffer)+bufOffset, 1, bytesToRead, m_file);
    return nSize > 0 ? nSize : -1;
}

void CRhoFile::readString(String& strData){
    if ( !isOpened() )
        return;

    int nSize = size();
    strData.resize(nSize);
    nSize = fread(&strData[0], 1, nSize, m_file);
    strData[nSize] = 0;
}

void CRhoFile::readStringW(StringW& strTextW)
{
    if ( !isOpened() )
        return;

    int nSize = size();
    char* buf = (char*)malloc(nSize+1);
    nSize = fread(buf, 1, nSize, m_file);
    buf[nSize] = 0;
    common::convertToStringW(buf,strTextW);
    free(buf);
}

InputStream* CRhoFile::getInputStream()
{
    if ( m_pInputStream )
        delete m_pInputStream;

    m_pInputStream = new CFileInputStream(*this);
    return m_pInputStream;
}

void CRhoFile::flush(){
    if ( !isOpened() )
        return;

    fflush(m_file);
}

void CRhoFile::close(){
    if ( !isOpened() )
        return;

    if ( m_pInputStream )
        delete m_pInputStream;

    m_pInputStream = 0;

    fclose(m_file);
    m_file = 0;
}

void CRhoFile::movePosToStart(){
    if ( !isOpened() )
        return;

    fseek(m_file,0,SEEK_SET);
}

void CRhoFile::movePosToEnd(){
    if ( !isOpened() )
        return;

    fseek(m_file,0,SEEK_END);
}

void CRhoFile::setPosTo(int nPos){
    if ( !isOpened() || nPos < 0 )
        return;

    fseek(m_file,nPos,SEEK_SET);
}

unsigned int CRhoFile::size(){
    if ( !isOpened() )
        return 0;

    return getFileSize( m_strPath.c_str() );
}

bool CRhoFile::isFileExist( const char* szFilePath ){
    struct stat st;
    memset(&st,0, sizeof(st));
    return stat(szFilePath, &st) == 0;
}

unsigned int CRhoFile::getFileSize( const char* szFilePath ){
    struct stat st;
    memset(&st,0, sizeof(st));
    int rc = stat(szFilePath, &st);
    if ( rc == 0 && st.st_size > 0 )
        return st.st_size;

    return 0;
}

void CRhoFile::loadTextFile(const char* szFilePath, String& strFile)
{
    common::CRhoFile oFile;
    if ( oFile.open( szFilePath, common::CRhoFile::OpenReadOnly) )
        oFile.readString(strFile);
}

void CRhoFile::deleteFile( const char* szFilePath ){
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    StringW wFileName;
    common::convertToStringW(szFilePath,wFileName);
    DeleteFile(wFileName.c_str());
#else
    remove(szFilePath);
#endif
}

void CRhoFile::deleteFilesInFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    StringW wFolderName;
    common::convertToStringW(szFolderPath,wFolderName);
    StringW wFolderMask = wFolderName + L"/*";

    WIN32_FIND_DATAW FindFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;

    hFind = FindFirstFileW(wFolderMask.c_str(), &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
        return;

    while (FindNextFileW(hFind, &FindFileData) != 0)
    {
        if ( FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY )
            continue;

        StringW wFileName = wFolderName + L"/" + FindFileData.cFileName;
        DeleteFileW(wFileName.c_str());
    }

    FindClose(hFind);

#else
    delete_files_in_folder(szFolderPath);
#endif
}

#if defined(OS_WINDOWS) || defined(OS_WINCE)
    extern "C" int _mkdir(const char * dir);
#endif

/*static*/ void CRhoFile::createFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    _mkdir(szFolderPath);
#else
    mkdir(szFolderPath, S_IRWXU);
#endif
}

/*static*/ void CRhoFile::renameFile( const char* szOldFilePath, const char* szNewFilePath )
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    StringW wNewFileName, wOldFileName;
    common::convertToStringW(szNewFilePath,wNewFileName);
    common::convertToStringW(szOldFilePath,wOldFileName);

	BOOL res = MoveFileW( wOldFileName.c_str(), wNewFileName.c_str());
#else
    rename( szOldFilePath, szNewFilePath );
#endif

}

}
}
<commit_msg>fix append file issue<commit_after>#include "RhoFile.h"
#include "common/StringConverter.h"

namespace rho{
namespace common{

class CFileInputStream : public InputStream
{
    CRhoFile& m_oFile;
public:
    CFileInputStream(CRhoFile& oFile) : m_oFile(oFile){}

    virtual  int available(){ return m_oFile.size(); }
    virtual  int read(){ return m_oFile.readByte(); }
    virtual  int read(void* buffer, int bufOffset, int bytesToRead){ return m_oFile.readData(buffer, bufOffset, bytesToRead); }
    virtual  void reset(){ m_oFile.movePosToStart(); }
};

bool CRhoFile::isOpened(){
    return m_file!=0;
}

bool CRhoFile::open( const char* szFilePath, EOpenModes eMode ){
    m_strPath = szFilePath;
    if ( eMode == OpenForAppend || eMode == OpenForReadWrite ){
        m_file = fopen(szFilePath,"r+b");

        if ( !m_file && !isFileExist(szFilePath) )
            m_file = fopen(szFilePath,"wb");

        if ( eMode == OpenForAppend )
            movePosToEnd();

    }else if ( eMode == OpenReadOnly )
        m_file = fopen(szFilePath,"rb");
    else if ( eMode == OpenForWrite )
        m_file = fopen(szFilePath,"wb");

    return isOpened();
}

unsigned int CRhoFile::write( const void* data, unsigned int len ){
    if ( !isOpened() )
        return 0;

    return static_cast<unsigned int>( fwrite(data,1, len, m_file) );
}

int CRhoFile::readByte()
{
    unsigned char buf[1];
    int nSize = fread(buf, 1, 1, m_file);

    return nSize > 0 ? buf[0] : -1;
}

int CRhoFile::readData(void* buffer, int bufOffset, int bytesToRead)
{
    int nSize = fread(((char*)buffer)+bufOffset, 1, bytesToRead, m_file);
    return nSize > 0 ? nSize : -1;
}

void CRhoFile::readString(String& strData){
    if ( !isOpened() )
        return;

    int nSize = size();
    strData.resize(nSize);
    nSize = fread(&strData[0], 1, nSize, m_file);
    strData[nSize] = 0;
}

void CRhoFile::readStringW(StringW& strTextW)
{
    if ( !isOpened() )
        return;

    int nSize = size();
    char* buf = (char*)malloc(nSize+1);
    nSize = fread(buf, 1, nSize, m_file);
    buf[nSize] = 0;
    common::convertToStringW(buf,strTextW);
    free(buf);
}

InputStream* CRhoFile::getInputStream()
{
    if ( m_pInputStream )
        delete m_pInputStream;

    m_pInputStream = new CFileInputStream(*this);
    return m_pInputStream;
}

void CRhoFile::flush(){
    if ( !isOpened() )
        return;

    fflush(m_file);
}

void CRhoFile::close(){
    if ( !isOpened() )
        return;

    if ( m_pInputStream )
        delete m_pInputStream;

    m_pInputStream = 0;

    fclose(m_file);
    m_file = 0;
}

void CRhoFile::movePosToStart(){
    if ( !isOpened() )
        return;

    fseek(m_file,0,SEEK_SET);
}

void CRhoFile::movePosToEnd(){
    if ( !isOpened() )
        return;

    int nRes = fseek(m_file,0,SEEK_END);
    fpos_t pos = 0;
    int nRes2 = fgetpos(m_file, &pos );

    if ( !nRes2 )
        nRes2 = 0;
}

void CRhoFile::setPosTo(int nPos){
    if ( !isOpened() || nPos < 0 )
        return;

    fseek(m_file,nPos,SEEK_SET);
}

unsigned int CRhoFile::size(){
    if ( !isOpened() )
        return 0;

    return getFileSize( m_strPath.c_str() );
}

bool CRhoFile::isFileExist( const char* szFilePath ){
    struct stat st;
    memset(&st,0, sizeof(st));
    return stat(szFilePath, &st) == 0;
}

unsigned int CRhoFile::getFileSize( const char* szFilePath ){
    struct stat st;
    memset(&st,0, sizeof(st));
    int rc = stat(szFilePath, &st);
    if ( rc == 0 && st.st_size > 0 )
        return st.st_size;

    return 0;
}

void CRhoFile::loadTextFile(const char* szFilePath, String& strFile)
{
    common::CRhoFile oFile;
    if ( oFile.open( szFilePath, common::CRhoFile::OpenReadOnly) )
        oFile.readString(strFile);
}

void CRhoFile::deleteFile( const char* szFilePath ){
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    StringW wFileName;
    common::convertToStringW(szFilePath,wFileName);
    DeleteFile(wFileName.c_str());
#else
    remove(szFilePath);
#endif
}

void CRhoFile::deleteFilesInFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    StringW wFolderName;
    common::convertToStringW(szFolderPath,wFolderName);
    StringW wFolderMask = wFolderName + L"/*";

    WIN32_FIND_DATAW FindFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;

    hFind = FindFirstFileW(wFolderMask.c_str(), &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
        return;

    while (FindNextFileW(hFind, &FindFileData) != 0)
    {
        if ( FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY )
            continue;

        StringW wFileName = wFolderName + L"/" + FindFileData.cFileName;
        DeleteFileW(wFileName.c_str());
    }

    FindClose(hFind);

#else
    delete_files_in_folder(szFolderPath);
#endif
}

#if defined(OS_WINDOWS) || defined(OS_WINCE)
    extern "C" int _mkdir(const char * dir);
#endif

/*static*/ void CRhoFile::createFolder(const char* szFolderPath)
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    _mkdir(szFolderPath);
#else
    mkdir(szFolderPath, S_IRWXU);
#endif
}

/*static*/ void CRhoFile::renameFile( const char* szOldFilePath, const char* szNewFilePath )
{
#if defined(OS_WINDOWS) || defined(OS_WINCE)
    StringW wNewFileName, wOldFileName;
    common::convertToStringW(szNewFilePath,wNewFileName);
    common::convertToStringW(szOldFilePath,wOldFileName);

	BOOL res = MoveFileW( wOldFileName.c_str(), wNewFileName.c_str());
#else
    rename( szOldFilePath, szNewFilePath );
#endif

}

}
}
<|endoftext|>