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

/* $Id$ */

//This class produces PHOS digits of one event
//using AliPHOSRawFitter.
//
//   For example:
//   TClonesArray *digits = new TClonesArray("AliPHOSDigit",100);
//   AliRawReader* rawReader = new AliRawReaderDate("2006run2211.raw");
//   AliPHOSRawDecoder dc(rawReader);
//   while (rawReader->NextEvent()) {
//     AliPHOSRawDigiProducer producer;
//     producer.MakeDigits(digits,&dc);
//   }

// Author: Boris Polichtchouk

// --- ROOT system ---
#include "TClonesArray.h"

// --- AliRoot header files ---
#include "AliPHOSRawDigiProducer.h"
#include "AliPHOSRawFitterv0.h"
#include "AliPHOSGeometry.h"
#include "AliPHOSDigit.h"
#include "AliPHOSCalibData.h"
#include "AliPHOSPulseGenerator.h"
#include "AliCaloRawStreamV3.h"
#include "AliLog.h"

ClassImp(AliPHOSRawDigiProducer)

AliPHOSCalibData * AliPHOSRawDigiProducer::fgCalibData  = 0 ;

//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::AliPHOSRawDigiProducer():
  TObject(),
  fEmcMinE(0.),
  fCpvMinE(0.),
  fSampleQualityCut(1.),
  fSampleToSec(0.),
  fEmcCrystals(0),
  fGeom(0),
  fPulseGenerator(0),
  fRawReader(0),
  fRawStream(0)
{
  // Default constructor

  fGeom=AliPHOSGeometry::GetInstance() ;
  if(!fGeom) fGeom = AliPHOSGeometry::GetInstance("IHEP");

  fEmcCrystals=fGeom->GetNCristalsInModule()*fGeom->GetNModules() ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  GetCalibrationParameters() ;

}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::AliPHOSRawDigiProducer(AliRawReader *rawReader,
					       AliAltroMapping **mapping):
  TObject(),
  fEmcMinE(0.),
  fCpvMinE(0.),
  fSampleQualityCut(1.),
  fSampleToSec(0.),
  fEmcCrystals(0),
  fGeom(0),
  fPulseGenerator(0),
  fRawReader(rawReader),
  fRawStream(0)
{
  // Default constructor

  fGeom=AliPHOSGeometry::GetInstance() ;
  if(!fGeom) fGeom = AliPHOSGeometry::GetInstance("IHEP");

  fEmcCrystals=fGeom->GetNCristalsInModule()*fGeom->GetNModules() ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  GetCalibrationParameters() ;

  fRawStream = new AliCaloRawStreamV3(rawReader,"PHOS",mapping);

}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::AliPHOSRawDigiProducer(const AliPHOSRawDigiProducer &dp):
  TObject(),
  fEmcMinE(0.),
  fCpvMinE(0.),
  fSampleQualityCut(1.),
  fSampleToSec(0.),
  fEmcCrystals(0),
  fGeom(0),
  fPulseGenerator(0),
  fRawReader(0),
  fRawStream(0)
{
  // Copy constructor

  fEmcMinE = dp.fEmcMinE ;
  fCpvMinE = dp.fCpvMinE ;
  fSampleQualityCut = dp.fSampleQualityCut;
  fSampleToSec = dp.fSampleToSec ;
  fEmcCrystals = dp.fEmcCrystals ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  fGeom = dp.fGeom ;
}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer& AliPHOSRawDigiProducer::operator= (const AliPHOSRawDigiProducer &dp)
{
  // Assign operator

  if(&dp == this) return *this;

  fEmcMinE = dp.fEmcMinE ;
  fCpvMinE = dp.fCpvMinE ;
  fSampleQualityCut = dp.fSampleQualityCut ;
  fSampleToSec = dp.fSampleToSec ;
  fEmcCrystals = dp.fEmcCrystals ;
  fGeom = dp.fGeom ;
  if(fPulseGenerator) delete fPulseGenerator ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  return  *this;
}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::~AliPHOSRawDigiProducer()
{
  // Destructor
  if(fPulseGenerator) delete fPulseGenerator ;
  fPulseGenerator=0 ;
  delete fRawStream;
}
//--------------------------------------------------------------------------------------
void AliPHOSRawDigiProducer::MakeDigits(TClonesArray *digits, AliPHOSRawFitterv0* fitter)
{
  //Makes the job.
  //TClonesArray *digits and raw data fitter should be provided by calling function.

  digits->Clear();

  Int_t iDigit=0 ;
  Int_t relId[4], absId=-1, caloFlag=-1;

  const Double_t baseLine=1. ; //Minimal energy of digit in ADC ch.

  //Calculate conversion coeff. from Sample time step to seconds
  //If OCDB contains negative or zero value - use one from RCU trailer
  //Negative value in OCDB is used only for simulation of raw digits
  if(fgCalibData->GetSampleTimeStep()>0.)
    fSampleToSec=fgCalibData->GetSampleTimeStep() ;
  else
    fSampleToSec=fRawStream->GetTSample() ;

  //Temporary array for LowGain digits
  TClonesArray tmpLG("AliPHOSDigit",10000) ;
  Int_t ilgDigit=0 ;

  //Let fitter subtract pedestals in case of ZS
  fitter->SetCalibData(fgCalibData) ;

  while (fRawStream->NextDDL()) {
    while (fRawStream->NextChannel()) {
      relId[0] = 5 - fRawStream->GetModule() ; // counts from 1 to 5
      relId[1] = 0;
      relId[2] = fRawStream->GetCellX()  + 1; // counts from 1 to 64
      relId[3] = fRawStream->GetCellZ()  + 1; // counts from 1 to 56
      caloFlag = fRawStream->GetCaloFlag();   // 0=LG, 1=HG, 2=TRU

      if(caloFlag!=0 && caloFlag!=1) continue; //TRU data!

      fitter->SetChannelGeo(relId[0],relId[2],relId[3],caloFlag);

      if(fitter->GetAmpOffset()==0 && fitter->GetAmpThreshold()==0) {
	short value = fRawStream->GetAltroCFG1();
	bool ZeroSuppressionEnabled = (value >> 15) & 0x1;
	if(ZeroSuppressionEnabled) {
	  short offset = (value >> 10) & 0xf;
	  short threshold = value & 0x3ff;
	  fitter->SubtractPedestals(kFALSE);
	  fitter->SetAmpOffset(offset);
	  fitter->SetAmpThreshold(threshold);
	}
      }

      fGeom->RelToAbsNumbering(relId, absId);

      Int_t nBunches = 0;
      while (fRawStream->NextBunch()) {
	nBunches++;
	if (nBunches > 1) continue;
	const UShort_t *sig = fRawStream->GetSignals();
	Int_t sigStart  = fRawStream->GetStartTimeBin();
	Int_t sigLength = fRawStream->GetBunchLength();
	fitter->Eval(sig,sigStart,sigLength);
      } // End of NextBunch()

      fitter->SetNBunches(nBunches);

      Double_t energy = fitter->GetEnergy() ;
      Double_t time   = fitter->GetTime() ;
      if(energy<=baseLine) //in ADC channels
	continue ;

      //remove digits with bad shape. Fitter should calculate quality so that
      //in default case quality [0,1], while larger values of quality mean somehow
      //corrupted samples, 999 means obviously corrupted sample.
      //It is difficult to fit samples with overflow (even setting cut on overflow values)
      //because too few points are left to fit. So we do not evaluate samples with overflow

      if(fitter->GetSignalQuality() > fSampleQualityCut && !(fitter->IsOverflow()))
	continue ;

//       energy = CalibrateE(energy,relId,lowGainFlag) ;
//       time   = CalibrateT(time,relId,lowGainFlag) ;

      //convert time from sample bin units to s
      time*=fSampleToSec ;

      if(energy <= 0.)
	continue;

      if (caloFlag == AliCaloRawStreamV3::kLowGain) {
	new(tmpLG[ilgDigit]) AliPHOSDigit(-1,absId,(Float_t)energy,(Float_t)time);
	ilgDigit++ ;
      }
      else if (caloFlag == AliCaloRawStreamV3::kHighGain) {
	if(fitter->IsOverflow()) //Keep this digit to replace it by Low Gain later.
	  //If there is no LogGain it wil be removed by cut on Min E
	  new((*digits)[iDigit]) AliPHOSDigit(-1,absId,-1.f,(Float_t)time);
	else
	  new((*digits)[iDigit]) AliPHOSDigit(-1,absId,(Float_t)energy,(Float_t)time);
	iDigit++;
      }
    } // End of NextChannel()

    //Now scan created LG and HG digits and keep only those which appeared in both lists
    //replace energy of HighGain digits only if there is overflow
    //negative energy (overflow)
    digits->Sort() ;
    tmpLG.Sort() ;
    Int_t iLG = 0;
    Int_t nLG1 = tmpLG.GetEntriesFast()-1 ;

    for(Int_t iDig=0 ; iDig < digits->GetEntriesFast() ; iDig++) {
      AliPHOSDigit * digHG = dynamic_cast<AliPHOSDigit*>(digits->At(iDig)) ;
      if (!digHG) continue;
      AliPHOSDigit * digLG = dynamic_cast<AliPHOSDigit*>(tmpLG.At(iLG)) ;
      while(digLG && iLG<nLG1 && digHG->GetId()> digLG->GetId()){
	iLG++ ;
	digLG = dynamic_cast<AliPHOSDigit*>(tmpLG.At(iLG)) ;
      }
      absId=digHG->GetId() ;
      fGeom->AbsToRelNumbering(absId,relId) ;

      if(digLG && digHG->GetId() == digLG->GetId()){ //we found pair
	if(digHG->GetEnergy()<0.){ //This is overflow in HG
	  digHG->SetTime(digLG->GetTime()) ;
	  digHG->SetEnergy(digLG->GetEnergy()) ;
	}
      }
      else{ //no pair - remove
	if(digHG->GetEnergy()<0.) //no pair, in saturation
	  digits->RemoveAt(iDig) ;
      }
    }
  } // End of NextDDL()

  CleanDigits(digits) ;

}
//____________________________________________________________________________
Double_t AliPHOSRawDigiProducer::CalibrateE(Double_t amp, Int_t* relId, Bool_t isLowGain)
{
  // Convert EMC LG amplitude to HG (multipli by ~16)
  // Calibration parameters are taken from calibration data base
  if(fgCalibData){
    Int_t   module = relId[0];
    Int_t   column = relId[3];
    Int_t   row    = relId[2];
    if(relId[1]==0) { // this is EMC
      if(isLowGain){
        amp*= fgCalibData->GetHighLowRatioEmc(module,column,row);
      }
      return amp ;
    }
  }
  return 0;
}
//____________________________________________________________________________
Double_t AliPHOSRawDigiProducer::CalibrateT(Double_t time, Int_t * relId, Bool_t /* isLowGain */)
{
  //Calibrate time
  time*=fPulseGenerator->GetRawFormatTimeTrigger() ;
  if(fgCalibData){
    Int_t   module = relId[0];
    Int_t   column = relId[3];
    Int_t   row    = relId[2];
    if(relId[1]==0) { // this is EMC
      time += fgCalibData->GetTimeShiftEmc(module,column,row);
      return time ;
    }
  }

  return -999.;
}
//____________________________________________________________________________
void AliPHOSRawDigiProducer::CleanDigits(TClonesArray * digits)
{
  // remove digits with amplitudes below threshold.
  // remove digits in bad channels
  // sort digits with icreasing AbsId

  //remove digits in bad map and below threshold
  Bool_t isBadMap = 0 ;
  if(fgCalibData->GetNumOfEmcBadChannels()){
    isBadMap=1 ;
  }

  for(Int_t i=0; i<digits->GetEntriesFast(); i++){
    AliPHOSDigit * digit = static_cast<AliPHOSDigit*>(digits->At(i)) ;
    if(!digit)
      continue  ;
    if ( (IsInEMC(digit) && digit->GetEnergy() < fEmcMinE) ||
	 (IsInCPV(digit) && digit->GetEnergy() < fCpvMinE) ){
      digits->RemoveAt(i) ;
      continue ;
    }
    if(isBadMap){ //check bad map now
      Int_t relid[4] ;
      fGeom->AbsToRelNumbering(digit->GetId(), relid) ;
      if(fgCalibData->IsBadChannelEmc(relid[0],relid[3],relid[2])){
	digits->RemoveAt(i) ;
      }
    }
  }

  //Compress, sort and set indexes
  digits->Compress() ;
//  digits->Sort(); already sorted earlier
  for (Int_t i = 0 ; i < digits->GetEntriesFast() ; i++) {
    AliPHOSDigit *digit = static_cast<AliPHOSDigit*>( digits->At(i) ) ;
    digit->SetIndexInList(i) ;
  }
}
//____________________________________________________________________________
Bool_t AliPHOSRawDigiProducer::IsInEMC(AliPHOSDigit * digit) const
{
  // Tells if (true) or not (false) the digit is in a PHOS-EMC module
  return digit->GetId() <= fEmcCrystals ;

}

//____________________________________________________________________________
Bool_t AliPHOSRawDigiProducer::IsInCPV(AliPHOSDigit * digit) const
{
  // Tells if (true) or not (false) the digit is in a PHOS-CPV module
  return digit->GetId() > fEmcCrystals ;
}
//____________________________________________________________________________
void AliPHOSRawDigiProducer::GetCalibrationParameters()
{
  // Set calibration parameters:
  // if calibration database exists, they are read from database,
  // otherwise, reconstruction stops in the constructor of AliPHOSCalibData
  //
  // It is a user responsilibity to open CDB before reconstruction, for example:
  // AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage("local://CalibDB");

  if (!fgCalibData){
    fgCalibData = new AliPHOSCalibData(-1); //use AliCDBManager's run number
  }
  if (fgCalibData->GetCalibDataEmc() == 0)
    AliFatal("Calibration parameters for PHOS EMC not found. Stop reconstruction.\n");
  if (fgCalibData->GetCalibDataCpv() == 0)
    AliFatal("Calibration parameters for PHOS CPV not found. Stop reconstruction.\n");
}
<commit_msg>Low gain calibration fixed.<commit_after>/**************************************************************************
 * Copyright(c) 2007, ALICE Experiment at CERN, All rights reserved.      *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//This class produces PHOS digits of one event
//using AliPHOSRawFitter.
//
//   For example:
//   TClonesArray *digits = new TClonesArray("AliPHOSDigit",100);
//   AliRawReader* rawReader = new AliRawReaderDate("2006run2211.raw");
//   AliPHOSRawDecoder dc(rawReader);
//   while (rawReader->NextEvent()) {
//     AliPHOSRawDigiProducer producer;
//     producer.MakeDigits(digits,&dc);
//   }

// Author: Boris Polichtchouk

// --- ROOT system ---
#include "TClonesArray.h"

// --- AliRoot header files ---
#include "AliPHOSRawDigiProducer.h"
#include "AliPHOSRawFitterv0.h"
#include "AliPHOSGeometry.h"
#include "AliPHOSDigit.h"
#include "AliPHOSCalibData.h"
#include "AliPHOSPulseGenerator.h"
#include "AliCaloRawStreamV3.h"
#include "AliLog.h"

ClassImp(AliPHOSRawDigiProducer)

AliPHOSCalibData * AliPHOSRawDigiProducer::fgCalibData  = 0 ;

//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::AliPHOSRawDigiProducer():
  TObject(),
  fEmcMinE(0.),
  fCpvMinE(0.),
  fSampleQualityCut(1.),
  fSampleToSec(0.),
  fEmcCrystals(0),
  fGeom(0),
  fPulseGenerator(0),
  fRawReader(0),
  fRawStream(0)
{
  // Default constructor

  fGeom=AliPHOSGeometry::GetInstance() ;
  if(!fGeom) fGeom = AliPHOSGeometry::GetInstance("IHEP");

  fEmcCrystals=fGeom->GetNCristalsInModule()*fGeom->GetNModules() ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  GetCalibrationParameters() ;

}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::AliPHOSRawDigiProducer(AliRawReader *rawReader,
					       AliAltroMapping **mapping):
  TObject(),
  fEmcMinE(0.),
  fCpvMinE(0.),
  fSampleQualityCut(1.),
  fSampleToSec(0.),
  fEmcCrystals(0),
  fGeom(0),
  fPulseGenerator(0),
  fRawReader(rawReader),
  fRawStream(0)
{
  // Default constructor

  fGeom=AliPHOSGeometry::GetInstance() ;
  if(!fGeom) fGeom = AliPHOSGeometry::GetInstance("IHEP");

  fEmcCrystals=fGeom->GetNCristalsInModule()*fGeom->GetNModules() ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  GetCalibrationParameters() ;

  fRawStream = new AliCaloRawStreamV3(rawReader,"PHOS",mapping);

}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::AliPHOSRawDigiProducer(const AliPHOSRawDigiProducer &dp):
  TObject(),
  fEmcMinE(0.),
  fCpvMinE(0.),
  fSampleQualityCut(1.),
  fSampleToSec(0.),
  fEmcCrystals(0),
  fGeom(0),
  fPulseGenerator(0),
  fRawReader(0),
  fRawStream(0)
{
  // Copy constructor

  fEmcMinE = dp.fEmcMinE ;
  fCpvMinE = dp.fCpvMinE ;
  fSampleQualityCut = dp.fSampleQualityCut;
  fSampleToSec = dp.fSampleToSec ;
  fEmcCrystals = dp.fEmcCrystals ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  fGeom = dp.fGeom ;
}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer& AliPHOSRawDigiProducer::operator= (const AliPHOSRawDigiProducer &dp)
{
  // Assign operator

  if(&dp == this) return *this;

  fEmcMinE = dp.fEmcMinE ;
  fCpvMinE = dp.fCpvMinE ;
  fSampleQualityCut = dp.fSampleQualityCut ;
  fSampleToSec = dp.fSampleToSec ;
  fEmcCrystals = dp.fEmcCrystals ;
  fGeom = dp.fGeom ;
  if(fPulseGenerator) delete fPulseGenerator ;
  fPulseGenerator = new AliPHOSPulseGenerator();
  return  *this;
}
//--------------------------------------------------------------------------------------
AliPHOSRawDigiProducer::~AliPHOSRawDigiProducer()
{
  // Destructor
  if(fPulseGenerator) delete fPulseGenerator ;
  fPulseGenerator=0 ;
  delete fRawStream;
}
//--------------------------------------------------------------------------------------
void AliPHOSRawDigiProducer::MakeDigits(TClonesArray *digits, AliPHOSRawFitterv0* fitter)
{
  //Makes the job.
  //TClonesArray *digits and raw data fitter should be provided by calling function.

  digits->Clear();

  Int_t iDigit=0 ;
  Int_t relId[4], absId=-1, caloFlag=-1;

  const Double_t baseLine=1. ; //Minimal energy of digit in ADC ch.

  //Calculate conversion coeff. from Sample time step to seconds
  //If OCDB contains negative or zero value - use one from RCU trailer
  //Negative value in OCDB is used only for simulation of raw digits
  if(fgCalibData->GetSampleTimeStep()>0.)
    fSampleToSec=fgCalibData->GetSampleTimeStep() ;
  else
    fSampleToSec=fRawStream->GetTSample() ;

  //Temporary array for LowGain digits
  TClonesArray tmpLG("AliPHOSDigit",10000) ;
  Int_t ilgDigit=0 ;

  //Let fitter subtract pedestals in case of ZS
  fitter->SetCalibData(fgCalibData) ;

  while (fRawStream->NextDDL()) {
    while (fRawStream->NextChannel()) {
      relId[0] = 5 - fRawStream->GetModule() ; // counts from 1 to 5
      relId[1] = 0;
      relId[2] = fRawStream->GetCellX()  + 1; // counts from 1 to 64
      relId[3] = fRawStream->GetCellZ()  + 1; // counts from 1 to 56
      caloFlag = fRawStream->GetCaloFlag();   // 0=LG, 1=HG, 2=TRU

      if(caloFlag!=0 && caloFlag!=1) continue; //TRU data!

      fitter->SetChannelGeo(relId[0],relId[2],relId[3],caloFlag);

      if(fitter->GetAmpOffset()==0 && fitter->GetAmpThreshold()==0) {
	short value = fRawStream->GetAltroCFG1();
	bool ZeroSuppressionEnabled = (value >> 15) & 0x1;
	if(ZeroSuppressionEnabled) {
	  short offset = (value >> 10) & 0xf;
	  short threshold = value & 0x3ff;
	  fitter->SubtractPedestals(kFALSE);
	  fitter->SetAmpOffset(offset);
	  fitter->SetAmpThreshold(threshold);
	}
      }

      fGeom->RelToAbsNumbering(relId, absId);

      Int_t nBunches = 0;
      while (fRawStream->NextBunch()) {
	nBunches++;
	if (nBunches > 1) continue;
	const UShort_t *sig = fRawStream->GetSignals();
	Int_t sigStart  = fRawStream->GetStartTimeBin();
	Int_t sigLength = fRawStream->GetBunchLength();
	fitter->Eval(sig,sigStart,sigLength);
      } // End of NextBunch()

      fitter->SetNBunches(nBunches);

      Double_t energy = fitter->GetEnergy() ;
      Double_t time   = fitter->GetTime() ;
      if(energy<=baseLine) //in ADC channels
	continue ;

      //remove digits with bad shape. Fitter should calculate quality so that
      //in default case quality [0,1], while larger values of quality mean somehow
      //corrupted samples, 999 means obviously corrupted sample.
      //It is difficult to fit samples with overflow (even setting cut on overflow values)
      //because too few points are left to fit. So we do not evaluate samples with overflow

      if(fitter->GetSignalQuality() > fSampleQualityCut && !(fitter->IsOverflow()))
	continue ;

      energy = CalibrateE(energy,relId,!caloFlag) ;
//       time   = CalibrateT(time,relId,lowGainFlag) ;

      //convert time from sample bin units to s
      time*=fSampleToSec ;

      if(energy <= 0.)
	continue;

      if (caloFlag == AliCaloRawStreamV3::kLowGain) {
	new(tmpLG[ilgDigit]) AliPHOSDigit(-1,absId,(Float_t)energy,(Float_t)time);
	ilgDigit++ ;
      }
      else if (caloFlag == AliCaloRawStreamV3::kHighGain) {
	if(fitter->IsOverflow()) //Keep this digit to replace it by Low Gain later.
	  //If there is no LogGain it wil be removed by cut on Min E
	  new((*digits)[iDigit]) AliPHOSDigit(-1,absId,-1.f,(Float_t)time);
	else
	  new((*digits)[iDigit]) AliPHOSDigit(-1,absId,(Float_t)energy,(Float_t)time);
	iDigit++;
      }
    } // End of NextChannel()

    //Now scan created LG and HG digits and keep only those which appeared in both lists
    //replace energy of HighGain digits only if there is overflow
    //negative energy (overflow)
    digits->Sort() ;
    tmpLG.Sort() ;
    Int_t iLG = 0;
    Int_t nLG1 = tmpLG.GetEntriesFast()-1 ;

    for(Int_t iDig=0 ; iDig < digits->GetEntriesFast() ; iDig++) {
      AliPHOSDigit * digHG = dynamic_cast<AliPHOSDigit*>(digits->At(iDig)) ;
      if (!digHG) continue;
      AliPHOSDigit * digLG = dynamic_cast<AliPHOSDigit*>(tmpLG.At(iLG)) ;
      while(digLG && iLG<nLG1 && digHG->GetId()> digLG->GetId()){
	iLG++ ;
	digLG = dynamic_cast<AliPHOSDigit*>(tmpLG.At(iLG)) ;
      }
      absId=digHG->GetId() ;
      fGeom->AbsToRelNumbering(absId,relId) ;

      if(digLG && digHG->GetId() == digLG->GetId()){ //we found pair
	if(digHG->GetEnergy()<0.){ //This is overflow in HG
	  digHG->SetTime(digLG->GetTime()) ;
	  digHG->SetEnergy(digLG->GetEnergy()) ;
	}
      }
      else{ //no pair - remove
	if(digHG->GetEnergy()<0.) //no pair, in saturation
	  digits->RemoveAt(iDig) ;
      }
    }
  } // End of NextDDL()

  CleanDigits(digits) ;

}
//____________________________________________________________________________
Double_t AliPHOSRawDigiProducer::CalibrateE(Double_t amp, Int_t* relId, Bool_t isLowGain)
{
  // Convert EMC LG amplitude to HG (multipli by ~16)
  // Calibration parameters are taken from calibration data base
  if(fgCalibData){
    Int_t   module = relId[0];
    Int_t   column = relId[3];
    Int_t   row    = relId[2];
    if(relId[1]==0) { // this is EMC
      if(isLowGain){
        amp*= fgCalibData->GetHighLowRatioEmc(module,column,row);
      }
      return amp ;
    }
  }
  return 0;
}
//____________________________________________________________________________
Double_t AliPHOSRawDigiProducer::CalibrateT(Double_t time, Int_t * relId, Bool_t /* isLowGain */)
{
  //Calibrate time
  time*=fPulseGenerator->GetRawFormatTimeTrigger() ;
  if(fgCalibData){
    Int_t   module = relId[0];
    Int_t   column = relId[3];
    Int_t   row    = relId[2];
    if(relId[1]==0) { // this is EMC
      time += fgCalibData->GetTimeShiftEmc(module,column,row);
      return time ;
    }
  }

  return -999.;
}
//____________________________________________________________________________
void AliPHOSRawDigiProducer::CleanDigits(TClonesArray * digits)
{
  // remove digits with amplitudes below threshold.
  // remove digits in bad channels
  // sort digits with icreasing AbsId

  //remove digits in bad map and below threshold
  Bool_t isBadMap = 0 ;
  if(fgCalibData->GetNumOfEmcBadChannels()){
    isBadMap=1 ;
  }

  for(Int_t i=0; i<digits->GetEntriesFast(); i++){
    AliPHOSDigit * digit = static_cast<AliPHOSDigit*>(digits->At(i)) ;
    if(!digit)
      continue  ;
    if ( (IsInEMC(digit) && digit->GetEnergy() < fEmcMinE) ||
	 (IsInCPV(digit) && digit->GetEnergy() < fCpvMinE) ){
      digits->RemoveAt(i) ;
      continue ;
    }
    if(isBadMap){ //check bad map now
      Int_t relid[4] ;
      fGeom->AbsToRelNumbering(digit->GetId(), relid) ;
      if(fgCalibData->IsBadChannelEmc(relid[0],relid[3],relid[2])){
	digits->RemoveAt(i) ;
      }
    }
  }

  //Compress, sort and set indexes
  digits->Compress() ;
//  digits->Sort(); already sorted earlier
  for (Int_t i = 0 ; i < digits->GetEntriesFast() ; i++) {
    AliPHOSDigit *digit = static_cast<AliPHOSDigit*>( digits->At(i) ) ;
    digit->SetIndexInList(i) ;
  }
}
//____________________________________________________________________________
Bool_t AliPHOSRawDigiProducer::IsInEMC(AliPHOSDigit * digit) const
{
  // Tells if (true) or not (false) the digit is in a PHOS-EMC module
  return digit->GetId() <= fEmcCrystals ;

}

//____________________________________________________________________________
Bool_t AliPHOSRawDigiProducer::IsInCPV(AliPHOSDigit * digit) const
{
  // Tells if (true) or not (false) the digit is in a PHOS-CPV module
  return digit->GetId() > fEmcCrystals ;
}
//____________________________________________________________________________
void AliPHOSRawDigiProducer::GetCalibrationParameters()
{
  // Set calibration parameters:
  // if calibration database exists, they are read from database,
  // otherwise, reconstruction stops in the constructor of AliPHOSCalibData
  //
  // It is a user responsilibity to open CDB before reconstruction, for example:
  // AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage("local://CalibDB");

  if (!fgCalibData){
    fgCalibData = new AliPHOSCalibData(-1); //use AliCDBManager's run number
  }
  if (fgCalibData->GetCalibDataEmc() == 0)
    AliFatal("Calibration parameters for PHOS EMC not found. Stop reconstruction.\n");
  if (fgCalibData->GetCalibDataCpv() == 0)
    AliFatal("Calibration parameters for PHOS CPV not found. Stop reconstruction.\n");
}
<|endoftext|>


<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/AliTRDinfoGen.h"
#include "PWG1/TRD/AliTRDpwg1Helper.h"
#include "PWG1/TRD/info/AliTRDeventInfo.h"
#include "PWG1/TRD/info/AliTRDeventCuts.h"
#endif

void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co)
{
  Bool_t mc=mgr->GetMCtruthEventHandler();
  //AliLog::SetClassDebugLevel("AliTRDinfoGen", 2);
  AliTRDinfoGen *info(NULL);
  mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen"));
  info->SetDebugLevel(0);
  info->SetMCdata(mc);
  info->SetLocalTrkSelection();
  info->SetOCDB("alien://folder=/alice/data/2010/OCDB");
  // settings for collisions
  info->SetCollision(/*kFALSE*/);
  if(info->IsCollision()){
    AliTRDeventCuts ec;
    if(mc) ec.AddTrigger("kMB");
    else {
/*      Int_t bunches[] = ;
      ec.SetBunchSelection();*/
      ec.AddTrigger("CINT1B-ABCE-NOPF-ALL");
      ec.AddTrigger("CINT5-B-NOPF-ALL");
      ec.AddTrigger("CINT1WU-B-NOPF-ALL");
      ec.AddTrigger("CINT5WU-B-NOPF-ALL");
      ec.AddTrigger("CINT7WU-I-NOPF-ALL");
      ec.AddTrigger("CSCO1-ABCE-NOPF-CENT"); // cosmic SPD trigger
    }
    info->SetLocalEvSelection(ec);
  }

  // Connect IO slots
  mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer());
  co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]);

  // add last monitor container
  AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName()));
  mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon);
}

<commit_msg>drop trigger selection in AliTRDinfoGen<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/AliTRDinfoGen.h"
#include "PWG1/TRD/AliTRDpwg1Helper.h"
#include "PWG1/TRD/info/AliTRDeventInfo.h"
#include "PWG1/TRD/info/AliTRDeventCuts.h"
#endif

void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co)
{
  Bool_t mc=mgr->GetMCtruthEventHandler();
  //AliLog::SetClassDebugLevel("AliTRDinfoGen", 2);
  AliTRDinfoGen *info(NULL);
  mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen"));
  info->SetDebugLevel(0);
  info->SetMCdata(mc);
  info->SetLocalTrkSelection();
  info->SetOCDB("alien://folder=/alice/data/2010/OCDB");
  // settings for collisions
  info->SetCollision(/*kFALSE*/);
  if(info->IsCollision()){
    AliTRDeventCuts ec;
    if(mc){
      ec.SetEventType(0);
//      ec.AddTrigger("MB1");
    } else {
/*      Int_t bunches[] = ;
      ec.SetBunchSelection();*/
/*      ec.AddTrigger("CINT1B-ABCE-NOPF-ALL");
      ec.AddTrigger("CINT5-B-NOPF-ALL");
      ec.AddTrigger("CINT1WU-B-NOPF-ALL");
      ec.AddTrigger("CINT5WU-B-NOPF-ALL");
      ec.AddTrigger("CINT7WU-I-NOPF-ALL");
      ec.AddTrigger("CSCO1-ABCE-NOPF-CENT"); // cosmic SPD trigger
*/
    }
    info->SetLocalEvSelection(ec);
  }

  // Connect IO slots
  mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer());
  co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]);

  // add last monitor container
  AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName()));
  mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon);
}

<|endoftext|>


<commit_before>#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileWriter.h"

#include "itkFFTComplexToComplexImageFilter.h"
#include "itkFFTShiftImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkComplexToModulusImageFilter.h"

typedef std::complex< double >                                         PixelType;
typedef otb::Image< PixelType,2 >                                      ImageType;
typedef otb::Image<double,2>                                           RealImageType;
typedef itk::FFTComplexToComplexImageFilter< PixelType::value_type,
                                           ImageType::ImageDimension > FFTType;
typedef FFTType::OutputImageType                                       FFTOutputImageType;
typedef itk::FFTShiftImageFilter<FFTOutputImageType,FFTOutputImageType> ShiftFilterType;
typedef itk::ConstantPadImageFilter<ImageType,ImageType>          PadFilterType;
typedef FFTType::TransformDirectionType                                FFTDirectionType;
typedef otb::ImageFileReader< ImageType >                              ReaderType;
typedef otb::ImageFileWriter<FFTOutputImageType>                       FFTWriterType;
typedef otb::StreamingImageFileWriter< ImageType >                     WriterType
;typedef otb::StreamingImageFileWriter< RealImageType >                RealWriterType;
typedef itk::ComplexToModulusImageFilter<FFTOutputImageType,RealImageType>      ModulusFilterType;
typedef itk::MinimumMaximumImageCalculator<RealImageType>              MinMaxCalculatorType;

class ComplexConjugateProduct
{
public:
  inline PixelType operator()(const PixelType & a, const PixelType & b) const
  {
    return a * vcl_conj(b);
  }
};

typedef itk::BinaryFunctorImageFilter<FFTOutputImageType,FFTOutputImageType,FFTOutputImageType,ComplexConjugateProduct> ConjugateProductFilterType;

int main(int argc, char * argv[])
{
  if(argc!=3)
    {
    std::cerr<<argv[0]<<" infname1 infname2"<<std::endl;
    return EXIT_FAILURE;
    }

  const char * infname1 = argv[1];
  const char * infname2 = argv[2];

  ReaderType::Pointer reader1 = ReaderType::New();
  reader1->SetFileName(infname1);
  reader1->UpdateOutputInformation();

  ReaderType::Pointer reader2 = ReaderType::New();
  reader2->SetFileName(infname2);
  reader2->UpdateOutputInformation();

  if(reader1->GetOutput()->GetLargestPossibleRegion()
     != reader2->GetOutput()->GetLargestPossibleRegion())
    {
    std::cerr<<"Images sizes must match."<<std::endl;
    return EXIT_FAILURE;
    }

  ImageType::SizeType size = reader1->GetOutput()->GetLargestPossibleRegion().GetSize();
  size[0]=size[0]/2;
  size[1]=size[1]/2;

  PadFilterType::Pointer pad1 = PadFilterType::New();
  pad1->SetInput(reader1->GetOutput());
  pad1->SetPadBound(size);
  std::cout<<"Pad size: "<<size<<std::endl;

  WriterType::Pointer writer1 = WriterType::New();
  writer1->SetFileName("paded1.tif");
  writer1->SetInput(pad1->GetOutput());
  writer1->Update();

  PadFilterType::Pointer pad2 = PadFilterType::New();
  pad2->SetInput(reader2->GetOutput());
  pad2->SetPadBound(size);

  WriterType::Pointer writer2 = WriterType::New();
  writer2->SetFileName("paded2.tif");
  writer2->SetInput(pad2->GetOutput());
  writer2->Update();

  FFTType::Pointer fft = FFTType::New();
  fft->SetInput(pad1->GetOutput());
  fft->Update();

  FFTOutputImageType::Pointer fft1 = fft->GetOutput();

  FFTWriterType::Pointer writer3 = FFTWriterType::New();
  writer3->SetFileName("fft1.tif");
  writer3->SetInput(fft1);
  writer3->Update();

  fft = FFTType::New();
  fft->SetInput(pad2->GetOutput());
  fft->Update();

  FFTOutputImageType::Pointer fft2 = fft->GetOutput();

  FFTWriterType::Pointer writer4 = FFTWriterType::New();
  writer4->SetFileName("fft2.tif");
  writer4->SetInput(fft2);
  writer4->Update();

  ConjugateProductFilterType::Pointer conjProd = ConjugateProductFilterType::New();
  conjProd->SetInput1(fft1);
  conjProd->SetInput2(fft2);

  FFTWriterType::Pointer writer5 = FFTWriterType::New();
  writer5->SetFileName("fftprod.tif");
  writer5->SetInput(conjProd->GetOutput());
  writer5->Update();

  fft = FFTType::New();
  fft->SetInput(conjProd->GetOutput());
  fft->SetTransformDirection(FFTType::INVERSE);
  fft->Update();

  FFTOutputImageType::Pointer ifft = fft->GetOutput();

  ShiftFilterType::Pointer shifter = ShiftFilterType::New();
  shifter->SetInput(ifft);

  FFTWriterType::Pointer writer6 = FFTWriterType::New();
  writer6->SetFileName("invfftprod.tif");
  writer6->SetInput(shifter->GetOutput());
  writer6->Update();

  ModulusFilterType::Pointer modulus = ModulusFilterType::New();
  modulus->SetInput(shifter->GetOutput());
  modulus->Update();

  RealWriterType::Pointer writer7 = RealWriterType::New();
  writer7->SetInput(modulus->GetOutput());
  writer7->SetFileName("modinvfftprod.tif");
  writer7->Update();

  MinMaxCalculatorType::Pointer minMax = MinMaxCalculatorType::New();
  minMax->SetImage(modulus->GetOutput());
  minMax->ComputeMaximum();

  std::cout<<"Maximum:  "<<minMax->GetMaximum()<<std::endl;
  std::cout<<"Position: "<<minMax->GetIndexOfMaximum()<<std::endl;

  std::cout<<"Estimated offset: "<<std::endl;
  std::cout<<(int)minMax->GetIndexOfMaximum()[0]-(int)reader1->GetOutput()->GetLargestPossibleRegion().GetSize()[0]/2<<"\t";
  std::cout<<(int)minMax->GetIndexOfMaximum()[1]-(int)reader1->GetOutput()->GetLargestPossibleRegion().GetSize()[1]/2<<std::endl;

  return EXIT_SUCCESS;
}

<commit_msg>ENH: Computing normalized coherency<commit_after>#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileWriter.h"

#include "itkFFTComplexToComplexImageFilter.h"
#include "itkFFTShiftImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkComplexToModulusImageFilter.h"
#include "itkDivideImageFilter.h"

typedef std::complex< double >                                         PixelType;
typedef otb::Image< PixelType,2 >                                      ImageType;
typedef otb::Image<double,2>                                           RealImageType;
typedef itk::FFTComplexToComplexImageFilter< PixelType::value_type,
                                           ImageType::ImageDimension > FFTType;
typedef FFTType::OutputImageType                                       FFTOutputImageType;
typedef itk::FFTShiftImageFilter<FFTOutputImageType,FFTOutputImageType> ShiftFilterType;
typedef itk::ConstantPadImageFilter<ImageType,ImageType>          PadFilterType;
typedef FFTType::TransformDirectionType                                FFTDirectionType;
typedef otb::ImageFileReader< ImageType >                              ReaderType;
typedef otb::ImageFileWriter<FFTOutputImageType>                       FFTWriterType;
typedef otb::StreamingImageFileWriter< ImageType >                     WriterType
;typedef otb::StreamingImageFileWriter< RealImageType >                RealWriterType;
typedef itk::ComplexToModulusImageFilter<FFTOutputImageType,RealImageType>      ModulusFilterType;
typedef itk::MinimumMaximumImageCalculator<RealImageType>              MinMaxCalculatorType;
typedef itk::DivideImageFilter<FFTOutputImageType,RealImageType,FFTOutputImageType> DivideFilterType;
class ComplexConjugateProduct
{
public:
  inline PixelType operator()(const PixelType & a, const PixelType & b) const
  {
    return a * vcl_conj(b);
  }
};

typedef itk::BinaryFunctorImageFilter<FFTOutputImageType,FFTOutputImageType,FFTOutputImageType,ComplexConjugateProduct> ConjugateProductFilterType;

int main(int argc, char * argv[])
{
  if(argc!=3)
    {
    std::cerr<<argv[0]<<" infname1 infname2"<<std::endl;
    return EXIT_FAILURE;
    }

  const char * infname1 = argv[1];
  const char * infname2 = argv[2];

  ReaderType::Pointer reader1 = ReaderType::New();
  reader1->SetFileName(infname1);
  reader1->UpdateOutputInformation();

  ReaderType::Pointer reader2 = ReaderType::New();
  reader2->SetFileName(infname2);
  reader2->UpdateOutputInformation();

  if(reader1->GetOutput()->GetLargestPossibleRegion()
     != reader2->GetOutput()->GetLargestPossibleRegion())
    {
    std::cerr<<"Images sizes must match."<<std::endl;
    return EXIT_FAILURE;
    }

  ImageType::SizeType size = reader1->GetOutput()->GetLargestPossibleRegion().GetSize();
  size[0]=size[0]/2;
  size[1]=size[1]/2;

  PadFilterType::Pointer pad1 = PadFilterType::New();
  pad1->SetInput(reader1->GetOutput());
  pad1->SetPadBound(size);
  std::cout<<"Pad size: "<<size<<std::endl;

  WriterType::Pointer writer1 = WriterType::New();
  writer1->SetFileName("paded1.tif");
  writer1->SetInput(pad1->GetOutput());
  writer1->Update();

  PadFilterType::Pointer pad2 = PadFilterType::New();
  pad2->SetInput(reader2->GetOutput());
  pad2->SetPadBound(size);

  WriterType::Pointer writer2 = WriterType::New();
  writer2->SetFileName("paded2.tif");
  writer2->SetInput(pad2->GetOutput());
  writer2->Update();

  FFTType::Pointer fft = FFTType::New();
  fft->SetInput(pad1->GetOutput());
  fft->Update();

  FFTOutputImageType::Pointer fft1 = fft->GetOutput();

  FFTWriterType::Pointer writer3 = FFTWriterType::New();
  writer3->SetFileName("fft1.tif");
  writer3->SetInput(fft1);
  writer3->Update();

  fft = FFTType::New();
  fft->SetInput(pad2->GetOutput());
  fft->Update();

  FFTOutputImageType::Pointer fft2 = fft->GetOutput();

  FFTWriterType::Pointer writer4 = FFTWriterType::New();
  writer4->SetFileName("fft2.tif");
  writer4->SetInput(fft2);
  writer4->Update();

  ConjugateProductFilterType::Pointer conjProd = ConjugateProductFilterType::New();
  conjProd->SetInput1(fft1);
  conjProd->SetInput2(fft2);

  // Try to normalise to get the normalized coherence coeff
  ModulusFilterType::Pointer conjProdMod = ModulusFilterType::New();
  conjProdMod->SetInput(conjProd->GetOutput());

  DivideFilterType::Pointer conjProdNorm = DivideFilterType::New();
  conjProdNorm->SetInput1(conjProd->GetOutput());
  conjProdNorm->SetInput2(conjProdMod->GetOutput());

  FFTWriterType::Pointer writer5 = FFTWriterType::New();
  writer5->SetFileName("fftprod.tif");
  writer5->SetInput(conjProdNorm->GetOutput());
  writer5->Update();

  fft = FFTType::New();
  fft->SetInput(conjProdNorm->GetOutput());
  fft->SetTransformDirection(FFTType::INVERSE);
  fft->Update();

  FFTOutputImageType::Pointer ifft = fft->GetOutput();

  ShiftFilterType::Pointer shifter = ShiftFilterType::New();
  shifter->SetInput(ifft);

  FFTWriterType::Pointer writer6 = FFTWriterType::New();
  writer6->SetFileName("invfftprod.tif");
  writer6->SetInput(shifter->GetOutput());
  writer6->Update();

  ModulusFilterType::Pointer modulus = ModulusFilterType::New();
  modulus->SetInput(shifter->GetOutput());
  modulus->Update();

  RealWriterType::Pointer writer7 = RealWriterType::New();
  writer7->SetInput(modulus->GetOutput());
  writer7->SetFileName("modinvfftprod.tif");
  writer7->Update();

  MinMaxCalculatorType::Pointer minMax = MinMaxCalculatorType::New();
  minMax->SetImage(modulus->GetOutput());
  minMax->ComputeMaximum();

  std::cout<<"Maximum:  "<<minMax->GetMaximum()<<std::endl;
  std::cout<<"Position: "<<minMax->GetIndexOfMaximum()<<std::endl;

  std::cout<<"Estimated offset: "<<std::endl;
  std::cout<<(int)minMax->GetIndexOfMaximum()[0]-(int)reader1->GetOutput()->GetLargestPossibleRegion().GetSize()[0]/2<<"\t";
  std::cout<<(int)minMax->GetIndexOfMaximum()[1]-(int)reader1->GetOutput()->GetLargestPossibleRegion().GetSize()[1]/2<<std::endl;

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include <QtTest>
#include <qmlprofiler/abstracttimelinemodel.h>
#include <qmlprofiler/abstracttimelinemodel_p.h>

using namespace QmlProfiler;

static const int DefaultRowHeight = 30;
static const int NumItems = 10;
static const qint64 ItemDuration = 1 << 19;
static const qint64 ItemSpacing = 1 << 20;

class DummyModelPrivate;
class DummyModel : public AbstractTimelineModel
{
    Q_OBJECT
    Q_DECLARE_PRIVATE(DummyModel)
    friend class tst_AbstractTimelineModel;
public:
    DummyModel(QString displayName = tr("dummy"), QObject *parent = 0);
    const QmlProfilerModelManager *modelManager() const;
    int rowCount() const;
    int selectionId(int index) const { return index; }
    QColor color(int) const { return QColor(); }
    QVariantList labels() const { return QVariantList(); }
    QVariantMap details(int) const { return QVariantMap(); }
    int row(int) const { return 1; }
    quint64 features() const { return 0; }

protected:
    void loadData();
};

class DummyModelPrivate : public AbstractTimelineModel::AbstractTimelineModelPrivate
{
    Q_DECLARE_PUBLIC(DummyModel)
};

class tst_AbstractTimelineModel : public QObject
{
    Q_OBJECT

private slots:
    void modelManager();
    void isEmpty();
    void rowHeight();
    void rowOffset();
    void height();
    void traceTime();
    void accepted();
    void expand();
    void hide();
    void displayName();
    void defaultValues();
    void colorByHue();
    void colorByTypeId();
    void colorByFraction();
};

DummyModel::DummyModel(QString displayName, QObject *parent) :
    AbstractTimelineModel(new DummyModelPrivate, displayName, QmlDebug::MaximumMessage,
                          QmlDebug::MaximumRangeType, parent)
{
}

const QmlProfilerModelManager *DummyModel::modelManager() const
{
    Q_D(const DummyModel);
    return d->modelManager;
}

int DummyModel::rowCount() const
{
    return isEmpty() ? 1 : 2;
}

void DummyModel::loadData()
{
    for (int i = 0; i < NumItems; ++i)
        insert(i * ItemSpacing, ItemDuration);
}

void tst_AbstractTimelineModel::modelManager()
{
    DummyModel dummy;
    QCOMPARE(dummy.modelManager(), (QmlProfilerModelManager *)0);
    QmlProfilerModelManager manager(0);
    dummy.setModelManager(&manager);
    QCOMPARE(dummy.modelManager(), &manager);
    QmlProfilerModelManager manager2(0);
    dummy.setModelManager(&manager2);
    QCOMPARE(dummy.modelManager(), &manager2);
}

void tst_AbstractTimelineModel::isEmpty()
{
    DummyModel dummy;
    QVERIFY(dummy.isEmpty());
    QmlProfilerModelManager manager(0);
    dummy.setModelManager(&manager);
    dummy.loadData();
    QVERIFY(!dummy.isEmpty());
    dummy.clear();
    QVERIFY(dummy.isEmpty());
}

void tst_AbstractTimelineModel::rowHeight()
{
    DummyModel dummy;
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    // Cannot set while not expanded
    dummy.setRowHeight(0, 100);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    dummy.setExpanded(true);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    // Cannot set smaller than default
    dummy.setRowHeight(0, DefaultRowHeight - 1);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    dummy.setRowHeight(0, 100);
    QCOMPARE(dummy.rowHeight(0), 100);

    dummy.loadData();
    dummy.setRowHeight(1, 50);
    QCOMPARE(dummy.rowHeight(0), 100);
    QCOMPARE(dummy.rowHeight(1), 50);

    // Row heights ignored while collapsed ...
    dummy.setExpanded(false);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);
    QCOMPARE(dummy.rowHeight(1), DefaultRowHeight);

    // ... but restored when re-expanding
    dummy.setExpanded(true);
    QCOMPARE(dummy.rowHeight(0), 100);
    QCOMPARE(dummy.rowHeight(1), 50);
}

void tst_AbstractTimelineModel::rowOffset()
{
    DummyModel dummy;
    QCOMPARE(dummy.rowOffset(0), 0);

    dummy.loadData();
    dummy.setExpanded(true);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), DefaultRowHeight);

    dummy.setRowHeight(0, 100);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), 100);

    dummy.setRowHeight(1, 50);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), 100);

    // Row heights ignored while collapsed ...
    dummy.setExpanded(false);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), DefaultRowHeight);

    // ... but restored when re-expanding
    dummy.setExpanded(true);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), 100);
}

void tst_AbstractTimelineModel::height()
{
    DummyModel dummy;
    QCOMPARE(dummy.height(), DefaultRowHeight);
    dummy.loadData();
    QCOMPARE(dummy.height(), 2 * DefaultRowHeight);
    dummy.setExpanded(true);
    QCOMPARE(dummy.height(), 2 * DefaultRowHeight);
    dummy.setRowHeight(0, 80);
    QCOMPARE(dummy.height(), DefaultRowHeight + 80);
}

void tst_AbstractTimelineModel::traceTime()
{
    DummyModel dummy;
    QmlProfilerModelManager manager(0);
    dummy.setModelManager(&manager);
    QCOMPARE(dummy.traceStartTime(), -1);
    QCOMPARE(dummy.traceEndTime(), -1);
    QCOMPARE(dummy.traceDuration(), 0);
}

void tst_AbstractTimelineModel::accepted()
{
    DummyModel dummy;
    QmlProfilerDataModel::QmlEventTypeData event;
    event.message = QmlDebug::MaximumMessage;
    event.rangeType = QmlDebug::MaximumRangeType;
    QVERIFY(dummy.accepted(event));
    event.message = QmlDebug::Event;
    QVERIFY(!dummy.accepted(event));
    event.rangeType = QmlDebug::Painting;
    QVERIFY(!dummy.accepted(event));
    event.message = QmlDebug::MaximumMessage;
    QVERIFY(!dummy.accepted(event));
}

void tst_AbstractTimelineModel::expand()
{
    DummyModel dummy;
    QSignalSpy spy(&dummy, SIGNAL(expandedChanged()));
    QVERIFY(!dummy.expanded());
    dummy.setExpanded(true);
    QVERIFY(dummy.expanded());
    QCOMPARE(spy.count(), 1);
    dummy.setExpanded(true);
    QVERIFY(dummy.expanded());
    QCOMPARE(spy.count(), 1);
    dummy.setExpanded(false);
    QVERIFY(!dummy.expanded());
    QCOMPARE(spy.count(), 2);
    dummy.setExpanded(false);
    QVERIFY(!dummy.expanded());
    QCOMPARE(spy.count(), 2);
}

void tst_AbstractTimelineModel::hide()
{
    DummyModel dummy;
    QSignalSpy spy(&dummy, SIGNAL(hiddenChanged()));
    QVERIFY(!dummy.hidden());
    dummy.setHidden(true);
    QVERIFY(dummy.hidden());
    QCOMPARE(spy.count(), 1);
    dummy.setHidden(true);
    QVERIFY(dummy.hidden());
    QCOMPARE(spy.count(), 1);
    dummy.setHidden(false);
    QVERIFY(!dummy.hidden());
    QCOMPARE(spy.count(), 2);
    dummy.setHidden(false);
    QVERIFY(!dummy.hidden());
    QCOMPARE(spy.count(), 2);
}

void tst_AbstractTimelineModel::displayName()
{
    QLatin1String name("testest");
    DummyModel dummy(name);
    QCOMPARE(dummy.displayName(), name);
}

void tst_AbstractTimelineModel::defaultValues()
{
    DummyModel dummy;
    dummy.loadData();
    QCOMPARE(dummy.location(0), QVariantMap());
    QCOMPARE(dummy.isSelectionIdValid(0), false);
    QCOMPARE(dummy.selectionIdForLocation(QString(), 0, 0), -1);
    QCOMPARE(dummy.bindingLoopDest(0), -1);
    QCOMPARE(dummy.relativeHeight(0), 1.0);
    QCOMPARE(dummy.rowMinValue(0), 0);
    QCOMPARE(dummy.rowMaxValue(0), 0);
}

void tst_AbstractTimelineModel::colorByHue()
{
    DummyModel dummy;
    QCOMPARE(dummy.colorByHue(10), QColor::fromHsl(10, 150, 166));
    QCOMPARE(dummy.colorByHue(500), QColor::fromHsl(140, 150, 166));
}

void tst_AbstractTimelineModel::colorByTypeId()
{
    DummyModel dummy;
    dummy.loadData();
    QCOMPARE(dummy.colorBySelectionId(5), QColor::fromHsl(5 * 25, 150, 166));
}

void tst_AbstractTimelineModel::colorByFraction()
{
    DummyModel dummy;
    QCOMPARE(dummy.colorByFraction(0.5), QColor::fromHsl(0.5 * 96 + 10, 150, 166));
}

QTEST_MAIN(tst_AbstractTimelineModel)

#include "tst_abstracttimelinemodel.moc"
<commit_msg>QmlProfiler: Update abstracttimelinemodel test<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include <QtTest>
#include <qmlprofiler/abstracttimelinemodel.h>
#include <qmlprofiler/abstracttimelinemodel_p.h>

using namespace QmlProfiler;

static const int DefaultRowHeight = 30;
static const int NumItems = 10;
static const qint64 ItemDuration = 1 << 19;
static const qint64 ItemSpacing = 1 << 20;

class DummyModelPrivate;
class DummyModel : public AbstractTimelineModel
{
    Q_OBJECT
    Q_DECLARE_PRIVATE(DummyModel)
    friend class tst_AbstractTimelineModel;
public:
    DummyModel(QString displayName = tr("dummy"), QObject *parent = 0);
    const QmlProfilerModelManager *modelManager() const;
    int selectionId(int index) const { return index; }
    QColor color(int) const { return QColor(); }
    QVariantList labels() const { return QVariantList(); }
    QVariantMap details(int) const { return QVariantMap(); }
    int row(int) const { return 1; }
    quint64 features() const { return 0; }

protected:
    void loadData();
};

class DummyModelPrivate : public AbstractTimelineModel::AbstractTimelineModelPrivate
{
    Q_DECLARE_PUBLIC(DummyModel)
};

class tst_AbstractTimelineModel : public QObject
{
    Q_OBJECT

private slots:
    void modelManager();
    void isEmpty();
    void rowHeight();
    void rowOffset();
    void height();
    void traceTime();
    void accepted();
    void expand();
    void hide();
    void displayName();
    void defaultValues();
    void colorByHue();
    void colorByTypeId();
    void colorByFraction();
};

DummyModel::DummyModel(QString displayName, QObject *parent) :
    AbstractTimelineModel(new DummyModelPrivate, displayName, QmlDebug::MaximumMessage,
                          QmlDebug::MaximumRangeType, parent)
{
}

const QmlProfilerModelManager *DummyModel::modelManager() const
{
    Q_D(const DummyModel);
    return d->modelManager;
}

void DummyModel::loadData()
{
    Q_D(DummyModel);
    for (int i = 0; i < NumItems; ++i)
        insert(i * ItemSpacing, ItemDuration, 0);
    d->collapsedRowCount = d->expandedRowCount = 2;
}

void tst_AbstractTimelineModel::modelManager()
{
    DummyModel dummy;
    QCOMPARE(dummy.modelManager(), (QmlProfilerModelManager *)0);
    QmlProfilerModelManager manager(0);
    dummy.setModelManager(&manager);
    QCOMPARE(dummy.modelManager(), &manager);
    QmlProfilerModelManager manager2(0);
    dummy.setModelManager(&manager2);
    QCOMPARE(dummy.modelManager(), &manager2);
}

void tst_AbstractTimelineModel::isEmpty()
{
    DummyModel dummy;
    QVERIFY(dummy.isEmpty());
    QmlProfilerModelManager manager(0);
    dummy.setModelManager(&manager);
    dummy.loadData();
    QVERIFY(!dummy.isEmpty());
    dummy.clear();
    QVERIFY(dummy.isEmpty());
}

void tst_AbstractTimelineModel::rowHeight()
{
    DummyModel dummy;
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    // Cannot set while not expanded
    dummy.setRowHeight(0, 100);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    dummy.setExpanded(true);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    // Cannot set smaller than default
    dummy.setRowHeight(0, DefaultRowHeight - 1);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);

    dummy.setRowHeight(0, 100);
    QCOMPARE(dummy.rowHeight(0), 100);

    dummy.loadData();
    dummy.setRowHeight(1, 50);
    QCOMPARE(dummy.rowHeight(0), 100);
    QCOMPARE(dummy.rowHeight(1), 50);

    // Row heights ignored while collapsed ...
    dummy.setExpanded(false);
    QCOMPARE(dummy.rowHeight(0), DefaultRowHeight);
    QCOMPARE(dummy.rowHeight(1), DefaultRowHeight);

    // ... but restored when re-expanding
    dummy.setExpanded(true);
    QCOMPARE(dummy.rowHeight(0), 100);
    QCOMPARE(dummy.rowHeight(1), 50);
}

void tst_AbstractTimelineModel::rowOffset()
{
    DummyModel dummy;
    QCOMPARE(dummy.rowOffset(0), 0);

    dummy.loadData();
    dummy.setExpanded(true);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), DefaultRowHeight);

    dummy.setRowHeight(0, 100);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), 100);

    dummy.setRowHeight(1, 50);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), 100);

    // Row heights ignored while collapsed ...
    dummy.setExpanded(false);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), DefaultRowHeight);

    // ... but restored when re-expanding
    dummy.setExpanded(true);
    QCOMPARE(dummy.rowOffset(0), 0);
    QCOMPARE(dummy.rowOffset(1), 100);
}

void tst_AbstractTimelineModel::height()
{
    DummyModel dummy;
    QmlProfilerModelManager manager(0);
    dummy.setModelManager(&manager);
    QCOMPARE(dummy.height(), DefaultRowHeight);
    dummy.loadData();
    QCOMPARE(dummy.height(), 2 * DefaultRowHeight);
    dummy.setExpanded(true);
    QCOMPARE(dummy.height(), 2 * DefaultRowHeight);
    dummy.setRowHeight(0, 80);
    QCOMPARE(dummy.height(), DefaultRowHeight + 80);
}

void tst_AbstractTimelineModel::traceTime()
{
    DummyModel dummy;
    QmlProfilerModelManager manager(0);
    dummy.setModelManager(&manager);
    QCOMPARE(dummy.traceStartTime(), -1);
    QCOMPARE(dummy.traceEndTime(), -1);
    QCOMPARE(dummy.traceDuration(), 0);
}

void tst_AbstractTimelineModel::accepted()
{
    DummyModel dummy;
    QmlProfilerDataModel::QmlEventTypeData event;
    event.message = QmlDebug::MaximumMessage;
    event.rangeType = QmlDebug::MaximumRangeType;
    QVERIFY(dummy.accepted(event));
    event.message = QmlDebug::Event;
    QVERIFY(!dummy.accepted(event));
    event.rangeType = QmlDebug::Painting;
    QVERIFY(!dummy.accepted(event));
    event.message = QmlDebug::MaximumMessage;
    QVERIFY(!dummy.accepted(event));
}

void tst_AbstractTimelineModel::expand()
{
    DummyModel dummy;
    QSignalSpy spy(&dummy, SIGNAL(expandedChanged()));
    QVERIFY(!dummy.expanded());
    dummy.setExpanded(true);
    QVERIFY(dummy.expanded());
    QCOMPARE(spy.count(), 1);
    dummy.setExpanded(true);
    QVERIFY(dummy.expanded());
    QCOMPARE(spy.count(), 1);
    dummy.setExpanded(false);
    QVERIFY(!dummy.expanded());
    QCOMPARE(spy.count(), 2);
    dummy.setExpanded(false);
    QVERIFY(!dummy.expanded());
    QCOMPARE(spy.count(), 2);
}

void tst_AbstractTimelineModel::hide()
{
    DummyModel dummy;
    QSignalSpy spy(&dummy, SIGNAL(hiddenChanged()));
    QVERIFY(!dummy.hidden());
    dummy.setHidden(true);
    QVERIFY(dummy.hidden());
    QCOMPARE(spy.count(), 1);
    dummy.setHidden(true);
    QVERIFY(dummy.hidden());
    QCOMPARE(spy.count(), 1);
    dummy.setHidden(false);
    QVERIFY(!dummy.hidden());
    QCOMPARE(spy.count(), 2);
    dummy.setHidden(false);
    QVERIFY(!dummy.hidden());
    QCOMPARE(spy.count(), 2);
}

void tst_AbstractTimelineModel::displayName()
{
    QLatin1String name("testest");
    DummyModel dummy(name);
    QCOMPARE(dummy.displayName(), name);
}

void tst_AbstractTimelineModel::defaultValues()
{
    DummyModel dummy;
    dummy.loadData();
    QCOMPARE(dummy.location(0), QVariantMap());
    QCOMPARE(dummy.isSelectionIdValid(0), false);
    QCOMPARE(dummy.selectionIdForLocation(QString(), 0, 0), -1);
    QCOMPARE(dummy.bindingLoopDest(0), -1);
    QCOMPARE(dummy.relativeHeight(0), 1.0);
    QCOMPARE(dummy.rowMinValue(0), 0);
    QCOMPARE(dummy.rowMaxValue(0), 0);
}

void tst_AbstractTimelineModel::colorByHue()
{
    DummyModel dummy;
    QCOMPARE(dummy.colorByHue(10), QColor::fromHsl(10, 150, 166));
    QCOMPARE(dummy.colorByHue(500), QColor::fromHsl(140, 150, 166));
}

void tst_AbstractTimelineModel::colorByTypeId()
{
    DummyModel dummy;
    dummy.loadData();
    QCOMPARE(dummy.colorBySelectionId(5), QColor::fromHsl(5 * 25, 150, 166));
}

void tst_AbstractTimelineModel::colorByFraction()
{
    DummyModel dummy;
    QCOMPARE(dummy.colorByFraction(0.5), QColor::fromHsl(0.5 * 96 + 10, 150, 166));
}

QTEST_MAIN(tst_AbstractTimelineModel)

#include "tst_abstracttimelinemodel.moc"
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Core/IEPlugin/ObjToField_Plugin.h>
#include <Core/IEPlugin/NrrdField_Plugin.h>
#include <Core/IEPlugin/MatlabFiles_Plugin.h>
#include <Core/IEPlugin/SimpleTextFileToMatrix_Plugin.h>
#include <Core/IEPlugin/EcgsimFileToMatrix_Plugin.h>
#include <Core/IEPlugin/PointCloudField_Plugin.h>
#include <Core/IEPlugin/IGBFileToMatrix_Plugin.h>
#include <Core/IEPlugin/CurveField_Plugin.h>
#include <Core/IEPlugin/TriSurfField_Plugin.h>
#include <Core/IEPlugin/TetVolField_Plugin.h>
#include <Core/IEPlugin/CARPMesh_Plugin.h>
#include <Core/IEPlugin/CARPFiber_Plugin.h>
#include <Core/ImportExport/Field/FieldIEPlugin.h>
#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/IEPlugin/IEPluginInit.h>

using namespace SCIRun;
using namespace SCIRun::Core::Logging;

void IEPluginManager::Initialize()
{
  static FieldIEPluginLegacyAdapter ObjToField_plugin("ObjToField", "*.obj", "", ObjToField_reader, FieldToObj_writer);

  static FieldIEPluginLegacyAdapter NrrdToField_plugin("NrrdFile","*.nhdr *.nrrd", "*.nrrd", NrrdToField_reader, FieldToNrrd_writer);
  static FieldIEPluginLegacyAdapter NodalNrrdToField_plugin("NrrdFile[DataOnNodes]","*.nhdr *.nrrd", "", Nodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter ModalNrrdToField_plugin("NrrdFile[DataOnElements]","*.nhdr *.nrrd", "", Modal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPNodalNrrdToField_plugin("NrrdFile[DataOnNodes,InvertParity]","*.nhdr *.nrrd", "", IPNodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPModalNrrdToField_plugin("NrrdFile[DataOnElements,InvertParity]","*.nhdr *.nrrd", "", IPModal_NrrdToField_reader, nullptr);

  static FieldIEPluginLegacyAdapter MatlabField_plugin("Matlab Field", "*.mat", "*.mat", MatlabField_reader, MatlabField_writer);

  static MatrixIEPluginLegacyAdapter MatlabMatrix_plugin("Matlab Matrix","*.mat", "*.mat", MatlabMatrix_reader, MatlabMatrix_writer);
  //TODO
  //static NrrdIEPluginLegacyAdapter MatlabNrrd_plugin("Matlab Matrix",".mat", "*.mat",MatlabNrrd_reader,MatlabNrrd_writer);

  static MatrixIEPluginLegacyAdapter SimpleTextFileMatrix_plugin("SimpleTextFile","*.*", "",SimpleTextFileMatrix_reader,SimpleTextFileMatrix_writer);

  static FieldIEPluginLegacyAdapter PointCloudField_plugin("PointCloudField", "*.pts *.pos *.txt", "", TextToPointCloudField_reader, PointCloudFieldToText_writer);

  static FieldIEPluginLegacyAdapter CurveField_plugin("CurveField", "*.pts *.pos *.edge", "", TextToCurveField_reader, CurveFieldToTextBaseIndexZero_writer);

  static MatrixIEPluginLegacyAdapter EcgsimFileMatrix_plugin("ECGSimFile", "", "", EcgsimFileMatrix_reader, EcgsimFileMatrix_writer);
  //static MatrixIEPluginLegacyAdapter IgbFileMatrix_plugin("IGBFile", "*.igb", "*.igb", IgbFileMatrix_reader, IgbFileMatrix_writer);

  static FieldIEPluginLegacyAdapter TriSurfField_plugin("TriSurfField", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldBaseIndexOne_plugin("TriSurfField[BaseIndex 1]", "*.fac *.pts", "", nullptr, TriSurfFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter CVRTI_FacPtsFileToTriSurf_plugin("CVRTI_FacPtsFileToTriSurf", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToM_plugin("TriSurfFieldToM", "*.m", "", MToTriSurfField_reader, TriSurfFieldToM_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldVtk_plugin("TriSurfFieldToVtk", "*.vtk", "", nullptr, TriSurfFieldToVtk_writer);
  static FieldIEPluginLegacyAdapter VtkFromTriSurfField_plugin("VtkToTriSurfField", "*.vtk", "", VtkToTriSurfField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxt_plugin("TriSurfFieldToExotxt", "*.ex2", "", nullptr, TriSurfFieldToExotxt_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxtBaseIndexOne_plugin("TriSurfFieldToExotxt[BaseIndex 1]", "*.ex2", "", nullptr, TriSurfFieldToExotxtBaseIndexOne_writer);

  static FieldIEPluginLegacyAdapter TetVolField_plugin("TetVolField","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, TetVolFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter CARPMesh_plugin("CARPMesh","*.elem *.pts *.lon", "", nullptr, CARPMesh_writer);
  static FieldIEPluginLegacyAdapter CARPFiber_plugin("CARPFiber","*.lon", "", nullptr, CARPFiber_writer);
  static FieldIEPluginLegacyAdapter TetVolFieldBaseIndexOne_plugin("TetVolField[BaseIndex 1]", "*.tet *.pts", "", nullptr, TetVolFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter JHU_elemsPtsFileToTetVol_plugin("JHUFileToTetVol","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TetVolFieldVtk_plugin("TetVolFieldToVtk", "*.vtk", "", nullptr, TetVolFieldToVtk_writer);
}
<commit_msg>Changing the commented out line of IGBfile<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Core/IEPlugin/ObjToField_Plugin.h>
#include <Core/IEPlugin/NrrdField_Plugin.h>
#include <Core/IEPlugin/MatlabFiles_Plugin.h>
#include <Core/IEPlugin/SimpleTextFileToMatrix_Plugin.h>
#include <Core/IEPlugin/EcgsimFileToMatrix_Plugin.h>
#include <Core/IEPlugin/PointCloudField_Plugin.h>
#include <Core/IEPlugin/IgbFileToMatrix_Plugin.h>
#include <Core/IEPlugin/CurveField_Plugin.h>
#include <Core/IEPlugin/TriSurfField_Plugin.h>
#include <Core/IEPlugin/TetVolField_Plugin.h>
#include <Core/IEPlugin/CARPMesh_Plugin.h>
#include <Core/IEPlugin/CARPFiber_Plugin.h>
#include <Core/ImportExport/Field/FieldIEPlugin.h>
#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/IEPlugin/IEPluginInit.h>

using namespace SCIRun;
using namespace SCIRun::Core::Logging;

void IEPluginManager::Initialize()
{
  static FieldIEPluginLegacyAdapter ObjToField_plugin("ObjToField", "*.obj", "", ObjToField_reader, FieldToObj_writer);

  static FieldIEPluginLegacyAdapter NrrdToField_plugin("NrrdFile","*.nhdr *.nrrd", "*.nrrd", NrrdToField_reader, FieldToNrrd_writer);
  static FieldIEPluginLegacyAdapter NodalNrrdToField_plugin("NrrdFile[DataOnNodes]","*.nhdr *.nrrd", "", Nodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter ModalNrrdToField_plugin("NrrdFile[DataOnElements]","*.nhdr *.nrrd", "", Modal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPNodalNrrdToField_plugin("NrrdFile[DataOnNodes,InvertParity]","*.nhdr *.nrrd", "", IPNodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPModalNrrdToField_plugin("NrrdFile[DataOnElements,InvertParity]","*.nhdr *.nrrd", "", IPModal_NrrdToField_reader, nullptr);

  static FieldIEPluginLegacyAdapter MatlabField_plugin("Matlab Field", "*.mat", "*.mat", MatlabField_reader, MatlabField_writer);

  static MatrixIEPluginLegacyAdapter MatlabMatrix_plugin("Matlab Matrix","*.mat", "*.mat", MatlabMatrix_reader, MatlabMatrix_writer);
  //TODO
  //static NrrdIEPluginLegacyAdapter MatlabNrrd_plugin("Matlab Matrix",".mat", "*.mat",MatlabNrrd_reader,MatlabNrrd_writer);

  static MatrixIEPluginLegacyAdapter SimpleTextFileMatrix_plugin("SimpleTextFile","*.*", "",SimpleTextFileMatrix_reader,SimpleTextFileMatrix_writer);

  static FieldIEPluginLegacyAdapter PointCloudField_plugin("PointCloudField", "*.pts *.pos *.txt", "", TextToPointCloudField_reader, PointCloudFieldToText_writer);

  static FieldIEPluginLegacyAdapter CurveField_plugin("CurveField", "*.pts *.pos *.edge", "", TextToCurveField_reader, CurveFieldToTextBaseIndexZero_writer);

  static MatrixIEPluginLegacyAdapter EcgsimFileMatrix_plugin("ECGSimFile", "", "", EcgsimFileMatrix_reader, EcgsimFileMatrix_writer);
  static MatrixIEPluginLegacyAdapter IgbFileMatrix_plugin("IGBFile", "*.igb", "*.igb", IgbFileMatrix_reader, IgbFileMatrix_writer);

  static FieldIEPluginLegacyAdapter TriSurfField_plugin("TriSurfField", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldBaseIndexOne_plugin("TriSurfField[BaseIndex 1]", "*.fac *.pts", "", nullptr, TriSurfFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter CVRTI_FacPtsFileToTriSurf_plugin("CVRTI_FacPtsFileToTriSurf", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToM_plugin("TriSurfFieldToM", "*.m", "", MToTriSurfField_reader, TriSurfFieldToM_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldVtk_plugin("TriSurfFieldToVtk", "*.vtk", "", nullptr, TriSurfFieldToVtk_writer);
  static FieldIEPluginLegacyAdapter VtkFromTriSurfField_plugin("VtkToTriSurfField", "*.vtk", "", VtkToTriSurfField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxt_plugin("TriSurfFieldToExotxt", "*.ex2", "", nullptr, TriSurfFieldToExotxt_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxtBaseIndexOne_plugin("TriSurfFieldToExotxt[BaseIndex 1]", "*.ex2", "", nullptr, TriSurfFieldToExotxtBaseIndexOne_writer);

  static FieldIEPluginLegacyAdapter TetVolField_plugin("TetVolField","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, TetVolFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter CARPMesh_plugin("CARPMesh","*.elem *.pts *.lon", "", nullptr, CARPMesh_writer);
  static FieldIEPluginLegacyAdapter CARPFiber_plugin("CARPFiber","*.lon", "", nullptr, CARPFiber_writer);
  static FieldIEPluginLegacyAdapter TetVolFieldBaseIndexOne_plugin("TetVolField[BaseIndex 1]", "*.tet *.pts", "", nullptr, TetVolFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter JHU_elemsPtsFileToTetVol_plugin("JHUFileToTetVol","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TetVolFieldVtk_plugin("TetVolFieldToVtk", "*.vtk", "", nullptr, TetVolFieldToVtk_writer);
}
<|endoftext|>


<commit_before>/**
* @author Olaf Radicke <briefkasten@olaf-rdicke.de>
* @date 2013
* @copyright GNU Affero General Public License
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or later
* version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <tntdb/connect.h>
#include <tntdb/statement.h>
#include <tntdb/error.h>
#include <tntdb/row.h>
#include <tntdb/transaction.h>
#include <cxxtools/log.h>

#include <Core/manager/TableManager.h>
#include <Core/models/Config.h>

/*#include <iostream>  */
// #include <ostream>
#include <sstream>

log_define("TableManager")

TableManager::TableManager()
    : m_conn(tntdb::connectCached( Config::it().dbDriver() ))
{ }

// G -------------------------------------------------------------------------

std::string TableManager::getTabeVersion(){
    std::string  tabVersion;

    tntdb::Statement st = m_conn.prepare( " SELECT data_value \
         FROM metadata \
         WHERE data_name = :data_name ;");

    // Wenn wir nur einen einzelnen Wert lesen wollen, dann verwenden wir tntdb::Statement::selectValue().

    tntdb::Value value = st.set( "data_name", "tableversion" )
                       .selectValue();

    value.get(tabVersion);
    return tabVersion;

}

// S -------------------------------------------------------------------------

bool TableManager::setUpdate2(){
    tntdb::Transaction trans(m_conn);
    std::ostringstream sqlCommand;

    try{
        sqlCommand << "CREATE TABLE account_trust ("
        << "    id                   SERIAL    PRIMARY KEY,"
        << "    trusted_account_id   BIGINT    NOT NULL,"
        << "    guarantor_id         BIGINT    NOT NULL,"
        << "    createtime           TIMESTAMP NOT NULL,"
        << "    FOREIGN KEY  (trusted_account_id)   REFERENCES account (id),"
        << "    FOREIGN KEY  (guarantor_id) REFERENCES account (id)"
        << ");";
        m_conn.prepare( sqlCommand.str() ).execute();
        sqlCommand.flush();

        sqlCommand << "-- COMMENT ON TABLE account_trust IS 'Links for user trust user.';";
        m_conn.prepare( sqlCommand.str() ).execute();
        sqlCommand.flush();

        sqlCommand << "-- COMMENT ON COLUMN account_trust.trusted_account_id IS "
        << "'The account where we are in trust.';";
        m_conn.prepare( sqlCommand.str() ).execute();
        sqlCommand.flush();

        sqlCommand << "-- COMMENT ON COLUMN account_trust.guarantor_id IS "
        << "'This account give the guarant.';";
        m_conn.prepare( sqlCommand.str() ).execute();
        sqlCommand.flush();

        //  Default value
        sqlCommand << "INSERT INTO account_trust"
        << "("
        << "    trusted_account_id,"
        << "    guarantor_id,"
        << "    createtime"
        << ")"
        << "VALUES ("
        << "    1,"
        << "    1,"
        << "    now()"
        << ");";
        m_conn.prepare( sqlCommand.str() ).execute();
        sqlCommand.flush();

        sqlCommand << "UPDATE metadata "
        << "SET data_value = '00002', "
        << "data_parameter = 'alpha' "
        << "WHERE data_name = 'tableversion';";
        m_conn.prepare( sqlCommand.str() ).execute();
        sqlCommand.flush();

        trans.commit();
    }catch (...) {
        return false;
    }
    return true;
}

//  U ------------------------------------------------------------------------

    bool TableManager::update(){
        std::string version = getTabeVersion();

        if ( version == "00001" ) {
            if( setUpdate2() == false){
                log_info( "Table update 00002 failed!");
                return false;
            }else{
                log_info( "Table update 00002 is successful!");
            }
        }

/*      for next version...
        if ( version = "00002" ) {
            if( setUpdate3() == false){
                log_info( "Table update 00003 failed!");
                return false;
            }else{
                log_info( "Table update 00003 is successful!");
            }
        }
*/

        return true;

    }
<commit_msg>bugfix in table update.<commit_after>/**
* @author Olaf Radicke <briefkasten@olaf-rdicke.de>
* @date 2013
* @copyright GNU Affero General Public License
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or later
* version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <tntdb/connect.h>
#include <tntdb/statement.h>
#include <tntdb/error.h>
#include <tntdb/row.h>
#include <tntdb/transaction.h>
#include <cxxtools/log.h>

#include <Core/manager/TableManager.h>
#include <Core/models/Config.h>

/*#include <iostream>  */
// #include <ostream>
#include <sstream>

log_define("TableManager")

TableManager::TableManager()
    : m_conn(tntdb::connectCached( Config::it().dbDriver() ))
{ }

// G -------------------------------------------------------------------------

std::string TableManager::getTabeVersion(){
    std::string  tabVersion;

    tntdb::Statement st = m_conn.prepare( " SELECT data_value \
         FROM metadata \
         WHERE data_name = :data_name ;");

    // Wenn wir nur einen einzelnen Wert lesen wollen, dann verwenden wir tntdb::Statement::selectValue().

    tntdb::Value value = st.set( "data_name", "tableversion" )
                       .selectValue();

    value.get(tabVersion);
    return tabVersion;

}

// S -------------------------------------------------------------------------

bool TableManager::setUpdate2(){
    tntdb::Transaction trans(m_conn);
    std::ostringstream sqlCommand;
    std::ostringstream sqlCommand5;
    std::ostringstream sqlCommand6;

    try{
        sqlCommand << "CREATE TABLE account_trust ("
        << "    id                   SERIAL    PRIMARY KEY,"
        << "    trusted_account_id   BIGINT    NOT NULL,"
        << "    guarantor_id         BIGINT    NOT NULL,"
        << "    createtime           TIMESTAMP NOT NULL,"
        << "    FOREIGN KEY  (trusted_account_id)   REFERENCES account (id),"
        << "    FOREIGN KEY  (guarantor_id) REFERENCES account (id)"
        << ");";
        m_conn.prepare( sqlCommand.str() ).execute();
//         sqlCommand.flush();

        //  Default value
        sqlCommand5 << "INSERT INTO account_trust"
        << "("
        << "    trusted_account_id,"
        << "    guarantor_id,"
        << "    createtime"
        << ")"
        << "VALUES ("
        << "    1,"
        << "    1,"
        << "    now()"
        << ");";
        m_conn.prepare( sqlCommand5.str() ).execute();
//         sqlCommand.flush();

        sqlCommand6 << "UPDATE metadata "
        << "SET data_value = '00002', "
        << "data_parameter = 'alpha' "
        << "WHERE data_name = 'tableversion';";
        m_conn.prepare( sqlCommand6.str() ).execute();
//         sqlCommand.flush();

        trans.commit();
    }catch (...) {
        return false;
    }
    return true;
}

//  U ------------------------------------------------------------------------

    bool TableManager::update(){
        std::string version = getTabeVersion();

        if ( version == "00001" ) {
            if( setUpdate2() == false){
                log_info( "Table update 00002 failed!");
                return false;
            }else{
                log_info( "Table update 00002 is successful!");
            }
        }

/*      for next version...
        if ( version = "00002" ) {
            if( setUpdate3() == false){
                log_info( "Table update 00003 failed!");
                return false;
            }else{
                log_info( "Table update 00003 is successful!");
            }
        }
*/

        return true;

    }
<|endoftext|>


<commit_before>#include "AnnSpace.hpp"

namespace Elysia{

	AnnSpace::AnnSpace(){
		child[0] = NULL;
		child[1] = NULL;
		parent = NULL;
	}

	bool AnnSpace::isLeaf(){
		if (child[0] == NULL){
			assert(child[1] == NULL);
			return true;
		}
		else{
			return false;
		}
	}

	int AnnSpace::chooseChild(float x, float y){
		if(whichAxis == XAXIS){
			if(x > partitionPoint){return 1;}
			else{return 0;}
		}
		else{
			if(y  > partitionPoint){return 1;}
			else{return 0;}
		}
	}

	void AnnSpace::partitionSpace(STANNSpatialSearch* stann){
		std::vector<float> XArray;
		std::vector<float> YArray;
		for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.end();++i){
			Neuron* current=*i;
			Vector3f location  = current->getLocation();
			XArray.push_back(location.x);
			YArray.push_back(location.y);
		}
		child[0] = new AnnSpace();
		child[1] = new AnnSpace();
		child[0]->setParent(this);
		child[1]->setParent(this);
		//This algorithm is a super primitive way of partitioning the space. Something like k-means might be better
		//As the number of points becomes large, I expect the exactness of this for ANN improves and it's not that
		//bad to begin with. If someone wants to put k-means in here (or some other thing for calling partitions), cool.
		sort(XArray.begin(), XArray.end());
		sort(YArray.begin(), YArray.end());
		float Xdist = XArray[int(XArray.size()/2) + 1] - XArray[int(XArray.size())];
		float Ydist = XArray[int(YArray.size()/2) + 1] - YArray[int(YArray.size())];

		if(Xdist > Ydist){
			class CompareNeuronbyX {
				public:
				bool operator() (const Neuron*a, const Neuron*b) const {
				return a->getLocation().x<b->getLocation().x;
				}
			};

			std::sort(neuronList.begin(),neuronList.end(),CompareNeuronbyX());
			Neuron* midpoint = neuronList[int(neuronList.size()/2)];
			float partition = (XArray[int(XArray.size()/2) + 1] + XArray[int(XArray.size())])/2;

			for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.begin()+neuronList.size()/2;++i){

				child[0]->addPoint(*i, stann);
			}
			for(std::vector<Neuron*>::iterator i=neuronList.begin()+neuronList.size()/2;i!=neuronList.end();++i){
				child[1]->addPoint(*i, stann);
			}
		}
		else{
			class CompareNeuronbyY {
				public:
				bool operator() (const Neuron*a, const Neuron*b) const {
				return a->getLocation().y<b->getLocation().y;
				}
			};
			std::sort(neuronList.begin(),neuronList.end(),CompareNeuronbyY());
			Neuron* midpoint = neuronList[int(neuronList.size()/2)];

			float partition = (YArray[int(YArray.size()/2) + 1] + YArray[int(YArray.size())])/2;

			for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.begin()+neuronList.size()/2;++i){
				child[0]->addPoint(*i, stann);
			}
			for(std::vector<Neuron*>::iterator i=neuronList.begin()+neuronList.size()/2;i!=neuronList.end();++i){
				child[1]->addPoint(*i, stann);
			}
		}
		neuronList.clear();
	}

	void AnnSpace::deletePoint(Neuron* neuron, STANNSpatialSearch* stann){
		if(this->isLeaf()){
			if(neuronList.size() > stann->pointLowerThreshold+1){
				std::vector<Neuron *>::iterator result = std::find(neuronList.begin(), neuronList.end(), neuron);
				neuronList.erase(result);
			}
			else{

				//DETERMINE MERGE POINT
				//MERGE SPACE
			}
		}
		else{
			Vector3f location = neuron->getLocation();
			child[chooseChild(location.x, location.y)] -> addPoint(neuron, stann);
		}
	}

	void AnnSpace::addPoint(Neuron* neuron, STANNSpatialSearch* stann){
		if(this->isLeaf()){
			neuronList.push_back(neuron);
			if(stann->pointUpperThreshold > neuronList.size() + 1){
				//PARTITION
			}
		}
		else{
			Vector3f location = neuron->getLocation();
			child[chooseChild(location.x, location.y)] -> addPoint(neuron, stann);
		}
	}

	Neuron* AnnSpace::findNN(float x, float y, Neuron* exclude){
		if(this->isLeaf()){
			Vector3f queryPoint;
			queryPoint.x = x;
			queryPoint.y = y;
			queryPoint.z = 0;
			float maxDistance;
			Neuron * maxDistanceItem=NULL;
			for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.end();++i) {
				Neuron * current=*i;//find out what's "inside" i
				float currentDistance=(current->getLocation()-queryPoint).length();
				if ((maxDistanceItem==NULL || currentDistance<maxDistance) && current != exclude){
					maxDistance=currentDistance;
					maxDistanceItem=current;
				}
			}
			return maxDistanceItem;
		}
		else{
			return child[chooseChild(x, y)] -> findNN(x, y, exclude);
		}
	}

	void AnnSpace::mergeSpace(){}

}
<commit_msg>moved compare functors outside function<commit_after>#include "AnnSpace.hpp"

namespace Elysia{

	AnnSpace::AnnSpace(){
		child[0] = NULL;
		child[1] = NULL;
		parent = NULL;
	}

	bool AnnSpace::isLeaf(){
		if (child[0] == NULL){
			assert(child[1] == NULL);
			return true;
		}
		else{
			return false;
		}
	}

	int AnnSpace::chooseChild(float x, float y){
		if(whichAxis == XAXIS){
			if(x > partitionPoint){return 1;}
			else{return 0;}
		}
		else{
			if(y  > partitionPoint){return 1;}
			else{return 0;}
		}
	}

	class CompareNeuronbyY {
		public:
		bool operator() (const Neuron*a, const Neuron*b) const {
		return a->getLocation().y<b->getLocation().y;
		}
	};
	class CompareNeuronbyX {
		public:
		bool operator() (const Neuron*a, const Neuron*b) const {
		return a->getLocation().x<b->getLocation().x;
		}
	};

	void AnnSpace::partitionSpace(STANNSpatialSearch* stann){
		std::vector<float> XArray;
		std::vector<float> YArray;
		for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.end();++i){
			Neuron* current=*i;
			Vector3f location  = current->getLocation();
			XArray.push_back(location.x);
			YArray.push_back(location.y);
		}
		child[0] = new AnnSpace();
		child[1] = new AnnSpace();
		child[0]->setParent(this);
		child[1]->setParent(this);
		//This algorithm is a super primitive way of partitioning the space. Something like k-means might be better
		//As the number of points becomes large, I expect the exactness of this for ANN improves and it's not that
		//bad to begin with. If someone wants to put k-means in here (or some other thing for calling partitions), cool.
		sort(XArray.begin(), XArray.end());
		sort(YArray.begin(), YArray.end());
		float Xdist = XArray[int(XArray.size()/2) + 1] - XArray[int(XArray.size())];
		float Ydist = XArray[int(YArray.size()/2) + 1] - YArray[int(YArray.size())];

		if(Xdist > Ydist){
			class CompareNeuronbyX {
				public:
				bool operator() (const Neuron*a, const Neuron*b) const {
				return a->getLocation().x<b->getLocation().x;
				}
			};

			std::sort(neuronList.begin(),neuronList.end(),CompareNeuronbyX());
			Neuron* midpoint = neuronList[int(neuronList.size()/2)];
			float partition = (XArray[int(XArray.size()/2) + 1] + XArray[int(XArray.size())])/2;

			for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.begin()+neuronList.size()/2;++i){

				child[0]->addPoint(*i, stann);
			}
			for(std::vector<Neuron*>::iterator i=neuronList.begin()+neuronList.size()/2;i!=neuronList.end();++i){
				child[1]->addPoint(*i, stann);
			}
		}
		else{

			std::sort(neuronList.begin(),neuronList.end(),CompareNeuronbyY());
			Neuron* midpoint = neuronList[int(neuronList.size()/2)];

			float partition = (YArray[int(YArray.size()/2) + 1] + YArray[int(YArray.size())])/2;

			for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.begin()+neuronList.size()/2;++i){
				child[0]->addPoint(*i, stann);
			}
			for(std::vector<Neuron*>::iterator i=neuronList.begin()+neuronList.size()/2;i!=neuronList.end();++i){
				child[1]->addPoint(*i, stann);
			}
		}
		neuronList.clear();
	}

	void AnnSpace::deletePoint(Neuron* neuron, STANNSpatialSearch* stann){
		if(this->isLeaf()){
			if(neuronList.size() > stann->pointLowerThreshold+1){
				std::vector<Neuron *>::iterator result = std::find(neuronList.begin(), neuronList.end(), neuron);
				neuronList.erase(result);
			}
			else{

				//DETERMINE MERGE POINT
				//MERGE SPACE
			}
		}
		else{
			Vector3f location = neuron->getLocation();
			child[chooseChild(location.x, location.y)] -> addPoint(neuron, stann);
		}
	}

	void AnnSpace::addPoint(Neuron* neuron, STANNSpatialSearch* stann){
		if(this->isLeaf()){
			neuronList.push_back(neuron);
			if(stann->pointUpperThreshold > neuronList.size() + 1){
				//PARTITION
			}
		}
		else{
			Vector3f location = neuron->getLocation();
			child[chooseChild(location.x, location.y)] -> addPoint(neuron, stann);
		}
	}

	Neuron* AnnSpace::findNN(float x, float y, Neuron* exclude){
		if(this->isLeaf()){
			Vector3f queryPoint;
			queryPoint.x = x;
			queryPoint.y = y;
			queryPoint.z = 0;
			float maxDistance;
			Neuron * maxDistanceItem=NULL;
			for(std::vector<Neuron*>::iterator i=neuronList.begin();i!=neuronList.end();++i) {
				Neuron * current=*i;//find out what's "inside" i
				float currentDistance=(current->getLocation()-queryPoint).length();
				if ((maxDistanceItem==NULL || currentDistance<maxDistance) && current != exclude){
					maxDistance=currentDistance;
					maxDistanceItem=current;
				}
			}
			return maxDistanceItem;
		}
		else{
			return child[chooseChild(x, y)] -> findNN(x, y, exclude);
		}
	}

	void AnnSpace::mergeSpace(){}

}
<|endoftext|>