Project
Loading...
Searching...
No Matches
PHOSEnergyCalibDevice.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
19#include "CCDB/CcdbApi.h"
21#include "CCDB/CcdbObjectInfo.h"
23
24#include <fairmq/Device.h>
25#include <fairlogger/Logger.h>
26#include <string>
27#include <filesystem>
28
29using namespace o2::phos;
30
32{
34
35 mPtMin = ic.options().get<float>("ptminmgg");
36 mEminHGTime = ic.options().get<float>("eminhgtime");
37 mEminLGTime = ic.options().get<float>("eminlgtime");
38 mEDigMin = ic.options().get<float>("ecalibdigitmin");
39 mECluMin = ic.options().get<float>("ecalibclumin");
40
41 if (mOutputDir.compare("/dev/null")) {
42 mOutputDir = o2::utils::Str::rectifyDirectory(mOutputDir);
43 }
44 if (mMetaFileDir.compare("/dev/null")) {
45 mMetaFileDir = o2::utils::Str::rectifyDirectory(mMetaFileDir);
46 }
47
48 LOG(info) << "Energy calibration options";
49 LOG(info) << " output-dif=" << mOutputDir;
50 bool toFillDigits = mOutputDir.compare("/dev/null");
51 if (toFillDigits) {
52 LOG(info) << " Digits tree will be created";
53 } else {
54 LOG(info) << " Digits tree will NOT be created";
55 }
56 LOG(info) << " meta-output-dir=" << mMetaFileDir;
57 LOG(info) << " mgg histo ptMin=" << mPtMin;
58 LOG(info) << " Emin for HG time=" << mEminHGTime;
59 LOG(info) << " Emin for LG time=" << mEminLGTime;
60 LOG(info) << " Emin for out digits=" << mEDigMin;
61 LOG(info) << " Cluster Emin for out digits=" << mECluMin;
62
63 LOG(info) << " Root output dir=" << mOutputDir;
64
65 mCalibrator = std::make_unique<PHOSEnergyCalibrator>();
66
67 // read calibration and bad map objects and send them to calibrator
68 if (!mHasCalib && !mUseCCDB) {
69 mCalibParams = std::make_unique<CalibParams>(1); // Create test calibration coefficients
70 mCalibrator->setCalibration(mCalibParams.get());
71 mBadMap = std::make_unique<BadChannelsMap>(); // Create empty bad map
72 mCalibrator->setBadMap(mBadMap.get());
73 LOG(info) << "No reading BadMap/Calibration from ccdb requested, set default";
74 mHasCalib = true;
75 }
76 mCalibrator->setCuts(mPtMin, mEminHGTime, mEminLGTime, mEminHGTime, mEminLGTime);
77 mCalibrator->setFillDigitsTree(toFillDigits);
78 mCalibrator->setUpdateAtTheEndOfRunOnly();
79
80 // Create geometry instance (inclusing reading mis-alignement)
81 // instance will be pick up by Calibrator
83}
84
85//___________________________________________________________________
87{
88 static bool initOnceDone = false;
89 if (!initOnceDone) {
90 initOnceDone = true;
91 mDataTakingContext = pc.services().get<DataTakingContext>();
92 }
94}
95
97{
99
100 // Do not use ccdb if already created
101 if (!mHasCalib) { // Default map and calibration was not set, use CCDB
102 LOG(info) << "Getting calib from CCDB";
103 // update BadMap and calibration if necessary
104 auto badMapPtr = pc.inputs().get<o2::phos::BadChannelsMap*>("bdmap");
105 mCalibrator->setBadMap(badMapPtr.get());
106
107 auto calibPtr = pc.inputs().get<o2::phos::CalibParams*>("clb");
108 mCalibrator->setCalibration(calibPtr.get());
109 mHasCalib = true;
110 }
111 mOutputDigits.clear();
112
113 auto tfcounter = o2::header::get<o2::framework::DataProcessingHeader*>(pc.inputs().get("clusters").header)->startTime; // is this the timestamp of the current TF?
114 const gsl::span<const Cluster>& clusters = pc.inputs().get<gsl::span<Cluster>>("clusters");
115 const gsl::span<const CluElement>& cluelements = pc.inputs().get<gsl::span<CluElement>>("cluelements");
116 const gsl::span<const TriggerRecord>& cluTR = pc.inputs().get<gsl::span<TriggerRecord>>("clusterTriggerRecords");
117
118 LOG(debug) << "[PHOSEnergyCalibDevice - run] Received " << cluTR.size() << " TRs and " << clusters.size() << " clusters, running calibration";
119 if (mRunStartTime == 0) {
120 const auto& tinfo = pc.services().get<o2::framework::TimingInfo>();
121 mRunStartTime = tinfo.creation; // approximate time in ms
122 mRunNumber = tinfo.runNumber;
123
124 auto LHCPeriodStr = pc.services().get<RawDeviceService>().device()->fConfig->GetProperty<std::string>("LHCPeriod", "");
125 if (!(LHCPeriodStr.empty())) {
126 mLHCPeriod = LHCPeriodStr;
127 } else {
128 const char* months[12] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
129 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
130 std::time_t tt = mRunStartTime / 1000; // ms->s
131 std::tm* ltm = std::gmtime(&tt);
132 mLHCPeriod = (std::string)months[ltm->tm_mon];
133 LOG(warning) << "LHCPeriod is not available, using current month " << mLHCPeriod;
134 }
135 }
136 o2::base::TFIDInfoHelper::fillTFIDInfo(pc, mCalibrator->getCurrentTFInfo());
137 mCalibrator->process(tfcounter, clusters, cluelements, cluTR, mOutputDigits);
138
140}
141
143{
144 mCalibrator->checkSlotsToFinalize(o2::calibration::INFINITE_TF);
145 mCalibrator->endOfStream();
146 writeOutFile();
147}
148
150{
151 // DDS stop method: simply write the latest tree
152 LOG(info) << "STOP: writing output digits file";
153 writeOutFile();
154}
156{
157
158 if (mOutputDigits.size() < 2) { // nothing to fill, need at least 2 cluster per event
159 return;
160 }
161
162 LOG(info) << "Filling tree with " << mOutputDigits.size() << " digits";
163 if (!mFileOut) { // create file and tree
164 if (mWriteRootOutput) {
165 mFileName = mOutputDir + fmt::format("PHOS_CalibDigits_{}.root", mRunNumber);
166 LOG(info) << "Creating new tree for PHOS calib digits, output file=" << mFileName;
167 mFileOut = std::make_unique<TFile>(mFileName.c_str(), "recreate");
168 mFileMetaData = std::make_unique<o2::dataformats::FileMetaData>();
169 mHistoFileName = mOutputDir + fmt::format("PHOS_CalibHistos_{}.root", mRunNumber);
170 mHistoFileOut = std::make_unique<TFile>(mHistoFileName.c_str(), "recreate");
171 mHistoFileMetaData = std::make_unique<o2::dataformats::FileMetaData>();
172 mFileOut->cd();
173 }
174 // else Tree will be memory resident
175 if (!mTreeOut) {
176 LOG(info) << "Creating new tree for PHOS calib digits";
177 mTreeOut = std::make_unique<TTree>("phosCalibDig", "O2 PHOS calib tree");
178 }
179 }
180 auto* br = mTreeOut->GetBranch("PHOSCalib");
181 if (!br) {
182 br = mTreeOut->Branch("PHOSCalib", &mOutputDigits);
183 }
184 mTreeOut->Fill();
185}
186
188{
189 if (!mWriteRootOutput) {
190 return;
191 }
192 // write collected vector and metadata
193 if (!mTreeOut) { // nothing to write,
194 return;
195 }
196 LOG(info) << "Writing calibration digits";
197
198 int nbits = mTreeOut->Write();
199 LOG(info) << "Wrote " << nbits << " bits";
200 mTreeOut.reset();
201 mFileOut->Close();
202 mFileOut.reset();
203
204 // write metaFile data
205 mFileMetaData->fillFileData(mFileName);
206 mFileMetaData->setDataTakingContext(mDataTakingContext);
207 mFileMetaData->type = "calib";
208 mFileMetaData->priority = "high";
209
210 std::string metaFileNameTmp = mMetaFileDir + fmt::format("PHOS_CalibDigits_{}.tmp", mRunNumber);
211 std::string metaFileName = mMetaFileDir + fmt::format("PHOS_CalibDigits_{}.done", mRunNumber);
212 if (mMetaFileDir.compare("/dev/null")) {
213 try {
214 std::ofstream metaFileOut(metaFileNameTmp);
215 metaFileOut << *mFileMetaData.get();
216 metaFileOut.close();
217 std::filesystem::rename(metaFileNameTmp, metaFileName);
218 } catch (std::exception const& e) {
219 LOG(error) << "Failed to store PHOS meta data file " << metaFileName << ", reason: " << e.what();
220 }
221 LOG(info) << "Stored metadate file " << mFileName << ".done";
222 } else {
223 LOG(info) << "Scipped storing metafile as meta-dir=" << mMetaFileDir;
224 }
225 mFileMetaData.reset();
226
227 LOG(info) << "Writing calibration histograms";
228 mHistoFileOut->cd();
229 mHistoFileOut->WriteObjectAny(mCalibrator->getCollectedHistos(), "o2::phos::ETCalibHistos", "histos");
230 mHistoFileOut->Close();
231 mHistoFileOut.reset();
232
233 // write metaFile data
234 mHistoFileMetaData->fillFileData(mHistoFileName);
235 mHistoFileMetaData->setDataTakingContext(mDataTakingContext);
236 mHistoFileMetaData->type = "calib";
237 mHistoFileMetaData->priority = "high";
238
239 metaFileNameTmp = mMetaFileDir + fmt::format("PHOS_CalibHistos_{}.tmp", mRunNumber);
240 metaFileName = mMetaFileDir + fmt::format("PHOS_CalibHistos_{}.done", mRunNumber);
241 if (mMetaFileDir.compare("/dev/null")) {
242 try {
243 std::ofstream metaFileOut(metaFileNameTmp);
244 metaFileOut << *mHistoFileMetaData.get();
245 metaFileOut.close();
246 std::filesystem::rename(metaFileNameTmp, metaFileName);
247 } catch (std::exception const& e) {
248 LOG(error) << "Failed to store PHOS histos meta data file " << metaFileName << ", reason: " << e.what();
249 }
250 LOG(info) << "Stored histos metadate file " << mHistoFileName << ".done";
251 }
252 mHistoFileMetaData.reset();
253}
254o2::framework::DataProcessorSpec o2::phos::getPHOSEnergyCalibDeviceSpec(bool useCCDB, const std::string& outputDir, const std::string& metaFileDir, bool writeRootOutput)
255{
256
257 std::vector<InputSpec> inputs;
258 inputs.emplace_back("clusters", o2::header::gDataOriginPHS, "CLUSTERS", 0, o2::framework::Lifetime::Timeframe);
259 inputs.emplace_back("cluelements", o2::header::gDataOriginPHS, "CLUELEMENTS", 0, o2::framework::Lifetime::Timeframe);
260 inputs.emplace_back("clusterTriggerRecords", o2::header::gDataOriginPHS, "CLUSTERTRIGREC", 0, o2::framework::Lifetime::Timeframe);
261 if (useCCDB) {
262 inputs.emplace_back("bdmap", o2::header::gDataOriginPHS, "PHS_BM", 0, o2::framework::Lifetime::Condition, o2::framework::ccdbParamSpec("PHS/Calib/BadMap"));
263 inputs.emplace_back("clb", o2::header::gDataOriginPHS, "PHS_Calibr", 0, o2::framework::Lifetime::Condition, o2::framework::ccdbParamSpec("PHS/Calib/CalibParams"));
264 }
265 auto ccdbRequest = std::make_shared<o2::base::GRPGeomRequest>(true, // orbitResetTime
266 true, // GRPECS=true
267 false, // GRPLHCIF
268 false, // GRPMagField
269 false, // askMatLUT
271 inputs);
273 std::vector<OutputSpec> outputs;
274
275 return o2::framework::DataProcessorSpec{"PHOSEnergyCalibDevice",
276 inputs,
277 outputs,
278 o2::framework::adaptFromTask<PHOSEnergyCalibDevice>(useCCDB, ccdbRequest, outputDir, metaFileDir, writeRootOutput),
280 {"ptminmgg", o2::framework::VariantType::Float, 1.5f, {"minimal pt to fill mgg calib histos"}},
281 {"eminhgtime", o2::framework::VariantType::Float, 1.5f, {"minimal E (GeV) to fill HG time calib histos"}},
282 {"eminlgtime", o2::framework::VariantType::Float, 5.f, {"minimal E (GeV) to fill LG time calib histos"}},
283 {"ecalibdigitmin", o2::framework::VariantType::Float, 0.05f, {"minimal digtit E (GeV) to keep digit for calibration"}},
284 {"ecalibclumin", o2::framework::VariantType::Float, 0.4f, {"minimal cluster E (GeV) to keep digit for calibration"}}}};
285}
Utils and constants for calibration and related workflows.
std::ostringstream debug
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h configStandalone Processing settings for neural network proc_nn std::string Specify inference device(cpu(default), rocm, cuda)") AddOption(nnInferenceDeviceId
char error[CURL_ERROR_SIZE]
Device to collect histos and digits for PHOS energy and time calibration.
void checkUpdates(o2::framework::ProcessingContext &pc)
static GRPGeomHelper & instance()
void setRequest(std::shared_ptr< GRPGeomRequest > req)
ConfigParamRegistry const & options()
Definition InitContext.h:33
decltype(auto) get(R binding, int part=0) const
InputRecord & inputs()
The inputs associated with this processing context.
ServiceRegistryRef services()
The services registry associated with this processing context.
CCDB container for bad (masked) channels in PHOS.
static Geometry * GetInstance()
Definition Geometry.h:63
void updateTimeDependentParams(ProcessingContext &pc)
void endOfStream(o2::framework::EndOfStreamContext &ec) final
This is invoked whenever we have an EndOfStream event.
void init(o2::framework::InitContext &ic) final
void run(o2::framework::ProcessingContext &pc) final
void stop() final
This is invoked on stop.
constexpr o2::header::DataOrigin gDataOriginPHS
Definition DataHeader.h:577
constexpr TFType INFINITE_TF
Definition TimeSlot.h:30
std::vector< ConfigParamSpec > ccdbParamSpec(std::string const &path, int runDependent, std::vector< CCDBMetadata > metadata={}, int qrate=0)
o2::framework::DataProcessorSpec getPHOSEnergyCalibDeviceSpec(bool useCCDB, const std::string &outputDir, const std::string &metaFileDir, bool writeRootOutput)
static void fillTFIDInfo(o2::framework::ProcessingContext &pc, o2::dataformats::TFIDInfo &ti)
static std::string rectifyDirectory(const std::string_view p)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::vector< Cluster > clusters