Belle II Software development
eclTimeShiftsAlgorithm Class Reference

Calibrate ecl crystals using previously created payloads. More...

#include <eclTimeShiftsAlgorithm.h>

Inheritance diagram for eclTimeShiftsAlgorithm:
CalibrationAlgorithm

Public Types

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

Public Member Functions

 eclTimeShiftsAlgorithm ()
 ..Constructor
 
 ~eclTimeShiftsAlgorithm () override
 ..Destructor
 
const std::string & getPrefix () const
 Get the prefix used for getting calibration data.
 
const std::string & getCollectorName () const
 Alias for prefix.
 
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.
 
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.
 
const 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.
 
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 () const
 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 algorithm (set by developers in constructor)
 
bool loadInputJson (const std::string &jsonString)
 Load the m_inputJson variable from a string (useful from Python interface). The return 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>.
 

Static Public Member Functions

static bool checkPyExpRun (PyObject *pyObj)
 Checks that a PyObject can be successfully converted to an ExpRun type.
 
static Calibration::ExpRun convertPyExpRun (PyObject *pyObj)
 Performs the conversion of PyObject to ExpRun.
 

Public Attributes

std::string debugFilenameBase
 Name of file with debug output, eclTimeShiftsAlgorithm.root by default.
 
double timeShiftForPlotStyle [52] = {}
 List of time offsets, one per crate, used just to centre the time constants around zero.
 
double crysCrateShift_min = 0.0
 Plotting time min for crystal+crate shift plots.
 
double crysCrateShift_max = 0.0
 Plotting time max for crystal+crate shift plots.
 
bool algorithmReadPayloads = false
 Whether or not to have the algorithm code to loop over all the runs and read the payloads itself.
 

Protected Member Functions

EResult calibrate () override
 ..Run algorithm
 
void setInputFileNames (const std::vector< std::string > &inputFileNames)
 Set the input file names used for this algorithm.
 
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.
 
const 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 setDescription (const std::string &description)
 Set algorithm description (in constructor)
 
void clearCalibrationData ()
 Clear calibration data.
 
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 internally 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.
 

Static Protected Member Functions

static void updateDBObjPtrs (const unsigned int event, const int run, const int experiment)
 Updates any DBObjPtrs by calling update(event) for DBStore.
 
static Calibration::ExpRun getAllGranularityExpRun ()
 Returns the Exp,Run pair that means 'Everything'. Currently unused.
 

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

DBObjPtr< ECLCrystalCalibm_ECLCrystalTimeOffset
 ECLCrystalTimeOffset payload that we want to read from the DB.
 
DBObjPtr< ECLCrystalCalibm_ECLCrateTimeOffset
 ECLCrateTimeOffset payload that we want to read from the DB.
 
DBObjPtr< ECLReferenceCrystalPerCrateCalibm_refCrysIDzeroingCrate
 payload that we want to read from the DB
 
const int m_numCrystals = ECLElementNumbers::c_NCrystals
 Number of Crystals expected.
 
const int m_numCrates = 52
 Number of Crates expected.
 
Int_t m_run_perCrystal
 Run number.
 
Int_t m_exp_perCrystal
 Experiment number.
 
Int_t m_crystalID
 Crystal ID number.
 
Double_t m_crateTimeConst
 Crate time calibration constant.
 
Double_t m_crystalTimeConst
 Crystal time calibration constant.
 
Double_t m_crateTimeUnc
 Uncertainty on the crate time calibration constant.
 
Double_t m_crystalTimeUnc
 Uncertainty on the crystal time calibration constant.
 
Int_t m_crateID
 Crate ID number.
 
Int_t m_refCrystalID
 Crystal ID number for the reference crystal.
 
double m_tcrate_min_cut = -150
 Minimum value cut for the crate time calibration constant for plotting.
 
double m_tcrate_max_cut = 150
 Maximum value cut for the crate time calibration constant for plotting.
 
double m_tcrate_unc_min_cut = 0.0001
 Minimum value cut for the crate time calibration constant uncertainty for plotting.
 
double m_tcrate_unc_max_cut = 999.
 Maximum value cut for the crate time calibration constant uncertainty for plotting.
 
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 Calibration::ExpRun m_allExpRun = make_pair(-1, -1)
 allExpRun
 

Detailed Description

Calibrate ecl crystals using previously created payloads.

Definition at line 36 of file eclTimeShiftsAlgorithm.h.

Member Enumeration Documentation

◆ EResult

enum EResult
inherited

The result of calibration.

Enumerator
c_OK 

Finished successfully =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.

40 {
41 c_OK,
42 c_Iterate,
43 c_NotEnoughData,
44 c_Failure,
45 c_Undefined
46 };

Constructor & Destructor Documentation

◆ eclTimeShiftsAlgorithm()

..Constructor


Definition at line 41 of file eclTimeShiftsAlgorithm.cc.

41 :
42 CalibrationAlgorithm("eclTimeShiftsPlottingCollector"),
43 debugFilenameBase("ECL_time_offsets"),
44 timeShiftForPlotStyle{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
48 m_ECLCrystalTimeOffset("ECLCrystalTimeOffset"),
49 m_ECLCrateTimeOffset("ECLCrateTimeOffset"),
50 m_refCrysIDzeroingCrate("ECLReferenceCrystalPerCrateCalib")//,
51{
53 "Plots the ecl crystal and crate time calibations."
54 );
55}
void setDescription(const std::string &description)
Set algorithm description (in constructor)
CalibrationAlgorithm(const std::string &collectorModuleName)
Constructor - sets the prefix for collected objects (won't be accesses until execute(....
bool algorithmReadPayloads
Whether or not to have the algorithm code to loop over all the runs and read the payloads itself.
DBObjPtr< ECLReferenceCrystalPerCrateCalib > m_refCrysIDzeroingCrate
payload that we want to read from the DB
DBObjPtr< ECLCrystalCalib > m_ECLCrateTimeOffset
ECLCrateTimeOffset payload that we want to read from the DB.
double crysCrateShift_max
Plotting time max for crystal+crate shift plots.
double crysCrateShift_min
Plotting time min for crystal+crate shift plots.
std::string debugFilenameBase
Name of file with debug output, eclTimeShiftsAlgorithm.root by default.
DBObjPtr< ECLCrystalCalib > m_ECLCrystalTimeOffset
ECLCrystalTimeOffset payload that we want to read from the DB.
double timeShiftForPlotStyle[52]
List of time offsets, one per crate, used just to centre the time constants around zero.

◆ ~eclTimeShiftsAlgorithm()

~eclTimeShiftsAlgorithm ( )
inlineoverride

..Destructor

Definition at line 43 of file eclTimeShiftsAlgorithm.h.

43{}

Member Function Documentation

◆ boundaryFindingSetup()

virtual void boundaryFindingSetup ( std::vector< Calibration::ExpRun > ,
int  )
inlineprotectedvirtualinherited

If you need to make some changes to your algorithm class before 'findPayloadBoundaries' is run, make them in this function.

Reimplemented in PXDAnalyticGainCalibrationAlgorithm, PXDValidationAlgorithm, SVD3SampleCoGTimeCalibrationAlgorithm, SVD3SampleELSTimeCalibrationAlgorithm, SVDClusterAbsoluteTimeShifterAlgorithm, SVDCoGTimeCalibrationAlgorithm, TestBoundarySettingAlgorithm, and TestCalibrationAlgorithm.

Definition at line 252 of file CalibrationAlgorithm.h.

252{};

◆ boundaryFindingTearDown()

virtual void boundaryFindingTearDown ( )
inlineprotectedvirtualinherited

Put your algorithm back into a state ready for normal execution if you need to.

Definition at line 257 of file CalibrationAlgorithm.h.

257{};

◆ calibrate()

CalibrationAlgorithm::EResult calibrate ( )
overrideprotectedvirtual

..Run algorithm

Put root into batch mode so that we don't try to open a graphics window

Apply the cuts to the values extracted from the tree

Write out a few values for quality control purposes

Determine the minimum and maximum run numbers for labelling purposes

Test that the DBObjects are valid

Get the vectors from the input payloads

Loop over all the experiments and runs and extract the crate times

Set up ECL channel mapper and determine the payload IoV and Revision

Populate database contents

Get the vectors from the input payload

Make a crate time offset vector with an entry per crate (instead of per crystal) and convert from ADC counts to ns. Also store the sum of the crystal and crate times

Write out a few values for quality control purposes

Shift all the crystal+crate times by the mean time to naturally roughly centre all the crys+crate+shift times

Now that the timing information has be read in, fill the crate time offsets and general time shifts into the histograms

Implements CalibrationAlgorithm.

Definition at line 57 of file eclTimeShiftsAlgorithm.cc.

58{
60 gROOT->SetBatch();
61
62 B2INFO("eclTimeShiftsAlgorithm parameters:");
63 B2INFO("debugFilenameBase = " << debugFilenameBase);
64 B2INFO("algorithmReadPayloads = " << algorithmReadPayloads);
65 B2INFO("timeShiftForPlotStyle = {");
66 for (int crateTest = 0; crateTest < 51; crateTest++) {
67 B2INFO(timeShiftForPlotStyle[crateTest] << ",");
68 }
69 B2INFO(timeShiftForPlotStyle[51] << "}");
70
71
72 //------------------------------------------------------------------------
73 /* Conversion coefficient from ADC ticks to nanoseconds
74 1/(4fRF) = 0.4913 ns/clock tick, where fRF is the accelerator RF frequency.
75 Same for all crystals. */
76
77 //..First need to set event, run, exp number
78 const auto expRunList = getRunList();
79 const int iEvt = 1;
80 const int iRun = expRunList[0].second;
81 const int iExp = expRunList[0].first;
82 DBObjPtr<Belle2::HardwareClockSettings> clock_info("HardwareClockSettings");
83 updateDBObjPtrs(iEvt, iRun, iExp);
84 const double TICKS_TO_NS = 1.0 / (4.0 * EclConfiguration::getRF()) * 1e3;
85
86
87 //------------------------------------------------------------------------
88 /* Set up variables for storing timing information and cutting on
89 timing quality */
90
91 vector< vector<double> > allCrates_crate_times ;
92 vector< vector<double> > allCrates_run_nums ; // not an integer for plotting purposes
93 vector< vector<double> > allCrates_time_unc ;
94 vector< vector<double> > allCrates_crystalCrate_times ;
95 vector< vector<double> > allCrates_crystalCrate_times_unc ;
96
97 vector<int> allRunNums;
98
99 vector<double> mean_crystalCrate_time_ns(m_numCrates, 0);
100
101 vector< double > blank_vector = {} ;
102 for (int temp_crate_id = 0; temp_crate_id < m_numCrates; temp_crate_id++) {
103 allCrates_crate_times.push_back(blank_vector) ;
104 allCrates_run_nums.push_back(blank_vector) ;
105 allCrates_time_unc.push_back(blank_vector) ;
106 allCrates_crystalCrate_times.push_back(blank_vector) ;
107 allCrates_crystalCrate_times_unc.push_back(blank_vector) ;
108 }
109 // This results in : allCrates_crate_time[index for crate number][index for run number]
110
111
112
113 //------------------------------------------------------------------------
114 /* Extract the crystal and crate calibration constant information from the
115 tree as extracted by the collector. */
116
117 // Pulling in data from collector output. It now returns shared_ptr<T> so the underlying pointer
118 // will delete itself automatically at the end of this scope unless you do something
119 auto tree_perCrys = getObjectPtr<TTree>("tree_perCrystal");
120 if (!tree_perCrys) {
121 B2ERROR("Tree of calibration constants does not exist.");
122 return c_Failure;
123 }
124 B2INFO("Number of Entries in tree_perCrystal was " << tree_perCrys->GetEntries());
125 B2INFO("Number of Entries in tree_perCrystal / 8736 = " << float(tree_perCrys->GetEntries()) / ECLElementNumbers::c_NCrystals);
126
127
128 // Define the variables to be read in from the tree
129 tree_perCrys->SetBranchAddress("run", &m_run_perCrystal);
130 tree_perCrys->SetBranchAddress("exp", &m_exp_perCrystal);
131 tree_perCrys->SetBranchAddress("crystalID", &m_crystalID);
132 tree_perCrys->SetBranchAddress("crateID", &m_crateID);
133 tree_perCrys->SetBranchAddress("crateTimeConst", &m_crateTimeConst);
134 tree_perCrys->SetBranchAddress("crateTimeUnc", &m_crateTimeUnc);
135 tree_perCrys->SetBranchAddress("crystalTimeConst", &m_crystalTimeConst);
136 tree_perCrys->SetBranchAddress("crystalTimeUnc", &m_crystalTimeUnc);
137 tree_perCrys->SetBranchAddress("refCrystalID", &m_refCrystalID);
138
139
140 int referenceRunNum = -1;
141 int referenceExpNum = -1;
142 //int numAnalysedRuns = 0 ;
143 int previousRunNumTree = -1 ;
144 vector<double> Crate_time_ns_tree(m_numCrates) ;
145 vector<double> Crate_time_tick_tree(m_numCrates) ;
146 vector<double> Crate_time_unc_ns_tree(m_numCrates) ;
147 vector<double> crystalCrate_time_ns_tree(m_numCrates);
148 vector<double> crystalCrate_time_unc_ns_tree(m_numCrates);
149
150
151 Int_t numEntriesCrysTree = (Int_t)tree_perCrys->GetEntries();
152
153 // Loop through the entire tree
154 for (Int_t tree_crys_i = 0; tree_crys_i < numEntriesCrysTree; tree_crys_i++) {
155 for (Int_t tree_crys_j = 0; tree_crys_j < m_numCrystals; tree_crys_j++) {
156 tree_perCrys->GetEntry(tree_crys_i);
157 //B2INFO("tree_crys_i, tree_crys_j = " << tree_crys_i << ", " << tree_crys_j);
158 if (tree_crys_j != m_numCrystals - 1) {
159 tree_crys_i++;
160 }
161
162 // Make sure that all the information read in for 8736 crystals are all from one (exp,run).
163 if (tree_crys_j == 0) {
164 referenceExpNum = m_exp_perCrystal;
165 referenceRunNum = m_run_perCrystal;
166 B2INFO("Looking at exp,run " << m_exp_perCrystal << ", " << m_run_perCrystal);
167 }
168 if ((m_exp_perCrystal != referenceExpNum) or
169 (m_run_perCrystal != referenceRunNum) or
170 (m_run_perCrystal == previousRunNumTree)) {
171
172 B2ERROR("m_exp_perCrystal, referenceExpNum" << m_exp_perCrystal << ", " << referenceExpNum);
173 B2ERROR("m_run_perCrystal, referenceRunNum" << m_run_perCrystal << ", " << referenceRunNum);
174 B2ERROR("m_run_perCrystal, previousRunNumTree" << m_run_perCrystal << ", " << previousRunNumTree);
175 B2ERROR("Exp/run number problem");
176 return c_Failure;
177 }
178
179
180 int crateID_temp = m_crateID;
181 Crate_time_ns_tree[crateID_temp - 1] = m_crateTimeConst * TICKS_TO_NS ;
182 Crate_time_tick_tree[crateID_temp - 1] = m_crateTimeConst ;
183 Crate_time_unc_ns_tree[crateID_temp - 1] = m_crateTimeUnc * TICKS_TO_NS ;
184
186 B2INFO("exp, run, cell ID (0..8735), m_crateID, m_crateTimeConst = " << m_exp_perCrystal << ", " <<
187 m_run_perCrystal << ", " << tree_crys_j << ", " << m_crateID << ", " << m_crateTimeConst << " +/- " << m_crateTimeUnc << " ticks") ;
188 crystalCrate_time_ns_tree[crateID_temp - 1] = (m_crystalTimeConst + m_crateTimeConst) * TICKS_TO_NS;
189
190 crystalCrate_time_unc_ns_tree[crateID_temp - 1] = TICKS_TO_NS * sqrt(
193 } else if (tree_crys_j == 0 || tree_crys_j == 8735) {
194 B2INFO("m_exp_perCrystal, m_run_perCrystal, cell ID (0..8735), m_crateID, m_crateTimeConst = " << m_exp_perCrystal << ", " <<
195 m_run_perCrystal << ", " << tree_crys_j << ", " << m_crateID << ", " << m_crateTimeConst << " ns") ;
196 } else {
197 B2DEBUG(22, "m_exp_perCrystal, m_run_perCrystal, cell ID (0..8735), m_crateID, m_crateTimeConst = " << m_exp_perCrystal << ", " <<
198 m_run_perCrystal << ", " << tree_crys_j << ", " << m_crateID << ", " << m_crateTimeConst << " ns") ;
199 }
200
201 }
202
203 //------------------------------------------------------------------------
205
206 bool savedThisRunNum = false;
207 for (int iCrate = 0; iCrate < m_numCrates; iCrate++) {
208 double tcrate = Crate_time_ns_tree[iCrate] ;
209 double tcrate_unc = Crate_time_unc_ns_tree[iCrate];
210 if ((tcrate < m_tcrate_max_cut) &&
211 (tcrate > m_tcrate_min_cut) &&
212 (fabs(tcrate_unc) > m_tcrate_unc_min_cut) &&
213 (fabs(tcrate_unc) < m_tcrate_unc_max_cut)) {
214 double tcrystalCrate = crystalCrate_time_ns_tree[iCrate];
215 double tcrystalCrate_unc = crystalCrate_time_unc_ns_tree[iCrate];
216 allCrates_crate_times[iCrate].push_back(tcrate) ;
217 allCrates_run_nums[iCrate].push_back(m_run_perCrystal) ;
218 allCrates_time_unc[iCrate].push_back(tcrate_unc) ;
219 allCrates_crystalCrate_times[iCrate].push_back(tcrystalCrate) ;
220 allCrates_crystalCrate_times_unc[iCrate].push_back(tcrystalCrate_unc) ;
221
222 mean_crystalCrate_time_ns[iCrate] += tcrystalCrate ;
223
224 if (!savedThisRunNum) {
225 allRunNums.push_back(m_run_perCrystal);
226 savedThisRunNum = true;
227 }
228 }
229 }
230
231 //------------------------------------------------------------------------
233 for (int ic = 0; ic < m_numCrates; ic++) {
234 B2INFO("Crate " << ic + 1 << ", t_crate = " << Crate_time_tick_tree[ic] << " ticks = "
235 << Crate_time_ns_tree[ic] << " +- " << Crate_time_unc_ns_tree[ic]
236 << " ns; t crys+crate (no shifts) = " << crystalCrate_time_ns_tree[ic] << " +- "
237 << crystalCrate_time_unc_ns_tree[ic] << " ns") ;
238 }
239
240 previousRunNumTree = m_run_perCrystal;
241
242 }
243
244
245 B2INFO("Finished reading tree calibration constants. Now extracting here by stepping through runs.");
246
247
248
249
250
251 //------------------------------------------------------------------------
253
254
255 bool minRunNumBool = false;
256 bool maxRunNumBool = false;
257 int minRunNum = -1;
258 int maxRunNum = -1;
259 int minExpNum = -1;
260 int maxExpNum = -1;
261 for (auto expRun : getRunList()) {
262 int expNumber = expRun.first;
263 int runNumber = expRun.second;
264 if (!minRunNumBool) {
265 minExpNum = expNumber;
266 minRunNum = runNumber;
267 minRunNumBool = true;
268 }
269 if (!maxRunNumBool) {
270 maxExpNum = expNumber;
271 maxRunNum = runNumber;
272 maxRunNumBool = true;
273 }
274 if (((minRunNum > runNumber) && (minExpNum >= expNumber)) ||
275 (minExpNum > expNumber)) {
276 minExpNum = expNumber;
277 minRunNum = runNumber;
278 }
279 if (((maxRunNum < runNumber) && (maxExpNum <= expNumber)) ||
280 (maxExpNum < expNumber)) {
281 maxExpNum = expNumber;
282 maxRunNum = runNumber;
283 }
284 }
285
286 B2INFO("minExpNum = " << minExpNum) ;
287 B2INFO("minRunNum = " << minRunNum) ;
288 B2INFO("maxExpNum = " << maxExpNum) ;
289 B2INFO("maxRunNum = " << maxRunNum) ;
290
291
292 if (minExpNum != maxExpNum) {
293 B2ERROR("The runs must all come from the same experiment");
294 return c_Failure;
295 }
296
297 int experiment = minExpNum;
298
299
300 //------------------------------------------------------------------------
301 //------------------------------------------------------------------------
302 //------------------------------------------------------------------------
303 //------------------------------------------------------------------------
304 /* Extract out the time offset information from the database directly.
305 This method loops over all run numbers so it can more easily pick up
306 old payloads. It is not the preferred method to use if the payloads
307 have iov gaps.*/
308
310 //------------------------------------------------------------------------
311 // Get the input run list (should be only 1) for us to use to update the DBObjectPtrs
312 auto runs = getRunList();
313 /* Take the first run. For the crystal cosmic calibrations, because of the crate
314 calibrations, there is not a known correct run to use within the range. */
315 ExpRun chosenRun = runs.front();
316 B2INFO("merging using the ExpRun (" << chosenRun.second << "," << chosenRun.first << ")");
317 // After here your DBObjPtrs are correct
318 updateDBObjPtrs(1, chosenRun.second, chosenRun.first);
319
320 //------------------------------------------------------------------------
321 // Test the DBObjects we want to exist and fail if not all of them do.
322 bool allObjectsFound = true;
323
325 // Check that the payloads we want to merge are sufficiently loaded
327 allObjectsFound = false;
328 B2ERROR("No valid DBObject found for 'ECLCrystalTimeOffset'");
329 }
330
331 // Check that the crate payload is loaded (used for transforming cosmic payload)
333 allObjectsFound = false;
334 B2ERROR("No valid DBObject found for 'ECLCrateTimeOffset'");
335 }
336
338 allObjectsFound = false;
339 B2ERROR("No valid DBObject found for 'refCrysIDzeroingCrate'");
340 }
341
342
343 if (allObjectsFound) {
344 B2INFO("Valid objects found for 'ECLCrystalTimeOffset'");
345 B2INFO("Valid object found for 'ECLCrateTimeOffset'");
346 B2INFO("Valid object found for 'refCrysIDzeroingCrate'");
347 } else {
348 B2INFO("eclTimeShiftsAlgorithm: Exiting with failure. Some missing valid objects.");
349 return c_Failure;
350 }
351
352
353 //------------------------------------------------------------------------
355 vector<float> crystalCalib = m_ECLCrystalTimeOffset->getCalibVector();
356 B2INFO("Loaded 'ECLCrystalTimeOffset' calibrations");
357
358 vector<float> crateCalib = m_ECLCrateTimeOffset->getCalibVector();
359
360 B2INFO("Loaded 'ECLCrateTimeOffset' calibration with default exp/run");
361
362 B2INFO("eclTimeShiftsAlgorithm:: loaded ECLCrateTimeOffset from the database"
363 << LogVar("IoV", m_ECLCrateTimeOffset.getIoV())
364 << LogVar("Checksum", m_ECLCrateTimeOffset.getChecksum()));
365
366 for (int cellID = 1; cellID <= m_numCrystals; cellID += 511) {
367 B2INFO("crystalCalib = " << crystalCalib[cellID - 1]);
368 B2INFO("crateCalib = " << crateCalib[cellID - 1]);
369 }
370
371 vector<short> refCrystals = m_refCrysIDzeroingCrate->getReferenceCrystals();
372 for (int icrate = 0; icrate < m_numCrates; icrate++) {
373 B2INFO("reference crystal for crate " << icrate + 1 << " = " << refCrystals[icrate]);
374 }
375
376
377
378 //------------------------------------------------------------------------
380 for (int run = minRunNum; run <= maxRunNum; run++) {
381 B2INFO("---------") ;
382 B2INFO("Looking at run " << run) ;
383
384 vector<int>::iterator it = find(allRunNums.begin(), allRunNums.end(), run);
385 if (it != allRunNums.end()) {
386 int pos = it - allRunNums.begin() ;
387 B2INFO("allRunNums[" << pos << "] = " << allRunNums[pos]);
388 B2INFO("Run " << run << " already processed so skipping it.");
389 continue;
390 } else {
391 B2INFO("New run. Starting to extract information");
392 }
393
394 // Forloading database for a specific run
395 int eventNumberForCrates = 1;
396
397 StoreObjPtr<EventMetaData> evtPtr;
398 // simulate the initialize() phase where we can register objects in the DataStore
400 evtPtr.registerInDataStore();
402 // now construct the event metadata
403 evtPtr.construct(eventNumberForCrates, run, experiment);
404 // and update the database contents
405 DBStore& dbstore = DBStore::Instance();
406 dbstore.update();
407 // this is only needed it the payload might be intra-run dependent,
408 // that is if it might change during one run as well
409 dbstore.updateEvent();
410 updateDBObjPtrs(eventNumberForCrates, run, experiment);
411
412
413 //------------------------------------------------------------------------
415 shared_ptr< ECL::ECLChannelMapper > crystalMapper(new ECL::ECLChannelMapper()) ;
416 crystalMapper->initFromDB();
417
419 B2INFO("eclTimeShiftsAlgorithm:: loaded ECLCrystalTimeOffset from the database"
420 << LogVar("IoV", m_ECLCrystalTimeOffset.getIoV())
421 << LogVar("Checksum", m_ECLCrystalTimeOffset.getChecksum()));
422 B2INFO("eclTimeShiftsAlgorithm:: loaded ECLCrateTimeOffset from the database"
423 << LogVar("IoV", m_ECLCrateTimeOffset.getIoV())
424 << LogVar("Checksum", m_ECLCrateTimeOffset.getChecksum()));
425
426
427 //------------------------------------------------------------------------
429
430 vector<float> crystalTimeOffsetsCalib;
431 vector<float> crystalTimeOffsetsCalibUnc;
432 crystalTimeOffsetsCalib = m_ECLCrystalTimeOffset->getCalibVector();
433 crystalTimeOffsetsCalibUnc = m_ECLCrystalTimeOffset->getCalibUncVector();
434
435 vector<float> crateTimeOffsetsCalib;
436 vector<float> crateTimeOffsetsCalibUnc;
437 crateTimeOffsetsCalib = m_ECLCrateTimeOffset->getCalibVector();
438 crateTimeOffsetsCalibUnc = m_ECLCrateTimeOffset->getCalibUncVector();
439
440 //------------------------------------------------------------------------
444 vector<double> Crate_time_ns(m_numCrates) ;
445 vector<double> Crate_time_tick(m_numCrates) ;
446 vector<double> Crate_time_unc_ns(m_numCrates) ;
447 vector<double> crystalCrate_time_ns(m_numCrates);
448 vector<double> crystalCrate_time_unc_ns(m_numCrates);
449
450 for (int crysID = 1; crysID <= m_numCrystals; crysID++) {
451 int crateID_temp = crystalMapper->getCrateID(crysID) ;
452 Crate_time_ns[crateID_temp - 1] = crateTimeOffsetsCalib[crysID - 1] * TICKS_TO_NS ;
453 Crate_time_tick[crateID_temp - 1] = crateTimeOffsetsCalib[crysID - 1] ;
454 Crate_time_unc_ns[crateID_temp - 1] = crateTimeOffsetsCalibUnc[crysID - 1] * TICKS_TO_NS ;
455
456 if (crysID == refCrystals[crateID_temp - 1]) {
457 crystalCrate_time_ns[crateID_temp - 1] = (crystalTimeOffsetsCalib[crysID - 1] +
458 crateTimeOffsetsCalib[crysID - 1]) * TICKS_TO_NS;
459
460 crystalCrate_time_unc_ns[crateID_temp - 1] = TICKS_TO_NS * sqrt(
461 (crateTimeOffsetsCalibUnc[crysID - 1] * crateTimeOffsetsCalibUnc[crysID - 1]) +
462 (crystalTimeOffsetsCalibUnc[crysID - 1] * crystalTimeOffsetsCalibUnc[crysID - 1])) ;
463 }
464 }
465
466
467 for (int iCrate = 0; iCrate < m_numCrates; iCrate++) {
468 double tcrate = Crate_time_ns[iCrate] ;
469 double tcrate_unc = Crate_time_unc_ns[iCrate];
470 if ((tcrate < m_tcrate_max_cut) &&
471 (tcrate > m_tcrate_min_cut) &&
472 (fabs(tcrate_unc) > m_tcrate_unc_min_cut) &&
473 (fabs(tcrate_unc) < m_tcrate_unc_max_cut)) {
474 double tcrystalCrate = crystalCrate_time_ns[iCrate];
475 double tcrystalCrate_unc = crystalCrate_time_unc_ns[iCrate];
476 allCrates_crate_times[iCrate].push_back(tcrate) ;
477 allCrates_run_nums[iCrate].push_back(run) ;
478 allCrates_time_unc[iCrate].push_back(tcrate_unc) ;
479 allCrates_crystalCrate_times[iCrate].push_back(tcrystalCrate) ;
480 allCrates_crystalCrate_times_unc[iCrate].push_back(tcrystalCrate_unc) ;
481
482 mean_crystalCrate_time_ns[iCrate] += tcrystalCrate ;
483 }
484 }
485
486
487 //------------------------------------------------------------------------
489 for (int ic = 0; ic < m_numCrates; ic++) {
490 B2INFO("Crate " << ic + 1 << ", t_crate = " << Crate_time_tick[ic] << " ticks = "
491 << Crate_time_ns[ic] << " +- " << Crate_time_unc_ns[ic]
492 << " ns; t crys+crate (no shift) = " << crystalCrate_time_ns[ic] << " +- "
493 << crystalCrate_time_unc_ns[ic] << " ns") ;
494 }
495
496 /* Shift the run number to the end of the iov so that we can skip runs
497 that have the payload with the same revision number */
498 int IOV_exp_high = m_ECLCrateTimeOffset.getIoV().getExperimentHigh() ;
499 int IOV_run_high = m_ECLCrateTimeOffset.getIoV().getRunHigh() ;
500 B2INFO(LogVar("IOV_exp_high", IOV_exp_high));
501 B2INFO(LogVar("IOV_run_high", IOV_run_high));
502 if (IOV_run_high == -1) {
503 B2INFO("IOV_run_high is -1 so stop looping over all runs");
504 break;
505 } else {
506 B2INFO("Set run number to higher iov run number");
507 run = IOV_run_high;
508 }
509 B2INFO("now set run = " << run);
510 }
511 }
512
513
514
515
516 //------------------------------------------------------------------------
517 //------------------------------------------------------------------------
518 //------------------------------------------------------------------------
519 //------------------------------------------------------------------------
522 B2INFO("Shift all run crys+crate+off times. Show the results for a subset of crates/runs:");
523 for (int iCrate = 0; iCrate < m_numCrates; iCrate++) {
524 double mean_time = mean_crystalCrate_time_ns[iCrate] / allCrates_crate_times[iCrate].size() ;
525 B2INFO("Mean crys+crate times for all runs used as offset (crate " << iCrate + 1 << ") = " << mean_time);
526
527 for (long unsigned int jRun = 0; jRun < allCrates_crate_times[iCrate].size(); jRun++) {
528 allCrates_crystalCrate_times[iCrate][jRun] += -mean_time + timeShiftForPlotStyle[iCrate] ;
529 if (jRun < 50 || iCrate == 1 || iCrate == 40 || iCrate == 51) {
530 B2INFO("allCrates_crystalCrate_times(crate " << iCrate + 1 << ", run counter " << jRun + 1 << ", runNum " <<
531 allCrates_run_nums[iCrate][jRun] << " | after shifting mean) = " <<
532 allCrates_crystalCrate_times[iCrate][jRun]);
533 }
534 }
535 }
536
537
538
539 //------------------------------------------------------------------------
540 //------------------------------------------------------------------------
543 TFile* tcratefile = 0;
544
545 B2INFO("Debug output rootfile: " << debugFilenameBase);
546 string runNumsString = string("_") + to_string(minExpNum) + "_" + to_string(minRunNum) + string("-") +
547 to_string(maxExpNum) + "_" + to_string(maxRunNum);
548 string debugFilename = debugFilenameBase + runNumsString + string(".root");
549 TString fname = debugFilename;
550
551 tcratefile = new TFile(fname, "recreate");
552 tcratefile->cd();
553 B2INFO("Debugging histograms written to " << fname);
554
555 for (int i = 0; i < m_numCrates; i++) {
556 B2INFO("Starting to make crate time jump plots for crate " << i + 1);
557 shared_ptr< TCanvas > cSmart(new TCanvas);
558
559 Double_t* single_crate_crate_times = &allCrates_crate_times[i][0] ;
560 Double_t* single_crate_run_nums = &allCrates_run_nums[i][0] ;
561 Double_t* single_crate_time_unc = &allCrates_time_unc[i][0] ;
562 Double_t* single_crate_crystalCrate_times = &allCrates_crystalCrate_times[i][0] ;
563 Double_t* single_crate_crystalCrate_times_unc = &allCrates_crystalCrate_times_unc[i][0] ;
564 B2INFO("Done setting up the arrays for the crate " << i + 1);
565
566 ostringstream ss;
567 ss << setw(2) << setfill('0') << i + 1 ;
568 string paddedCrateID(ss.str());
569
570 // ----- crate time constants vs run number ------
571 shared_ptr< TGraphErrors > g_tcrate_vs_runNum(new TGraphErrors(allCrates_crate_times[i].size(), single_crate_run_nums,
572 single_crate_crate_times, NULL, single_crate_time_unc)) ;
573 // NULL for run number errors = 0 for all
574
575 string tgraph_title = string("e") + to_string(minExpNum) + string("r") + to_string(minRunNum) +
576 string("-e") + to_string(maxExpNum) + string("r") + to_string(maxRunNum) ;
577
578 string tgraph_name_short = "crateTimeVSrunNum_" ;
579 tgraph_name_short = tgraph_name_short + runNumsString + "_crate";
580
581 tgraph_title = tgraph_title + string("_crate") + paddedCrateID ;
582 tgraph_name_short = tgraph_name_short + paddedCrateID ;
583 tgraph_title = tgraph_title + string(" (") + to_string(m_tcrate_min_cut) + string(" < tcrate < ") +
584 to_string(m_tcrate_max_cut) + string(" ns, ") + to_string(m_tcrate_unc_min_cut) +
585 string(" < tcrate unc. < ") + to_string(m_tcrate_unc_max_cut) + string(" ns cuts)") ;
586
587 g_tcrate_vs_runNum->SetName(tgraph_name_short.c_str()) ;
588 g_tcrate_vs_runNum->SetTitle(tgraph_title.c_str()) ;
589 g_tcrate_vs_runNum->GetXaxis()->SetTitle("Run number") ;
590 g_tcrate_vs_runNum->GetYaxis()->SetTitle("Crate time [ns]") ;
591
592 g_tcrate_vs_runNum->GetYaxis()->SetRangeUser(m_tcrate_min_cut, m_tcrate_max_cut) ;
593
594 g_tcrate_vs_runNum->Draw("AP") ;
595 g_tcrate_vs_runNum->SetMarkerSize(0.8) ;
596 g_tcrate_vs_runNum->Draw("AP") ;
597
598 shared_ptr< TLatex > Leg1(new TLatex);
599 Leg1->SetNDC();
600 Leg1->SetTextAlign(11);
601 Leg1->SetTextFont(42);
602 Leg1->SetTextSize(0.035);
603 Leg1->SetTextColor(1);
604 Leg1->AppendPad();
605
606 g_tcrate_vs_runNum->Write() ;
607 cSmart->SaveAs((tgraph_name_short + string(".pdf")).c_str()) ;
608
609 B2INFO("Saved pdf: " << tgraph_name_short << ".pdf");
610
611
612 // ----- crystal + crate time constants + offset vs run number ------
613 shared_ptr< TGraphErrors > g_crateCrystalTime_vs_runNum(new TGraphErrors(allCrates_crystalCrate_times[i].size(),
614 single_crate_run_nums,
615 single_crate_crystalCrate_times, NULL, single_crate_crystalCrate_times_unc)) ;
616
617 tgraph_title = string("e") + to_string(minExpNum) + string("r") + to_string(minRunNum) +
618 string("-e") + to_string(maxExpNum) + string("r") + to_string(maxRunNum) ;
619
620 tgraph_name_short = "crystalCrateTimeVSrunNum_" ;
621 tgraph_name_short = tgraph_name_short + runNumsString + "_crate";
622
623 tgraph_title = tgraph_title + string("_crate") + paddedCrateID ;
624 tgraph_name_short = tgraph_name_short + paddedCrateID ;
625 tgraph_title = tgraph_title + string(" (") + to_string(m_tcrate_min_cut) + string(" < tcrate < ") +
626 to_string(m_tcrate_max_cut) + string(" ns, ") + to_string(m_tcrate_unc_min_cut) +
627 string(" < tcrate unc. < ") + to_string(m_tcrate_unc_max_cut) + string(" ns cuts)") ;
628
629
630 g_crateCrystalTime_vs_runNum->SetName(tgraph_name_short.c_str()) ;
631 g_crateCrystalTime_vs_runNum->SetTitle(tgraph_title.c_str()) ;
632 g_crateCrystalTime_vs_runNum->GetXaxis()->SetTitle("Run number") ;
633 g_crateCrystalTime_vs_runNum->GetYaxis()->SetTitle("Crate time + Crystal time + centring overall offset [ns]") ;
634
635 g_crateCrystalTime_vs_runNum->GetYaxis()->SetRangeUser(crysCrateShift_min, crysCrateShift_max) ;
636
637 g_crateCrystalTime_vs_runNum->Draw("AP") ;
638 g_crateCrystalTime_vs_runNum->SetMarkerSize(0.8) ;
639 g_crateCrystalTime_vs_runNum->Draw("AP") ;
640
641 g_crateCrystalTime_vs_runNum->Write() ;
642 cSmart->SaveAs((tgraph_name_short + string(".pdf")).c_str()) ;
643
644 B2INFO("Saved pdf: " << tgraph_name_short << ".pdf");
645
646 // ----- crystal + crate time constants + offset vs run counter------
647 // This will remove gaps and ignore the actual run number
648
649 /* Define a vector to store a renumbering of the run numbers, incrementing
650 by +1 so that there are no gaps. The runs are not in order so the
651 run numbers&indices first have to be sorted before the "run counter"
652 numbers can used.*/
653 int numRunsWithCrateTimes = allCrates_crystalCrate_times[i].size();
654 vector<Double_t> counterVec(numRunsWithCrateTimes);
655
656
657 // Vector to store element
658 // with respective present index
659 vector<pair<int, double> > runNum_index_pairs;
660
661 // Inserting element in pair vector
662 // to keep track of previous indexes
663 for (int pairIndex = 0; pairIndex < numRunsWithCrateTimes; pairIndex++) {
664 runNum_index_pairs.push_back(make_pair(allCrates_run_nums[i][pairIndex], pairIndex));
665 }
666
667 B2INFO("Crate id = " << i + 1);
668 B2INFO("Unsorted run numbers");
669 for (int runCounter = 0; runCounter < numRunsWithCrateTimes; runCounter++) {
670 B2INFO("Run number, run number vector index = " << runNum_index_pairs[runCounter].first << ", " <<
671 runNum_index_pairs[runCounter].second);
672 }
673
674 // Sorting pair vector
675 sort(runNum_index_pairs.begin(), runNum_index_pairs.end());
676
677 // Fill the run counter vector
678 for (int runCounter = 0; runCounter < numRunsWithCrateTimes; runCounter++) {
679 counterVec[runNum_index_pairs[runCounter].second] = runCounter + 1;
680 }
681
682 B2INFO("Run numbers with index and times");
683 for (int runCounter = 0; runCounter < numRunsWithCrateTimes; runCounter++) {
684 int idx = (int) round(counterVec[runCounter]);
685 B2INFO("Vector index, Run number, run number sorting order index, tcrystal+tcrate+shifts = " << runCounter << ", " <<
686 allCrates_run_nums[i][runCounter] << ", " << idx << ", " << single_crate_crystalCrate_times[idx - 1] << " ns");
687 }
688
689
690 if (numRunsWithCrateTimes > 0) {
691 shared_ptr< TGraphErrors > g_crateCrystalTime_vs_runCounter(new TGraphErrors(numRunsWithCrateTimes, &counterVec[0],
692 single_crate_crystalCrate_times, NULL, single_crate_crystalCrate_times_unc)) ;
693
694 tgraph_title = string("e") + to_string(minExpNum) + string("r") + to_string(minRunNum) +
695 string("-e") + to_string(maxExpNum) + string("r") + to_string(maxRunNum) ;
696
697
698 tgraph_name_short = "crystalCrateTimeVSrunCounter_" ;
699 tgraph_name_short = tgraph_name_short + runNumsString + "_crate";
700
701
702 tgraph_title = tgraph_title + string("_crate") + paddedCrateID ;
703 tgraph_name_short = tgraph_name_short + paddedCrateID ;
704 tgraph_title = tgraph_title + string(" (") + to_string(m_tcrate_min_cut) + string(" < tcrate < ") +
705 to_string(m_tcrate_max_cut) + string(" ns, ") + to_string(m_tcrate_unc_min_cut) +
706 string(" < tcrate unc. < ") + to_string(m_tcrate_unc_max_cut) + string(" ns cuts)") ;
707
708
709 g_crateCrystalTime_vs_runCounter->SetName(tgraph_name_short.c_str()) ;
710 g_crateCrystalTime_vs_runCounter->SetTitle(tgraph_title.c_str()) ;
711 g_crateCrystalTime_vs_runCounter->GetXaxis()->SetTitle("Run counter (remove gaps from run numbers)") ;
712 g_crateCrystalTime_vs_runCounter->GetYaxis()->SetTitle("Crate time + Crystal time + centring overall offset [ns]") ;
713
714 g_crateCrystalTime_vs_runCounter->GetYaxis()->SetRangeUser(crysCrateShift_min, crysCrateShift_max) ;
715 g_crateCrystalTime_vs_runCounter->GetXaxis()->SetRangeUser(0, numRunsWithCrateTimes + 1) ;
716
717 g_crateCrystalTime_vs_runCounter->Draw("AP") ;
718 g_crateCrystalTime_vs_runCounter->SetMarkerSize(0.8) ;
719 g_crateCrystalTime_vs_runCounter->Draw("AP") ;
720
721 g_crateCrystalTime_vs_runCounter->Write() ;
722 cSmart->SaveAs((tgraph_name_short + string(".pdf")).c_str()) ;
723 B2INFO("Saved pdf: " << tgraph_name_short << ".pdf");
724
725 B2INFO("Finished making crate time jump plots for crate " << i + 1);
726 } else {
727 B2INFO("Crate " << i + 1 << " has no entries that pass all the cuts so no crystalCrateTimeVSrunCounter_crate plot will be made.");
728 }
729 }
730
731
732
733
734 /* Loop over all the runs and crates and let the user know when a crate time jump
735 has occurred. Jumps can be of various sizes so have different thresholds. */
736 double smallThreshold = 1 ; //ns
737 double largeThreshold = 6.5 ; //ns
738
739 B2INFO("======================= Crate time jumps =========================");
740 B2INFO("======================= Small threshold jumps ====================");
741 B2INFO("Crate ID = 1..52");
742 B2INFO("==================================================================");
743
744 for (int i = 0; i < m_numCrates; i++) {
745 int numRunsWithCrateTimes = allCrates_crystalCrate_times[i].size();
746 for (int runCounter = 0; runCounter < numRunsWithCrateTimes - 1; runCounter++) {
747 int run_i = allCrates_run_nums[i][runCounter] ;
748 int run_f = allCrates_run_nums[i][runCounter + 1] ;
749 double time_i = allCrates_crystalCrate_times[i][runCounter] ;
750 double time_f = allCrates_crystalCrate_times[i][runCounter + 1] ;
751
752 if (fabs(time_f - time_i) > smallThreshold) {
753 B2INFO("Crate " << i + 1 << " has crate time jump > " << smallThreshold << " ns: t(run " << run_f << ") = " << time_f <<
754 " ns - t(run " << run_i << ") = " << time_i << " ns = " << time_f - time_i);
755 }
756 }
757 }
758
759
760 B2INFO("~~~~~~~~~~~~~~~~~~~~~~~ Large threshold jumps ~~~~~~~~~~~~~~~~~~~~");
761 B2INFO("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
762
763 for (int i = 0; i < m_numCrates; i++) {
764 int numRunsWithCrateTimes = allCrates_crystalCrate_times[i].size();
765 for (int runCounter = 0; runCounter < numRunsWithCrateTimes - 1; runCounter++) {
766 int run_i = allCrates_run_nums[i][runCounter] ;
767 int run_f = allCrates_run_nums[i][runCounter + 1] ;
768 double time_i = allCrates_crystalCrate_times[i][runCounter] ;
769 double time_f = allCrates_crystalCrate_times[i][runCounter + 1] ;
770
771 if (fabs(time_f - time_i) > largeThreshold) {
772 B2INFO("WARNING: Crate " << i + 1 << " has crate time jump > " << largeThreshold << " ns: t(run " << run_f << ") = " << time_f <<
773 " ns - t(run " << run_i << ") = " << time_i << " ns = " << time_f - time_i);
774 }
775 }
776 }
777
778
779
780
781 // Just in case, we remember the current TDirectory so we can return to it
782 TDirectory* executeDir = gDirectory;
783
784 tcratefile->Write();
785 tcratefile->Close();
786 // Go back to original TDirectory
787 executeDir->cd();
788
789 return c_OK;
790}
static void updateDBObjPtrs(const unsigned int event, const int run, const int experiment)
Updates any DBObjPtrs by calling update(event) for DBStore.
const std::vector< Calibration::ExpRun > & getRunList() const
Get the list of runs for which calibration is called.
@ c_OK
Finished successfully =0 in Python.
static DataStore & Instance()
Instance of singleton Store.
Definition DataStore.cc:53
void setInitializeActive(bool active)
Setter for m_initializeActive.
Definition DataStore.cc:93
static double getRF()
See m_rf.
Double_t m_crateTimeConst
Crate time calibration constant.
double m_tcrate_unc_min_cut
Minimum value cut for the crate time calibration constant uncertainty for plotting.
const int m_numCrates
Number of Crates expected.
double m_tcrate_max_cut
Maximum value cut for the crate time calibration constant for plotting.
double m_tcrate_min_cut
Minimum value cut for the crate time calibration constant for plotting.
const int m_numCrystals
Number of Crystals expected.
Double_t m_crystalTimeUnc
Uncertainty on the crystal time calibration constant.
Double_t m_crateTimeUnc
Uncertainty on the crate time calibration constant.
double m_tcrate_unc_max_cut
Maximum value cut for the crate time calibration constant uncertainty for plotting.
Double_t m_crystalTimeConst
Crystal time calibration constant.
Int_t m_refCrystalID
Crystal ID number for the reference crystal.
bool registerInDataStore(DataStore::EStoreFlags storeFlags=DataStore::c_WriteOut)
Register the object/array in the DataStore.
bool construct(Args &&... params)
Construct an object of type T in this StoreObjPtr, using the provided constructor arguments.
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 t...
static DBStore & Instance()
Instance of a singleton DBStore.
Definition DBStore.cc:26
void updateEvent()
Updates all intra-run dependent objects.
Definition DBStore.cc:140
void update()
Updates all objects that are outside their interval of validity.
Definition DBStore.cc:77
double sqrt(double a)
sqrt for double
Definition beamHelpers.h:28
const int c_NCrystals
Number of crystals.

◆ checkPyExpRun()

bool checkPyExpRun ( PyObject * pyObj)
staticinherited

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.

29{
30 // Is it a sequence?
31 if (PySequence_Check(pyObj)) {
32 Py_ssize_t nObj = PySequence_Length(pyObj);
33 // Does it have 2 objects in it?
34 if (nObj != 2) {
35 B2DEBUG(29, "ExpRun was a Python sequence which didn't have exactly 2 entries!");
36 return false;
37 }
38 PyObject* item1, *item2;
39 item1 = PySequence_GetItem(pyObj, 0);
40 item2 = PySequence_GetItem(pyObj, 1);
41 // Did the GetItem work?
42 if ((item1 == NULL) || (item2 == NULL)) {
43 B2DEBUG(29, "A PyObject pointer was NULL in the sequence");
44 return false;
45 }
46 // Are they longs?
47 if (PyLong_Check(item1) && PyLong_Check(item2)) {
48 long value1, value2;
49 value1 = PyLong_AsLong(item1);
50 value2 = PyLong_AsLong(item2);
51 if (((value1 == -1) || (value2 == -1)) && PyErr_Occurred()) {
52 B2DEBUG(29, "An error occurred while converting the PyLong to long");
53 return false;
54 }
55 } else {
56 B2DEBUG(29, "One or more of the PyObjects in the ExpRun wasn't a long");
57 return false;
58 }
59 // Make sure to kill off the reference GetItem gave us responsibility for
60 Py_DECREF(item1);
61 Py_DECREF(item2);
62 } else {
63 B2DEBUG(29, "ExpRun was not a Python sequence.");
64 return false;
65 }
66 return true;
67}

◆ clearCalibrationData()

void clearCalibrationData ( )
inlineprotectedinherited

Clear calibration data.

Definition at line 324 of file CalibrationAlgorithm.h.

324{m_data.clearCalibrationData();}

◆ commit() [1/2]

bool commit ( )
inherited

Submit constants from last calibration into database.

Definition at line 302 of file CalibrationAlgorithm.cc.

303{
304 if (getPayloads().empty())
305 return false;
306 list<Database::DBImportQuery> payloads = getPayloads();
307 B2INFO("Committing " << payloads.size() << " payloads to database.");
308 return Database::Instance().storeData(payloads);
309}
std::list< Database::DBImportQuery > & getPayloads()
Get constants (in TObjects) for database update from last execution.
static Database & Instance()
Instance of a singleton Database.
Definition Database.cc:42
bool storeData(const std::string &name, TObject *object, const IntervalOfValidity &iov)
Store an object in the database.
Definition Database.cc:141

◆ commit() [2/2]

bool commit ( std::list< Database::DBImportQuery > payloads)
inherited

Submit constants from a (potentially previous) set of payloads.

Definition at line 312 of file CalibrationAlgorithm.cc.

313{
314 if (payloads.empty())
315 return false;
316 return Database::Instance().storeData(payloads);
317}

◆ convertPyExpRun()

ExpRun convertPyExpRun ( PyObject * pyObj)
staticinherited

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.

71{
72 ExpRun expRun;
73 PyObject* itemExp, *itemRun;
74 itemExp = PySequence_GetItem(pyObj, 0);
75 itemRun = PySequence_GetItem(pyObj, 1);
76 expRun.first = PyLong_AsLong(itemExp);
77 Py_DECREF(itemExp);
78 expRun.second = PyLong_AsLong(itemRun);
79 Py_DECREF(itemRun);
80 return expRun;
81}

◆ dumpOutputJson()

const std::string dumpOutputJson ( ) const
inlineinherited

Dump the JSON string of the output JSON object.

Definition at line 223 of file CalibrationAlgorithm.h.

223{return m_jsonExecutionOutput.dump();}

◆ execute() [1/2]

CalibrationAlgorithm::EResult execute ( PyObject * runs,
int iteration = 0,
IntervalOfValidity iov = IntervalOfValidity() )
inherited

Runs calibration over Python list of runs. Converts to C++ and then calls the other execute() function.

Definition at line 83 of file CalibrationAlgorithm.cc.

84{
85 B2DEBUG(29, "Running execute() using Python Object as input argument");
86 // Reset the execution specific data in case the algorithm was previously called
87 m_data.reset();
88 m_data.setIteration(iteration);
89 vector<ExpRun> vecRuns;
90 // Is it a list?
91 if (PySequence_Check(runs)) {
92 boost::python::handle<> handle(boost::python::borrowed(runs));
93 boost::python::list listRuns(handle);
94
95 int nList = boost::python::len(listRuns);
96 for (int iList = 0; iList < nList; ++iList) {
97 boost::python::object pyExpRun(listRuns[iList]);
98 if (!checkPyExpRun(pyExpRun.ptr())) {
99 B2ERROR("Received Python ExpRuns couldn't be converted to C++");
100 m_data.setResult(c_Failure);
101 return c_Failure;
102 } else {
103 vecRuns.push_back(convertPyExpRun(pyExpRun.ptr()));
104 }
105 }
106 } else {
107 B2ERROR("Tried to set the input runs but we didn't receive a Python sequence object (list,tuple).");
108 m_data.setResult(c_Failure);
109 return c_Failure;
110 }
111 return execute(vecRuns, iteration, iov);
112}
static bool checkPyExpRun(PyObject *pyObj)
Checks that a PyObject can be successfully converted to an ExpRun type.
EResult execute(std::vector< Calibration::ExpRun > runs={}, int iteration=0, IntervalOfValidity iov=IntervalOfValidity())
Runs calibration over vector of runs for a given iteration.
static Calibration::ExpRun convertPyExpRun(PyObject *pyObj)
Performs the conversion of PyObject to ExpRun.
ExecutionData m_data
Data specific to a SINGLE execution of the algorithm. Gets reset at the beginning of execution.

◆ execute() [2/2]

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.

115{
116 // Check if we are calling this function directly and need to reset, or through Python where it was already done.
117 if (m_data.getResult() != c_Undefined) {
118 m_data.reset();
119 m_data.setIteration(iteration);
120 }
121
122 if (m_inputFileNames.empty()) {
123 B2ERROR("There aren't any input files set. Please use CalibrationAlgorithm::setInputFiles()");
124 m_data.setResult(c_Failure);
125 return c_Failure;
126 }
127
128 // Did we receive runs to execute over explicitly?
129 if (!(runs.empty())) {
130 for (auto expRun : runs) {
131 B2DEBUG(29, "ExpRun requested = (" << expRun.first << ", " << expRun.second << ")");
132 }
133 // We've asked explicitly for certain runs, but we should check if the data granularity is 'run'
134 if (strcmp(getGranularity().c_str(), "all") == 0) {
135 B2ERROR(("The data is collected with granularity=all (exp=-1,run=-1), but you seem to request calibration for specific runs."
136 " We'll continue but using ALL the input data given instead of the specific runs requested."));
137 }
138 } else {
139 // If no runs are provided, infer the runs from all collected data
140 runs = getRunListFromAllData();
141 // Let's check that we have some now
142 if (runs.empty()) {
143 B2ERROR("No collected data in input files.");
144 m_data.setResult(c_Failure);
145 return c_Failure;
146 }
147 for (auto expRun : runs) {
148 B2DEBUG(29, "ExpRun requested = (" << expRun.first << ", " << expRun.second << ")");
149 }
150 }
151
152 m_data.setRequestedRuns(runs);
153 if (iov.empty()) {
154 // If no user specified IoV we use the IoV from the executed run list
155 iov = IntervalOfValidity(runs[0].first, runs[0].second, runs[runs.size() - 1].first, runs[runs.size() - 1].second);
156 }
157 m_data.setRequestedIov(iov);
158 // After here, the getObject<...>(...) helpers start to work
159
161 m_data.setResult(result);
162 return result;
163}
std::vector< Calibration::ExpRun > getRunListFromAllData() const
Get the complete list of runs from inspection of collected data.
std::vector< std::string > m_inputFileNames
List of input files to the Algorithm, will initially be user defined but then gets the wildcards expa...
EResult
The result of calibration.
@ c_Undefined
Not yet known (before execution) =4 in Python.
const std::string & getGranularity() const
Get the granularity of collected data.
virtual EResult calibrate()=0
Run algo on data - pure virtual: needs to be implemented.

◆ fillRunToInputFilesMap()

void fillRunToInputFilesMap ( )
inherited

Fill the mapping of ExpRun -> Files.

Definition at line 331 of file CalibrationAlgorithm.cc.

332{
333 m_runsToInputFiles.clear();
334 // Save TDirectory to change back at the end
335 TDirectory* dir = gDirectory;
336 RunRange* runRange;
337 // Construct the TDirectory name where we expect our objects to be
338 string runRangeObjName(getPrefix() + "/" + RUN_RANGE_OBJ_NAME);
339 for (const auto& fileName : m_inputFileNames) {
340 //Open TFile to get the objects
341 unique_ptr<TFile> f;
342 f.reset(TFile::Open(fileName.c_str(), "READ"));
343 runRange = dynamic_cast<RunRange*>(f->Get(runRangeObjName.c_str()));
344 if (runRange) {
345 // Insert or extend the run -> file mapping for this ExpRun
346 auto expRuns = runRange->getExpRunSet();
347 for (const auto& expRun : expRuns) {
348 auto runFiles = m_runsToInputFiles.find(expRun);
349 if (runFiles != m_runsToInputFiles.end()) {
350 (runFiles->second).push_back(fileName);
351 } else {
352 m_runsToInputFiles.insert(std::make_pair(expRun, std::vector<std::string> {fileName}));
353 }
354 }
355 } else {
356 B2WARNING("Missing a RunRange object for file: " << fileName);
357 }
358 }
359 dir->cd();
360}
const std::string & getPrefix() const
Get the prefix used for getting calibration data.
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 setti...
const std::set< Calibration::ExpRun > & getExpRunSet()
Get access to the stored set.
Definition RunRange.h:64

◆ findPayloadBoundaries()

const std::vector< ExpRun > findPayloadBoundaries ( std::vector< Calibration::ExpRun > runs,
int iteration = 0 )
inherited

Used to discover the ExpRun boundaries that you want the Python CAF to execute on. This is optional and only used in some.

Definition at line 521 of file CalibrationAlgorithm.cc.

522{
523 m_boundaries.clear();
524 if (m_inputFileNames.empty()) {
525 B2ERROR("There aren't any input files set. Please use CalibrationAlgorithm::setInputFiles()");
526 return m_boundaries;
527 }
528 // Reset the internal execution data just in case something is hanging around
529 m_data.reset();
530 if (runs.empty()) {
531 // Want to loop over all runs we could possibly know about
532 runs = getRunListFromAllData();
533 }
534 // Let's check that we have some now
535 if (runs.empty()) {
536 B2ERROR("No collected data in input files.");
537 return m_boundaries;
538 }
539 // In order to find run boundaries we must have collected with data granularity == 'run'
540 if (strcmp(getGranularity().c_str(), "all") == 0) {
541 B2ERROR("The data is collected with granularity='all' (exp=-1,run=-1), and we can't use that to find run boundaries.");
542 return m_boundaries;
543 }
544 m_data.setIteration(iteration);
545 // User defined setup function
546 boundaryFindingSetup(runs, iteration);
547 std::vector<ExpRun> runList;
548 // Loop over run list and call derived class "isBoundaryRequired" member function
549 for (auto currentRun : runs) {
550 runList.push_back(currentRun);
551 m_data.setRequestedRuns(runList);
552 // After here, the getObject<...>(...) helpers start to work
553 if (isBoundaryRequired(currentRun)) {
554 m_boundaries.push_back(currentRun);
555 }
556 // Only want run-by-run
557 runList.clear();
558 // Don't want memory hanging around
559 m_data.clearCalibrationData();
560 }
561 m_data.reset();
563 return m_boundaries;
564}
std::vector< Calibration::ExpRun > m_boundaries
When using the boundaries functionality from isBoundaryRequired, this is used to store the boundaries...
virtual void boundaryFindingTearDown()
Put your algorithm back into a state ready for normal execution if you need to.
virtual void boundaryFindingSetup(std::vector< Calibration::ExpRun >, int)
If you need to make some changes to your algorithm class before 'findPayloadBoundaries' is run,...
virtual bool isBoundaryRequired(const Calibration::ExpRun &)
Given the current collector data, make a decision about whether or not this run should be the start o...

◆ getAllGranularityExpRun()

static Calibration::ExpRun getAllGranularityExpRun ( )
inlinestaticprotectedinherited

Returns the Exp,Run pair that means 'Everything'. Currently unused.

Definition at line 327 of file CalibrationAlgorithm.h.

327{return m_allExpRun;}

◆ getCollectorName()

const 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 algorithm.

Definition at line 164 of file CalibrationAlgorithm.h.

164{return getPrefix();}

◆ getDescription()

const std::string & getDescription ( ) const
inlineinherited

Get the description of the algorithm (set by developers in constructor)

Definition at line 216 of file CalibrationAlgorithm.h.

216{return m_description;}

◆ getExpRunString()

string getExpRunString ( Calibration::ExpRun & expRun) const
privateinherited

Gets the "exp.run" string repr. of (exp,run)

Definition at line 254 of file CalibrationAlgorithm.cc.

255{
256 string expRunString;
257 expRunString += to_string(expRun.first);
258 expRunString += ".";
259 expRunString += to_string(expRun.second);
260 return expRunString;
261}

◆ getFullObjectPath()

string getFullObjectPath ( const std::string & name,
Calibration::ExpRun expRun ) const
privateinherited

constructs the full TDirectory + Key name of an object in a TFile based on its name and exprun

Definition at line 263 of file CalibrationAlgorithm.cc.

264{
265 string dirName = getPrefix() + "/" + name;
266 string objName = name + "_" + getExpRunString(expRun);
267 return dirName + "/" + objName;
268}
std::string getExpRunString(Calibration::ExpRun &expRun) const
Gets the "exp.run" string repr. of (exp,run)

◆ getGranularity()

const std::string & getGranularity ( ) const
inlineinherited

Get the granularity of collected data.

Definition at line 188 of file CalibrationAlgorithm.h.

188{return m_granularityOfData;};

◆ getGranularityFromData()

string getGranularityFromData ( ) const
protectedinherited

Get the granularity of collected data.

Definition at line 384 of file CalibrationAlgorithm.cc.

385{
386 // Save TDirectory to change back at the end
387 TDirectory* dir = gDirectory;
388 const RunRange* runRange;
389 string runRangeObjName(getPrefix() + "/" + RUN_RANGE_OBJ_NAME);
390 // We only check the first file
391 string fileName = m_inputFileNames[0];
392 unique_ptr<TFile> f;
393 f.reset(TFile::Open(fileName.c_str(), "READ"));
394 runRange = dynamic_cast<RunRange*>(f->Get(runRangeObjName.c_str()));
395 if (!runRange) {
396 B2FATAL("The input file " << fileName << " does not contain a RunRange object at "
397 << runRangeObjName << ". Please set your input files to exclude it.");
398 return "";
399 }
400 string granularity = runRange->getGranularity();
401 dir->cd();
402 return granularity;
403}
const std::string & getGranularity() const
Gets the m_granularity.
Definition RunRange.h:110

◆ getInputFileNames()

PyObject * getInputFileNames ( )
inherited

Get the input file names used for this algorithm and pass them out as a Python list of unicode strings.

Definition at line 245 of file CalibrationAlgorithm.cc.

246{
247 PyObject* objInputFileNames = PyList_New(m_inputFileNames.size());
248 for (size_t i = 0; i < m_inputFileNames.size(); ++i) {
249 PyList_SetItem(objInputFileNames, i, Py_BuildValue("s", m_inputFileNames[i].c_str()));
250 }
251 return objInputFileNames;
252}

◆ getInputJsonObject()

const nlohmann::json & getInputJsonObject ( ) const
inlineprotectedinherited

Get the entire top level JSON object. We explicitly say this must be of object type so that we might pick.

Definition at line 357 of file CalibrationAlgorithm.h.

357{return m_jsonExecutionInput;}

◆ getInputJsonValue()

template<class T>
const T getInputJsonValue ( const std::string & key) const
inlineprotectedinherited

Get an input JSON value using a key. The normal exceptions are raised when the key doesn't exist.

Definition at line 350 of file CalibrationAlgorithm.h.

351 {
352 return m_jsonExecutionInput.at(key);
353 }

◆ getIovFromAllData()

IntervalOfValidity getIovFromAllData ( ) const
inherited

Get the complete IoV from inspection of collected data.

Definition at line 326 of file CalibrationAlgorithm.cc.

327{
329}
RunRange getRunRangeFromAllData() const
Get the complete RunRange from inspection of collected data.
IntervalOfValidity getIntervalOfValidity()
Make IntervalOfValidity from the set, spanning all runs. Works because sets are sorted by default.
Definition RunRange.h:70

◆ getIteration()

int getIteration ( ) const
inlineprotectedinherited

Get current iteration.

Definition at line 269 of file CalibrationAlgorithm.h.

269{ return m_data.getIteration(); }

◆ getObjectPtr()

template<class T>
std::shared_ptr< T > getObjectPtr ( std::string name)
inlineprotectedinherited

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.

Definition at line 285 of file CalibrationAlgorithm.h.

286 {
287 if (m_runsToInputFiles.size() == 0)
288 fillRunToInputFilesMap();
289 return getObjectPtr<T>(name, m_data.getRequestedRuns());
290 }

◆ getOutputJsonValue()

template<class T>
const T getOutputJsonValue ( const std::string & key) const
inlineprotectedinherited

Get a value using a key from the JSON output object, not sure why you would want to do this.

Definition at line 342 of file CalibrationAlgorithm.h.

343 {
344 return m_jsonExecutionOutput.at(key);
345 }

◆ getPayloads()

std::list< Database::DBImportQuery > & getPayloads ( )
inlineinherited

Get constants (in TObjects) for database update from last execution.

Definition at line 204 of file CalibrationAlgorithm.h.

204{return m_data.getPayloads();}

◆ getPayloadValues()

std::list< Database::DBImportQuery > getPayloadValues ( ) const
inlineinherited

Get constants (in TObjects) for database update from last execution but passed by VALUE.

Definition at line 207 of file CalibrationAlgorithm.h.

207{return m_data.getPayloadValues();}

◆ getPrefix()

const std::string & getPrefix ( ) const
inlineinherited

Get the prefix used for getting calibration data.

Definition at line 146 of file CalibrationAlgorithm.h.

146{return m_prefix;}

◆ getRunList()

const std::vector< Calibration::ExpRun > & getRunList ( ) const
inlineprotectedinherited

Get the list of runs for which calibration is called.

Definition at line 266 of file CalibrationAlgorithm.h.

266{return m_data.getRequestedRuns();}

◆ getRunListFromAllData()

vector< ExpRun > getRunListFromAllData ( ) const
inherited

Get the complete list of runs from inspection of collected data.

Definition at line 319 of file CalibrationAlgorithm.cc.

320{
321 RunRange runRange = getRunRangeFromAllData();
322 set<ExpRun> expRunSet = runRange.getExpRunSet();
323 return vector<ExpRun>(expRunSet.begin(), expRunSet.end());
324}

◆ getRunRangeFromAllData()

RunRange getRunRangeFromAllData ( ) const
inherited

Get the complete RunRange from inspection of collected data.

Definition at line 362 of file CalibrationAlgorithm.cc.

363{
364 // Save TDirectory to change back at the end
365 TDirectory* dir = gDirectory;
366 RunRange runRange;
367 // Construct the TDirectory name where we expect our objects to be
368 string runRangeObjName(getPrefix() + "/" + RUN_RANGE_OBJ_NAME);
369 for (const auto& fileName : m_inputFileNames) {
370 //Open TFile to get the objects
371 unique_ptr<TFile> f;
372 f.reset(TFile::Open(fileName.c_str(), "READ"));
373 const RunRange* runRangeOther = dynamic_cast<RunRange*>(f->Get(runRangeObjName.c_str()));
374 if (runRangeOther) {
375 runRange.merge(runRangeOther);
376 } else {
377 B2WARNING("Missing a RunRange object for file: " << fileName);
378 }
379 }
380 dir->cd();
381 return runRange;
382}
virtual void merge(const RunRange *other)
Implementation of merging - other is added to the set (union)
Definition RunRange.h:52

◆ getVecInputFileNames()

const std::vector< std::string > & getVecInputFileNames ( ) const
inlineprotectedinherited

Get the input file names used for this algorithm as a STL vector.

Definition at line 275 of file CalibrationAlgorithm.h.

275{return m_inputFileNames;}

◆ inputJsonKeyExists()

bool inputJsonKeyExists ( const std::string & key) const
inlineprotectedinherited

Test for a key in the input JSON object.

Definition at line 360 of file CalibrationAlgorithm.h.

360{return m_jsonExecutionInput.count(key);}

◆ isBoundaryRequired()

virtual bool isBoundaryRequired ( const Calibration::ExpRun & )
inlineprotectedvirtualinherited

Given the current collector data, make a decision about whether or not this run should be the start of a payload boundary.

Reimplemented in PXDAnalyticGainCalibrationAlgorithm, PXDValidationAlgorithm, SVD3SampleCoGTimeCalibrationAlgorithm, SVD3SampleELSTimeCalibrationAlgorithm, SVDClusterAbsoluteTimeShifterAlgorithm, SVDCoGTimeCalibrationAlgorithm, TestBoundarySettingAlgorithm, and TestCalibrationAlgorithm.

Definition at line 243 of file CalibrationAlgorithm.h.

244 {
245 B2ERROR("You didn't implement a isBoundaryRequired() member function in your CalibrationAlgorithm but you are calling it!");
246 return false;
247 }

◆ loadInputJson()

bool loadInputJson ( const std::string & jsonString)
inherited

Load the m_inputJson variable from a string (useful from Python interface). The return bool indicates success or failure.

Definition at line 503 of file CalibrationAlgorithm.cc.

504{
505 try {
506 auto jsonInput = nlohmann::json::parse(jsonString);
507 // Input string has an object (dict) as the top level object?
508 if (jsonInput.is_object()) {
509 m_jsonExecutionInput = jsonInput;
510 return true;
511 } else {
512 B2ERROR("JSON input string isn't an object type i.e. not a '{}' at the top level.");
513 return false;
514 }
515 } catch (nlohmann::json::parse_error&) {
516 B2ERROR("Parsing of JSON input string failed");
517 return false;
518 }
519}
nlohmann::json m_jsonExecutionInput
Optional input JSON object used to make decisions about how to execute the algorithm code.

◆ resetInputJson()

void resetInputJson ( )
inlineprotectedinherited

Clears the m_inputJson member variable.

Definition at line 330 of file CalibrationAlgorithm.h.

330{m_jsonExecutionInput.clear();}

◆ resetOutputJson()

void resetOutputJson ( )
inlineprotectedinherited

Clears the m_outputJson member variable.

Definition at line 333 of file CalibrationAlgorithm.h.

333{m_jsonExecutionOutput.clear();}

◆ saveCalibration() [1/6]

void saveCalibration ( TClonesArray * data,
const std::string & name )
protectedinherited

Store DBArray payload with given name with default IOV.

Definition at line 297 of file CalibrationAlgorithm.cc.

298{
299 saveCalibration(data, name, m_data.getRequestedIov());
300}
void saveCalibration(TClonesArray *data, const std::string &name)
Store DBArray payload with given name with default IOV.

◆ saveCalibration() [2/6]

void saveCalibration ( TClonesArray * data,
const std::string & name,
const IntervalOfValidity & iov )
protectedinherited

Store DBArray with given name and custom IOV.

Definition at line 276 of file CalibrationAlgorithm.cc.

277{
278 B2DEBUG(29, "Saving calibration TClonesArray '" << name << "' to payloads list.");
279 getPayloads().emplace_back(name, data, iov);
280}

◆ saveCalibration() [3/6]

void saveCalibration ( TObject * data)
protectedinherited

Store DB payload with default name and default IOV.

Definition at line 287 of file CalibrationAlgorithm.cc.

288{
289 saveCalibration(data, DataStore::objectName(data->IsA(), ""));
290}
static std::string objectName(const TClass *t, const std::string &name)
Return the storage name for an object of the given TClass and name.
Definition DataStore.cc:150

◆ saveCalibration() [4/6]

void saveCalibration ( TObject * data,
const IntervalOfValidity & iov )
protectedinherited

Store DB payload with default name and custom IOV.

Definition at line 282 of file CalibrationAlgorithm.cc.

283{
284 saveCalibration(data, DataStore::objectName(data->IsA(), ""), iov);
285}

◆ saveCalibration() [5/6]

void saveCalibration ( TObject * data,
const std::string & name )
protectedinherited

Store DB payload with given name with default IOV.

Definition at line 292 of file CalibrationAlgorithm.cc.

293{
294 saveCalibration(data, name, m_data.getRequestedIov());
295}

◆ saveCalibration() [6/6]

void saveCalibration ( TObject * data,
const std::string & name,
const IntervalOfValidity & iov )
protectedinherited

Store DB payload with given name and custom IOV.

Definition at line 270 of file CalibrationAlgorithm.cc.

271{
272 B2DEBUG(29, "Saving calibration TObject = '" << name << "' to payloads list.");
273 getPayloads().emplace_back(name, data, iov);
274}

◆ setDescription()

void setDescription ( const std::string & description)
inlineprotectedinherited

Set algorithm description (in constructor)

Definition at line 321 of file CalibrationAlgorithm.h.

321{m_description = description;}

◆ setInputFileNames() [1/2]

void setInputFileNames ( const 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.

195{
196 // A lot of code below is tweaked from RootInputModule::initialize,
197 // since we're basically copying the functionality anyway.
198 if (inputFileNames.empty()) {
199 B2WARNING("You have called setInputFileNames() with an empty list. Did you mean to do that?");
200 return;
201 }
202 auto tmpInputFileNames = RootIOUtilities::expandWordExpansions(inputFileNames);
203
204 // We'll use a set to enforce sorted unique file paths as we check them
205 set<string> setInputFileNames;
206 // Check that files exist and convert to absolute paths
207 for (auto path : tmpInputFileNames) {
208 string fullPath = fs::absolute(path).string();
209 if (fs::exists(fullPath)) {
210 setInputFileNames.insert(fs::canonical(fullPath).string());
211 } else {
212 B2WARNING("Couldn't find the file " << path);
213 }
214 }
215
216 if (setInputFileNames.empty()) {
217 B2WARNING("No valid files specified!");
218 return;
219 } else {
220 // Reset the run -> files map as our files are likely different
221 m_runsToInputFiles.clear();
222 }
223
224 // Open TFile to check they can be accessed by ROOT
225 TDirectory* dir = gDirectory;
226 for (const string& fileName : setInputFileNames) {
227 unique_ptr<TFile> f;
228 try {
229 f.reset(TFile::Open(fileName.c_str(), "READ"));
230 } catch (logic_error&) {
231 //this might happen for ~invaliduser/foo.root
232 //actually undefined behaviour per standard, reported as ROOT-8490 in JIRA
233 }
234 if (!f || !f->IsOpen()) {
235 B2FATAL("Couldn't open input file " + fileName);
236 }
237 }
238 dir->cd();
239
240 // Copy the entries of the set to a vector
241 m_inputFileNames = vector<string>(setInputFileNames.begin(), setInputFileNames.end());
243}
std::string m_granularityOfData
Granularity of input data. This only changes when the input files change so it isn't specific to an e...
void setInputFileNames(PyObject *inputFileNames)
Set the input file names used for this algorithm from a Python list.
std::string getGranularityFromData() const
Get the granularity of collected data.
std::vector< std::string > expandWordExpansions(const std::vector< std::string > &filenames)
Performs wildcard expansion using wordexp(), returns matches.

◆ setInputFileNames() [2/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.

167{
168 // The reasoning for this very 'manual' approach to extending the Python interface
169 // (instead of using boost::python) is down to my fear of putting off final users with
170 // complexity on their side.
171 //
172 // I didn't want users that inherit from this class to be forced to use boost and
173 // to have to define a new python module just to use the CAF. A derived class from
174 // from a boost exposed class would need to have its own boost python module definition
175 // to allow access from a steering file and to the base class functions (I think).
176 // I also couldn't be bothered to write a full framework to get around the issue in a similar
177 // way to Module()...maybe there's an easy way.
178 //
179 // But this way we can allow people to continue using their ROOT implemented classes and inherit
180 // easily from this one. But add in a few helper functions that work with Python objects
181 // created in their steering file i.e. instead of being forced to use STL objects as input
182 // to the algorithm.
183 if (PyList_Check(inputFileNames)) {
184 boost::python::handle<> handle(boost::python::borrowed(inputFileNames));
185 boost::python::list listInputFileNames(handle);
186 auto vecInputFileNames = PyObjConvUtils::convertPythonObject(listInputFileNames, vector<string>());
187 setInputFileNames(vecInputFileNames);
188 } else {
189 B2ERROR("Tried to set the input files but we didn't receive a Python list.");
190 }
191}
Scalar convertPythonObject(const boost::python::object &pyObject, Scalar)
Convert from Python to given type.

◆ setOutputJsonValue()

template<class T>
void setOutputJsonValue ( const std::string & key,
const T & value )
inlineprotectedinherited

Set a key:value pair for the outputJson object, expected to used internally during calibrate()

Definition at line 337 of file CalibrationAlgorithm.h.

337{m_jsonExecutionOutput[key] = value;}

◆ setPrefix()

void setPrefix ( const std::string & prefix)
inlineinherited

Set the prefix used to identify datastore objects.

Definition at line 167 of file CalibrationAlgorithm.h.

167{m_prefix = prefix;}

◆ updateDBObjPtrs()

void updateDBObjPtrs ( const unsigned int event,
const int run,
const int experiment )
staticprotectedinherited

Updates any DBObjPtrs by calling update(event) for DBStore.

Definition at line 405 of file CalibrationAlgorithm.cc.

406{
407 // Construct an EventMetaData object but NOT in the Datastore
408 EventMetaData emd(event, run, experiment);
409 // Explicitly update while avoiding registering a Datastore object
411 // Also update the intra-run objects to the event at the same time (maybe unnecessary...)
413}

Member Data Documentation

◆ algorithmReadPayloads

bool algorithmReadPayloads = false

Whether or not to have the algorithm code to loop over all the runs and read the payloads itself.

Definition at line 60 of file eclTimeShiftsAlgorithm.h.

◆ crysCrateShift_max

double crysCrateShift_max = 0.0

Plotting time max for crystal+crate shift plots.

Definition at line 56 of file eclTimeShiftsAlgorithm.h.

◆ crysCrateShift_min

double crysCrateShift_min = 0.0

Plotting time min for crystal+crate shift plots.

Definition at line 55 of file eclTimeShiftsAlgorithm.h.

◆ debugFilenameBase

std::string debugFilenameBase

Name of file with debug output, eclTimeShiftsAlgorithm.root by default.

Definition at line 49 of file eclTimeShiftsAlgorithm.h.

◆ m_allExpRun

const ExpRun m_allExpRun = make_pair(-1, -1)
staticprivateinherited

allExpRun

Definition at line 364 of file CalibrationAlgorithm.h.

◆ m_boundaries

std::vector<Calibration::ExpRun> m_boundaries
protectedinherited

When using the boundaries functionality from isBoundaryRequired, this is used to store the boundaries. It is cleared when.

Definition at line 261 of file CalibrationAlgorithm.h.

◆ m_crateID

Int_t m_crateID
private

Crate ID number.

Definition at line 92 of file eclTimeShiftsAlgorithm.h.

◆ m_crateTimeConst

Double_t m_crateTimeConst
private

Crate time calibration constant.

Definition at line 88 of file eclTimeShiftsAlgorithm.h.

◆ m_crateTimeUnc

Double_t m_crateTimeUnc
private

Uncertainty on the crate time calibration constant.

Definition at line 90 of file eclTimeShiftsAlgorithm.h.

◆ m_crystalID

Int_t m_crystalID
private

Crystal ID number.

Definition at line 87 of file eclTimeShiftsAlgorithm.h.

◆ m_crystalTimeConst

Double_t m_crystalTimeConst
private

Crystal time calibration constant.

Definition at line 89 of file eclTimeShiftsAlgorithm.h.

◆ m_crystalTimeUnc

Double_t m_crystalTimeUnc
private

Uncertainty on the crystal time calibration constant.

Definition at line 91 of file eclTimeShiftsAlgorithm.h.

◆ m_data

ExecutionData m_data
privateinherited

Data specific to a SINGLE execution of the algorithm. Gets reset at the beginning of execution.

Definition at line 382 of file CalibrationAlgorithm.h.

◆ m_description

std::string m_description {""}
privateinherited

Description of the algorithm.

Definition at line 385 of file CalibrationAlgorithm.h.

385{""};

◆ m_ECLCrateTimeOffset

DBObjPtr<ECLCrystalCalib> m_ECLCrateTimeOffset
private

ECLCrateTimeOffset payload that we want to read from the DB.

Definition at line 73 of file eclTimeShiftsAlgorithm.h.

◆ m_ECLCrystalTimeOffset

DBObjPtr<ECLCrystalCalib> m_ECLCrystalTimeOffset
private

ECLCrystalTimeOffset payload that we want to read from the DB.

Definition at line 70 of file eclTimeShiftsAlgorithm.h.

◆ m_exp_perCrystal

Int_t m_exp_perCrystal
private

Experiment number.

Definition at line 86 of file eclTimeShiftsAlgorithm.h.

◆ m_granularityOfData

std::string m_granularityOfData
privateinherited

Granularity of input data. This only changes when the input files change so it isn't specific to an execution.

Definition at line 379 of file CalibrationAlgorithm.h.

◆ m_inputFileNames

std::vector<std::string> m_inputFileNames
privateinherited

List of input files to the Algorithm, will initially be user defined but then gets the wildcards expanded during execute()

Definition at line 373 of file CalibrationAlgorithm.h.

◆ m_jsonExecutionInput

nlohmann::json m_jsonExecutionInput = nlohmann::json::object()
privateinherited

Optional input JSON object used to make decisions about how to execute the algorithm code.

Definition at line 397 of file CalibrationAlgorithm.h.

◆ m_jsonExecutionOutput

nlohmann::json m_jsonExecutionOutput = nlohmann::json::object()
privateinherited

Optional output JSON object that can be set during the execution by the underlying algorithm code.

Definition at line 403 of file CalibrationAlgorithm.h.

◆ m_numCrates

const int m_numCrates = 52
private

Number of Crates expected.

Definition at line 82 of file eclTimeShiftsAlgorithm.h.

◆ m_numCrystals

const int m_numCrystals = ECLElementNumbers::c_NCrystals
private

Number of Crystals expected.

Definition at line 79 of file eclTimeShiftsAlgorithm.h.

◆ m_prefix

std::string m_prefix {""}
privateinherited

The name of the TDirectory the collector objects are contained within.

Definition at line 388 of file CalibrationAlgorithm.h.

388{""};

◆ m_refCrysIDzeroingCrate

DBObjPtr<ECLReferenceCrystalPerCrateCalib> m_refCrysIDzeroingCrate
private

payload that we want to read from the DB

Definition at line 76 of file eclTimeShiftsAlgorithm.h.

◆ m_refCrystalID

Int_t m_refCrystalID
private

Crystal ID number for the reference crystal.

Definition at line 97 of file eclTimeShiftsAlgorithm.h.

◆ m_run_perCrystal

Int_t m_run_perCrystal
private

Run number.

Definition at line 85 of file eclTimeShiftsAlgorithm.h.

◆ m_runsToInputFiles

std::map<Calibration::ExpRun, std::vector<std::string> > m_runsToInputFiles
privateinherited

Map of Runs to input files. Gets filled when you call getRunRangeFromAllData, gets cleared when setting input files again.

Definition at line 376 of file CalibrationAlgorithm.h.

◆ m_tcrate_max_cut

double m_tcrate_max_cut = 150
private

Maximum value cut for the crate time calibration constant for plotting.

Definition at line 101 of file eclTimeShiftsAlgorithm.h.

◆ m_tcrate_min_cut

double m_tcrate_min_cut = -150
private

Minimum value cut for the crate time calibration constant for plotting.

Definition at line 100 of file eclTimeShiftsAlgorithm.h.

◆ m_tcrate_unc_max_cut

double m_tcrate_unc_max_cut = 999.
private

Maximum value cut for the crate time calibration constant uncertainty for plotting.

Definition at line 103 of file eclTimeShiftsAlgorithm.h.

◆ m_tcrate_unc_min_cut

double m_tcrate_unc_min_cut = 0.0001
private

Minimum value cut for the crate time calibration constant uncertainty for plotting.

Definition at line 102 of file eclTimeShiftsAlgorithm.h.

◆ timeShiftForPlotStyle

double timeShiftForPlotStyle[52] = {}

List of time offsets, one per crate, used just to centre the time constants around zero.

Definition at line 53 of file eclTimeShiftsAlgorithm.h.

53{};

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