Belle II Software  release-08-01-10
SpaceResolutionCalibrationAlgorithm Class Reference

Class for Space resolution calibration. More...

#include <SpaceResolutionCalibrationAlgorithm.h>

Inheritance diagram for SpaceResolutionCalibrationAlgorithm:
Collaboration diagram for SpaceResolutionCalibrationAlgorithm:

Public Types

enum  EResult {
  c_OK ,
  c_Iterate ,
  c_NotEnoughData ,
  c_Failure ,
  c_Undefined
}
 The result of calibration. More...
 

Public Member Functions

 SpaceResolutionCalibrationAlgorithm ()
 Constructor.
 
 ~SpaceResolutionCalibrationAlgorithm ()
 Destructor.
 
void setDebug (bool debug=false)
 Set Debug mode.
 
void setMinimumNDF (double ndf)
 minimum NDF required for track
 
void setMinimumPval (double pval)
 Minimum Pval required.
 
void setBinWidth (double bw)
 Bin width of each slide.
 
void setBField (bool bfield)
 Work with B field or not;.
 
void setStoreHisto (bool storeHist=false)
 Store histograms durring the calibration or not.
 
void enableTextOutput (bool output=true)
 Enable text output of calibration result.
 
void setOutputFileName (std::string outputname)
 output file name
 
void setHistFileName (const std::string &name)
 Set name for histogram output.
 
void setThreshold (double th=0.6)
 Set threshold for the fraction of fitted results.
 
std::string getPrefix () const
 Get the prefix used for getting calibration data.
 
bool checkPyExpRun (PyObject *pyObj)
 Checks that a PyObject can be successfully converted to an ExpRun type. More...
 
Calibration::ExpRun convertPyExpRun (PyObject *pyObj)
 Performs the conversion of PyObject to ExpRun. More...
 
std::string getCollectorName () const
 Alias for prefix. More...
 
void setPrefix (const std::string &prefix)
 Set the prefix used to identify datastore objects.
 
void setInputFileNames (PyObject *inputFileNames)
 Set the input file names used for this algorithm from a Python list. More...
 
PyObject * getInputFileNames ()
 Get the input file names used for this algorithm and pass them out as a Python list of unicode strings.
 
std::vector< Calibration::ExpRun > getRunListFromAllData () const
 Get the complete list of runs from inspection of collected data.
 
RunRange getRunRangeFromAllData () const
 Get the complete RunRange from inspection of collected data.
 
IntervalOfValidity getIovFromAllData () const
 Get the complete IoV from inspection of collected data.
 
void fillRunToInputFilesMap ()
 Fill the mapping of ExpRun -> Files.
 
std::string getGranularity () const
 Get the granularity of collected data.
 
EResult execute (std::vector< Calibration::ExpRun > runs={}, int iteration=0, IntervalOfValidity iov=IntervalOfValidity())
 Runs calibration over vector of runs for a given iteration. More...
 
EResult execute (PyObject *runs, int iteration=0, IntervalOfValidity iov=IntervalOfValidity())
 Runs calibration over Python list of runs. Converts to C++ and then calls the other execute() function.
 
std::list< Database::DBImportQuery > & getPayloads ()
 Get constants (in TObjects) for database update from last execution.
 
std::list< Database::DBImportQuerygetPayloadValues ()
 Get constants (in TObjects) for database update from last execution but passed by VALUE.
 
bool commit ()
 Submit constants from last calibration into database.
 
bool commit (std::list< Database::DBImportQuery > payloads)
 Submit constants from a (potentially previous) set of payloads.
 
const std::string & getDescription () const
 Get the description of the algoithm (set by developers in constructor)
 
bool loadInputJson (const std::string &jsonString)
 Load the m_inputJson variable from a string (useful from Python interface). The rturn bool indicates success or failure.
 
const std::string dumpOutputJson () const
 Dump the JSON string of the output JSON object.
 
const std::vector< Calibration::ExpRun > findPayloadBoundaries (std::vector< Calibration::ExpRun > runs, int iteration=0)
 Used to discover the ExpRun boundaries that you want the Python CAF to execute on. This is optional and only used in some.
 
template<>
std::shared_ptr< TTree > getObjectPtr (const std::string &name, const std::vector< Calibration::ExpRun > &requestedRuns)
 Specialization of getObjectPtr<TTree>.
 

Protected Member Functions

EResult calibrate () override
 Run algo on data. More...
 
void createHisto ()
 create histogram
 
void storeHisto ()
 store histogram
 
void write ()
 save calibration, in text file or db
 
void prepare ()
 Prepare the calibration of space resolution.
 
double getUpperBoundaryForFit (TGraphErrors *graph)
 search max point at boundary region
 
void setInputFileNames (std::vector< std::string > inputFileNames)
 Set the input file names used for this algorithm. More...
 
virtual bool isBoundaryRequired (const Calibration::ExpRun &)
 Given the current collector data, make a decision about whether or not this run should be the start of a payload boundary.
 
virtual void boundaryFindingSetup (std::vector< Calibration::ExpRun >, int)
 If you need to make some changes to your algorithm class before 'findPayloadBoundaries' is run, make them in this function.
 
virtual void boundaryFindingTearDown ()
 Put your algorithm back into a state ready for normal execution if you need to.
 
const std::vector< Calibration::ExpRun > & getRunList () const
 Get the list of runs for which calibration is called.
 
int getIteration () const
 Get current iteration.
 
std::vector< std::string > getVecInputFileNames () const
 Get the input file names used for this algorithm as a STL vector.
 
template<class T >
std::shared_ptr< T > getObjectPtr (const std::string &name, const std::vector< Calibration::ExpRun > &requestedRuns)
 Get calibration data object by name and list of runs, the Merge function will be called to generate the overall object.
 
template<class T >
std::shared_ptr< T > getObjectPtr (std::string name)
 Get calibration data object (for all runs the calibration is requested for) This function will only work during or after execute() has been called once.
 
template<>
shared_ptr< TTree > getObjectPtr (const string &name, const vector< ExpRun > &requestedRuns)
 We cheekily cast the TChain to TTree for the returned pointer so that the user never knows Hopefully this doesn't cause issues if people do low level stuff to the tree...
 
std::string getGranularityFromData () const
 Get the granularity of collected data.
 
void saveCalibration (TClonesArray *data, const std::string &name)
 Store DBArray payload with given name with default IOV.
 
void saveCalibration (TClonesArray *data, const std::string &name, const IntervalOfValidity &iov)
 Store DBArray with given name and custom IOV.
 
void saveCalibration (TObject *data)
 Store DB payload with default name and default IOV.
 
void saveCalibration (TObject *data, const IntervalOfValidity &iov)
 Store DB payload with default name and custom IOV.
 
void saveCalibration (TObject *data, const std::string &name)
 Store DB payload with given name with default IOV.
 
void saveCalibration (TObject *data, const std::string &name, const IntervalOfValidity &iov)
 Store DB payload with given name and custom IOV.
 
void updateDBObjPtrs (const unsigned int event, const int run, const int experiment)
 Updates any DBObjPtrs by calling update(event) for DBStore.
 
void setDescription (const std::string &description)
 Set algorithm description (in constructor)
 
void clearCalibrationData ()
 Clear calibration data.
 
Calibration::ExpRun getAllGranularityExpRun () const
 Returns the Exp,Run pair that means 'Everything'. Currently unused.
 
void resetInputJson ()
 Clears the m_inputJson member variable.
 
void resetOutputJson ()
 Clears the m_outputJson member variable.
 
template<class T >
void setOutputJsonValue (const std::string &key, const T &value)
 Set a key:value pair for the outputJson object, expected to used interally during calibrate()
 
template<class T >
const T getOutputJsonValue (const std::string &key) const
 Get a value using a key from the JSON output object, not sure why you would want to do this.
 
template<class T >
const T getInputJsonValue (const std::string &key) const
 Get an input JSON value using a key. The normal exceptions are raised when the key doesn't exist.
 
const nlohmann::json & getInputJsonObject () const
 Get the entire top level JSON object. We explicitly say this must be of object type so that we might pick.
 
bool inputJsonKeyExists (const std::string &key) const
 Test for a key in the input JSON object.
 

Protected Attributes

std::vector< Calibration::ExpRun > m_boundaries
 When using the boundaries functionality from isBoundaryRequired, this is used to store the boundaries. It is cleared when.
 

Private Member Functions

std::string getExpRunString (Calibration::ExpRun &expRun) const
 Gets the "exp.run" string repr. of (exp,run)
 
std::string getFullObjectPath (const std::string &name, Calibration::ExpRun expRun) const
 constructs the full TDirectory + Key name of an object in a TFile based on its name and exprun
 

Private Attributes

double m_minNdf = 5
 Minimum NDF

 
double m_minPval = 0.
 Minimum Prob(chi2) of track.
 
double m_binWidth = 0.05
 width of each bin, unit cm
 
bool m_debug = false
 Debug or not.
 
bool m_storeHisto = false
 Store histogram or not.
 
bool m_bField = true
 Work with BField, fit range and initial parameters is different incase B and noB.
 
double m_threshold = 0.6
 minimal requirement for the fraction of fitted results
 
double m_sigma [56][2][18][7][8]
 new sigma prameters.
 
TGraphErrors * m_gFit [56][2][18][7]
 sigma*sigma graph for fit
 
TGraphErrors * m_graph [56][2][18][7]
 sigma graph.
 
TH2F * m_hBiased [56][2][Max_nalpha][Max_ntheta]
 2D histogram of biased residual
 
TH2F * m_hUnbiased [56][2][Max_nalpha][Max_ntheta]
 2D histogram of unbiased residual
 
TH1F * m_hMeanBiased [56][2][Max_nalpha][Max_ntheta]
 mean histogram biased residual
 
TH1F * m_hSigmaBiased [56][2][Max_nalpha][Max_ntheta]
 sigma histogram of biased residual
 
TH1F * m_hMeanUnbiased [56][2][Max_nalpha][Max_ntheta]
 mean histogram of unbiased residual
 
TH1F * m_hSigmaUnbiased [56][2][Max_nalpha][Max_ntheta]
 sigma histogram of ubiased residual
 
int m_fitStatus [56][2][Max_nalpha][Max_ntheta] = {{{{0}}}}
 Fit flag; 1:OK ; 0:error.
 
int m_nAlphaBins
 number of alpha bins
 
int m_nThetaBins
 number of theta bins
 
float m_lowerAlpha [18]
 Lower boundays of alpha bins.
 
float m_upperAlpha [18]
 Upper boundays of alpha bins.
 
float m_iAlpha [18]
 represented alphas of alpha bins.
 
float m_lowerTheta [7]
 Lower boundays of theta bins.
 
float m_upperTheta [7]
 Upper boundays of theta bins.
 
float m_iTheta [7]
 represented alphas of theta bins.
 
unsigned short m_sigmaParamMode = 0
 sigma mode for this calibration.
 
double m_sigmaPost [56][2][18][7][8]
 sigma prameters before calibration
 
unsigned short m_sigmaParamModePost
 sigma mode before this calibration.
 
bool m_textOutput = false
 output text file if true
 
std::string m_outputFileName = "sigma_new.dat"
 Output sigma filename.
 
std::string m_histName = "histSigma.root"
 root file name
 
DBObjPtr< CDCGeometrym_cdcGeo
 Geometry of CDC.
 
std::vector< std::string > m_inputFileNames
 List of input files to the Algorithm, will initially be user defined but then gets the wildcards expanded during execute()
 
std::map< Calibration::ExpRun, std::vector< std::string > > m_runsToInputFiles
 Map of Runs to input files. Gets filled when you call getRunRangeFromAllData, gets cleared when setting input files again.
 
std::string m_granularityOfData
 Granularity of input data. This only changes when the input files change so it isn't specific to an execution.
 
ExecutionData m_data
 Data specific to a SINGLE execution of the algorithm. Gets reset at the beginning of execution.
 
std::string m_description {""}
 Description of the algorithm.
 
std::string m_prefix {""}
 The name of the TDirectory the collector objects are contained within.
 
nlohmann::json m_jsonExecutionInput = nlohmann::json::object()
 Optional input JSON object used to make decisions about how to execute the algorithm code.
 
nlohmann::json m_jsonExecutionOutput = nlohmann::json::object()
 Optional output JSON object that can be set during the execution by the underlying algorithm code.
 

Static Private Attributes

static const int Max_nalpha = 18
 Maximum alpha bin.
 
static const int Max_ntheta = 7
 maximum theta bin

 
static const unsigned short Max_np = 40
 Maximum number of point =1/binwidth.
 
static const Calibration::ExpRun m_allExpRun = make_pair(-1, -1)
 allExpRun
 

Detailed Description

Class for Space resolution calibration.

Definition at line 28 of file SpaceResolutionCalibrationAlgorithm.h.

Member Enumeration Documentation

◆ EResult

enum EResult
inherited

The result of calibration.

Enumerator
c_OK 

Finished successfuly =0 in Python.

c_Iterate 

Needs iteration =1 in Python.

c_NotEnoughData 

Needs more data =2 in Python.

c_Failure 

Failed =3 in Python.

c_Undefined 

Not yet known (before execution) =4 in Python.

Definition at line 40 of file CalibrationAlgorithm.h.

Member Function Documentation

◆ calibrate()

CalibrationAlgorithm::EResult calibrate ( )
overrideprotectedvirtual

Run algo on data.

Upper limit of fitting.

Implements CalibrationAlgorithm.

Definition at line 312 of file SpaceResolutionCalibrationAlgorithm.cc.

313 {
314 
315  B2INFO("Start calibration");
316  gPrintViaErrorHandler = true; // Suppress huge log output from TMinuit
317  gROOT->SetBatch(1);
318  gErrorIgnoreLevel = 3001;
319 
320  const auto exprun = getRunList()[0];
321  B2INFO("ExpRun used for DB Geometry : " << exprun.first << " " << exprun.second);
322  updateDBObjPtrs(1, exprun.second, exprun.first);
323  // B2INFO("Creating CDCGeometryPar object");
324  // CDC::CDCGeometryPar::Instance(&(*m_cdcGeo));
325 
326  prepare();
327  createHisto();
328 
329  TF1* func = new TF1("func", "[0]/(x*x + [1])+[2]* x+[3]+[4]*exp([5]*(x-[6])*(x-[6]))", 0, 1.);
330  TH1F* hprob = new TH1F("h1", "", 20, 0, 1);
331  double upFit;
332  double intp6;
333 
334  for (int i = 0; i < 56; ++i) {
335  for (int lr = 0; lr < 2; ++lr) {
336  for (int al = 0; al < m_nAlphaBins; ++al) {
337  for (int th = 0; th < m_nThetaBins; ++th) {
338  if (!m_gFit[i][lr][al][th]) continue;
339  if (m_fitStatus[i][lr][al][th] != -1) { /*if graph exist, do fitting*/
340  upFit = getUpperBoundaryForFit(m_gFit[i][lr][al][th]);
341  intp6 = upFit + 0.2;
342  B2DEBUG(199, "xmax for fitting: " << upFit);
343 
344  func->SetParameters(5E-6, 0.007, 1E-4, 1E-5, 0.00008, -30, intp6);
345  func->SetParLimits(0, 1E-7, 1E-4);
346  func->SetParLimits(1, 0.0045, 0.02);
347  func->SetParLimits(2, 1E-6, 0.0005);
348  func->SetParLimits(3, 1E-8, 0.0005);
349  func->SetParLimits(4, 0., 0.001);
350  func->SetParLimits(5, -40, 0.);
351  func->SetParLimits(6, intp6 - 0.5, intp6 + 0.2);
352 
353  B2DEBUG(21, "Fitting for layer: " << i << "lr: " << lr << " ial" << al << " ith:" << th);
354  B2DEBUG(21, "Fit status before fit:" << m_fitStatus[i][lr][al][th]);
355 
356  for (int j = 0; j < 10; j++) {
357 
358  B2DEBUG(21, "loop: " << j);
359  B2DEBUG(21, "Int p6: " << intp6);
360  B2DEBUG(21, "Number of Point: " << m_gFit[i][lr][al][th]->GetN());
361  Int_t stat = m_gFit[i][lr][al][th]->Fit("func", "MQE", "", 0.05, upFit);
362  B2DEBUG(21, "stat of fit" << stat);
363  std::string Fit_status = gMinuit->fCstatu.Data();
364  B2DEBUG(21, "FIT STATUS: " << Fit_status);
365  if (Fit_status == "OK" || Fit_status == "SUCCESSFUL" || Fit_status == "CALL LIMIT"
366  || Fit_status == "PROBLEMS") {//need to found better way
367  if (fabs(func->Eval(0.3)) > 0.00035 || func->Eval(0.3) < 0) {
368  func->SetParameters(5E-6, 0.007, 1E-4, 1E-7, 0.0007, -30, intp6 + 0.05 * j);
369  func->SetParLimits(6, intp6 + 0.05 * j - 0.5, intp6 + 0.05 * j + 0.2);
370  // func->SetParameters(defaultparsmall);
371  m_fitStatus[i][lr][al][th] = 0;
372  } else {
373  B2DEBUG(21, "Prob of fit: " << func->GetProb());
374  m_fitStatus[i][lr][al][th] = 1;
375  break;
376  }
377  } else {
378  m_fitStatus[i][lr][al][th] = 0;
379  func->SetParameters(5E-6, 0.007, 1E-4, 1E-7, 0.0007, -30, intp6 + 0.05 * j);
380  func->SetParLimits(6, intp6 + 0.05 * j - 0.5, intp6 + 0.05 * j + 0.2);
381  upFit += 0.025;
382  if (j == 9) {
383  // TCanvas* c1 = new TCanvas("c1", "", 600, 600);
384  // m_gFit[i][lr][al][th]->Draw();
385  // c1->SaveAs(Form("Sigma_Fit_Error_%s_%d_%d_%d_%d.png", Fit_status.c_str(), i, lr, al, th));
386  // B2WARNING("Fit error: " << i << " " << lr << " " << al << " " << th);
387  }
388  }
389  }
390  if (m_fitStatus[i][lr][al][th] == 1) {
391  B2DEBUG(21, "ProbFit: Lay_lr_al_th: " << i << " " << lr << " " << al << " " << th << func->GetProb());
392  hprob->Fill(func->GetProb());
393  func->GetParameters(m_sigma[i][lr][al][th]);
394  }
395  }
396  }
397  }
398  }
399  }
400 
401  write();
402  storeHisto();
403 
404  const int nTotal = 56 * 2 * m_nAlphaBins * m_nThetaBins;
405  int nFitCompleted = 0;
406  for (int l = 0; l < 56; ++l) {
407  for (int lr = 0; lr < 2; ++lr) {
408  for (int al = 0; al < m_nAlphaBins; ++al) {
409  for (int th = 0; th < m_nThetaBins; ++th) {
410  if (m_fitStatus[l][lr][al][th] == 1) {
411  nFitCompleted += 1;
412  }
413  }
414  }
415  }
416  }
417 
418  if (static_cast<double>(nFitCompleted) / nTotal < m_threshold) {
419  B2WARNING("Less than " << m_threshold * 100 << " % of Sigmas were fitted.");
420  return c_NotEnoughData;
421  }
422 
423  return c_OK;
424 }
R E
internal precision of FFTW codelets
void prepare()
Prepare the calibration of space resolution.
double m_threshold
minimal requirement for the fraction of fitted results
double getUpperBoundaryForFit(TGraphErrors *graph)
search max point at boundary region
TGraphErrors * m_gFit[56][2][18][7]
sigma*sigma graph for fit
int m_fitStatus[56][2][Max_nalpha][Max_ntheta]
Fit flag; 1:OK ; 0:error.
void updateDBObjPtrs(const unsigned int event, const int run, const int experiment)
Updates any DBObjPtrs by calling update(event) for DBStore.
@ c_OK
Finished successfuly =0 in Python.
@ c_NotEnoughData
Needs more data =2 in Python.
const std::vector< Calibration::ExpRun > & getRunList() const
Get the list of runs for which calibration is called.

◆ checkPyExpRun()

bool checkPyExpRun ( PyObject *  pyObj)
inherited

Checks that a PyObject can be successfully converted to an ExpRun type.

Checks if the PyObject can be converted to ExpRun.

Definition at line 28 of file CalibrationAlgorithm.cc.

◆ convertPyExpRun()

ExpRun convertPyExpRun ( PyObject *  pyObj)
inherited

Performs the conversion of PyObject to ExpRun.

Converts the PyObject to an ExpRun. We've preoviously checked the object so this assumes a lot about the PyObject.

Definition at line 70 of file CalibrationAlgorithm.cc.

◆ execute()

CalibrationAlgorithm::EResult execute ( std::vector< Calibration::ExpRun >  runs = {},
int  iteration = 0,
IntervalOfValidity  iov = IntervalOfValidity() 
)
inherited

Runs calibration over vector of runs for a given iteration.

You can also specify the IoV to save the database payload as. By default the Algorithm will create an IoV from your requested ExpRuns, or from the overall ExpRuns of the input data if you haven't specified ExpRuns in this function.

No checks are performed to make sure that a IoV you specify matches the data you ran over, it simply labels the IoV to commit to the database later.

Definition at line 114 of file CalibrationAlgorithm.cc.

◆ getCollectorName()

std::string getCollectorName ( ) const
inlineinherited

Alias for prefix.

For convenience and less writing, we say developers to set this to default collector module name in constructor of base class. One can however use the dublets of collector+algorithm multiple times with different settings. To bind these together correctly, the prefix has to be set the same for algo and collector. So we call the setter setPrefix rather than setModuleName or whatever. This getter will work out of the box for default cases -> return the name of module you have to add to your path to collect data for this algorihtm.

Definition at line 164 of file CalibrationAlgorithm.h.

◆ setInputFileNames() [1/2]

void setInputFileNames ( PyObject *  inputFileNames)
inherited

Set the input file names used for this algorithm from a Python list.

Set the input file names used for this algorithm and resolve the wildcards.

Definition at line 166 of file CalibrationAlgorithm.cc.

◆ setInputFileNames() [2/2]

void setInputFileNames ( std::vector< std::string >  inputFileNames)
protectedinherited

Set the input file names used for this algorithm.

Set the input file names used for this algorithm and resolve the wildcards.

Definition at line 194 of file CalibrationAlgorithm.cc.


The documentation for this class was generated from the following files: