18#include <nlohmann/json.hpp>
19#include <TClonesArray.h>
20#include <TDirectory.h>
23#include <framework/database/Database.h>
24#include <framework/database/IntervalOfValidity.h>
25#include <framework/logging/Logger.h>
26#include <calibration/Utilities.h>
27#include <calibration/dataobjects/RunRange.h>
60 B2DEBUG(100,
"Resetting ExecutionData of algorithm");
82 B2DEBUG(29,
"Setting Iteration of Algorithm to " << iteration);
107 void setCalibObj(
const std::string& name,
const RunRange& runRange,
const std::shared_ptr<TNamed>& objectPtr)
131 std::map<std::pair<std::string, RunRange>, std::shared_ptr<TNamed>>
m_mapCalibData;
198 EResult execute(std::vector<Calibration::ExpRun> runs = {},
int iteration = 0, IntervalOfValidity iov = IntervalOfValidity());
201 EResult execute(PyObject* runs,
int iteration = 0, IntervalOfValidity iov = IntervalOfValidity());
213 bool commit(std::list<Database::DBImportQuery> payloads);
229 const std::vector<Calibration::ExpRun>
findPayloadBoundaries(std::vector<Calibration::ExpRun> runs,
int iteration = 0);
245 B2ERROR(
"You didn't implement a isBoundaryRequired() member function in your CalibrationAlgorithm but you are calling it!");
279 std::shared_ptr<T>
getObjectPtr(
const std::string& name,
const std::vector<Calibration::ExpRun>& requestedRuns);
316 void updateDBObjPtrs(
const unsigned int event,
const int run,
const int experiment);
370 std::string
getFullObjectPath(
const std::string& name, Calibration::ExpRun expRun)
const;
415 const std::vector<Calibration::ExpRun>& requestedRuns)
418 RunRange runRangeRequested(requestedRuns);
419 std::shared_ptr<T> objOutputPtr = std::dynamic_pointer_cast<T>(
m_data.
getCalibObj(name, runRangeRequested));
423 std::shared_ptr<T> mergedObjPtr(
nullptr);
424 bool mergedEmpty =
true;
425 TDirectory* dir = gDirectory;
431 list.SetOwner(
false);
434 std::string runRangeObjName(
getPrefix() +
"/" + Calibration::RUN_RANGE_OBJ_NAME);
438 for (
auto expRunRequested : requestedRuns) {
442 B2WARNING(
"No input file found with data collected from run "
443 "(" << expRunRequested.first <<
"," << expRunRequested.second <<
")");
446 auto files = searchFiles->second;
447 for (
auto fileName : files) {
450 std::unique_ptr<TFile> f;
451 f.reset(TFile::Open(fileName.c_str(),
"READ"));
452 runRangeData =
dynamic_cast<RunRange*
>(f->Get(runRangeObjName.c_str()));
455 if (runSet.find(expRunRequested) == runSet.end()) {
456 B2WARNING(
"Something went wrong with the mapping of ExpRun -> Input Files. "
457 "(" << expRunRequested.first <<
"," << expRunRequested.second <<
") not in " << fileName);
461 TDirectory* objDir = f->GetDirectory(objDirName.c_str());
463 B2ERROR(
"Directory for requested object " << name <<
" not found: " << objDirName);
467 for (
auto key : * (objDir->GetListOfKeys())) {
468 std::string keyName = key->GetName();
469 B2DEBUG(100,
"Adding found object " << keyName <<
" in the directory " << objDir->GetPath());
470 T* objOther = (T*)objDir->Get(keyName.c_str());
473 mergedObjPtr = std::shared_ptr<T>(
dynamic_cast<T*
>(objOther->Clone(name.c_str())));
474 mergedObjPtr->SetDirectory(0);
482 mergedObjPtr->Merge(&list);
490 std::unique_ptr<TFile> f;
491 f.reset(TFile::Open(fileName.c_str(),
"READ"));
494 std::string objPath = objDirName +
"/" + name +
"_1";
495 T* objOther = (T*)f->Get(objPath.c_str());
496 B2DEBUG(100,
"Adding " << objPath);
499 mergedObjPtr = std::shared_ptr<T>(
dynamic_cast<T*
>(objOther->Clone(name.c_str())));
500 mergedObjPtr->SetDirectory(0);
507 mergedObjPtr->Merge(&list);
512 objOutputPtr = mergedObjPtr;
514 B2ERROR(
"No data found for object " << name);
517 objOutputPtr->SetDirectory(0);
519 std::shared_ptr<TNamed> storedObjPtr = std::static_pointer_cast<TNamed>(objOutputPtr);
521 B2DEBUG(100,
"Passing back merged data " << name);
528 template<> std::shared_ptr<TTree>
530 const std::string& name,
531 const std::vector<Calibration::ExpRun>& requestedRuns);
A class to hold all data that is needed ONLY for the most recent single execution of the algorithm.
std::list< Database::DBImportQuery > & getPayloads()
Get constants (in TObjects) for database update from last calibration.
std::list< Database::DBImportQuery > getPayloadValues()
Get constants (in TObjects) for database update from last calibration but passed by VALUE.
const std::vector< Calibration::ExpRun > & getRequestedRuns() const
Returns the vector of ExpRuns.
void setResult(EResult result)
Setter for current iteration.
std::map< std::pair< std::string, RunRange >, std::shared_ptr< TNamed > > m_mapCalibData
Map of shared pointers to merged calibration objects created by getObjectPtr() calls.
IntervalOfValidity m_iov
Current IoV to be executed, default empty. Will be either set by user explicitly or generated from co...
void setRequestedIov(const IntervalOfValidity &iov=IntervalOfValidity(0, 0, -1, -1))
Sets the requested IoV for this execution, based on the.
int m_iteration
current iteration for execution
void setCalibObj(const std::string &name, const RunRange &runRange, const std::shared_ptr< TNamed > &objectPtr)
Insert a newly created object in m_mapCalibData. Overwrites a previous entry if one exists.
void setRequestedRuns(const std::vector< Calibration::ExpRun > &requestedRuns)
Sets the vector of ExpRuns.
int getIteration() const
Getter for current iteration.
void setIteration(int iteration)
Setter for current iteration.
std::vector< Calibration::ExpRun > m_requestedRuns
Runs for which the calibration has been last requested, either requested explicitly or generated from...
std::list< Database::DBImportQuery > m_payloads
Payloads saved by execution.
EResult getResult() const
Getter for current result.
EResult m_result
Result of execution, default undefined to indicate we haven't run yet.
void reset()
Resets this class back to what is needed at the beginning of an execution.
std::shared_ptr< TNamed > getCalibObj(const std::string &name, const RunRange &runRange) const
Get a previously created object in m_mapCalibData if one exists, otherwise return shared_ptr(nullptr)
void clearCalibrationData()
Clear calibration data.
const IntervalOfValidity & getRequestedIov() const
Getter for requested IOV.
Base class for calibration algorithms.
std::list< Database::DBImportQuery > & getPayloads()
Get constants (in TObjects) for database update from last execution.
std::string getExpRunString(Calibration::ExpRun &expRun) const
Gets the "exp.run" string repr. of (exp,run)
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 saveCalibration(TClonesArray *data, const std::string &name)
Store DBArray payload with given name with default IOV.
bool checkPyExpRun(PyObject *pyObj)
Checks that a PyObject can be successfully converted to an ExpRun type.
static const Calibration::ExpRun m_allExpRun
allExpRun
std::list< Database::DBImportQuery > getPayloadValues()
Get constants (in TObjects) for database update from last execution but passed by VALUE.
bool inputJsonKeyExists(const std::string &key) const
Test for a key in the input JSON object.
void updateDBObjPtrs(const unsigned int event, const int run, const int experiment)
Updates any DBObjPtrs by calling update(event) for DBStore.
std::vector< Calibration::ExpRun > m_boundaries
When using the boundaries functionality from isBoundaryRequired, this is used to store the boundaries...
PyObject * getInputFileNames()
Get the input file names used for this algorithm and pass them out as a Python list of unicode string...
EResult execute(std::vector< Calibration::ExpRun > runs={}, int iteration=0, IntervalOfValidity iov=IntervalOfValidity())
Runs calibration over vector of runs for a given iteration.
std::vector< Calibration::ExpRun > getRunListFromAllData() const
Get the complete list of runs from inspection of collected data.
void setDescription(const std::string &description)
Set algorithm description (in constructor)
Calibration::ExpRun getAllGranularityExpRun() const
Returns the Exp,Run pair that means 'Everything'. Currently unused.
virtual void boundaryFindingTearDown()
Put your algorithm back into a state ready for normal execution if you need to.
std::string m_prefix
The name of the TDirectory the collector objects are contained within.
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
std::shared_ptr< T > getObjectPtr(std::string name)
Get calibration data object (for all runs the calibration is requested for) This function will only w...
const std::vector< Calibration::ExpRun > & getRunList() const
Get the list of runs for which calibration is called.
virtual void boundaryFindingSetup(std::vector< Calibration::ExpRun >, int)
If you need to make some changes to your algorithm class before 'findPayloadBoundaries' is run,...
const std::string & getDescription() const
Get the description of the algorithm (set by developers in constructor)
std::string getPrefix() const
Get the prefix used for getting calibration data.
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.
std::vector< std::string > m_inputFileNames
List of input files to the Algorithm, will initially be user defined but then gets the wildcards expa...
int getIteration() const
Get current iteration.
std::string getCollectorName() const
Alias for prefix.
EResult
The result of calibration.
@ 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.
void resetInputJson()
Clears the m_inputJson member variable.
std::string m_granularityOfData
Granularity of input data. This only changes when the input files change so it isn't specific to an e...
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.
nlohmann::json m_jsonExecutionInput
Optional input JSON object used to make decisions about how to execute the algorithm code.
void setInputFileNames(PyObject *inputFileNames)
Set the input file names used for this algorithm from a Python list.
void setOutputJsonValue(const std::string &key, const T &value)
Set a key:value pair for the outputJson object, expected to used internally during calibrate()
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....
void setPrefix(const std::string &prefix)
Set the prefix used to identify datastore objects.
nlohmann::json m_jsonExecutionOutput
Optional output JSON object that can be set during the execution by the underlying algorithm code.
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...
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...
bool loadInputJson(const std::string &jsonString)
Load the m_inputJson variable from a string (useful from Python interface). The return bool indicates...
virtual ~CalibrationAlgorithm()
Virtual destructor (base class)
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 ...
std::string getGranularityFromData() const
Get the granularity of collected data.
void fillRunToInputFilesMap()
Fill the mapping of ExpRun -> Files.
std::vector< std::string > getVecInputFileNames() const
Get the input file names used for this algorithm as a STL vector.
bool commit()
Submit constants from last calibration into database.
std::string m_description
Description of the algorithm.
const std::string dumpOutputJson() const
Dump the JSON string of the output JSON object.
virtual EResult calibrate()=0
Run algo on data - pure virtual: needs to be implemented.
Calibration::ExpRun convertPyExpRun(PyObject *pyObj)
Performs the conversion of PyObject to ExpRun.
void resetOutputJson()
Clears the m_outputJson member variable.
std::string getGranularity() const
Get the granularity of collected data.
CalibrationAlgorithm(const std::string &collectorModuleName)
Constructor - sets the prefix for collected objects (won't be accesses until execute(....
void clearCalibrationData()
Clear calibration data.
ExecutionData m_data
Data specific to a SINGLE execution of the algorithm. Gets reset at the beginning of execution.
A class that describes the interval of experiments/runs for which an object in the database is valid.
Mergeable object holding (unique) set of (exp,run) pairs.
const std::set< Calibration::ExpRun > & getExpRunSet()
Get access to the stored set.
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...
Abstract base class for different kinds of events.