Project
Loading...
Searching...
No Matches
CheckResidSpec.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
15#include <algorithm>
16#include <array>
17#include <charconv>
18#include <cctype>
19#include <limits>
20#include <optional>
21#include <string_view>
22#include <utility>
23#include <vector>
25#include <TStopwatch.h>
45#include "ITStracking/IOUtils.h"
53#include <TROOT.h>
54#include <TStyle.h>
55#include <TLatex.h>
56#include <TCanvas.h>
57#include <TLegend.h>
58#include <TLegendEntry.h>
59#include <TH1F.h>
60#include <TH2F.h>
61#include <TProfile.h>
62#include <TGraph.h>
63#include <TF1.h>
64#ifdef WITH_OPENMP
65#include <omp.h>
66#endif
67
68// Attention: in case the residuals are checked with geometry different from the one used for initial reconstruction,
69// pass a --configKeyValues option for vertex refit as:
70// ;pvertexer.useMeanVertexConstraint=false;pvertexer.meanVertexExtraErrSelection=0.2;pvertexer.iniScale2=100;pvertexer.acceptableScale2=10.;
71// In any case, it is better to pass ;pvertexer.useMeanVertexConstraint=false;
72
73namespace o2::checkresid
74{
75using namespace o2::framework;
78
85
86class CheckResidSpec final : public Task
87{
88 public:
89 CheckResidSpec(std::shared_ptr<DataRequest> dr, std::shared_ptr<o2::base::GRPGeomRequest> gr, GTrackID::mask_t src, bool drawOnly, bool postProcOnly)
90 : mDataRequest(dr), mGGCCDBRequest(gr), mTracksSrc(src), mDrawOnly(drawOnly), mPostProcOnly(postProcOnly)
91 {
92 }
93 ~CheckResidSpec() final = default;
94 void init(InitContext& ic) final;
95 void run(ProcessingContext& pc) final;
96 void endOfStream(EndOfStreamContext& ec) final;
97 void finaliseCCDB(ConcreteDataMatcher& matcher, void* obj) final;
98 void process();
99
100 private:
101 void updateTimeDependentParams(ProcessingContext& pc);
102 bool refitPV(o2::dataformats::PrimaryVertex& pv, int vid);
103 bool refitITStrack(o2::track::TrackParCov& track, GTrackID gid);
104 bool processITSTrack(const o2::its::TrackITS& iTrack, const o2::dataformats::PrimaryVertex& pv, o2::checkresid::Track& resTrack, o2::track::PID pid);
105 void bookHistos();
106 void fillHistos(const o2::checkresid::Track& trc);
107 void postProcessHistos();
108 void drawHistos();
109
110 o2::itsmft::ChipMappingITS mChipMap;
111 o2::globaltracking::RecoContainer* mRecoData = nullptr;
112 int mNThreads = 1;
113 bool mMeanVertexUpdated = false;
114 float mITSROFrameLengthMUS = 0.f;
115 o2::dataformats::MeanVertexObject mMeanVtx{};
116 ITSClusters mITSClustersArray;
117 std::vector<int16_t> mITSClusterSizes;
118 const o2::itsmft::TopologyDictionary* mITSDict = nullptr;
119 o2::vertexing::PVertexer mVertexer;
120 std::shared_ptr<DataRequest> mDataRequest;
121 std::shared_ptr<o2::base::GRPGeomRequest> mGGCCDBRequest;
122 std::unique_ptr<o2::utils::TreeStreamRedirector> mDBGOut;
123 GTrackID::mask_t mTracksSrc{};
124
125 bool mDrawOnly = false;
126 bool mPostProcOnly = false;
127 bool mDraw = false;
128 bool mFillHistos = true;
129 bool mFillTree = true;
130 std::vector<std::unique_ptr<o2::HistoManager>> mHManV{};
131 std::vector<o2::dataformats::PrimaryVertex> mPVUsed;
132 o2::HistoManager* mHMan = nullptr;
133};
134
136{
137 mDraw = true;
138 if (!mDrawOnly) {
139 mDraw = ic.options().get<bool>("draw-report");
140 mFillHistos = !ic.options().get<bool>("no-hist");
141 mFillTree = !ic.options().get<bool>("no-tree");
142 mNThreads = ic.options().get<int>("nthreads");
143 }
145 int lane = ic.services().get<const o2::framework::DeviceSpec>().inputTimesliceId;
146 int maxLanes = ic.services().get<const o2::framework::DeviceSpec>().maxInputTimeslices;
147 std::string nm = params.outname;
148 if (maxLanes > 1) {
149 o2::conf::ConfigurableParam::updateFromString(fmt::format("checkresid.outname={}_t{}", nm, lane));
150 }
151 if (lane == 0) {
152 params.printKeyValues();
153 }
154 if (mDraw) {
155 mFillHistos = true;
156 }
157 if (!mDrawOnly && mFillHistos) {
158 bookHistos();
159 }
160 if (!params.ext_hm_list.empty()) {
161 auto vecNames = o2::utils::Str::tokenize(params.ext_hm_list, ",;");
162 auto vecLegends = o2::utils::Str::tokenize(params.ext_leg_list, ',');
163 bool useLeg = true;
164 if (vecNames.size() != vecLegends.size()) {
165 LOGP(warn, "{} legend names provided for {} external histomanagers, will use file names as legends", vecLegends.size(), vecNames.size());
166 useLeg = false;
167 }
168 int cntH = 0;
169 for (const auto& vn : vecNames) {
170 LOGP(info, "Loading external HistoManager {}", vn);
171 mHManV.emplace_back() = std::make_unique<o2::HistoManager>("", vn, true);
172 auto hm = mHManV.back().get();
173 if (!hm) {
174 LOGP(error, "Failed to load histograms from {}", vn);
175 mHManV.pop_back();
176 } else {
177 hm->SetName(useLeg ? vecLegends[cntH].c_str() : vn.c_str());
178 }
179 cntH++;
180 }
181 }
182 if (mDrawOnly) {
183 return;
184 }
186#ifndef WITH_OPENMP
187 if (mNThreads > 1) {
188 LOGP(warn, "No OpenMP");
189 }
190 mNThreads = 1;
191#endif
192 if (mFillTree) {
193 mDBGOut = std::make_unique<o2::utils::TreeStreamRedirector>(fmt::format("{}.root", params.outname).c_str(), "recreate");
194 }
195}
196
198{
199 bool quit = false;
200 if (mPostProcOnly) {
201
202 postProcessHistos();
203 quit = true;
204 }
205 if (mDrawOnly) {
206 drawHistos();
207 quit = true;
208 }
209 if (quit) {
210 if (mPostProcOnly && o2::checkresid::CheckResidConfig::Instance().savePostprocessed) {
211 for (const auto& hm : mHManV) {
212 if (hm) {
213 hm->write();
214 }
215 }
216 }
218 pc.services().get<ControlService>().readyToQuit(QuitRequest::Me);
219 return;
220 }
222 mRecoData = &recoData;
223 mRecoData->collectData(pc, *mDataRequest.get()); // select tracks of needed type, with minimal cuts, the real selected will be done in the vertexer
224 mRecoData = &recoData;
225 updateTimeDependentParams(pc); // Make sure this is called after recoData.collectData, which may load some conditions
226 process();
227 mRecoData = nullptr;
228}
229
230void CheckResidSpec::updateTimeDependentParams(ProcessingContext& pc)
231{
234 static bool initOnceDone = false;
235 if (!initOnceDone) { // this params need to be queried only once
237 initOnceDone = true;
238 // Note: reading of the ITS AlpideParam needed for ITS timing is done by the RecoContainer
241 if (!grp->isDetContinuousReadOut(DetID::ITS)) {
242 mITSROFrameLengthMUS = alpParams.roFrameLengthTrig / 1.e3; // ITS ROFrame duration in \mus
243 } else {
244 mITSROFrameLengthMUS = alpParams.roFrameLengthInBC * o2::constants::lhc::LHCBunchSpacingNS * 1e-3; // ITS ROFrame duration in \mus
245 }
247 geom->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::T2L, o2::math_utils::TransformType::L2G, o2::math_utils::TransformType::T2G));
248 o2::conf::ConfigurableParam::updateFromString("pvertexer.useTimeInChi2=false;");
249 mVertexer.init();
250 }
251 if (mMeanVertexUpdated) {
252 mMeanVertexUpdated = false;
253 mVertexer.setMeanVertex(&mMeanVtx);
254 mVertexer.initMeanVertexConstraint();
255 }
256}
257
259{
260 if (!mITSDict) {
261 LOGP(fatal, "ITS data is not loaded");
262 }
263 const auto itsTracks = mRecoData->getITSTracks();
264 // const auto itsLbls = mRecoData->getITSTracksMCLabels();
265 const auto itsClRefs = mRecoData->getITSTracksClusterRefs();
267 int nLr = mDataRequest->getITSPerLayer() ? o2::globaltracking::MaxITSLayers : 1;
268 mITSClustersArray.init(nLr);
269 mITSClusterSizes.clear();
270 for (int lr = 0; lr < nLr; lr++) { // with a single (monolithic) input all clusters are in the layer slot 0
271 mITSClustersArray.beginLayer(lr);
272 const auto clusITS = mRecoData->getITSClusters(lr);
273 auto pattIt = mRecoData->getITSClustersPatterns(lr).begin();
274 {
275 auto sizePattIt = mRecoData->getITSClustersPatterns(lr).begin();
276 mITSClustersArray.getClusters().reserve(mITSClustersArray.size() + clusITS.size());
277 mITSClusterSizes.reserve(mITSClusterSizes.size() + clusITS.size());
278 for (const auto& clu : clusITS) {
279 const auto pattID = clu.getPatternID();
280 if (pattID == o2::itsmft::CompCluster::InvalidPatternID || mITSDict->isGroup(pattID)) {
281 o2::itsmft::ClusterPattern patt(sizePattIt);
282 mITSClusterSizes.emplace_back(patt.getNPixels());
283 } else {
284 mITSClusterSizes.emplace_back(mITSDict->getNpixels(pattID));
285 }
286 }
287 }
288 o2::its::ioutils::convertCompactClusters(clusITS, pattIt, mITSClustersArray.getClusters(), mITSDict);
289 }
290 mITSClustersArray.finalize();
291
292 auto pvvec = mRecoData->getPrimaryVertices();
293 auto trackIndex = mRecoData->getPrimaryVertexMatchedTracks(); // Global ID's for associated tracks
294 auto vtxRefs = mRecoData->getPrimaryVertexMatchedTrackRefs(); // references from vertex to these track IDs
295 auto prop = o2::base::Propagator::Instance();
296 static int TFCount = 0;
297 int nv = vtxRefs.size() - 1;
298 std::vector<std::vector<checkresid::Track>> slots;
299 mPVUsed.clear();
300 slots.resize(mNThreads);
301 int nvGood = 0, nvUse = 0, nvRefFail = 0;
302 long pvFitDuration{};
303 for (int iv = 0; iv < nv; iv++) {
304 const auto& vtref = vtxRefs[iv];
305 auto pve = pvvec[iv];
306 if (pve.getNContributors() < params.minPVContributors) {
307 continue;
308 }
309 nvGood++;
310 if (params.refitPV) {
311 LOGP(debug, "Refitting PV#{} of {} tracks", iv, pve.getNContributors());
312 auto tStartPVF = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
313 bool res = refitPV(pve, iv);
314 pvFitDuration += std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::system_clock::now()).time_since_epoch().count() - tStartPVF;
315 if (!res) {
316 nvRefFail++;
317 continue;
318 }
319 }
320 nvUse++;
321 mPVUsed.push_back(pve);
322 const auto& itsContRefs = vtref.getITSGloContributors();
323 int idMinITSGlo = 0, idMaxITSGlo = 0;
324 if (params.useITSGloContributors) {
325 if (itsContRefs.getFirstEntry() < vtref.getEntries() && itsContRefs.getEntries() == 0) {
326 LOGP(fatal, "Usage of stored ITS global contributors is requested but they are missing");
327 }
328 idMinITSGlo = itsContRefs.getFirstEntry();
329 idMaxITSGlo = idMinITSGlo + itsContRefs.getEntries();
330 }
331 int cntPVCont = 0;
332 for (int is = 0; is < GTrackID::NSources; is++) {
333 if (!params.useITSGloContributors && (!mTracksSrc[is] || !mRecoData->isTrackSourceLoaded(is))) {
334 continue;
335 }
336 int idMin = vtref.getFirstEntryOfSource(is), idMax = idMin + vtref.getEntriesOfSource(is);
337 DetID::mask_t dm = GTrackID::getSourceDetectorsMask(is);
338 if (!dm[DetID::ITS]) {
339 continue;
340 }
341#ifdef WITH_OPENMP
342#pragma omp parallel for schedule(dynamic) num_threads(mNThreads)
343#endif
344 for (int i = idMin; i < idMax; i++) {
345 auto vid = trackIndex[i];
346 bool pvCont = vid.isPVContributor();
347 if (!pvCont && (params.pvcontribOnly || params.useITSGloContributors)) {
348 continue;
349 }
350 GTrackID gidITS;
351 o2::track::PID pidITS;
352 if (params.useITSGloContributors) {
353 int id = idMinITSGlo + cntPVCont;
354 if (id >= idMaxITSGlo) {
355 LOGP(fatal, "Calculated GlobalContributor ITS track index {} exceeds number of stored indices {}", id, itsContRefs.getEntries());
356 }
357 pidITS = trackIndex[id].getSource();
358 gidITS = GTrackID(trackIndex[id].getIndex(), GTrackID::ITS);
359 cntPVCont++;
360 } else {
361 gidITS = mRecoData->getITSContributorGID(vid);
362 if (gidITS.getSource() != GTrackID::ITS) {
363 continue;
364 }
365 }
366 const auto& itsTrack = mRecoData->getITSTrack(gidITS);
367 if (itsTrack.getNClusters() < params.minITSCl) {
368 continue;
369 }
370 const auto& trc = params.useITSGloContributors ? ((o2::track::TrackParCov&)itsTrack) : mRecoData->getTrackParam(vid);
371 if (!params.useITSGloContributors) {
372 pidITS = trc.getPID();
373 }
374 auto pt = trc.getPt();
375 if (pt < params.minPt || pt > params.maxPt) {
376 continue;
377 }
378 if (std::abs(trc.getTgl()) > params.maxTgl) {
379 continue;
380 }
381#ifdef WITH_OPENMP
382 auto& accum = slots[omp_get_thread_num()];
383#else
384 auto& accum = slots[0];
385#endif
386 auto& resTrack = accum.emplace_back();
387 resTrack.gid = vid;
388 if (!processITSTrack(itsTrack, pve, resTrack, pidITS)) {
389 accum.pop_back();
390 continue;
391 }
392 }
393 }
394 }
395 // output
396 for (const auto& accum : slots) {
397 for (const auto& tr : accum) {
398 if (mDBGOut) {
399 (*mDBGOut) << "res" << "tr=" << tr << "\n";
400 }
401 if (mHMan) {
402 fillHistos(tr);
403 }
404 }
405 }
406 if (mDBGOut) {
407 (*mDBGOut) << "pvUsed" << "pv=" << mPVUsed << "\n";
408 }
409 if (mHMan) {
410 for (const auto& pv : mPVUsed) {
411 mHMan->getHisto(20000 + 0)->Fill(pv.getX());
412 mHMan->getHisto(20000 + 1)->Fill(pv.getY());
413 mHMan->getHisto(20000 + 2)->Fill(pv.getZ());
414 mHMan->getHisto(20000 + 3)->Fill(pv.getNContributors());
415 }
416 }
417 LOGP(info, "processed {} PVs out of {} good vertices (out of {} in total), PV refits took {} mus, {} refits failed", nvUse, nvGood, nv, pvFitDuration, nvRefFail);
418 TFCount++;
419}
420
421bool CheckResidSpec::processITSTrack(const o2::its::TrackITS& iTrack, const o2::dataformats::PrimaryVertex& pv, o2::checkresid::Track& resTrack, o2::track::PID pid)
422{
423 const auto itsClRefs = mRecoData->getITSTracksClusterRefs();
424 auto trFitInw = iTrack.getParamOut(); // seed for inward refit
425 auto trFitOut = iTrack.getParamIn(); // seed for outward refit
426 trFitInw.setPID(pid);
427 trFitOut.setPID(pid);
428 auto prop = o2::base::Propagator::Instance();
430 float pvAlpha = 0;
431 float bz = prop->getNominalBz();
432 std::array<const o2::BaseCluster<float>*, 8> clArr{};
433 std::array<int16_t, 8> clSizeArr{};
434 const auto& params = CheckResidConfig::Instance();
435 std::array<o2::track::TrackParCov, 8> extrapOut, extrapInw; // 2-way Kalman extrapolations, vertex + 7 layers
436 o2::track::TrackParCov trIBOutForIOB, trOBInwForIOB; // IB/OB sub-tracks (pre-R12 state) used for IOB residuals
437
438 auto rotateTrack = [bz](o2::track::TrackParCov& tr, float alpha, o2::track::TrackPar* refLin) {
439 return refLin ? tr.rotate(alpha, *refLin, bz) : tr.rotate(alpha);
440 };
441
442 auto accountCluster = [&](int i, std::array<o2::track::TrackParCov, 8>& extrapDest, o2::track::TrackParCov& tr, o2::track::TrackPar* refLin) {
443 if (clArr[i]) { // update with cluster
444 if (!rotateTrack(tr, i == 0 ? pvAlpha : geom->getSensorRefAlpha(clArr[i]->getSensorID()), refLin) ||
445 !prop->propagateTo(tr, refLin, clArr[i]->getX(), true)) {
446 return 0;
447 }
448 extrapDest[i] = tr; // before update
449 if (!tr.update(*clArr[i])) {
450 return 0;
451 }
452 } else {
453 extrapDest[i].invalidate();
454 return -1;
455 }
456 return 1;
457 };
458
459 auto inv2d = [](float s00, float s11, float s01) -> std::array<float, 3> {
460 auto det = s00 * s11 - s01 * s01;
461 if (det < 1e-16) {
462 LOGP(error, "Singular det {}, input: {} {} {}", det, s00, s11, s01);
463 return {0.f, 0.f, 0.f};
464 }
465 det = 1.f / det;
466 return {s11 * det, s00 * det, -s01 * det};
467 };
468
469 resTrack.points.clear();
470 if (!prop->propagateToDCA(pv, trFitOut, bz)) {
471 LOGP(debug, "Failed to propagateToDCA, {}", trFitOut.asString());
472 return false;
473 }
475 if (params.addPVAsCluster) {
476 float cosAlp, sinAlp;
477 pvAlpha = trFitOut.getAlpha();
478 o2::math_utils::sincos(trFitOut.getAlpha(), sinAlp, cosAlp); // vertex position rotated to track frame
479 bcPV.setXYZ(pv.getX() * cosAlp + pv.getY() * sinAlp, -pv.getX() * sinAlp + pv.getY() * cosAlp, pv.getZ());
480 bcPV.setSigmaY2(0.5 * (pv.getSigmaX2() + pv.getSigmaY2()));
481 bcPV.setSigmaZ2(pv.getSigmaZ2());
482 bcPV.setSensorID(-1);
483 clArr[0] = &bcPV;
484 }
485 // collect all track clusters to array, placing them to layer+1 slot
486 int nCl = iTrack.getNClusters();
487 for (int i = 0; i < nCl; i++) { // clusters are ordered from the outermost to the innermost
488 const auto& curClu = mITSClustersArray[itsClRefs[iTrack.getClusterEntry(i)]];
489
490 int llr = geom->getLayer(curClu.getSensorID());
491 if (clArr[1 + llr]) {
492 LOGP(error, "Cluster at lr {} was already assigned, old sens {}, new sens {}", llr, clArr[1 + llr]->getSensorID(), curClu.getSensorID());
493 }
494 clArr[1 + geom->getLayer(curClu.getSensorID())] = &curClu;
495 clSizeArr[1 + geom->getLayer(curClu.getSensorID())] = mITSClusterSizes[itsClRefs[iTrack.getClusterEntry(i)]];
496 }
497 o2::track::TrackPar refLinInw0, refLinOut0, *refLinOut = nullptr, *refLinInw = nullptr;
498 o2::track::TrackPar refLinIBOut0, refLinOBInw0, *refLinOBInw = nullptr, *refLinIBOut = nullptr;
499 if (params.useStableRef) {
500 refLinOut = &(refLinOut0 = trFitOut);
501 refLinInw = &(refLinInw0 = trFitInw);
502 }
503 trFitOut.resetCovariance();
504 trFitOut.setCov(trFitOut.getQ2Pt() * trFitOut.getQ2Pt() * trFitOut.getCov()[14], 14);
505 trFitInw.resetCovariance();
506 trFitInw.setCov(trFitInw.getQ2Pt() * trFitInw.getQ2Pt() * trFitInw.getCov()[14], 14);
507 // fit in inward and outward direction
508 for (int i = 0; i <= 7; i++) {
509 int resOut, resInw;
510 // process resOut in ascending order (0-->7) and resInw in descending order (7-->0)
511 if (!(resOut = accountCluster(i, extrapOut, trFitOut, refLinOut)) || !(resInw = accountCluster(7 - i, extrapInw, trFitInw, refLinInw))) {
512 return false;
513 }
514 // at layer 3, find the IB track (trIBOut) and the OB track (trOBInw)
515 // propagate both trcaks to a common radius, RCompIBOB (12cm), and rotates
516 // them to the same reference frame for comparison
517 if (i == 3 && resOut == 1 && resInw == 1 && (params.doIBOB || params.doIBOBresiduals) && nCl == 7) {
518 if (params.doIBOBresiduals) { // keep the un-rotated IB/OB sub-tracks for the per-layer IOB residuals below
519 trIBOutForIOB = trFitOut;
520 trOBInwForIOB = trFitInw;
521 }
522 resTrack.trIBOut = trFitOut; // outward track updated at outermost IB layer
523 resTrack.trOBInw = trFitInw; // inward track updated at innermost OB layer
524 o2::track::TrackPar refLinIBOut0, refLinIBIn0;
525 if (refLinOut) {
526 refLinIBOut = &(refLinIBOut0 = refLinOut0);
527 refLinOBInw = &(refLinOBInw0 = refLinInw0);
528 }
529 float xRref;
530 if (!resTrack.trOBInw.getXatLabR(params.rCompIBOB, xRref, bz) ||
531 !prop->propagateTo(resTrack.trOBInw, refLinOBInw, xRref, true) ||
532 !rotateTrack(resTrack.trOBInw, resTrack.trOBInw.getPhiPos(), refLinOBInw) || // propagate OB track to ref R and rotate
533 !rotateTrack(resTrack.trIBOut, resTrack.trOBInw.getAlpha(), refLinIBOut) ||
534 !prop->propagateTo(resTrack.trIBOut, refLinIBOut, resTrack.trOBInw.getX(), true)) { // rotate OB track to same frame and propagate to same X
535 // if any propagation or rotation steps fail, invalidate both tracks
536 return false;
537 }
538 }
539 }
540
541 // extrapolate the IB(OB) sub-track, w/o intermediate updates, to the cluster (or PV pseudo-cluster) of an OB(IB) layer, for the IOB residuals
542 auto extrapIOB = [&](const o2::track::TrackParCov& srcTr, int i) -> std::array<float, 4> { // {dy, dz, sig2y, sig2z}, sig2y<=0 : invalid
543 o2::track::TrackParCov tr = srcTr;
544 auto alpha = i == 0 ? pvAlpha : geom->getSensorRefAlpha(clArr[i]->getSensorID());
545 if (!rotateTrack(tr, alpha, nullptr) || !prop->propagateTo(tr, nullptr, clArr[i]->getX(), true)) {
546 return {0.f, 0.f, 0.f, 0.f};
547 }
548 return {clArr[i]->getY() - tr.getY(), clArr[i]->getZ() - tr.getZ(), tr.getSigmaY2() + clArr[i]->getSigmaY2(), tr.getSigmaZ2() + clArr[i]->getSigmaZ2()};
549 };
550 bool haveIOBTracks = params.doIBOBresiduals && nCl == 7 && trIBOutForIOB.getX() > 1 && trOBInwForIOB.getX() > 1;
551
552 bool innerDone = false;
553 if (params.doResid) {
554 for (int i = 0; i <= 7; i++) {
555 if (clArr[i]) {
556 // calculate interpolation as a weighted mean of inward/outward extrapolations to this layer
557 const auto &tInw = extrapInw[i], &tOut = extrapOut[i];
558 auto wInw = inv2d(tInw.getSigmaY2(), tInw.getSigmaZ2(), tInw.getSigmaZY());
559 auto wOut = inv2d(tOut.getSigmaY2(), tOut.getSigmaZ2(), tOut.getSigmaZY());
560 if (wInw[0] == 0.f || wOut[0] == 0.f) {
561 return false;
562 }
563 std::array<float, 3> wTot = {wInw[0] + wOut[0], wInw[1] + wOut[1], wInw[2] + wOut[2]};
564 auto cTot = inv2d(wTot[0], wTot[1], wTot[2]);
565 auto ywi = wInw[0] * tInw.getY() + wInw[2] * tInw.getZ() + wOut[0] * tOut.getY() + wOut[2] * tOut.getZ();
566 auto zwi = wInw[2] * tInw.getY() + wInw[1] * tInw.getZ() + wOut[2] * tOut.getY() + wOut[1] * tOut.getZ();
567 auto yw = ywi * cTot[0] + zwi * cTot[2];
568 auto zw = ywi * cTot[2] + zwi * cTot[1];
569 // posCl.push_back(clArr[i]->getXYZGlo(*o2::its::GeometryTGeo::Instance()));
570 auto phi = i == 0 ? tInw.getPhi() : tInw.getPhiPos();
571 o2::math_utils::bringTo02Pi(phi);
572 std::array<float, 4> iob{0.f, 0.f, 0.f, 0.f};
573 if (haveIOBTracks) {
574 int lr = i - 1; // -1 = vertex
575 if (lr <= 2) { // vertex or IB layer: extrapolate the OB sub-track to it (the vertex constrains the IB outward fit)
576 iob = extrapIOB(trOBInwForIOB, i);
577 } else { // OB layer: extrapolate the IB sub-track to it
578 iob = extrapIOB(trIBOutForIOB, i);
579 }
580 }
581 resTrack.points.emplace_back(clArr[i]->getY() - yw, clArr[i]->getZ() - zw, cTot[0] + clArr[i]->getSigmaY2(), cTot[1] + clArr[i]->getSigmaZ2(),
582 iob[0], iob[1], iob[2], iob[3], phi, clArr[i]->getZ(), 0.5 * (tInw.getSnp() + tOut.getSnp()), clSizeArr[i], clArr[i]->getSensorID(), i - 1);
583 if (!innerDone) {
584 resTrack.track = tInw;
585 innerDone = true;
586 }
587 } else {
588 LOGP(debug, "No cluster on lr {}", i);
589 }
590 }
591 }
592 return true;
593}
594
595bool CheckResidSpec::refitPV(o2::dataformats::PrimaryVertex& pv, int vid)
596{
598 std::vector<o2::track::TrackParCov> tracks;
599 std::vector<bool> useTrack;
600 std::vector<GTrackID> gidsITS;
601 int ntr = pv.getNContributors(), ntrIni = ntr;
602 tracks.reserve(ntr);
603 useTrack.reserve(ntr);
604 gidsITS.reserve(ntr);
605 const auto& vtref = mRecoData->getPrimaryVertexMatchedTrackRefs()[vid];
606 auto trackIndex = mRecoData->getPrimaryVertexMatchedTracks();
607 const auto& itsContRefs = vtref.getITSGloContributors();
608 if (params.useITSGloContributors && itsContRefs.getEntries()) {
609 int itr = itsContRefs.getFirstEntry(), itLim = itr + itsContRefs.getEntries();
610 for (; itr < itLim; itr++) {
611 auto tid = trackIndex[itr]; // these are ITS tracks, the Source part is substituted by the PID!!!
612 tracks.emplace_back().setPID(tid.getSource());
613 gidsITS.emplace_back(tid.getIndex(), GTrackID::ITS);
614 }
615 } else {
616 int itr = vtref.getFirstEntry(), itLim = itr + vtref.getEntries();
617 for (; itr < itLim; itr++) {
618 auto tid = trackIndex[itr];
619 if (tid.isPVContributor() && mRecoData->isTrackSourceLoaded(tid.getSource())) {
620 tracks.emplace_back().setPID(mRecoData->getTrackParam(tid).getPID());
621 gidsITS.push_back(mRecoData->getITSContributorGID(tid));
622 }
623 }
624 }
625 ntr = tracks.size();
626 useTrack.resize(ntr);
627#ifdef WITH_OPENMP
628#pragma omp parallel for schedule(dynamic) num_threads(mNThreads)
629#endif
630 for (int itr = 0; itr < ntr; itr++) {
631 if (!(useTrack[itr] = refitITStrack(tracks[itr], gidsITS[itr]))) {
632 tracks[itr] = mRecoData->getTrackParam(gidsITS[itr]); // this track will not be used but participates in prepareVertexRefit
633 }
634 }
635 ntr = 0;
636 for (auto v : useTrack) {
637 ntr++;
638 }
639 if (ntr < params.minPVContributors || !mVertexer.prepareVertexRefit(tracks, pv)) {
640 LOGP(warn, "Abandon vertex refit: NcontribNew = {} vs NcontribOld = {}", ntr, ntrIni);
641 return false;
642 }
643 LOGP(debug, "Original vtx: Nc:{} {}, chi2={}", pv.getNContributors(), pv.asString(), pv.getChi2());
644 auto pvSave = pv;
645 pv = mVertexer.refitVertexFull(useTrack, pv);
646 LOGP(debug, "Refitted vtx: Nc:{} {}, chi2={}", ntr, pv.asString(), pv.getChi2());
647 if (pv.getChi2() < 0.f) {
648 LOGP(warn, "Failed to refit PV {}", pvSave.asString());
649 return false;
650 }
651 return true;
652}
653
654bool CheckResidSpec::refitITStrack(o2::track::TrackParCov& track, GTrackID gid)
655{
656 // destination tack might have non-default PID assigned
657 const auto& trkITS = mRecoData->getITSTrack(gid);
658 const auto itsClRefs = mRecoData->getITSTracksClusterRefs();
659 const auto& params = CheckResidConfig::Instance();
660 auto pid = track.getPID();
661 track = trkITS.getParamOut();
662 track.resetCovariance();
663 track.setCov(track.getQ2Pt() * track.getQ2Pt() * track.getCov()[14], 14);
664 track.setPID(pid);
665 auto nCl = trkITS.getNumberOfClusters();
667 auto prop = o2::base::Propagator::Instance();
668 float bz = prop->getNominalBz();
670
671 for (int iCl = 0; iCl < nCl; iCl++) { // clusters are stored from outer to inner layers
672 const auto& cls = mITSClustersArray[itsClRefs[trkITS.getClusterEntry(iCl)]];
673 auto alpha = geom->getSensorRefAlpha(cls.getSensorID());
674 if (!(params.useStableRef ? track.rotate(alpha, refLin, bz) : track.rotate(alpha)) ||
675 !prop->propagateTo(track, params.useStableRef ? &refLin : nullptr, cls.getX(), true)) {
676 LOGP(debug, "refitITStrack failed on propagation to cl#{}, alpha={}, x={} | {}", iCl, alpha, cls.getX(), track.asString());
677 return false;
678 }
679 if (!track.update(cls)) {
680 LOGP(debug, "refitITStrack failed on update with cl#{}, | {}", iCl, track.asString());
681 return false;
682 }
683 }
684 return true;
685}
686
687void CheckResidSpec::fillHistos(const o2::checkresid::Track& trc)
688{
689 const auto& params = CheckResidConfig::Instance();
691 int np = trc.points.size();
692 auto pt = trc.track.getPt();
693 if (pt < params.minPt || pt > params.maxPt) {
694 return;
695 }
696 auto tgl = trc.track.getTgl();
697 // fills, for a given id offset, the dy/dz (+pull) vs phi/Z/pT/tgl histos of layer slot il
698 auto fillLayerResid = [&](int idOffset, int il, float phi, float z, float dy, float dz, float sig2y, float sig2z) {
699 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100)->Fill(phi, dy);
700 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100 + 1000)->Fill(z, dy);
701 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100 + 2000)->Fill(pt, dy);
702 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100 + 3000)->Fill(tgl, dy);
703 if (sig2y > 0) {
704 auto pull = dy / std::sqrt(sig2y);
705 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100 + 5)->Fill(phi, pull);
706 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100 + 5 + 1000)->Fill(z, pull);
707 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100 + 5 + 2000)->Fill(pt, pull);
708 mHMan->getHisto2F(idOffset + il * 10 + 0 * 100 + 5 + 3000)->Fill(tgl, pull);
709 }
710 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100)->Fill(phi, dz);
711 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100 + 1000)->Fill(z, dz);
712 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100 + 2000)->Fill(pt, dz);
713 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100 + 3000)->Fill(tgl, dz);
714 if (sig2z > 0) {
715 auto pull = dz / std::sqrt(sig2z);
716 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100 + 5)->Fill(phi, pull);
717 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100 + 5 + 1000)->Fill(z, pull);
718 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100 + 5 + 2000)->Fill(pt, pull);
719 mHMan->getHisto2F(idOffset + il * 10 + 1 * 100 + 5 + 3000)->Fill(tgl, pull);
720 }
721 };
722 // fills, for a given id offset, the per-chip dy/dz (+pull) histo of a layer point on sensor sens
723 auto fillChipResid = [&](int idOffset, int il, int lr, int sens, float dy, float dz, float sig2y, float sig2z) {
724 if (sens >= 0 && geom->getLayer(sens) == lr) {
725 const int halfBarrel = geom->getHalfBarrel(sens);
726 const int chip = geom->getFirstChipIndex(lr) + geom->getChipIdInLayer(sens);
727 const int chipHistoID = idOffset + (2 * il + halfBarrel) * 100 + 15000;
728 if (halfBarrel >= 0 && halfBarrel < 2) {
729 mHMan->getHisto2F(chipHistoID)->Fill(chip, dy);
730 mHMan->getHisto2F(chipHistoID + 10)->Fill(chip, dz);
731 if (sig2y > 0) {
732 mHMan->getHisto2F(chipHistoID + 5)->Fill(chip, dy / std::sqrt(sig2y));
733 }
734 if (sig2z > 0) {
735 mHMan->getHisto2F(chipHistoID + 15)->Fill(chip, dz / std::sqrt(sig2z));
736 }
737 }
738 }
739 };
740
741 for (int ip = 0; ip < np; ip++) {
742 const auto& pnt = trc.points[ip];
743 int il = pnt.lr >= 0 ? pnt.lr + 1 : 0;
744 fillLayerResid(0, il, pnt.phi, pnt.z, pnt.dy, pnt.dz, pnt.sig2y, pnt.sig2z);
745 if (pnt.lr >= 0) {
746 fillChipResid(0, il, pnt.lr, pnt.sens, pnt.dy, pnt.dz, pnt.sig2y, pnt.sig2z);
747 }
748 if (pnt.sig2yIOB > 0) { // IOB residual was computed for this point
749 fillLayerResid(100000, il, pnt.phi, pnt.z, pnt.dyIOB, pnt.dzIOB, pnt.sig2yIOB, pnt.sig2zIOB);
750 if (pnt.lr >= 0) {
751 fillChipResid(100000, il, pnt.lr, pnt.sens, pnt.dyIOB, pnt.dzIOB, pnt.sig2yIOB, pnt.sig2zIOB);
752 }
753 }
754 }
755 //--------------
756 if (trc.trIBOut.getX() > 1 && std::abs(trc.trIBOut.getX() - trc.trOBInw.getX()) < 0.1) {
757 for (int ip = 0; ip < 5; ip++) {
758 float d = trc.trIBOut.getParam(ip) - trc.trOBInw.getParam(ip);
759 mHMan->getHisto2F(10000 + ip * 10)->Fill(trc.trIBOut.getPhiPos(), d);
760 mHMan->getHisto2F(11000 + ip * 10)->Fill(trc.trIBOut.getZ(), d);
761 mHMan->getHisto2F(12000 + ip * 10)->Fill(pt, d);
762 mHMan->getHisto2F(13000 + ip * 10)->Fill(trc.track.getTgl(), d);
763 float sg = trc.trIBOut.getCovarElem(ip, ip) + trc.trOBInw.getCovarElem(ip, ip);
764 if (sg > 0) {
765 auto pull = d / std::sqrt(sg);
766 mHMan->getHisto2F(10000 + ip * 10 + 5)->Fill(trc.trIBOut.getPhiPos(), pull);
767 mHMan->getHisto2F(11000 + ip * 10 + 5)->Fill(trc.trIBOut.getZ(), pull);
768 mHMan->getHisto2F(12000 + ip * 10 + 5)->Fill(pt, pull);
769 mHMan->getHisto2F(13000 + ip * 10 + 5)->Fill(trc.track.getTgl(), pull);
770 }
771 }
772 }
773}
774
775void CheckResidSpec::bookHistos()
776{
778 mHManV.emplace_back() = std::make_unique<o2::HistoManager>("", fmt::format("{}_hman.root", params.outname));
779 mHMan = mHManV.back().get();
780 mHMan->SetName(params.outname.c_str());
781 auto defLogAxis = [](float xMn, float xMx, int nbin) { // get array for log axis
782 if (xMn <= 0 || xMx <= xMn || nbin < 2) {
783 LOGP(fatal, "Wrong log axis request: xmin = {} xmax = {} nbins = {}", xMn, xMx, nbin);
784 }
785 auto dx = std::log(xMx / xMn) / nbin;
786 std::vector<double> xax(nbin + 1);
787 for (int i = 0; i <= nbin; i++) {
788 xax[i] = xMn * std::exp(dx * i);
789 }
790 return xax;
791 };
792 float minPt = std::max(0.1f, params.minPt), maxPt = std::min(50.f, params.maxPt);
793 auto ptax = defLogAxis(minPt, maxPt, params.nBinsPt);
794
795 // books, for a given id offset (0 for the standard layer residuals, 100000 for the IOB ones) and name/title suffix,
796 // the dy/dz (+pull) vs phi/Z/pT/tgl histos and the per-chip histos; bookVtx controls whether the vtx (il=0) slot is booked
797 auto bookLayerResidHistos = [&](int idOffset, const std::string& suf, bool bookVtx) {
798 const float dyzScale = idOffset ? params.IOBScaleFactor : 1.f; // IOB residuals have a much larger range than the standard ones
799 for (int il = bookVtx ? 0 : 1; il < 8; il++) {
800 std::string lrName = il == 0 ? "Vtx" : fmt::format("Lr{}", il - 1);
801 const float maxDYZ = params.maxDYZ[il] * dyzScale;
802 for (int iyz = 0; iyz < 2; iyz++) {
803 std::string dname = fmt::format("{}{}", iyz == 0 ? "dy" : "dz", suf), dtit = fmt::format("{}{}", iyz == 0 ? "#DeltaY" : "#DeltaZ", suf.empty() ? "" : ("_" + suf));
804 auto h2 = new TH2F(fmt::format("{}_{}_{}", dname, lrName, "phi").c_str(), fmt::format("{}_{{{}}} vs {};#phi;{}", dtit, lrName, "#phi", dtit).c_str(), params.nBinsPhi, 0, TMath::Pi() * 2, params.nBinsRes, -maxDYZ, maxDYZ);
805 mHMan->addHisto(h2, idOffset + il * 10 + iyz * 100);
806 auto h2p = new TH2F(fmt::format("{}_{}_{}_pull", dname, lrName, "phi").c_str(), fmt::format("pull {}_{{{}}} vs {};#phi; pull{}", dtit, lrName, "phi", dtit).c_str(), params.nBinsPhi, 0, TMath::Pi() * 2, params.nBinsRes, -params.maxPull, params.maxPull);
807 mHMan->addHisto(h2p, idOffset + il * 10 + iyz * 100 + 5);
808
809 auto hz2 = new TH2F(fmt::format("{}_{}_{}", dname, lrName, "Z").c_str(), fmt::format("{}_{{{}}} vs {};Z;{}", dtit, lrName, "Z", dtit).c_str(), params.nBinsZ, -params.zranges[il], params.zranges[il], params.nBinsRes, -maxDYZ, maxDYZ);
810 mHMan->addHisto(hz2, idOffset + il * 10 + iyz * 100 + 1000);
811 auto hz2p = new TH2F(fmt::format("{}_{}_{}_pull", dname, lrName, "Z").c_str(), fmt::format("pull {}_{{{}}} vs {};Z; pull{}", dtit, lrName, "Z", dtit).c_str(), params.nBinsZ, -params.zranges[il], params.zranges[il], params.nBinsRes, -params.maxPull, params.maxPull);
812 mHMan->addHisto(hz2p, idOffset + il * 10 + iyz * 100 + 5 + 1000);
813
814 auto hpt2 = new TH2F(fmt::format("{}_{}_{}", dname, lrName, "Pt").c_str(), fmt::format("{}_{{{}}} vs {};p_{{T}};{}", dtit, lrName, "p_{T}", dtit).c_str(), params.nBinsPt, ptax.data(), params.nBinsRes, -maxDYZ, maxDYZ);
815 mHMan->addHisto(hpt2, idOffset + il * 10 + iyz * 100 + 2000);
816 auto hpt2p = new TH2F(fmt::format("{}_{}_{}_pull", dname, lrName, "Pt").c_str(), fmt::format("pull {}_{{{}}} vs {};p_{{T}}; pull{}", dtit, lrName, "p_{T}", dtit).c_str(), params.nBinsPt, ptax.data(), params.nBinsRes, -params.maxPull, params.maxPull);
817 mHMan->addHisto(hpt2p, idOffset + il * 10 + iyz * 100 + 5 + 2000);
818
819 auto htgl2 = new TH2F(fmt::format("{}_{}_{}", dname, lrName, "tgl").c_str(), fmt::format("{}_{{{}}} vs {};tg#lambda;{}", dtit, lrName, "tg#lambda", dtit).c_str(), params.nBinsTgl, -params.maxTgl, params.maxTgl, params.nBinsRes, -maxDYZ, maxDYZ);
820 mHMan->addHisto(htgl2, idOffset + il * 10 + iyz * 100 + 3000);
821 auto htgl2p = new TH2F(fmt::format("{}_{}_{}_pull", dname, lrName, "tgl").c_str(), fmt::format("pull {}_{{{}}} vs {};tg#lambda; pull{}", dtit, lrName, "tg#lambda", dtit).c_str(), params.nBinsTgl, -params.maxTgl, params.maxTgl, params.nBinsRes, -params.maxPull, params.maxPull);
822 mHMan->addHisto(htgl2p, idOffset + il * 10 + iyz * 100 + 5 + 3000);
823
824 if (il > 0) {
825 const int ilr = il - 1;
826 const int nChips = mChipMap.getNChipsOnLayer(ilr) / 2;
827 for (int ib = 0; ib < 2; ++ib) { // chips per halfbarrel
828 const int startChip = ib * nChips + mChipMap.getFirstChipsOnLayer(ilr);
829 auto hc2 = new TH2F(fmt::format("{}_{}_{}", dname, lrName, ib).c_str(), fmt::format("{} Lr{} HB{};chip;{}", dname, lrName, ib, dtit).c_str(), nChips, startChip - 0.5, startChip - 0.5 + nChips, params.nBinsRes, -maxDYZ, maxDYZ);
830 mHMan->addHisto(hc2, idOffset + (2 * il + ib) * 100 + iyz * 10 + 15000);
831 auto hc2p = new TH2F(fmt::format("{}_{}_{}_pull", dname, lrName, ib).c_str(), fmt::format("{} Lr{} HB{} pull;chip;pull{}", dname, lrName, ib, dtit).c_str(), nChips, startChip - 0.5, startChip - 0.5 + nChips, params.nBinsRes, -params.maxPull, params.maxPull);
832 mHMan->addHisto(hc2p, idOffset + (2 * il + ib) * 100 + iyz * 10 + 5 + 15000);
833 }
834 }
835 }
836 }
837 };
838 bookLayerResidHistos(0, "", true);
839 if (params.doIBOBresiduals) { // the vtx slot is included: the PV constrains the IB outward fit, so it gets an OB-extrapolated IOB residual too
840 bookLayerResidHistos(100000, "IOB", true);
841 }
842
843 for (int ip = 0; ip < 5; ip++) {
844 auto h2 = new TH2F(fmt::format("dPar{}_IBOBphi", ip).c_str(), fmt::format("#Delta par{} IB-OB vs phi;#phi;#Delta par{}", ip, ip).c_str(), params.nBinsPhi, 0, TMath::Pi() * 2, params.nBinsRes, -params.maxDPar[ip], params.maxDPar[ip]);
845 mHMan->addHisto(h2, 10000 + ip * 10);
846 auto h2p = new TH2F(fmt::format("dPar{}_IBOBphi_pull", ip).c_str(), fmt::format("pull #Delta par{} IB-OB vs phi;#phi;pull #Delta par{}", ip, ip).c_str(), params.nBinsPhi, 0, TMath::Pi() * 2, params.nBinsRes, -params.maxPull, params.maxPull);
847 mHMan->addHisto(h2p, 10000 + ip * 10 + 5);
848
849 auto hz2 = new TH2F(fmt::format("dPar{}_IBOBz", ip).c_str(), fmt::format("#Delta par{} IB-OB vs Z;Z;#Delta par{}", ip, ip).c_str(), params.nBinsZ, -20., 20., params.nBinsRes, -params.maxDPar[ip], params.maxDPar[ip]);
850 mHMan->addHisto(hz2, 11000 + ip * 10);
851 auto hz2p = new TH2F(fmt::format("dPar{}_IBOBz_pull", ip).c_str(), fmt::format("pull #Delta par{} IB-OB vs Z;Z;pull #Delta par{}", ip, ip).c_str(), params.nBinsZ, -20., 20., params.nBinsRes, -params.maxPull, params.maxPull);
852 mHMan->addHisto(hz2p, 11000 + ip * 10 + 5);
853
854 auto hpt2 = new TH2F(fmt::format("dPar{}_IBOBpt", ip).c_str(), fmt::format("#Delta par{} IB-OB vs pT;p_{{T}};#Delta par{}", ip, ip).c_str(), params.nBinsPt, ptax.data(), params.nBinsRes, -params.maxDPar[ip], params.maxDPar[ip]);
855 mHMan->addHisto(hpt2, 12000 + ip * 10);
856 auto hpt2p = new TH2F(fmt::format("dPar{}_IBOBpt_pull", ip).c_str(), fmt::format("pull #Delta par{} IB-OB vs pT;p_{{T}};pull #Delta par{}", ip, ip).c_str(), params.nBinsPt, ptax.data(), params.nBinsRes, -params.maxPull, params.maxPull);
857 mHMan->addHisto(hpt2p, 12000 + ip * 10 + 5);
858
859 auto htgl2 = new TH2F(fmt::format("dPar{}_IBOBtgl", ip).c_str(), fmt::format("#Delta par{} IB-OB vs tg#lambda;tg#lambda;#Delta par{}", ip, ip).c_str(), params.nBinsTgl, -params.maxTgl, params.maxTgl, params.nBinsRes, -params.maxDPar[ip], params.maxDPar[ip]);
860 mHMan->addHisto(htgl2, 13000 + ip * 10);
861 auto htgl2p = new TH2F(fmt::format("dPar{}_IBOBtgl_pull", ip).c_str(), fmt::format("pull #Delta par{} IB-OB vs tg#lambda;tg#lambda;pull #Delta par{}", ip, ip).c_str(), params.nBinsTgl, -params.maxTgl, params.maxTgl, params.nBinsRes, -params.maxPull, params.maxPull);
862 mHMan->addHisto(htgl2p, 13000 + ip * 10 + 5);
863 }
864 // used PV
865 mHMan->addHisto(new TH1F("pvX", "PV X;x;", params.nBinsPVXYZ, -params.maxHPVXY, params.maxHPVXY), 20000 + 0);
866 mHMan->addHisto(new TH1F("pvY", "PV Y;y;", params.nBinsPVXYZ, -params.maxHPVXY, params.maxHPVXY), 20000 + 1);
867 mHMan->addHisto(new TH1F("pvZ", "PV Z;z;", params.nBinsPVXYZ, -params.maxHPVZ, params.maxHPVZ), 20000 + 2);
868 mHMan->addHisto(new TH1F("pvN", "PV Contributors;Nc;", params.maxHPVN, 1.5, params.maxHPVN + 1.5), 20000 + 3);
869}
870
871void CheckResidSpec::postProcessHistos()
872{
873 printf("Fitting histos\n");
874 if (!mHMan) {
875 if (mHManV.empty()) {
876 LOGP(warn, "nothing to process");
877 return;
878 }
879 mHMan = mHManV[0].get();
880 }
882 auto gs = new TF1("gs", "gaus", -1, 1);
883 int maxH = mPostProcOnly ? mHManV.size() : 1;
884 TObjArray arr;
885 for (int ihm = 0; ihm < maxH; ihm++) {
886 auto* histm = mHManV[ihm].get();
887 if (!histm) {
888 continue;
889 }
890 auto fitSlices = [&](int id) {
891 auto h2 = histm->getHisto2F(id);
892 if (!h2 || h2->GetEntries() < params.minHistoStat2Fit) {
893 return;
894 }
895 h2->FitSlicesY(gs, 0, -1, 0, "QNR", &arr);
896 arr.SetOwner(true);
897 TH1* hmean = (TH1*)arr.RemoveAt(1);
898 if (hmean) {
899 hmean->SetTitle(Form("<%s>", h2->GetTitle()));
900 histm->addHisto(hmean, id + 1);
901 }
902 TH1* hsig = (TH1*)arr.RemoveAt(2);
903 if (hsig) {
904 hsig->SetTitle(Form("#sigma(%s)", h2->GetTitle()));
905 histm->addHisto(hsig, id + 2);
906 }
907 };
908 for (int ioffs = 0; ioffs <= 3; ioffs++) { // vs phi, Z, pT, tgl
909 int offs = ioffs * 1000;
910 for (int iht = 0; iht < 2; iht++) { // resid, pull
911 int offsV = iht == 0 ? 0 : 5;
912 for (int idOffset : {0, 100000}) { // standard and IOB residuals; fitSlices is a no-op if the histo was not booked
913 for (int il = 0; il < 8; il++) {
914 for (int iyz = 0; iyz < 2; iyz++) {
915 fitSlices(idOffset + il * 10 + iyz * 100 + offsV + offs);
916 }
917 }
918 }
919 for (int ip = 0; ip < 5; ip++) {
920 fitSlices(10000 + ip * 10 + offsV + offs);
921 }
922 }
923 }
924 for (int idOffset : {0, 100000}) {
925 for (int il = 1; il < 8; il++) {
926 for (int ib = 0; ib < 2; ib++) {
927 for (int iyz = 0; iyz < 2; iyz++) {
928 for (int iht = 0; iht < 2; iht++) {
929 const int offsV = iht == 0 ? 0 : 5;
930 fitSlices(idOffset + (2 * il + ib) * 100 + iyz * 10 + offsV + 15000);
931 }
932 }
933 }
934 }
935 }
936 }
937 delete gs;
938}
939
940void CheckResidSpec::drawHistos()
941{
942 // gROOT->SetBatch(true);
943 gStyle->SetTitleX(0.3);
944 gStyle->SetTitleY(0.88);
945 gStyle->SetTitleW(0.25);
946 gStyle->SetOptStat(0);
948 int nhm = mHManV.size();
949 std::array<unsigned int, 3> hcol{EColor::kRed, EColor::kBlue, EColor::kGreen + 2};
950 const auto hmNames = o2::utils::Str::tokenize(params.ext_hm_list, ",;");
951 const auto colorNames = o2::utils::Str::tokenize(params.ext_color_list, ",;");
952 const auto markerIDs = o2::utils::Str::tokenize(params.ext_marker_list, ",;");
953 bool useColors = colorNames.size() == hmNames.size() && !colorNames.empty();
954 bool useMarkers = markerIDs.size() == hmNames.size() && !markerIDs.empty();
955 if (!useColors) {
956 LOGP(warn, "{} color names provided for {} external histomanagers, will use automatic colors", colorNames.size(), hmNames.size());
957 }
958 if (!useMarkers) {
959 LOGP(warn, "{} marker IDs provided for {} external histomanagers, will use automatic markers", markerIDs.size(), hmNames.size());
960 }
961 constexpr std::array<std::pair<std::string_view, int>, 15> rootColors{{
962 {"kWhite", EColor::kWhite},
963 {"kBlack", EColor::kBlack},
964 {"kGray", EColor::kGray},
965 {"kRed", EColor::kRed},
966 {"kGreen", EColor::kGreen},
967 {"kBlue", EColor::kBlue},
968 {"kYellow", EColor::kYellow},
969 {"kMagenta", EColor::kMagenta},
970 {"kCyan", EColor::kCyan},
971 {"kOrange", EColor::kOrange},
972 {"kSpring", EColor::kSpring},
973 {"kTeal", EColor::kTeal},
974 {"kAzure", EColor::kAzure},
975 {"kViolet", EColor::kViolet},
976 {"kPink", EColor::kPink},
977 }};
978 auto parseColor = [&rootColors](const std::string& token) -> std::optional<int> {
979 std::string normalized;
980 normalized.reserve(token.size());
981 for (unsigned char ch : token) {
982 if (!std::isspace(ch)) {
983 normalized.push_back(ch);
984 }
985 }
986 for (const auto& [name, value] : rootColors) {
987 if (normalized.compare(0, name.size(), name) != 0) {
988 continue;
989 }
990 const auto increment = std::string_view(normalized).substr(name.size());
991 if (increment.empty()) {
992 return value;
993 }
994 if (increment.size() < 2 || (increment.front() != '+' && increment.front() != '-')) {
995 return std::nullopt;
996 }
997 int offset = 0;
998 const auto* begin = increment.data() + 1;
999 const auto* end = increment.data() + increment.size();
1000 auto [parsedEnd, error] = std::from_chars(begin, end, offset);
1001 if (error != std::errc{} || parsedEnd != end) {
1002 return std::nullopt;
1003 }
1004 const auto signedOffset = increment.front() == '-' ? -static_cast<long long>(offset) : static_cast<long long>(offset);
1005 const auto color = static_cast<long long>(value) + signedOffset;
1006 if (color < std::numeric_limits<int>::min() || color > std::numeric_limits<int>::max()) {
1007 return std::nullopt;
1008 }
1009 return static_cast<int>(color);
1010 }
1011 return std::nullopt;
1012 };
1013 std::vector<int> colors;
1014 if (useColors) {
1015 for (const auto& colorName : colorNames) {
1016 auto color = parseColor(colorName);
1017 if (!color) {
1018 LOGP(warn, "Unrecognized EColor name '{}', will use automatic colors", colorName);
1019 useColors = false;
1020 break;
1021 }
1022 colors.push_back(*color);
1023 }
1024 }
1025 std::vector<int> markers;
1026 if (useMarkers) {
1027 for (const auto& markerID : markerIDs) {
1028 int marker = 0;
1029 const auto* begin = markerID.data();
1030 const auto* end = begin + markerID.size();
1031 auto [parsedEnd, error] = std::from_chars(begin, end, marker);
1032 if (error != std::errc{} || parsedEnd != end) {
1033 LOGP(warn, "Unrecognized marker ID '{}', will use automatic markers", markerID);
1034 useMarkers = false;
1035 break;
1036 }
1037 markers.push_back(marker);
1038 }
1039 }
1040 std::unique_ptr<TLegend> lg;
1041 lg = std::make_unique<TLegend>(0.12, 0.13, 0.9, 0.13 + std::min(0.5f, nhm * 0.2f / 3.f));
1042 lg->SetFillStyle(0);
1043 lg->SetBorderSize(0);
1044 for (int i = 0; i < nhm; i++) {
1045 auto hman = mHManV[i].get();
1046 if (!hman || hman->GetLast() < 1) {
1047 continue;
1048 }
1049 const int marker = useMarkers ? markers[i] : 20 + i + (i % 2) * 4;
1050 const int color = useColors ? colors[i] : hcol[i % hcol.size()];
1051 hman->setMarkerStyle(marker, 0.5);
1052 hman->setColor(color);
1053 auto le = lg->AddEntry(hman->getHisto(1), hman->GetName(), "lp");
1054 le->SetTextColor(color);
1055 }
1056 TCanvas cly("cly", "", 600, 800), clz("clz", "", 600, 800), clpar("clpar", "", 600, 800);
1057 TCanvas czly("czly", "", 600, 800), czlz("czlz", "", 600, 800), czlpar("czlpar", "", 600, 800);
1058 TCanvas cchip("cchip", "", 600, 800);
1059 constexpr std::array<const char*, 4> chipTitles{"#DeltaY", "pull #DeltaY", "#DeltaZ", "pull #DeltaZ"};
1060 auto AddLabel = [](const char* txt, float x = 0.1, float y = 0.9, int color = kBlack, float size = 0.04) {
1061 TLatex* lt = new TLatex(x, y, txt);
1062 lt->SetNDC();
1063 lt->SetTextColor(color);
1064 lt->SetTextSize(size);
1065 lt->Draw();
1066 return lt;
1067 };
1068
1069 auto drawResLr = [this](TCanvas& canv, int offs, const float resMM[8], bool logX) {
1070 canv.Clear();
1071 canv.Divide(2, 4);
1072 int nh = this->mHManV.size();
1073 for (int i = 0; i < 8; i++) {
1074 canv.cd(i + 1);
1075 bool same = false;
1076 for (int j = 0; j < nh; j++) {
1077 auto hman = this->mHManV[j].get();
1078 if (!hman || hman->GetLast() < 1) {
1079 continue;
1080 }
1081 if (auto histo = hman->getHisto(10 * i + offs)) {
1082 histo->Draw(same ? "same" : "");
1083 if (!same) {
1084 histo->SetMinimum(-resMM[i]);
1085 histo->SetMaximum(resMM[i]);
1086 same = true;
1087 }
1088 }
1089 }
1090 gPad->SetGrid();
1091 gPad->SetLogx(logX);
1092 }
1093 };
1094
1095 auto drawResPar = [this](TCanvas& canv, int offs, const float resMM[8], bool logX) {
1096 canv.Clear();
1097 canv.Divide(2, 3);
1098 int nh = this->mHManV.size();
1099 for (int i = 0; i < 5; i++) {
1100 canv.cd(i + 1);
1101 bool same = false;
1102 for (int j = 0; j < nh; j++) {
1103 auto hman = this->mHManV[j].get();
1104 if (!hman || hman->GetLast() < 1) {
1105 continue;
1106 }
1107 if (auto histo = hman->getHisto(10 * i + offs)) {
1108 histo->Draw(same ? "same" : "");
1109 if (!same) {
1110 histo->SetMinimum(-resMM[i]);
1111 histo->SetMaximum(resMM[i]);
1112 same = true;
1113 }
1114 }
1115 }
1116 gPad->SetGrid();
1117 gPad->SetLogx(logX);
1118 }
1119 };
1120
1121 // draws the 8 dy/dz-vs-phi/Z/pT/tgl pages (standard idOffset=0, or IOB idOffset=100000) into pdfName
1122 auto drawLrResidPages = [&](const std::string& pdfName, int idOffset) {
1123 const float dyzScale = idOffset ? params.IOBScaleFactor : 1.f; // IOB residuals have a much larger range than the standard ones
1124 std::array<float, 8> resMMY, resMMZ;
1125 for (int i = 0; i < 8; i++) {
1126 resMMY[i] = params.resMMLrY[i] * dyzScale;
1127 resMMZ[i] = params.resMMLrZ[i] * dyzScale;
1128 }
1129 drawResLr(cly, idOffset + 1, resMMY.data(), false);
1130 cly.cd(2);
1131 lg->Draw();
1132 AddLabel("Y residuals", 0.1, 0.95);
1133 cly.Print(pdfName.c_str());
1134
1135 drawResLr(clz, idOffset + 101, resMMZ.data(), false);
1136 clz.cd(2);
1137 lg->Draw();
1138 AddLabel("Z residuals", 0.1, 0.95);
1139 clz.Print(pdfName.c_str());
1140
1141 drawResLr(czly, idOffset + 1001, resMMY.data(), false);
1142 czly.cd(2);
1143 lg->Draw();
1144 AddLabel("Y residuals", 0.1, 0.95);
1145 czly.Print(pdfName.c_str());
1146
1147 drawResLr(czlz, idOffset + 1101, resMMZ.data(), false);
1148 czlz.cd(2);
1149 lg->Draw();
1150 AddLabel("Z residuals", 0.1, 0.95);
1151 czlz.Print(pdfName.c_str());
1152
1153 drawResLr(czly, idOffset + 2001, resMMY.data(), true);
1154 czly.cd(2);
1155 lg->Draw();
1156 AddLabel("Y residuals", 0.1, 0.95);
1157 czly.Print(pdfName.c_str());
1158
1159 drawResLr(czlz, idOffset + 2101, resMMZ.data(), true);
1160 czlz.cd(2);
1161 lg->Draw();
1162 AddLabel("Z residuals", 0.1, 0.95);
1163 czlz.Print(pdfName.c_str());
1164
1165 drawResLr(czly, idOffset + 3001, resMMY.data(), false);
1166 czly.cd(2);
1167 lg->Draw();
1168 AddLabel("Y residuals", 0.1, 0.95);
1169 czly.Print(pdfName.c_str());
1170
1171 drawResLr(czlz, idOffset + 3101, resMMZ.data(), false);
1172 czlz.cd(2);
1173 lg->Draw();
1174 AddLabel("Z residuals", 0.1, 0.95);
1175 czlz.Print(pdfName.c_str());
1176 };
1177
1178 const std::string mainPdf = fmt::format("{}_hman.pdf", params.outname);
1179 cly.Print(Form("%s[", mainPdf.c_str()));
1180 drawLrResidPages(mainPdf, 0);
1181
1182 drawResPar(clpar, 10001, params.resMMPar, false);
1183 clpar.cd(6);
1184 lg->Draw();
1185 AddLabel("IB-OB tracks params differences at R = 12 cm", 0.2, 0.8);
1186 clpar.Print(mainPdf.c_str());
1187
1188 drawResPar(czlpar, 11001, params.resMMPar, false);
1189 czlpar.cd(6);
1190 lg->Draw();
1191 AddLabel("IB-OB tracks params differences at R = 12 cm", 0.2, 0.8);
1192 czlpar.Print(mainPdf.c_str());
1193
1194 drawResPar(czlpar, 12001, params.resMMPar, true);
1195 czlpar.cd(6);
1196 lg->Draw();
1197 AddLabel("IB-OB tracks params differences at R = 12 cm", 0.2, 0.8);
1198 czlpar.Print(mainPdf.c_str());
1199
1200 drawResPar(czlpar, 13001, params.resMMPar, false);
1201 czlpar.cd(6);
1202 lg->Draw();
1203 AddLabel("IB-OB tracks params differences at R = 12 cm", 0.2, 0.8);
1204 czlpar.Print(mainPdf.c_str());
1205
1206 auto getHMinMax = [this](int id, float marginFrac, float maxDev, int roundToMicrons) -> std::tuple<float, float, float> {
1207 float maxV = std::numeric_limits<float>::lowest(), minV = std::numeric_limits<float>::max();
1208 const int nh = this->mHManV.size();
1209 for (int j = 0; j < nh; j++) {
1210 if (!this->mHManV[j]) {
1211 continue;
1212 }
1213 if (auto histo = this->mHManV[j]->getHisto(id); histo != nullptr) {
1214 const int nb = histo->GetNbinsX();
1215 for (int ib = 1; ib <= nb; ib++) {
1216 float v = histo->GetBinContent(ib);
1217 maxV = std::max(maxV, v);
1218 minV = std::min(minV, v);
1219 }
1220 }
1221 }
1222 if (maxV < minV) {
1223 return {0.f, 1.f, 0.1f};
1224 }
1225 auto delta = maxV - minV;
1226 maxV += delta * marginFrac;
1227 minV -= delta * marginFrac;
1228 if (roundToMicrons > 0) {
1229 maxV = ((int(std::ceil(maxV * 1e4)) / roundToMicrons + 1) * roundToMicrons) * 1e-4;
1230 minV = ((int(std::floor(minV * 1e4)) / roundToMicrons - 1) * roundToMicrons) * 1e-4;
1231 }
1232 minV = std::max(minV, -maxDev);
1233 maxV = std::min(maxV, maxDev);
1234 return {minV, maxV, std::max(std::abs(minV), std::abs(maxV))};
1235 };
1236 auto collectSpread = [](TH1* hin, TH1* hout) {
1237 const int nb = hin->GetNbinsX();
1238 for (int ib = 1; ib <= nb; ib++) {
1239 if (hin->GetBinError(ib) != 0) {
1240 hout->Fill(hin->GetBinContent(ib));
1241 }
1242 }
1243 hout->SetLineColor(hin->GetLineColor());
1244 hout->SetMarkerColor(hin->GetMarkerColor());
1245 hout->SetMarkerStyle(hin->GetMarkerStyle());
1246 };
1247 int nh = this->mHManV.size();
1248 // Draw per-chip residual/pull means and sigmas, and their half-barrel and full-layer spreads.
1249 auto drawChipPages = [&](const std::string& pdfName, int idOffset) {
1250 for (int il = 1; il < 8; ++il) {
1251 for (int iht = 0; iht < 2; iht++) { // residual or pull
1252 for (int ib = 0; ib < 3; ib++) { // two half-barrels, then the full layer
1253 if (iht == 1 && ib < 2) {
1254 continue; // Draw pulls only for the full layer.
1255 }
1256 for (int iyz = 0; iyz < 2; iyz++) {
1257 cchip.Clear();
1258 cchip.Divide(1, ib == 2 ? 2 : 4);
1259 bool havePage = false;
1260 for (int iv = 0; iv < 2; iv++) { // mean or sigma
1261 const float yRange = (iyz == 0 ? params.resMMLrY[il] : params.resMMLrZ[il]) * (idOffset ? params.IOBScaleFactor : 1.f);
1262 const int baseID = idOffset + 15000 + iyz * 10 + 2 * il * 100 + iht * 5 + 1 + iv;
1263 // Use common spread axes for both half-barrels and their full-layer sum.
1264 auto [minV, maxV, absMax] = getHMinMax(baseID, 0.15, (iv == 0 ? 2 : 8) * yRange, 10);
1265 auto [minV1, maxV1, absMax1] = getHMinMax(baseID + 100, 0.15, (iv == 0 ? 2 : 8) * yRange, 10);
1266 minV = std::min(minV, minV1);
1267 maxV = std::max(maxV, maxV1);
1268 absMax = std::max(absMax, absMax1);
1269 if (iht == 1) {
1270 minV = iv ? 0.f : -params.maxPull;
1271 maxV = absMax = params.maxPull;
1272 }
1273 bool drawn = false;
1274 TH1* firstAuto = nullptr;
1275 float maxAuto = 0.f;
1276 for (int j = 0; j < nh; j++) {
1277 auto hman = this->mHManV[j].get();
1278 if (!hman) {
1279 continue;
1280 }
1281 TH1* hmeans = nullptr;
1282 for (int hb = ib == 2 ? 0 : ib; hb < (ib == 2 ? 2 : ib + 1); hb++) {
1283 const int id = baseID + hb * 100;
1284 auto histo = hman->getHisto(id);
1285 if (!histo) {
1286 continue;
1287 }
1288 if (!hmeans) {
1289 if (ib == 2) {
1290 hmeans = new TH1F(Form("%s_layer_spread", histo->GetName()), Form("Lr%d %s %s spread", il - 1, chipTitles[2 * iyz + iht], iv ? "sigma" : "mean"), params.nBinsRes, iv == 0 ? minV : std::max(0.f, minV), maxV);
1291 hman->addHisto(hmeans, idOffset + 25000 + il * 100 + iyz * 10 + iht * 5 + iv);
1292 } else {
1293 hmeans = new TH1F(Form("%s_spread", histo->GetName()), Form("%s spread;#<Delta>", histo->GetTitle()), params.nBinsRes, iv == 0 ? minV : std::max(0.f, minV), maxV);
1294 hman->addHisto(hmeans, id + 2);
1295 }
1296 }
1297 if (iht == 0) {
1298 hmeans->SetXTitle(iv ? "<#sigma>, cm" : "<#Delta>, cm");
1299 }
1300 collectSpread(histo, hmeans);
1301 if (ib < 2) {
1302 histo->SetMaximum(absMax);
1303 histo->SetMinimum(iv ? 0 : -absMax);
1304 if (il > 3) {
1305 histo->SetMarkerSize(0.3);
1306 histo->SetLineStyle(3);
1307 }
1308 cchip.cd(2 * iv + 1);
1309 histo->Draw(drawn ? "same" : "");
1310 gPad->SetGrid();
1311 }
1312 }
1313 if (!hmeans) {
1314 continue;
1315 }
1316 cchip.cd(ib == 2 ? iv + 1 : 2 * iv + 2);
1317 if (!drawn) {
1318 firstAuto = hmeans;
1319 }
1320 maxAuto = std::max(maxAuto, (float)hmeans->GetMaximum());
1321 hmeans->Draw(drawn ? "same" : "");
1322 drawn = havePage = true;
1323 }
1324 if (firstAuto) {
1325 firstAuto->SetMaximum(maxAuto * 1.25);
1326 gPad->SetGrid();
1327 gPad->Modified();
1328 }
1329 }
1330 if (havePage) {
1331 cchip.Print(pdfName.c_str());
1332 }
1333 }
1334 }
1335 }
1336 }
1337 };
1338 drawChipPages(mainPdf, 0);
1339 cly.Print(Form("%s]", mainPdf.c_str()));
1340
1341 // IOB residuals (dyIOB/dzIOB) are optional: only produce the extra PDF if at least one loaded HistoManager actually has them booked
1342 bool haveIOB = false;
1343 for (const auto& hm : mHManV) {
1344 if (hm && hm->getHisto2F(100000 + 1 * 10)) {
1345 haveIOB = true;
1346 break;
1347 }
1348 }
1349 if (haveIOB) {
1350 const std::string iobPdf = fmt::format("{}_iob_hman.pdf", params.outname);
1351 cly.Print(Form("%s[", iobPdf.c_str()));
1352 drawLrResidPages(iobPdf, 100000);
1353 drawChipPages(iobPdf, 100000);
1354 cly.Print(Form("%s]", iobPdf.c_str()));
1355 }
1356}
1357
1359{
1360 mDBGOut.reset();
1361 if (mHManV.size()) {
1362 postProcessHistos();
1363 }
1364 if (mDraw) {
1365 drawHistos();
1366 }
1367 if (auto nh = mHManV.size(); nh > 0 && !mPostProcOnly) {
1368 for (int ihm = 0; ihm < nh; ihm++) {
1369 if (mHManV[ihm]) {
1370 mHManV[ihm].get()->write();
1371 }
1372 }
1373 }
1374}
1375
1377{
1378 if (o2::base::GRPGeomHelper::instance().finaliseCCDB(matcher, obj)) {
1379 return;
1380 }
1381 if (matcher == ConcreteDataMatcher("GLO", "MEANVERTEX", 0)) {
1382 LOG(info) << "Imposing new MeanVertex: " << ((const o2::dataformats::MeanVertexObject*)obj)->asString();
1383 mMeanVtx = *(const o2::dataformats::MeanVertexObject*)obj;
1384 mMeanVertexUpdated = true;
1385 return;
1386 }
1387 if (matcher == ConcreteDataMatcher("ITS", "CLUSDICT", 0)) {
1388 LOG(info) << "cluster dictionary updated";
1389 mITSDict = (const o2::itsmft::TopologyDictionary*)obj;
1390 return;
1391 }
1392}
1393
1394DataProcessorSpec getCheckResidSpec(GTrackID::mask_t srcTracks, GTrackID::mask_t srcClusters, bool drawOnly, bool postProcOnly, bool itsStag)
1395{
1396 std::vector<OutputSpec> outputs;
1397 auto dataRequest = std::make_shared<DataRequest>();
1398 dataRequest->setITSPerLayer(itsStag);
1399 if (!drawOnly && !postProcOnly) {
1400 bool useMC = false;
1401 dataRequest->requestTracks(srcTracks, useMC);
1402 dataRequest->requestClusters(srcClusters, useMC);
1403 dataRequest->requestPrimaryVertices(useMC);
1404 dataRequest->inputs.emplace_back("meanvtx", "GLO", "MEANVERTEX", 0, Lifetime::Condition, ccdbParamSpec("GLO/Calib/MeanVertex", {}, 1));
1405 }
1406 auto ggRequest = drawOnly ? std::make_shared<o2::base::GRPGeomRequest>(false, false, false, false, false, o2::base::GRPGeomRequest::None, dataRequest->inputs) : std::make_shared<o2::base::GRPGeomRequest>(false, // orbitResetTime
1407 true, // GRPECS=true
1408 true, // GRPLHCIF
1409 true, // GRPMagField
1410 true, // askMatLUT
1412 dataRequest->inputs, true);
1413 Options opts;
1414 if (!drawOnly) {
1415 opts = Options{
1416 {"nthreads", VariantType::Int, 1, {"number of threads"}},
1417 {"no-tree", VariantType::Bool, false, {"do not fill residuals tree"}},
1418 {"no-hist", VariantType::Bool, false, {"do not fill residuals histograms"}},
1419 {"draw-report", VariantType::Bool, false, {"fill residuals report"}},
1420 };
1421 }
1422
1423 return DataProcessorSpec{
1424 "check-resid",
1425 dataRequest->inputs,
1426 outputs,
1427 AlgorithmSpec{adaptFromTask<CheckResidSpec>(dataRequest, ggRequest, srcTracks, drawOnly, postProcOnly)},
1428 opts};
1429}
1430
1431} // namespace o2::checkresid
Container of the ITS/MFT clusters addressed by the composed (layer,index) ID.
Wrapper container for different reconstructed object types.
Base track model for the Barrel, params only, w/o covariance.
Definition of the GeometryManager class.
std::ostringstream debug
int32_t i
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
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 Directory with events to Events directory is and not inside events d
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 false
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 true
Helper for geometry and GRP related CCDB requests.
Global index for barrel track: provides provenance (detectors combination), index in respective array...
char error[CURL_ERROR_SIZE]
Definition of the GeometryTGeo class.
std::vector< o2::its::TrackITS > tracks
Utility functions for MC particles.
Definition of the Names Generator class.
Primary vertex finder.
uint32_t j
Definition RawData.h:0
uint16_t pid
Definition RawData.h:2
uint32_t res
Definition RawData.h:0
Wrapper container for different reconstructed object types.
o2::track::TrackParCov TrackParCov
Definition Recon.h:39
Result of refitting TPC-ITS matched track.
Reference on ITS/MFT clusters set.
Referenc on track indices contributing to the vertex, with possibility chose tracks from specific sou...
void setSigmaZ2(T v)
void setSigmaY2(T v)
void setSensorID(std::int16_t sid)
Definition BaseCluster.h:92
void setXYZ(T x, T y, T z)
int addHisto(TH1 *histo, int at=-1)
TH2F * getHisto2F(int id) const
TH1 * getHisto(int id) const
void checkUpdates(o2::framework::ProcessingContext &pc)
static GRPGeomHelper & instance()
void setRequest(std::shared_ptr< GRPGeomRequest > req)
GPUd() value_type estimateLTFast(o2 static GPUd() float estimateLTIncrement(const o2 PropagatorImpl * Instance(bool uninitialized=false)
Definition Propagator.h:180
void endOfStream(EndOfStreamContext &ec) final
This is invoked whenever we have an EndOfStream event.
void run(ProcessingContext &pc) final
void finaliseCCDB(ConcreteDataMatcher &matcher, void *obj) final
CheckResidSpec(std::shared_ptr< DataRequest > dr, std::shared_ptr< o2::base::GRPGeomRequest > gr, GTrackID::mask_t src, bool drawOnly, bool postProcOnly)
void init(InitContext &ic) final
static void updateFromString(std::string const &)
Static class with identifiers, bitmasks and names for ALICE detectors.
Definition DetID.h:60
ServiceRegistryRef services()
Definition InitContext.h:34
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.
static GeometryTGeo * Instance()
int getClusterEntry(int i) const
Definition TrackITS.h:72
static constexpr int getNChipsOnLayer(int lr)
static constexpr int getFirstChipsOnLayer(int lr)
int getNPixels() const
Returns the number of fired pixels.
void beginLayer(int lr)
to be called once all the layers were filled
void init(int nLr)
< prepare for filling nLr layer slots, discarding the previous content
static constexpr unsigned short InvalidPatternID
Definition CompCluster.h:46
int getNpixels(int n) const
Returns the number of fired pixels of the n_th element.
bool isGroup(int n) const
Returns true if the element corresponds to a group of rare topologies.
PVertex refitVertexFull(const std::vector< bool > useTrack, const o2d::VertexBase &vtxSeed)
bool prepareVertexRefit(const TR &tracks, const o2d::VertexBase &vtxSeed)
Definition PVertexer.h:362
void setMeanVertex(const o2d::MeanVertexObject *v)
Definition PVertexer.h:98
GLfloat GLfloat GLfloat alpha
Definition glcorearb.h:279
GLint GLenum GLint x
Definition glcorearb.h:403
GLsizeiptr size
Definition glcorearb.h:659
GLuint color
Definition glcorearb.h:1272
GLuint GLuint end
Definition glcorearb.h:469
const GLdouble * v
Definition glcorearb.h:832
GLuint const GLchar * name
Definition glcorearb.h:781
GLdouble f
Definition glcorearb.h:310
GLint y
Definition glcorearb.h:270
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLenum const GLfloat * params
Definition glcorearb.h:272
GLintptr offset
Definition glcorearb.h:660
GLint GLenum GLboolean normalized
Definition glcorearb.h:867
GLint GLint GLsizei GLint GLenum format
Definition glcorearb.h:275
GLuint id
Definition glcorearb.h:650
GLdouble GLdouble GLdouble z
Definition glcorearb.h:843
uint8_t int statusCode int
o2::framework::DataProcessorSpec getCheckResidSpec(o2::dataformats::GlobalTrackID::mask_t srcTracks, o2::dataformats::GlobalTrackID::mask_t srcClus, bool drawOnly, bool postProcOnly, bool itsStag)
create a processor spec
o2::dataformats::GlobalTrackID GTrackID
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
std::vector< ConfigParamSpec > ccdbParamSpec(std::string const &path, int runDependent, std::vector< CCDBMetadata > metadata={}, int qrate=0)
constexpr int MaxITSLayers
constexpr unsigned int nChips
Definition SpecsV2.h:180
void convertCompactClusters(gsl::span< const itsmft::CompClusterExt > clusters, gsl::span< const unsigned char >::iterator &pattIt, std::vector< o2::BaseCluster< float > > &output, const itsmft::TopologyDictionary *dict)
convert compact clusters to 3D spacepoints
Definition IOUtils.cxx:35
o2::track::TrackParCov int int int float int nCl
const bool const int TrackITSInternal< NLayers > & track
const float const float const float bz
double * getX(double *xyDxy, int N)
double * getY(double *xyDxy, int N)
Enum< T >::Iterator begin(Enum< T >)
Definition Defs.h:158
TrackParCovF TrackParCov
Definition Track.h:33
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
void empty(int)
o2::track::TrackPar track
o2::track::TrackParCov trIBOut
o2::track::TrackParCov trOBInw
std::vector< Point > points
GTrackID getITSContributorGID(GTrackID source) const
auto getITSClustersPatterns(int layer=0) const
const o2::track::TrackParCov & getTrackParam(GTrackID gidx) const
void collectData(o2::framework::ProcessingContext &pc, const DataRequest &request)
const o2::its::TrackITS & getITSTrack(GTrackID gid) const
auto getITSClusters(int layer=0) const
static std::vector< std::string > tokenize(const std::string &src, char delim, bool trimToken=true, bool skipEmpty=true)
constexpr size_t max
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
Cluster clu