BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
BmnAligner.cxx
Go to the documentation of this file.
1/*
2 BM@N alignment routine
3 BM@N experiment at NICA complex, JINR, 2025
4
5 Department: Math & Soft Group of HEP lab
6 Author: Igor Polev, polev@jinr.int
7
8 BmnAligner class implementation
9*/
10
11#include "BmnAligner.h"
12
13#include "BmnAlignConfig.h"
14#include "BmnAlignDefines.h"
15#include "BmnHit.h"
16
17#include <Math/Functor.h>
18#include <TDecompLU.h>
19#include <TDecompSVD.h>
20#include <TError.h>
21#include <TFile.h>
22#include <TRandom.h>
23#include <algorithm>
24#include <cmath>
25#include <fairlogger/Logger.h>
26#include <iostream>
27
28/*
29 * Solver tuning. These are properties of the algorithm below, not of the
30 * alignment task: they change together with the code that reads them, and a
31 * run that changed one is not comparable with the regression baseline. They
32 * are therefore kept here rather than in any configuration a macro can reach.
33 * A value that turns out to need varying per run belongs in the BmnAligner
34 * interface, where the call site states it and the compiler checks it.
35 */
36namespace
37{
38// data ingest
39constexpr Double_t MSE_SLOW_THRESHOLD{2.0}; // seconds per MSE evaluation above which the progress bar is shown
40constexpr Int_t MIN_TRACKS_PER_THREAD{1000}; // multi-threading chunks
41constexpr Double_t MIN_HITS_PORTION{0.01}; // portion of tracks that must hit an element, a lower hit
42 // count is reported as a warning
43constexpr Double_t MAX_ELEMENT_Z_SPREAD{1.0}; // hit z spread within one element (cm) above which the
44 // hierarchy pivot is reported as poorly defined
45constexpr Double_t OUTLIER_FACTOR{3.0}; // reject a track if at least one hit pull deviates from the
46 // median by more than this factor times the pull MAD-sigma
47constexpr Int_t OUTLIER_MIN_SAMPLE{100}; // minimum usable tracks required to perform outlier rejection
48constexpr Double_t VERTEX_OUTLIER_FACTOR{
49 5.0}; // disable a vertex hit if its residual deviates from the median
50 // by more than this factor times the MAD-sigma (the macro/vertex.C window)
51constexpr Double_t MAD_TO_SIGMA{1.4826}; // sigma = MAD_TO_SIGMA * MAD for a normal distribution, 1 / Phi^-1(0.75)
52
53// target z fit, see FitTargetZ()
54constexpr Int_t Z0_MAX_STEPS{10}; // fits at most, each one inside the window of the previous one
55constexpr Double_t Z0_TOLERANCE{1.0E-4}; // cm, z0 change below which (with the same term count) the fit has converged
56constexpr Double_t Z0_WINDOW{5.0}; // pull widths off the fitted line beyond which a term is left out
57constexpr Int_t Z0_MIN_TERMS{100}; // fewer terms leave z0 undetermined
58
59// iteration control
60constexpr Double_t REL_PROGRESS_FAIL{-1.0}; // progress threshold to consider iteration failed
61constexpr Double_t MIN_PROGRESS_STEP{1E-3}; // absolute parameters tolerance for MSE convergence
62constexpr Double_t MIN_REL_PROGRESS{0.001}; // relative tolerance for MSE convergence
63constexpr Double_t REL_PROGRESS_GOOD{0.05}; // relative iteration progress to turn off regularization
64constexpr Int_t MIN_REGULAR_ITERS{2}; // minimum number of sequential iterations with regularization
65constexpr Int_t MAX_REGULAR_RETRY{0}; // maximum number of retries with regularization turned on
66constexpr Double_t ROUND_MIN_CHANGE{1E-3}; // share of the tracks whose state must change after a round
67 // for another round to run, see Align()
68
69// minimizers
70constexpr Double_t STEP_TOLERANCE_1D{0.01}; // absolute tolerance for 1D minimizer
71constexpr Int_t BRENT_GRID_SIZE{4}; // number of points in Brent preliminary grid
72constexpr Int_t LM_ITERATIONS_MIN{3}; // minimum number of Levenberg-Marquardt iterations (at least 2 required)
73constexpr Int_t LM_ITERATIONS_MAX{8}; // maximum number of Levenberg-Marquardt iterations (at least MIN + 1)
74constexpr Double_t LM_MULT_STEP{2.0}; // multiplier for Levenberg-Marquardt factor
75
76static_assert(LM_ITERATIONS_MIN >= 2, "Levenberg-Marquardt needs at least two iterations");
77static_assert(LM_ITERATIONS_MAX > LM_ITERATIONS_MIN, "Levenberg-Marquardt maximum must exceed the minimum");
78
79// one vertex track in the target z fit, x and y: the residual beam - track at the
80// target centre, the track slope, and the variance of the track there
81struct VertexTerm_t
82{
83 Double_t r[2], s[2], var[2];
84};
85
86// Median and MAD-sigma of the values that are not NaN. The buffer is scratch
87// space of the caller, so that a second call does not allocate again.
88std::pair<Double_t, Double_t> MedianAndSigma(const VecDouble_t& values, VecDouble_t& buffer)
89{
90 buffer.clear();
91 for (const Double_t x : values)
92 if (!std::isnan(x))
93 buffer.push_back(x);
94 if (buffer.empty())
95 return {TMath::QuietNaN(), TMath::QuietNaN()};
96
97 const auto mid{buffer.begin() + buffer.size() / 2};
98 std::nth_element(buffer.begin(), mid, buffer.end());
99 const Double_t median{*mid};
100 for (Double_t& x : buffer)
101 x = std::abs(x - median);
102 std::nth_element(buffer.begin(), mid, buffer.end());
103 return {median, MAD_TO_SIGMA * *mid};
104}
105} // anonymous namespace
106
107// TODO: track why ROOT consumes a lot of memory
108// TODO: refactor code for usage of const, noexcept etc.
109// TODO: refactor code for usage of smart pointers
110
112 BmnDetectorModel* modelDetector,
113 const char* filesListPath,
114 const char* constraintsPath,
115 const char* presigmaPath,
116 Int_t nThreads,
117 Bool_t withProgressBar)
118 : fpMeasureModel(measureModel)
119 , fpDetModel(modelDetector)
120 , fpConstraintsPath(constraintsPath)
121 , fpPresigmaPath(presigmaPath)
122 , fThreadsCnt(nThreads)
123{
124 TStopwatch timer;
125 LOG(state) << " > BmnAligner : initialization started";
126
127 TH1D::AddDirectory(kFALSE); // unbind all historgrams from default file
128 TH1D::StatOverflows(kTRUE); // do not ignore overflows in mean and stddev
129 fBrent.SetNpx(BRENT_GRID_SIZE); // lower bracketing points number to speed up Brent algorithm
130 if (withProgressBar)
132
133 if (!modelDetector->Initialized()) {
134 LOG(error) << "<!> detector model is not initialized: call Init() on it"
135 " right after construction (see BmnDetectorModel)";
136 LOG(state) << " < BmnAligner : initialization terminated";
137 return;
138 }
139 LOG(info) << " --- TASK CONFIG ---------------------------------------------------";
140 LOG(info) << " measure model: " << measureModel->Description();
141 LOG(info) << " detector model: " << modelDetector->Description();
142 LOG(info) << " -------------------------------------------------------------------";
143
144 // initialize ROOT file iterator
145 LOG(info) << " " << filesListPath << " : .root files list";
146 LOG(info) << " Tracks selection: " << BMN_TRACKS_CUT_STR;
147 LOG(info) << " Hits selection: " << BMN_HITS_CUT_STR;
148 LOG_IF(info, fpDetModel->TargetID() >= 0) << " Vertex hit: " << BMN_VERTEX_CUT_STR;
150 new BmnRootIterator(filesListPath, *fpDetModel, BmnDefaultTrackFilter(kTRUE /* whole track only */),
152 if (!fpRootIterator->Initialized()) {
153 LOG(error) << "<!> ROOT iterator initialization failed";
154 return;
155 }
156 fpRootIterator->CountElements();
157 fTotalTracks = fpRootIterator->GetTotalTracks();
158 fTotalHits = fpRootIterator->GetTotalHits();
159 if (!fTotalTracks || !fTotalHits) {
160 LOG(error) << "<!> dataset is invalid: " << fTotalTracks << " tracks, " << fTotalHits << " hits";
161 LOG(state) << " < BmnAligner : initialization terminated";
162 return;
163 }
164
165 // all track are usable by default
166 // TODO : replace std::vector with TBits
169
170 // Currently all hits are read from the files once and iterated in RAM during
171 // calculations. Previously available direct ROOT file reading during the
172 // calculations was deprecated and not supported at the moment.
173 // This mode can be resored with some effort if needed -- the virtual
174 // interface of BmnDataIterator is ready for that.
175
176 // CAUTION: fHits is reserved, not resized -- BmnHitRecord has no default
177 // constructor -- which is intentional. The records are built in place by
178 // PrepareData(). The pointers given to the iterator stay valid only while
179 // fHits and fFirstHits do not reallocate.
180 fHits.reserve(fTotalHits);
181 fFirstHits.resize(fTotalTracks + 1); // one extra element for iterator convenience
182 fAlphaRecs.resize(fTotalHits);
184
185 LOG(info) << Form(" %.1f GB of RAM required",
186 fTotalHits * (sizeof(BmnHitRecord) + sizeof(AlphaData_t)) / 1073741824.0);
187
188 // prepare set of iterators for parallelization by data
190
192 DoneInTime(timer, "initialization");
193}
194
196{
197 delete fpProgressBar;
198 delete fpTrackUsable;
199 delete fpRootIterator;
200 delete fpRamIterator;
201 if (fThreadsCnt > 1)
202 for (auto pItr : fpIterators)
203 delete pItr;
204}
205
206/*
207 * Reads the data into RAM and builds the parametrization and the priors on it.
208 *
209 * fitTargetZ: the nominal target position of the geometry file may be off by
210 * centimetres. With this flag the z where the tracks meet the beam is measured
211 * (FitTargetZ()) and the target is moved there in the detector model.
212 * The vertex hit is the beam line taken at the target z, so
213 * the data is then read once more, and the vertex hits are built at the new z.
214 * The target dZ stays a small correction, and its presigma keeps its meaning,
215 * now around the measured z. The solution files still hold the target dZ of
216 * the geometry file, see the target note in BmnAlignConfig.h.
217 */
218Bool_t BmnAligner::PrepareData(const char* dumpPath, Bool_t fitTargetZ)
219{
220 TStopwatch timer;
221 LOG(state) << " > BmnAligner : data preparation started";
222 if (!CheckInit("data preparation"))
223 return kFALSE;
224
225 // optional: compact copy of input data into a single .root file
226 // structure mirrors MakeTestTask output so the dump can be read back
227 // with BmnRootIterator (DstEventHeader branch is absent in the dump)
228 TFile* dumpFile{nullptr};
229 TTree* dumpTree{nullptr};
230 TClonesArray *dumpTrks{nullptr}, *dumpHits{nullptr},
231 *dumpBeam{nullptr}; // SiBT hits, kept only when the model builds a vertex hit from them
232 // cleanup helper - called on every exit when dumpPath is set
233 auto CleanupDump = [&]() {
234 if (!dumpPath)
235 return;
236 delete dumpFile; // also deletes dumpTree owned by the file directory
237 delete dumpTrks;
238 delete dumpHits;
239 delete dumpBeam;
240 };
241 if (dumpPath) {
242 dumpFile = new TFile(dumpPath, "RECREATE");
243 if (dumpFile->IsZombie()) {
244 LOG(error) << " <!> PrepareData: failed to create dump file " << dumpPath;
245 CleanupDump();
246 return kFALSE;
247 }
248 dumpFile->cd();
249 dumpTrks = new TClonesArray("CbmStsTrack", 200);
250 dumpHits = new TClonesArray("CbmStsHit", 200 * fpDetModel->Alignables());
251 // see comment in MakeTestTask about why an independent TTree is used
252 // instead of CloneTree(0) when source is a multi-file TChain
253 dumpTree = new TTree(fpRootIterator->GetChain().GetTree()->GetName(),
254 fpRootIterator->GetChain().GetTree()->GetTitle());
255 dumpTree->SetDirectory(dumpFile);
256 dumpTree->Branch(BMN_TRACKS_BRANCH_NAME, "TClonesArray", &dumpTrks);
257 dumpTree->Branch(BMN_HITS_BRANCH_NAME, "TClonesArray", &dumpHits);
258 // copied as plain BmnHit: that is all the iterator reads of them
259 if (fpDetModel->TargetID() >= 0) {
260 dumpBeam = new TClonesArray("BmnHit", 3);
261 dumpTree->Branch(BMN_BEAM_BRANCH_NAME, "TClonesArray", &dumpBeam);
262 }
263 LOG(info) << " " << dumpPath << " : dumping compacted input data to this file";
264 }
265
266 LOG(info) << " loading data from ROOT files into RAM...";
267
268 // The containers with one entry per element are sized from the detector
269 // model, the single source of that count, and reset here, so that the
270 // second load of fitTargetZ counts afresh.
271 const Int_t elements{fpDetModel->Alignables()};
272 fHitsPerDetector.assign(elements, 0);
273 fLeafZsum.assign(elements, 0.0);
274 fLeafZmin.assign(elements, TMath::Infinity());
275 fLeafZmax.assign(elements, -TMath::Infinity());
276 fMaxZvalue = 0.0;
277
278 Int_t detID, iTrack{0}, iHit{0}, // global hit index
279 stsHits{0}; // hits read from the files, the vertex hits not counted
280 Double_t Dx{0.0}, Dy{0.0};
281 fHits.clear(); // keeps the capacity, so a repeated call refills the same memory
282 fpProgressBar->Init();
283 fpRootIterator->ResetAll();
284 while (!fpRootIterator->EndOfTracks()) { // `while` instead of `for` is necessary here, see comment below
285 fFirstHits[iTrack] = iHit;
286
287 // dump-mode: the beam hits of the event go out once, with its first track
288 if (dumpBeam && fpRootIterator->IsNewEvent()) {
289 const TClonesArray& beamHits{*fpRootIterator->GetBeamHits()};
290 for (Int_t i = 0; i < beamHits.GetEntriesFast(); i++)
291 new ((*dumpBeam)[i]) BmnHit(*static_cast<const BmnHit*>(beamHits.At(i)));
292 }
293
294 // dump-mode: per-track array of hit indices local to the output event
295 TArrayI dumpHitArr;
296 Int_t dumpArrIdx{0};
297 if (dumpPath)
298 dumpHitArr.Set(fpRootIterator->HitsInTrack() - fpRootIterator->HasVertexHit());
299
300 // iterate hits in track
301 for (; !fpRootIterator->EndOfHits(); fpRootIterator->NextHit(), iHit++) {
302 detID = fpRootIterator->HitDetectorID();
303 // check if detector element encoding is valid
304 if (fpDetModel->UnknownID(detID)) {
305 const BmnRootIterator::Hit_t* hit{fpRootIterator->GetHit()};
306 LOG(error) << " <!> Unknown detector module encoding:"
307 << "\n iterator::HitDetectorID() = " << detID
308 << "\n DetectorModel::DecodeID() = " << fpDetModel->DecodeID(detID)
309 << "\n FairHit::GetDetectorID() = " << hit->GetDetectorID()
310 << "\n CbmStsHit::GetSystemId() = " << hit->GetSystemId()
311 << "\n CbmStsHit::GetStationNr() = " << hit->GetStationNr()
312 << "\n CbmStsHit::GetSectorNr() = " << hit->GetSectorNr()
313 << "\n CbmStsHit::GetSensorNr() = " << hit->GetSensorNr();
314 CleanupDump();
315 return kFALSE;
316 }
317 // count hits for each detector element
318 const Int_t detIdx{fpDetModel->Idx(detID)};
319 fHitsPerDetector[detIdx]++;
320
321 // null on the vertex hit, which has no counterpart in the files
322 const BmnRootIterator::Hit_t* srcHit{fpRootIterator->GetHit()};
323
324 // inplace hit copy
325 if (srcHit)
326 fHits.emplace_back(srcHit, *fpDetModel);
327 else
328 fHits.emplace_back(fpRootIterator->HitX(), fpRootIterator->HitY(), fpRootIterator->HitZ(),
329 1.0 / std::sqrt(fpRootIterator->HitWx()), 1.0 / std::sqrt(fpRootIterator->HitWy()),
330 detID);
331
332 // dump-mode: raw copy of hit into output event array
333 if (dumpPath && srcHit) {
334 Int_t newHitIdx{dumpHits->GetEntriesFast()};
335 new ((*dumpHits)[newHitIdx]) CbmStsHit(*srcHit);
336 dumpHitArr[dumpArrIdx++] = newHitIdx;
337 }
338
339 // find max Z value (for visualization only)
340 const Double_t hitZ{fpRootIterator->HitZ()};
341 if (hitZ > fMaxZvalue)
342 fMaxZvalue = hitZ;
343 // per-element z statistics: mean gives the hierarchy pivot, spread
344 // tells how well the hit-independent Jacobian holds
345 fLeafZsum[detIdx] += hitZ;
346 if (hitZ < fLeafZmin[detIdx])
347 fLeafZmin[detIdx] = hitZ;
348 if (hitZ > fLeafZmax[detIdx])
349 fLeafZmax[detIdx] = hitZ;
350 // calculate average hit position errors
351 if (srcHit) {
352 Dx += srcHit->GetDx();
353 Dy += srcHit->GetDy();
354 stsHits++;
355 }
356 } // loop over hits
357
358 // dump-mode: raw copy of track with hit indices rewritten to local positions
359 if (dumpPath) {
360 const BmnRootIterator::Track_t* srcTrack{fpRootIterator->GetTrack()};
361 Int_t newTrkIdx{dumpTrks->GetEntriesFast()};
362 CbmStsTrack* newTrack{new ((*dumpTrks)[newTrkIdx]) CbmStsTrack(*srcTrack)};
363 newTrack->SetStsHits(dumpHitArr);
364 }
365
366 fpRootIterator->NextTrack();
367 iTrack++;
368 // dump-mode: flush accumulated event if the next track opens a new one or there is none.
369 // CAUTION: the test looks one track ahead - NextTrack() must stay right before it
370 if (dumpPath && (fpRootIterator->IsNewEvent() || fpRootIterator->EndOfTracks())) {
371 dumpFile->cd();
372 dumpTree->Fill();
373 dumpTrks->Delete(); // Delete() over Clear() to avoid memory leaks
374 dumpHits->Delete();
375 if (dumpBeam)
376 dumpBeam->Delete();
377 }
378 } // loop over tracks
379 fFirstHits[iTrack] = iHit; // last syntetic element for iterator convenience
380 fpProgressBar->Clear();
381
382 // dump-mode: finalize output file
383 if (dumpPath) {
384 dumpFile->Write("", TObject::kOverwrite);
385 dumpFile->Close();
386 CleanupDump();
387 LOG(info) << " " << dumpPath << " : compacted data successfully created";
388 }
389
390 // An element without hits cannot be aligned at all, and its hierarchy pivot
391 // (the mean hit z below) is undefined. Few hits only leave its corrections
392 // poorly determined, which the priors can take care of.
393 const Int_t minHits{static_cast<Int_t>(MIN_HITS_PORTION * fTotalTracks / fpDetModel->MaxModulesInStation())};
394 Int_t emptyCount{0};
395 for (Int_t i = 0; i < Elements(); i++) {
396 const Int_t ID{fpDetModel->EncodedID(i)};
397 if (!fHitsPerDetector[i]) {
398 LOG(error) << " <!> PrepareData: detector element " << ID << " (" << fpDetModel->DecodeID(ID)
399 << ") has no hits";
400 emptyCount++;
401 } else if (fHitsPerDetector[i] < minHits)
402 LOG(warning) << Form(" ! detector element %d (%s) has only %d hits of %d expected", ID,
403 fpDetModel->DecodeID(ID).c_str(), fHitsPerDetector[i], minHits);
404 }
405 if (emptyCount) {
406 LOG(error) << " <!> PrepareData: " << emptyCount << " detector element(s) without hits, alignment stopped";
407 return kFALSE;
408 }
409
410 LOG(info) << " " << iTrack << " tracks loaded into RAM";
411 LOG(info) << " " << iHit << " hits loaded into RAM";
412 LOG(info) << Form(" (%.1e, %.1e) : average STS hit position errors in loaded data", Dx / stsHits, Dy / stsHits);
413 if (fpDetModel->TargetID() >= 0) {
414 const Int_t vertexHits{fHitsPerDetector[fpDetModel->Idx(fpDetModel->TargetID())]};
415 LOG(info) << Form(" %d (%.1f%%) tracks take the vertex hit", vertexHits, 100.0 * vertexHits / iTrack);
416 }
417
418 // Build the parameter layout. It has to happen before the configuration
419 // files below, which are addressed in that layout.
420 VecDouble_t leafZ(Elements(), 0.0);
421 Double_t maxZspread{0.0};
422 Int_t wideCount{0};
423 for (Int_t i = 0; i < Elements(); i++) {
424 leafZ[i] = fLeafZsum[i] / fHitsPerDetector[i];
425 const Double_t spread{fLeafZmax[i] - fLeafZmin[i]};
426 if (spread > maxZspread)
427 maxZspread = spread;
428 if (spread <= MAX_ELEMENT_Z_SPREAD)
429 continue;
430 LOG_IF(warning, !wideCount++)
431 << " ! these elements span more z than one plane would, so their pivot is a compromise:";
432 LOG(warning) << Form(" det %2d (id %9d, %s) : z = %.3f cm, spread %.3f cm", i, fpDetModel->EncodedID(i),
433 fpDetModel->DecodeID(fpDetModel->EncodedID(i)).c_str(), leafZ[i], spread);
434 }
435 LOG(info) << Form(" %.2e cm : largest hit z spread within a detector element", maxZspread);
436 fHierarchy.BeginBuild(*fpDetModel, leafZ);
437 // The detector model is the only source of composite nodes: its grouping
438 // follows from the enumeration scheme itself, so it cannot disagree with
439 // the element indices the constraints and presigmas are addressed by.
440 const std::vector<BmnDetectorModel::Composite> modelNodes{fpDetModel->Composites()};
441 for (const BmnDetectorModel::Composite& node : modelNodes)
442 if (!fHierarchy.AddComposite(node.name, node.parent, node.leaves, nullptr))
443 return kFALSE;
444 LOG(info) << (modelNodes.empty()
445 ? " flat parametrization: the detector model declares no composite nodes"
446 : Form(" %zu composite node(s) declared by the detector model", modelNodes.size()));
447 if (!fHierarchy.EndBuild()) {
448 LOG(error) << "<!> failed to build the detector hierarchy";
449 return kFALSE;
450 }
451
452 fPriors.Init(fHierarchy); // sizes the priors to the layout just built
454 return kFALSE;
456 return kFALSE;
457 if (!fPriors.Check(fHierarchy))
458 return kFALSE;
459 DoneInTime(timer, "data preparation");
460 if (!fitTargetZ)
461 return kTRUE;
462
463 const Double_t zC{0.5 * (fpDetModel->Target().zStart + fpDetModel->Target().zEnd)};
464 Double_t z0, z0Err;
465 if (!FitTargetZ(z0, z0Err))
466 return kFALSE;
467 fpDetModel->ShiftTarget(z0 - zC);
468 const Double_t dZsigma{
469 fPriors.SigmaAt(fHierarchy.Layout().ByNode()[fpDetModel->Idx(fpDetModel->TargetID())].params[idZ].full)};
470 const Bool_t beyond{dZsigma > 0.0 && TMath::Abs(z0 - zC) > dZsigma}; // no presigma: any shift is fine
471 const TString excess{beyond ? TString::Format(", more than its dZ presigma %.3f cm", dZsigma) : TString()};
472 const TString moved{
473 Form("%+.3f cm : target moved in the detector model, now from %.3f to %.3f cm%s; reading the data again",
474 z0 - zC, fpDetModel->Target().zStart, fpDetModel->Target().zEnd, excess.Data())};
475 LOG_IF(warning, beyond) << " ! " << moved;
476 LOG_IF(info, !beyond) << " " << moved;
477 return PrepareData(nullptr, kFALSE); // the dump, if any, is complete: it holds no vertex hits
478}
479
480Bool_t BmnAligner::LoadSolution(const char* jsonPath) // use jsonPath = "" to add blank solution
481{
482 if (!jsonPath)
483 return kTRUE;
484
485 TStopwatch timer;
486 LOG(state) << " > BmnAligner : loading solution from file";
487 if (!CheckInit("solution loading"))
488 return kFALSE;
489 if (jsonPath[0] == '\0') { // blank solution
490 LOG(info) << " filename is empty, adding blank solution";
492 if (fpRamIterator)
494 DoneInTime(timer, "solution load");
495 return kTRUE;
496 } else {
497 LOG(info) << " " << jsonPath << " : file to load solution from";
498 }
499
500 // reading the file is BmnAlignConfig's business; applying what it says -
501 // adding a result, redoing the local parameters - is ours
503 if (!BmnAlignConfig::ReadSolution(jsonPath, fHierarchy, solution))
504 return kFALSE;
505
506 if (!solution.leaves.empty()) {
508 for (const BmnAlignConfig::NodeValues& leaf : solution.leaves)
509 fpResultLast->A(leaf.node) = leaf.values;
510 fpResultLast->ConcatenateA();
511 }
512 if (fpResultLast && solution.zeroComposites) {
513 TVectorD& params{fpResultLast->A()};
514 // absent from the file means "no own share"
515 params.SetSub(fHierarchy.CompositeParamBase(), TVectorD(fHierarchy.CompositeParams()));
516 for (const BmnAlignConfig::NodeValues& comp : solution.composites)
517 for (const ParamRef& p : fHierarchy.Layout().ByNode()[comp.node].params)
518 params(p.full) = comp.values(p.prm);
519 }
520
521 if (fpRamIterator) // to make global params load into uninitialized object possible
523
524 DoneInTime(timer, "solution load");
525 return kTRUE;
526}
527
528Bool_t BmnAligner::SaveSolution(const char* jsonPath, Bool_t withAlpha)
529{
530 if (!jsonPath)
531 return kTRUE;
532 if (!CheckInit("solution saving"))
533 return kFALSE;
534 return BmnAlignConfig::WriteSolution(jsonPath, fHierarchy, ResultLast(), fTotalTracks, withAlpha);
535}
536
538{
539 // iterate tracks
540 Int_t iTrack;
541 BmnRamIterator* pItr;
542 SelectIterator(threadNum, iTrack, pItr);
543 for (pItr->ResetAll(); !pItr->EndOfTracks(); pItr->NextTrack(), iTrack++) {
544 BmnWeightedLine lineX, lineY;
545 for (; !pItr->EndOfHits(); pItr->NextHit()) {
546 SVect3 hit{pItr->HitX(), pItr->HitY(), pItr->HitZ()};
547 fpMeasureModel->AlignHitApproximately(hit, fpResultLast->A(fpDetModel->Idx(pItr->HitDetectorID())));
548 lineX.Add(hit(iZ), hit(iX), pItr->HitWx());
549 lineY.Add(hit(iZ), hit(iY), pItr->HitWy());
550 }
551 fpResultLast->Alpha(iTrack) = SVectLC(lineX.At0(), lineX.Slope(), lineY.At0(), lineY.Slope());
552 }
553}
554
555/*
556 * Randomize a solution level by level.
557 *
558 * Both sigma vectors are read by parameter index (0..BMN_GLOBAL_PARAMS_PD-1):
559 * pStdDevLeaf is the displacement given to an element on its own,
560 * pStdDevComp the one given to a composite node, null to leave that level alone.
561 *
562 * The composite level goes first, because A() holds the *effective* element
563 * corrections and those have to contain what the ancestors contribute:
564 * A = own + J * Pcomp. Randomizing elements alone produces a swarm of
565 * independent wiggles - precisely the alternative a hierarchy exists to tell
566 * apart from a coherent motion of a whole structure, so a test task built that
567 * way cannot exercise the mechanism it is meant to check.
568 */
569void BmnAligner::RandomizeSolution(BmnAlignResult& solution, TVectorD* pStdDevLeaf, TVectorD* pStdDevComp)
570{
571 TVectorD dP(fHierarchy.AllParams()); // random increments added by this call, full layout
572
573 // ---- composite level ----
574 if (pStdDevComp && pStdDevComp->NonZeros() && fHierarchy.CompositeCount()) {
575 for (const ParamRef& p : fHierarchy.Layout().Composites()) {
576 const Double_t sigma{(*pStdDevComp)[p.prm]};
577 if (sigma)
578 dP[p.full] = gRandom->Gaus(0.0, sigma);
579 }
580 // Propagate into the element corrections: they move with their
581 // ancestors. Only the increment - the effective corrections already hold
582 // what the composites carried before this call.
583 dP.SetSub(0, fHierarchy.J() * dP.GetSub(fHierarchy.CompositeParamBase(), fHierarchy.AllParams() - 1));
584 }
585
586 // ---- element level ----
587 SVectGL trueMeans; // what this call adds, averaged over the elements
588 for (const ParamRef& p : fHierarchy.Layout().Leaves()) {
589 const Double_t sigma{(*pStdDevLeaf)[p.prm]};
590 if (sigma)
591 dP[p.full] += gRandom->Gaus(0.0, sigma);
592 trueMeans(p.prm) += dP[p.full];
593 }
594 trueMeans *= 1.0 / fHierarchy.LeafCount();
595
596 solution.A() += dP;
597 solution.SeparateA();
598
599 // Compensate for non-ideal zero mean of random generator - including the
600 // mean the composite level just introduced, so that the truth satisfies the
601 // same centering the constraints impose on the solution. It is taken off the
602 // elements' own share (Pcomp stays as drawn), the two being indistinguishable
603 // to everything but the priors.
604 for (Int_t i = 0; i < Elements(); i++)
605 solution.A(i) -= trueMeans;
606
607 solution.ConcatenateA();
608}
609
610/*
611 * Main alignment loop.
612 * Due to non-linearity of dependence between measurements and alignment parameters,
613 * iterative alignment is required.
614 * zeroRand - StdDev for zero approximation randomization
615 * maxRounds - rounds of iterations at most, see the main loop; 1 judges the tracks once
616 */
618{
619 TStopwatch timer;
620 LOG(state) << " > BmnAligner : iterative alignment started";
621 if (!CheckInit("alignment"))
622 return kFALSE;
623 if (maxRounds < 1) {
624 LOG(error) << " <!> BmnAligner::Align: maxRounds " << maxRounds << " is less than 1";
625 return kFALSE;
626 }
627
628 // zero approximation generation
629 if (!fpResultLast)
631 if (zeroRand > 0.0) {
632 // read per correction, not per parameter - see RandomizeSolution
634 stdDev = zeroRand;
635 RandomizeSolution(*fpResultLast, &stdDev, nullptr);
636 LOG(info) << " zero approximation randomized with StdDev = " << zeroRand;
637 } else
638 LOG(info) << " zero approximation randomization skipped";
640
641 // outlier rejection: the vertex hits are tested on the starting geometry so that
642 // a bad one does not bend the lines of the first iteration, the tracks later on
643 const Bool_t outlierOn{OUTLIER_FACTOR > 0.0 && fTracksUsableCnt >= OUTLIER_MIN_SAMPLE},
644 vertexOn{fpDetModel->TargetID() >= 0};
645 LOG_IF(info, OUTLIER_FACTOR <= 0.0) << " outlier rejection skipped by setup";
646 LOG_IF(warning, OUTLIER_FACTOR > 0.0 && !outlierOn)
647 << " ! " << fTracksUsableCnt << " tracks available only, outlier rejection skipped";
648
649 if (vertexOn)
651 // the vertex hits are tested again once an iteration has taken up the large
652 // offsets of the starting geometry: the target z and the station halves
653 Bool_t outlierTest{outlierOn}, vertexTest{vertexOn};
654
655 // evaluate MSE calculation time - just for proper progress bar utilization
656 TStopwatch timerMSE;
657 timerMSE.Stop();
658 timerMSE.Reset();
659 TVectorD point(fHierarchy.AllParams());
660 for (Int_t i = 0; i < BMN_GLOBAL_PARAMS_PD; i++) {
661 gRandom->RndmArray(point.GetNrows(), point.GetMatrixArray());
662 timerMSE.Start(kFALSE);
663 CalculateMSE(point);
664 timerMSE.Stop();
665 }
666 fMSEclcSlow = timerMSE.RealTime() / BMN_GLOBAL_PARAMS_PD > MSE_SLOW_THRESHOLD;
667 if (!fMSEclcSlow)
668 fMSEclcTick = static_cast<UInt_t>(MSE_SLOW_THRESHOLD / timerMSE.RealTime() * BMN_GLOBAL_PARAMS_PD);
669 LOG(info) << " " << timerMSE.RealTime() / BMN_GLOBAL_PARAMS_PD << "s for single MSE calculation in average";
670
671 // ================================================================================================================
672 // === main alignment loop begin ==================================================================================
673
674 /*
675 * Rounds. Round 1 judges the vertex hits on the starting geometry and both
676 * tests once more on the first geometry that improved on it, then iterates
677 * to convergence. That geometry may still be far off: with a large
678 * misalignment a track crossing an element not yet in place is rejected
679 * for that alone, and the solution converges on a biased track set. So
680 * both tests are repeated on the converged geometry, and while they change
681 * the state of more than ROUND_MIN_CHANGE of the tracks, the iterations
682 * run again on the new track set. The tests are never run inside a round
683 * after its start: a track set changing under the MSE comparison of every
684 * iteration may never settle.
685 */
686 for (Int_t round{1};; round++) {
687 LOG(info) << Form(" --- round %d of %d at most", round, maxRounds);
688 fRegularIters = 0;
690 Int_t regularRetries{MAX_REGULAR_RETRY}, retriesLast;
691 Double_t progressAbs{0.0}, progressRel{MIN_REL_PROGRESS}, progressStep{MIN_PROGRESS_STEP};
692 while (TMath::Abs(progressRel) >= MIN_REL_PROGRESS || regularRetries > 0 || progressStep >= MIN_PROGRESS_STEP)
693 // regularRetries is never negative, but it is more safe - in case of future code changes
694 {
695 if (progressAbs < 0.0) { // no progress at all
696 if (!fRegularIters) { // regularization as a last resort
697 fRegularIters = MIN_REGULAR_ITERS;
698 fForceRegular = kTRUE; // negative progress may indicate devergence of quasi-Newton
699 if (progressRel <= REL_PROGRESS_FAIL) {
700 LOG(warn) << " ! "
701 "quasi-Newton iteration made very poor step - "
702 "reverting to previous approximation";
704 }
705 } else {
706 LOG(error) << " <!> BmnAligner::Align : algorithm is diverging";
707 return kFALSE;
708 }
709 } else if (progressRel < MIN_REL_PROGRESS && !fRegularIters) // progress is poor
710 fRegularIters = MIN_REGULAR_ITERS; // but we have regularization to try
711
712 // perform alignment iteration
713 if (!IterateAlignment()) {
714 LOG(error) << " <!> BmnAligner::Align : iteration failed";
715 return kFALSE;
716 }
717 progressAbs = fpResultPrev->GetValueMSE() - fpResultLast->GetValueMSE();
718 progressRel = progressAbs / fpResultPrev->GetValueMSE();
719 // How far the geometry moved. Measured over the leaf block alone:
720 // those are the *effective* corrections, so a composite that moves
721 // is already counted there, and adding its own share on top would
722 // count the same motion twice.
723 const TVectorD &prev{fpResultPrev->A()}, &curr{fpResultLast->A()};
724 const Int_t nLeaf{fHierarchy.LeafParams()};
725 progressStep = std::sqrt((prev.GetSub(0, nLeaf - 1) - curr.GetSub(0, nLeaf - 1)).Norm2Sqr());
726 LOG(info) << Form(" = %+.3f%% relative progress, MSE change : %.3e -> %.3e\n", progressRel * 100.0,
727 fpResultPrev->GetValueMSE(), fpResultLast->GetValueMSE());
728
729 retriesLast = regularRetries;
730 if (fRegularIters) {
731 // decide about regularization
732 if (progressRel >= REL_PROGRESS_GOOD)
733 fRegularIters = MIN_REGULAR_ITERS; // keep going!
734 else
735 fRegularIters--; // attention! be careful to keep it non-negative
736 if (!fRegularIters) {
738 if (progressRel < MIN_REL_PROGRESS && regularRetries > 0)
739 regularRetries--;
740 }
741 }
742 LOG_IF(info, retriesLast != regularRetries) << " " << regularRetries << " regularization retries left";
743
744 if (progressAbs <= 0.0)
745 continue;
746 Bool_t changed{kFALSE};
747 if (vertexTest) {
748 vertexTest = kFALSE;
749 changed |= SelectVertexHits() > 0;
750 }
751 // The starting geometry still holds the misalignment being sought: a track
752 // crossing a displaced element would be rejected for that alone, and the
753 // solution biased towards the start. So the outliers wait for the first
754 // geometry that improved on it.
755 if (outlierTest) {
756 outlierTest = kFALSE;
757 changed |= SelectOutliers() > 0;
758 }
759 // force one more iteration if the geometry has changed
760 if (changed)
761 progressStep = MIN_PROGRESS_STEP;
762 }
763
764 if (round >= maxRounds)
765 break;
766 const Int_t changed{(vertexOn ? SelectVertexHits() : 0) + (outlierOn ? SelectOutliers() : 0)};
767 if (changed <= ROUND_MIN_CHANGE * fTotalTracks) {
768 LOG(info) << " " << changed << " tracks or vertex hits changed state: the track set has settled";
769 break;
770 }
771 }
772
773 // === main alignment loop end ====================================================================================
774 // ================================================================================================================
775
776 LOG(info) << " " << fIterationResults.size() - 1 << " iterations until algorithm convergence criteria reached";
777 DoneInTime(timer, "iterative alignment");
778 return kTRUE;
779}
780
781/*
782 * One iteration of alignment. Consists of two parts:
783 * 1. parallel processing of tracks
784 * 2. final calculation of (global) alignment parameters
785 *
786 * Parallelized (intermediate) calculations implemented in ProcessTracks()
787 * method below, here only parallelization control is performed. Thus,
788 * calulations code is splitted between two methods: ProcessTracks() and
789 * IterateAlignment(). This code is marked by noticable comments.
790 *
791 * Calculations in ProcessTracks() performed according to:
792 * Volker Blobel, Claus Kleinwort
793 * "A New Method for the High-Precision Alignment of Track Detectors"
794 * http://arxiv.org/abs/hep-ex/0208021v1
795 * also widely known as Millepede method.
796 * This paper is referred below as _VBCK_. Variable naming is also corresponds to _VBCK_.
797 *
798 * Attention! In _VBCK_ (12) term z_k refers to track model which is incorrect
799 * in non-linear case. In general case it should refer to a _difference_ between
800 * measured value and track model. More accurate definition is given in documentation
801 * on Millepede-II software package published here:
802 * https://www.desy.de/~kleinwrt/MP2/doc/html/draftman_page.html
803 */
805{
806 TStopwatch timer;
807 fIteration++;
808 LOG(state) << " > #" << fIteration + 1 << " iteration started";
810
811 // prepare storage for parallel calculations
812 // the reduction below works in the leaf basis, the hierarchical one is
813 // entered right after it
814 const Int_t LeafParamsCnt{fHierarchy.LeafParams()};
815 TVectorD vB_dash(LeafParamsCnt); // b' from _VBCK_ (17)
816 TMatrixD mC_dash(LeafParamsCnt, LeafParamsCnt); // C' from _VBCK_ (17)
817
818 // run Millepede-like dimension reduction calculations in parallel
819 LOG(info) << " " << fThreadsCnt << " threads started to perform dimension reduction (Millepede)";
820 fpProgressBar->Init();
821 TStopwatch timerMille;
822 RunThreads(&BmnAligner::ProcessTracks, &vB_dash, &mC_dash);
823 LOG(info) << Form(" %.1fs (REAL) / %.1fs (CPU) took to complete dimension reduction", timerMille.RealTime(),
824 timerMille.CpuTime());
825 fpProgressBar->Clear();
826 fAlphaReady = kFALSE; // SolveGlobal() must finish Alpha calculations
827
828 // Change of basis from the leaf parametrization the reduction works in to
829 // the hierarchical one everything below is expressed in. Exact, since the
830 // propagation Jacobian does not depend on the individual hit - and a plain
831 // copy while the hierarchy carries no composite nodes.
832 const Int_t HierParamsCnt{fHierarchy.AllParams()};
833 TVectorD vB_h;
834 TMatrixD mC_h;
835 fHierarchy.PromoteSystem(vB_dash, mC_dash, vB_h, mC_h);
836
837 // fold prior knowledge into the reduced system. Applied to mC_h / vB_h
838 // rather than to the mCL / vBL copies on purpose: the Levenberg-Marquardt
839 // loop below rebuilds the diagonal from mC_h(i, i), so the prior takes
840 // part in regularization instead of being overwritten by it.
841 fPriors.Apply(vB_h, mC_h, fHierarchy, fpResultPrev ? &fpResultPrev->A() : nullptr);
842 LOG_IF(info, fPriors.presigmaCount) << " " << fPriors.presigmaCount << " parameter priors (presigmas) applied";
843
844 /*
845 * ---------------------------------------------------
846 * Final calculations of global parameters: _VBCK_(16)
847 * ---------------------------------------------------
848 */
849
850 /*
851 * Prepare system of linear equations for global parameters
852 * --------------------------------------------------------
853 * 1. make a copy of vB_dash and mC_dash (original matrices will be used too)
854 * 2. append with the independent user defined constraints (see BmnAlignPriors::Check)
855 * 3. iteratively solve linear systems with different regularization factors
856 * 4. check results of iterative regularization
857 * 5. select optimal regularization factor if possible
858 */
859
860 TStopwatch timerGlobal;
861 fMSEclcCounter = 0u;
862
863 // === processing constraints =====================================================================================
864
865 TVectorD vBL(vB_h);
866 TMatrixD mCL(mC_h);
867 if (const Int_t kept{fPriors.KeptCount()}) {
868 vBL.ResizeTo(HierParamsCnt + kept);
869 mCL.ResizeTo(HierParamsCnt + kept, HierParamsCnt + kept);
870 /*
871 * A constraint reads c_leaf . A + c_comp . P_comp = rhs
872 * where A is the vector of *effective* leaf corrections. With
873 * A = A_acc + T dP and P_comp = P_comp_acc + dP_comp this turns into
874 *
875 * [ c_leaf ; J^T c_leaf + c_comp ] . dP
876 * = rhs - c_leaf . A_acc - c_comp . P_comp_acc
877 *
878 * so a coefficient placed on a leaf parameter keeps constraining the
879 * same physical quantity once composites appear: the J^T c_leaf term
880 * makes the ancestors carry their share. Every iteration yields dP,
881 * not P, hence the accumulated part on the right.
882 */
883 const TVectorD vRhs{fPriors.rhs - fPriors.constraints * fpResultPrev->A()};
884 const TMatrixD& rows{fPriors.KeptRows()};
885 for (Int_t i = 0; i < kept; i++)
886 vBL[HierParamsCnt + i] = vRhs[fPriors.Kept()[i]];
887 mCL.SetSub(HierParamsCnt, 0, rows);
888 mCL.SetSub(0, HierParamsCnt, TMatrixD(TMatrixD::kTransposed, rows));
889 LOG(info) << " " << kept << " parameter constraints applied";
890 }
891
892 // === non-regularized solution ===================================================================================
893
894 LOG(info) << " solving non-regularized system for global parameters...";
895 // to complete local parameters calculation we must first solve non-regularized system without step optimization
896 Bool_t successNR{SolveGlobal(mCL, vBL, kFALSE)};
897 if (!successNR && !fRegularIters) {
898 LOG(warning) << " ! iteration failed to improve MSE";
900 } else if (!successNR) {
901 // only the non-regularized solve fills the errors, and it failed before
902 // doing so: carry the previous ones over rather than report zeros
903 fpResultLast->AErr() = fpResultPrev->AErr();
904 fpResultLast->AglCorr() = fpResultPrev->AglCorr();
905 fpResultLast->Cov() = fpResultPrev->Cov();
906 }
907
908 // === regularized solution =======================================================================================
909
910 if (fRegularIters) {
911
912 LOG(info) << " starting Levenberg-Marquardt regularization...";
913 // find crude range for LM factor in which to perform 1D optimization
914 Double_t valueMSEbest{fpResultPrev->GetValueMSE()}, LMfactorBest{0.0}, LMfactor{1.0};
915 Int_t LMiterarion{0};
916 Bool_t LMworking{kTRUE};
917 while ((LMworking || LMiterarion < LM_ITERATIONS_MIN) && LMiterarion < LM_ITERATIONS_MAX) {
918 if (LMfactor > 1.0)
919 // apply normalization factor to diagonal elements
920 for (Int_t i = 0; i < HierParamsCnt; i++)
921 mCL(i, i) = mC_h(i, i) * LMfactor;
922
923 // if regularization is not obligatory, first check non-regularized solution for sufficient progress
924 else if (!fForceRegular && successNR)
925 if (1.0 - fpResultLast->GetValueMSE() / valueMSEbest >= REL_PROGRESS_GOOD) {
926 // cancel regularization mode but keep retry count
927 fRegularIters = 0;
928 break;
929 }
930
931 if (SolveGlobal(mCL, vBL, kTRUE)) {
932 // evaluate results of successful iteration
933 if (fpResultLast->GetValueMSE() < valueMSEbest) {
934 valueMSEbest = fpResultLast->GetValueMSE();
935 LMfactorBest = LMfactor;
936 } else
937 LMworking = kFALSE; // stop if MSE is not improved
938 } else
939 LOG(warning) << Form(" ! LM regularization failed for F=%.3e", LMfactor);
940
941 LMfactor *= LM_MULT_STEP;
942 LMiterarion++;
943 } // end of Levenberg-Marquardt regularization loop
944
945 // regularization factor optimization function
946 RM::Functor1D fnLM([&mCL, &mC_h, &vBL, this, HierParamsCnt](Double_t factor) {
947 TMatrixD mCLcopy{mCL};
948 for (Int_t i = 0; i < HierParamsCnt; i++)
949 mCLcopy(i, i) = mC_h(i, i) * factor;
950 if (!SolveGlobal(mCLcopy, vBL, kTRUE)) // expected to allways succeed
951 throw std::runtime_error(Form("Levenberg-Marquardt failed (F=%.3e)", factor));
952 return fpResultLast->GetValueMSE();
953 });
954
955 // classification of Levenberg-Marquardt results
956 if (!fRegularIters) {
958 LOG(info) << Form(
959 " regularization cancelled : sufficient %+.1f%% progress achieved using non-regularized method",
960 100.0 * (fpResultLast->GetValueMSE() / fpResultPrev->GetValueMSE() - 1.0));
961
962 } else if (LMfactorBest < 1.0) {
963 LOG(warning) << " ! iteration failed to improve MSE";
965
966 } else if (LMfactorBest == 1.0 || LMworking) { // it works like XOR here
967 // LMfactor hits boundary values
968 if (LMworking)
969 LOG(info) // max possible LMfactor
970 << Form(" F = %.3e : LM regularization approached gradient descent", LMfactorBest);
971 else
972 LOG(info) // min possible LMfactor (1.0)
973 << " F = 1.0 : LM regularization did not improve results, using simple step regularization";
974 fnLM(LMfactorBest);
976
977 } else { // LMfactorBest > 1.0 and LMworking is false
978 // search for optimal LMfactor between LMfactorBest and LMfactorBest * LM_MULT_STEP
979
981 brent.SetNpx(BRENT_GRID_SIZE);
982 brent.SetFunction(fnLM, LMfactorBest, LMfactorBest * LM_MULT_STEP);
983 Bool_t success{brent.Minimize(static_cast<Int_t>(0.1 / STEP_TOLERANCE_1D), STEP_TOLERANCE_1D * 10.0,
984 STEP_TOLERANCE_1D)};
985 if (success)
986 LOG(info) << Form(" F = %.3e : optimal LM factor value", brent.XMinimum());
987 else
988 LOG(warning) << Form(" ! F = %.3e : rough LM factor value used, 1D optimization failed",
989 LMfactorBest);
990 fnLM(success ? brent.XMinimum() : LMfactorBest);
992
993 } // end if (LM results classification)
994 } else // end if (regularization)
995 // non-regularized path didn't fill residuals histograms - do it now
997
998 LOG(info) << Form(" %d MSE value calculations performed during iteration", fMSEclcCounter);
999 LOG(info) << Form(" %.1fs (REAL) / %.1fs (CPU) took to complete parameters estimation", timerGlobal.RealTime(),
1000 timerGlobal.CpuTime());
1001 // don't call MarkTime() here - it will be done in Align()
1002 LOG(state) << Form(" < #%d iteration took %.1fs (REAL) / %.1fs (CPU)", fIteration + 1, timer.RealTime(),
1003 timer.CpuTime());
1004 return kTRUE;
1005}
1006
1007Bool_t BmnAligner::SolveGlobal(const TMatrixD& mCL, const TVectorD& vBL, Bool_t optimStep)
1008{
1009 /*
1010 * Solve system of linear equations for global parameters
1011 * ------------------------------------------------------
1012 * 1. get direct solution using LU or SVD decomposition
1013 * 2. store Lagrange multipliers and SVD singular values (for analysis if required)
1014 * 3. find optimal step size in proposed direction
1015 * 4. calculate new approximation of global parameters
1016 * 5. in case of any failure proceed to next regularization factor
1017 */
1018
1019 // TODO: not necessary to solve full system with large LMfactor
1020
1021 // the system is stated in the hierarchical basis, while everything the
1022 // solution feeds (local parameters, MSE, stored corrections) lives in the
1023 // leaf one - see the mapping right after the Lagrange multipliers are split
1024 const Int_t HierParamsCnt{fHierarchy.AllParams()};
1025
1026 // === LU and SVD matrix decomposition ============================================================================
1027
1028 TDecompLU mLU{mCL};
1029 TDecompSVD mSVD{mCL};
1030 Bool_t success;
1031 // SVD is required to evaluate singularity even if LU succeeds
1032 if (!mSVD.Decompose()) { // SVD decomposition must always succeed
1033 LOG(warning) << " ! SVD decomposition failed";
1034 return kFALSE;
1035 }
1036 if (!optimStep) {
1037 fpResultLast->SVDSig().ResizeTo(mSVD.GetSig());
1038 fpResultLast->SVDv().ResizeTo(mSVD.GetV());
1039 fpResultLast->SVDSig() = mSVD.GetSig();
1040 fpResultLast->SVDv() = mSVD.GetV();
1041 }
1042
1043 // Suppress ROOT error messages: LU decomposition expected to fail sometimes
1044 auto oldErrorLevel{gErrorIgnoreLevel};
1046 success = mLU.Decompose();
1047 gErrorIgnoreLevel = oldErrorLevel; // Restore original error level
1048
1049 // === solution of C * x = B ======================================================================================
1050
1051 // Compute the full inverse via LU when it's available so we can reuse it
1052 // for parameter-error extraction below. Fall back to SVD-solve only when LU fails.
1053 TMatrixD mCLinv(mCL.GetNrows(), mCL.GetNcols());
1054 if (success) // LU decomposition succeeded
1055 mCLinv = mLU.Invert(success);
1056 // whichever LU step failed, there is no inverse to take the errors from
1057 const Bool_t invertFailed{!success};
1058 TVectorD vAL{success ? mCLinv * vBL : mSVD.Solve(vBL, success)};
1059 if (!success) { // both LU and SVD failed
1060 LOG(warning) << " ! global matrix inversion failed";
1061 return kFALSE;
1062 }
1063
1064 // === solution result processing =================================================================================
1065
1066 // separate and drop Lagrange multipliers
1067 Int_t activeConstCnt{vAL.GetNrows() - HierParamsCnt};
1068 if (activeConstCnt) {
1069 fpResultLast->L().ResizeTo(activeConstCnt);
1070 vAL.GetSub(HierParamsCnt, vAL.GetNrows() - 1, fpResultLast->L());
1071 }
1072 vAL.ResizeTo(HierParamsCnt);
1073
1074 // back to the leaf basis: CalculateLocals() and the corrections storage
1075 // below both expect the leaf layout the reduction produced
1076 TVectorD vALeaf;
1077 fHierarchy.ToLeaf(vAL, vALeaf);
1078
1079 // an element takes its *effective* correction, a composite its own share
1080 TVectorD& A{fpResultLast->A()};
1081 A = vAL;
1082 A.SetSub(0, vALeaf);
1083
1084 // The block below is computed once per iteration on the non-regularized solve.
1085 if (!optimStep) {
1086 // Update 1-sigma parameter errors and global correlation coefficients.
1087 // Covariance reflects the true MNE conditioning due to non-regularized solve.
1088 // mCLinv is stated in the hierarchical basis - element *own* shares and
1089 // composite shares. AErr() and Cov() describe what gets reported: the
1090 // effective element correction, and the composite's own share. See
1091 // ToEffectiveCov() for the map between the two.
1092 TMatrixD covEff;
1093 if (!invertFailed)
1094 fHierarchy.ToEffectiveCov(mCLinv.GetSub(0, HierParamsCnt - 1, 0, HierParamsCnt - 1), covEff);
1095 TVectorD &aErr{fpResultLast->AErr()}, &aCorr{fpResultLast->AglCorr()};
1096 for (const ParamRef& p : fHierarchy.Layout().All()) {
1097 const Double_t errSq{invertFailed ? TMath::Infinity() : covEff(p.full, p.full)};
1098 if (errSq == TMath::Infinity() || errSq < 0.0) {
1099 aErr(p.full) = TMath::Infinity();
1100 aCorr(p.full) = 1.0;
1101 } else {
1102 aErr(p.full) = std::sqrt(errSq);
1103 // Cauchy-Schwarz gives prod >= 1 for positive-definite C;
1104 // a numerical dip below 1 means an effectively uncorrelated param.
1105 // mCL needs no propagation here: under the change of basis
1106 // a_own -> a_leaf its leaf block is unchanged, being the
1107 // curvature taken at fixed composite parameters, and a
1108 // composite parameter is solved in this basis to begin with.
1109 const Double_t prod{errSq * mCL(p.full, p.full)};
1110 aCorr(p.full) = prod > 1.0 ? std::sqrt(1.0 - 1.0 / prod) : 0.0;
1111 }
1112 }
1113 // Update latest covariance for BmnAlignReport::Correlations().
1114 TMatrixDSym& Cov{fpResultLast->Cov()};
1115 for (const ParamRef& r : fHierarchy.Layout().All())
1116 for (const ParamRef& s : fHierarchy.Layout().All()) {
1117 if (s.full > r.full)
1118 break; // lower triangle, mirrored below
1119 const Double_t newValue{invertFailed ? TMath::Infinity() : covEff(r.full, s.full)};
1120 // TMatrixDSym does not keep its symmetry by itself - double assignment is required
1121 Cov(r.full, s.full) = Cov(s.full, r.full) = newValue;
1122 }
1123 }
1124
1125 // final calculation of local parameters
1126 if (!fAlphaReady) {
1127 LOG(info) << " updating local parameters...";
1130 }
1131
1132 // === next approximation build ===================================================================================
1133
1134 if (optimStep && !fAlphaReady) {
1135 LOG(warning) << " ! Step optimization requested while Alpha is not ready yet - check the code";
1136
1137 // find optimal step in proposed direction
1138 } else if (optimStep) {
1139 // 1D function to minimize
1140 RM::Functor1D fnMSE([this](Double_t step) {
1141 TVectorD point{fpResultPrev->A() + fpResultLast->A() * step};
1142 return CalculateMSE(point);
1143 });
1144 // search for initial segment containing the minimum
1145 Double_t valueMSE, stepMin{0.0}, stepMax{1.0};
1146 valueMSE = fnMSE(stepMax);
1147 while (valueMSE < fpResultPrev->GetValueMSE()) {
1148 stepMin = stepMax;
1149 stepMax *= 2.0;
1150 valueMSE = fnMSE(stepMax);
1151 }
1152 // find minimum using Brent method
1153 constexpr static const Int_t iterations{static_cast<Int_t>(1.0 / STEP_TOLERANCE_1D)};
1154 fBrent.SetFunction(fnMSE, stepMin, stepMax);
1155 success = fBrent.Minimize(iterations, STEP_TOLERANCE_1D, STEP_TOLERANCE_1D * 0.1);
1156 if (!success) {
1157 LOG(warning) << " ! Brent method failed to calculate step size";
1158 return kFALSE;
1159 }
1160 Double_t stepBest{fBrent.XMinimum()};
1161
1162 // Special note on inhomogeneous constraints and Brent step:
1163 // Step != 1 may lead to inhomogeneous constraints violation. To keep them satisfied one must
1164 // apply step = 1 along constraint-fixing direction (special decomposition of A is required).
1165 // In regular cases step < 1 is expected leading to iterative constraints satisfaction.
1166 // In case of (unlikely) divergence this issue must be solved (TODO).
1167 const Double_t cnstrFactor{std::fabs(1.0 - stepBest)};
1168 LOG_IF(warning, fPriors.inhomogeneous && cnstrFactor >= 1.0)
1169 << " ! Brent step = " << stepBest << ": inhomogeneous-constraint residual will "
1170 << (cnstrFactor > 1.0 ? "grow" : "not decay") << " this iteration";
1171
1172 // select new approximation of global parameters
1173 fpResultLast->A() *= stepBest;
1174 } // end if (regularization)
1175
1176 // make step and update global parameters
1177 fpResultLast->A() += fpResultPrev->A();
1178 fpResultLast->SeparateA();
1180
1181 return kTRUE;
1182}
1183
1185{
1186 /*
1187 * Final calculation of local parameters according to _VBCK_(7).
1188 * Attention! _VBCK_(7) contains an error:
1189 * in C_22^{-1} − C_22^{-1} C_12^T B C_12 C_22^{-1}
1190 * sing "−" before C_22^{-1} is wrong,
1191 * must be: C_22^{-1} + C_22^{-1} C_12^T B C_12 C_22^{-1}
1192 * With this correction in mind, joint normal equations
1193 * α_i = α_i* − Γ_i^{-1} G_i^T a
1194 * are equivalent to _VBCK_(7) row 2.
1195 * Notice: calulations of _VBCK_(7) are allready partially performed:
1196 * C_22^{-1} b_2 = α_i* stored by ProcessTracks() in fpResultCurrent->Alpha(iTrack)
1197 * C_22^{-1} C_12^T B C_12 C_22^{-1} b_2 folded into δa (*pvDA)
1198 * via b' = b_1 − C_12 α_i* calulated by ProcessTracks()
1199 * C_22^{-1} C_12^T B b_1 is the remaining piece of δa to be calculated here
1200 */
1201
1202 Int_t iTrack;
1203 BmnRamIterator* pItr;
1204 SelectIterator(threadNum, iTrack, pItr);
1205 for (pItr->ResetAll(); !pItr->EndOfTracks(); pItr->NextTrack(), iTrack++) {
1206 // TODO : implement unusable tracks skipping in iterator
1207 if (!fpTrackUsable->at(iTrack))
1208 continue;
1209
1210 SVectLC vDAlpha;
1211 for (Int_t iHit{fFirstHits[iTrack]}; iHit < fFirstHits[iTrack + 1]; iHit++) {
1212 const AlphaData_t& rec{fAlphaRecs[iHit]};
1213 if (rec.paramIdx < 0)
1214 continue; // disabled hit skip
1215
1216 vDAlpha +=
1218 }
1219
1220 // calculations according to _VBCK_(7)
1221 fpResultLast->Alpha(iTrack) -= vDAlpha;
1222 fpResultLast->Alpha(iTrack) += fpResultPrev->Alpha(iTrack);
1223 }
1224}
1225
1226/*
1227 * Millepede-like dimension reduction algorithm.
1228 * For detailes see:
1229 * http://arxiv.org/abs/hep-ex/0208021v1
1230 * https://www.desy.de/~kleinwrt/MP2/doc/html/draftman_page.html
1231 *
1232 * Each thread processes separate subset of all tracks defined by iterator.
1233 * Synchronization is necessary at result storage stage only.
1234 */
1235
1236void BmnAligner::ProcessTracks(TVectorD* pvB_dash, TMatrixD* pmC_dash, Int_t threadNum)
1237{
1238 // prepare vector of zeroes to be used for variables initialization
1239 static const VecDouble_t zeroes(
1240 std::max(static_cast<UInt_t>(SVectLC::kSize), static_cast<UInt_t>(SMatrLC::rep_type::kSize)
1241 // CAUTION: SMatrLC::kSize is D1*D2, larger than
1242 // the symmetric storage; SetElements asserts on that
1243 ),
1244 0.0);
1245 static const auto zStart = zeroes.begin();
1246
1247 const Int_t LeafParamsCnt{fHierarchy.LeafParams()};
1248
1249 // ROOT matrices and vectors are initialized with zeroes during construction
1250
1251 // accelerated ROOT vectors and matrices
1252 SMatrLC mGamma;
1253 SVectLC vBeta, vDelta;
1254 SMatrGL mCdelta; // one block of the mC_part update
1255 std::vector<SMatrGP> mG; // G term of the hit, needed until mGamma is inverted
1256 // non-accelerated ROOT matrices and vectors due to runtime-defined sizes
1257 TMatrixD mC_part(LeafParamsCnt, LeafParamsCnt);
1258 TVectorD vB_part(LeafParamsCnt);
1259 // non-accelerated alias to mCdelta: TMatrixDSub takes TMatrixD only
1261 amCdelta.Use(BMN_GLOBAL_PARAMS_PD, BMN_GLOBAL_PARAMS_PD, mCdelta.Array());
1262
1263 // v v^T in symmetric storage: RM::TensorProd returns a general matrix, which
1264 // symmetric storage refuses in += and =. MatRepSym stores the lower triangle
1265 // row by row, so the loop fills the storage in order; m(j, i) is the same
1266 // element as m(i, j).
1267 const auto TensorProdSelf = [](const SVectLC& v) {
1268 SMatrLC m;
1269 for (Int_t i{0}; i < BMN_LOCAL_PARAMS_PT; i++)
1270 for (Int_t j{0}; j <= i; j++)
1271 m(i, j) = v[i] * v[j];
1272 return m;
1273 };
1274
1275 // === iterate tracks =====================================================
1276 // ========================================================================
1277 Int_t iTrack;
1278 VecInt_t hitIdx; // index of the hit in fHits and fAlphaRecs
1279 BmnRamIterator* pItr;
1280 SelectIterator(threadNum, iTrack, pItr);
1281 for (pItr->ResetAll(); !pItr->EndOfTracks(); pItr->NextTrack(), iTrack++) {
1282 if (!fpTrackUsable->at(iTrack))
1283 continue;
1284
1285 // reset temporary variables
1286 vBeta.SetElements(zStart, SVectLC::kSize);
1287 mGamma.SetElements(zStart, SMatrLC::rep_type::kSize);
1288 mG.clear();
1289 hitIdx.clear();
1290
1291 const SVectLC& lc{fpResultPrev->Alpha(iTrack)};
1292
1293 // === iterate hits : first pass ======================================
1294 // ====================================================================
1295 // the iterator walks fHits in storage order, iHit follows it
1296 Int_t iHit{fFirstHits[iTrack]};
1297 for (pItr->ResetHits(); !pItr->EndOfHits(); pItr->NextHit(), iHit++) {
1298 AlphaData_t& alphaRec{fAlphaRecs[iHit]};
1299 alphaRec.paramIdx = -1; // stays negative unless the hit enters the global section below
1300
1301 if (!pItr->GetHit().IsEnabled())
1302 continue; // skip disabled vertex hits
1303
1304 // NOTICE: the code below is independent of sign and rotation order
1305 // selection; it is fully encapsulated in BmnMeasureModel
1306
1307 const Int_t iDet{fpDetModel->Idx(pItr->HitDetectorID())};
1308 const SVectGL& gl{fpResultPrev->A(iDet)};
1309 const Double_t z{pItr->HitZ()}, wx{pItr->HitWx()}, wy{pItr->HitWy()},
1310 wDx{wx * (pItr->HitX() - fpMeasureModel->X(z, gl, lc))},
1311 wDy{wy * (pItr->HitY() - fpMeasureModel->Y(z, gl, lc))};
1312
1313 // local section, terms of _VBCK_(11)
1314 const SVectLC vGradLx{fpMeasureModel->dXdAlpha(z)}, vGradLy{fpMeasureModel->dYdAlpha(z)};
1315 mGamma += wx * TensorProdSelf(vGradLx);
1316 mGamma += wy * TensorProdSelf(vGradLy);
1317 vBeta += wDx * vGradLx + wDy * vGradLy;
1318
1319 // global section, terms of _VBCK_(17)
1320 alphaRec.paramIdx = iDet * BMN_GLOBAL_PARAMS_PD;
1321 hitIdx.push_back(iHit);
1322
1323 const SVectGL vGradGx{fpMeasureModel->dXdA(z, lc)}, vGradGy{fpMeasureModel->dYdA(z, lc)};
1324 mG.emplace_back(wx * RM::TensorProd(vGradGx, vGradLx));
1325 mG.back() += wy * RM::TensorProd(vGradGy, vGradLy);
1326
1327 // the terms which do not depend on mGamma go to the result at once,
1328 // namely mCfull and vBfull (see below)
1329 const Int_t lower{alphaRec.paramIdx}, upper{lower + BMN_GLOBAL_PARAMS_PD - 1};
1330 mCdelta = wx * RM::TensorProd(vGradGx, vGradGx);
1331 mCdelta += wy * RM::TensorProd(vGradGy, vGradGy);
1332 TMatrixDSub(mC_part, lower, upper, lower, upper) += amCdelta;
1333 // there is no view access to TVector similar to TMatrixDSub
1334 for (Int_t k{0}; k < BMN_GLOBAL_PARAMS_PD; k++)
1335 vB_part[lower + k] += wDx * vGradGx[k] + wDy * vGradGy[k];
1336 } // loop over hits
1337
1338 // === local parameters pre-calculation : _VBCK_(11) =================
1339 // ====================================================================
1340 // Cholesky: mGamma is positive definite once each projection has two hits at different z
1341 if (!mGamma.InvertChol()) // mGamma^-1 is stored in mGamma
1342 throw std::runtime_error("matrix inversion failed while calculating local parameters");
1343 const SMatrLC& mGammaInv{mGamma}; // alias for readability
1344 vDelta = mGammaInv * vBeta;
1345 // store intermediate results for later local parameters calculation (no sycn is needed between threads)
1346 fpResultLast->Alpha(iTrack) = vDelta; // incomplete solution for dAlpha
1347 // corresponds to alpha_i^* in _VBCK_ (15)
1348 // and to a_2^* in _VBCK_ (5)
1349
1350 // === final reduced matrix calculation : _VBCK_(17) ==================
1351 // ====================================================================
1352
1353 // Using full-size matrices the pseudo-code would be
1354 // -----------------------------------------------
1355 // mC_part += mCfull - mGfull * mGamma * mGfullT;
1356 // vB_part += vBfull - mGfull * vDelta;
1357 // -----------------------------------------------
1358 // where mCfull, mGfull, vBfull dims are proportional to leaf params count
1359 // but for the sake of memory efficiency we use partial matrices instead.
1360 // The mCfull and vBfull terms are already added in the hit loop above,
1361 // only the terms with mGfull are left.
1362
1363 // loop over all partial matrices -- one per hit in the global section
1364 const Int_t globalHits{static_cast<Int_t>(hitIdx.size())};
1365 for (Int_t i{0}; i < globalHits; i++) {
1366 AlphaData_t& alphaRec{fAlphaRecs[hitIdx[i]]};
1367 const Int_t iLower{alphaRec.paramIdx}, iUpper{iLower + BMN_GLOBAL_PARAMS_PD - 1};
1368
1369 // temporary results for final Alpha calculation (outside this method)
1370 alphaRec.mGGammaInv = mG[i] * mGammaInv;
1371
1372 // negated term needed due to operator -= absence in TMatrixDSub interface
1373 const SMatrGP mGGammaInvNeg{-1.0 * alphaRec.mGGammaInv};
1374 // second loop over the partial matrices: C_dash is symmetric, so only the
1375 // blocks on and above the diagonal of mC_part are summed; the lower triangle
1376 // is copied from the upper one after the track loop
1377 for (Int_t j{0}; j < globalHits; j++) {
1378 const Int_t jLower{fAlphaRecs[hitIdx[j]].paramIdx}, jUpper{jLower + BMN_GLOBAL_PARAMS_PD - 1};
1379 if (iLower > jLower)
1380 continue;
1381 mCdelta = mGGammaInvNeg * RM::Transpose(mG[j]);
1382 TMatrixDSub(mC_part, iLower, iUpper, jLower, jUpper) += amCdelta;
1383 }
1384
1385 const SVectGL vBdelta{mG[i] * vDelta};
1386 for (Int_t k{0}; k < BMN_GLOBAL_PARAMS_PD; k++)
1387 vB_part[iLower + k] -= vBdelta[k];
1388 }
1389
1390 } // loop over tracks
1391
1392 // the lower triangle from the upper one, see the second loop over partial matrices
1393 for (Int_t r{1}; r < LeafParamsCnt; r++)
1394 for (Int_t c{0}; c < r; c++)
1395 mC_part(r, c) = mC_part(c, r);
1396
1397 // store final result
1398 std::lock_guard<std::mutex> lock(fMutexGlobal);
1399 *pmC_dash += mC_part;
1400 *pvB_dash += vB_part;
1401}
1402
1404{
1405 // to calculate MSE at arbitrary point we substitute this point in place of
1406 // final solution to keep cumbersome multithreaded MSE calculation scheme intact
1407 BmnAlignResult *pBackupSolution{fpResultLast}, tempSolution{*fpResultLast};
1408 tempSolution.A() = solution;
1409 tempSolution.SeparateA();
1410 fpResultLast = &tempSolution;
1411 Double_t valueMSE{CalculateMSE(kFALSE)};
1412 fpResultLast = pBackupSolution;
1413 return valueMSE;
1414}
1415
1417{
1418 fMSEclcCounter++; // MSE calculation is expensive because it requires to traverse all hits
1419 fpResultLast->ResetValueMSE();
1420 if (withResiduals) {
1421 fpResultLast->ResidualsX().Reset();
1422 fpResultLast->ResidualsY().Reset();
1423 fpResultLast->ResidualsSX().Reset();
1424 fpResultLast->ResidualsSY().Reset();
1425 }
1426 if (fMSEclcSlow)
1427 fpProgressBar->Init();
1429 if (fMSEclcSlow)
1430 fpProgressBar->Clear();
1431 else if (0 == fMSEclcCounter % fMSEclcTick)
1432 std::cout << " " << fMSEclcCounter << " MSE calculations\r" << std::flush;
1433 return fpResultLast->GetValueMSE();
1434}
1435
1436void BmnAligner::CalculateMSEpart(Bool_t withResiduals, Int_t threadNum)
1437{
1438 Double_t delta, omega, valueMSE{0.0}; // the share of this thread
1439 TH1D *pResX{nullptr}, *pResY{nullptr};
1440 TH2D *pResSX{nullptr}, *pResSY{nullptr};
1441
1442 if (withResiduals) {
1443 // use binning of target histograms to keep Add() compatible
1444 const TH1D& hX{fpResultLast->ResidualsX()};
1445 const TH1D& hY{fpResultLast->ResidualsY()};
1446 const TH2D& hSX{fpResultLast->ResidualsSX()};
1447 const TH2D& hSY{fpResultLast->ResidualsSY()};
1448 pResX = new TH1D(Form("residualsX_%lu", fpResultLast->GetHistCounter()), "Partial residuals by X",
1449 hX.GetNbinsX(), hX.GetXaxis()->GetXmin(), hX.GetXaxis()->GetXmax());
1450 pResY = new TH1D(Form("residualsY_%lu", fpResultLast->GetHistCounter()), "Partial residuals by Y",
1451 hY.GetNbinsX(), hY.GetXaxis()->GetXmin(), hY.GetXaxis()->GetXmax());
1452 pResSX = new TH2D(Form("residualsSX_%lu", fpResultLast->GetHistCounter()), "Partial synthetic X residuals",
1453 hSX.GetNbinsX(), hSX.GetXaxis()->GetXmin(), hSX.GetXaxis()->GetXmax(), hSX.GetNbinsY(),
1454 hSX.GetYaxis()->GetXmin(), hSX.GetYaxis()->GetXmax());
1455 pResSY = new TH2D(Form("residualsSY_%lu", fpResultLast->GetHistCounter()), "Partial synthetic Y residuals",
1456 hSY.GetNbinsX(), hSY.GetXaxis()->GetXmin(), hSY.GetXaxis()->GetXmax(), hSY.GetNbinsY(),
1457 hSY.GetYaxis()->GetXmin(), hSY.GetYaxis()->GetXmax());
1458 }
1459
1460 Int_t iTrack;
1461 BmnRamIterator* pItr;
1462 SelectIterator(threadNum, iTrack, pItr);
1463 for (pItr->ResetAll(); !pItr->EndOfTracks(); pItr->NextTrack(), iTrack++) {
1464 if (!fpTrackUsable->at(iTrack))
1465 continue;
1466
1467 // notice: the code below is independent of corrections sign selection
1468 const SVectLC& lc{fpResultLast->Alpha(iTrack)};
1469 for (; !pItr->EndOfHits(); pItr->NextHit()) {
1470 Int_t detectorIdx{fpDetModel->Idx(pItr->HitDetectorID())};
1471 const SVectGL& gl{fpResultLast->A(detectorIdx)};
1472 const Double_t z{pItr->HitZ()};
1473
1474 // a disabled vertex hit adds nothing to the MSE and stays out of the histograms too
1475 omega = pItr->HitWx();
1476 delta = pItr->HitX() - fpMeasureModel->X(z, gl, lc);
1477 valueMSE += omega * delta * delta;
1478 if (withResiduals && omega > 0.0) {
1479 pResX->Fill(delta);
1480 pResSX->Fill(z + pItr->HitX() * 0.1, delta);
1481 }
1482
1483 omega = pItr->HitWy();
1484 delta = pItr->HitY() - fpMeasureModel->Y(z, gl, lc);
1485 valueMSE += omega * delta * delta;
1486 if (withResiduals && omega > 0.0) {
1487 pResY->Fill(delta);
1488 pResSY->Fill(z + pItr->HitY() * 0.1, delta);
1489 }
1490 } // loop over hits
1491 } // loop over tracks
1492
1493 // store results
1494 std::lock_guard<std::mutex> lock(fMutexGlobal);
1495 fpResultLast->AddValueMSE(valueMSE);
1496 if (withResiduals) {
1497 fpResultLast->ResidualsX().Add(pResX);
1498 fpResultLast->ResidualsY().Add(pResY);
1499 fpResultLast->ResidualsSX().Add(pResSX);
1500 fpResultLast->ResidualsSY().Add(pResSY);
1501 delete pResX;
1502 delete pResY;
1503 delete pResSX;
1504 delete pResSY;
1505 }
1506}
1507
1508/*
1509 * The acceptance test of the vertex hits. A hit is enabled when its residual
1510 * lies within VERTEX_OUTLIER_FACTOR MAD-sigmas of the median in both
1511 * projections, and disabled otherwise. Every hit is tested again, the disabled
1512 * ones too, so a hit rejected on a poor geometry comes back on a better one.
1513 *
1514 * The residual is taken against the line through the other hits of the track,
1515 * see LeaveOneOut(). The width is a MAD, not an RMS, because the tracks not
1516 * coming from the vertex put a long tail on the residuals.
1517 */
1519{
1520 VecDouble_t rx(fTotalTracks, TMath::QuietNaN()), // NaN: the track takes no part
1522 LOG(info) << " vertex hit residuals calculation";
1523 fpProgressBar->Init();
1525 fpProgressBar->Clear();
1526
1527 const Int_t tested{
1528 static_cast<Int_t>(std::count_if(rx.begin(), rx.end(), [](Double_t r) { return !std::isnan(r); }))};
1529 if (tested < OUTLIER_MIN_SAMPLE) {
1530 LOG(warning) << " ! " << tested << " vertex hits available only, their test skipped";
1531 return 0;
1532 }
1533 VecDouble_t buffer;
1534 buffer.reserve(tested);
1535 const auto [cx, sx]{MedianAndSigma(rx, buffer)};
1536 const auto [cy, sy]{MedianAndSigma(ry, buffer)};
1537 LOG(info) << Form(" %.2e, %.2e : median vertex hit residual in X, Y", cx, cy);
1538 LOG(info) << Form(" %.2e, %.2e : MAD-sigma of vertex hit residuals in X, Y", sx, sy);
1539
1540 Int_t rejected{0}, changed{0};
1541 for (Int_t iTrack{0}; iTrack < fTotalTracks; iTrack++) {
1542 if (std::isnan(rx[iTrack]))
1543 continue;
1544 const Bool_t accept{std::abs(rx[iTrack] - cx) <= VERTEX_OUTLIER_FACTOR * sx
1545 && std::abs(ry[iTrack] - cy) <= VERTEX_OUTLIER_FACTOR * sy};
1546 BmnHitRecord& hit{fHits[fFirstHits[iTrack]]}; // the vertex hit comes first
1547 rejected += !accept;
1548 changed += hit.IsEnabled() != accept;
1549 hit.SetEnabled(accept);
1550 }
1551 LOG(info) << Form(" %d (%.1f%%) vertex hits rejected as outliers, their tracks kept; %d changed state", rejected,
1552 100.0 * rejected / tested, changed);
1553 if (changed)
1555 return changed;
1556}
1557
1559{
1560 const Int_t targetID{fpDetModel->TargetID()};
1561 VecLooHits_t hits;
1562 Int_t iTrack;
1563 BmnRamIterator* pItr;
1564 SelectIterator(threadNum, iTrack, pItr);
1565 for (pItr->ResetAll(); !pItr->EndOfTracks(); pItr->NextTrack(), iTrack++) {
1566 if (!fpTrackUsable->at(iTrack) || pItr->EndOfHits() || pItr->HitDetectorID() != targetID)
1567 continue;
1568 LeaveOneOut(pItr, hits);
1569 // each thread writes its own range of tracks, so no lock
1570 (*pRx)[iTrack] = hits.front().rx; // the vertex hit comes first
1571 (*pRy)[iTrack] = hits.front().ry;
1572 }
1573}
1574
1575/*
1576 * z0, where the tracks meet the beam
1577 * ----------------------------------
1578 * A track from z0 gives at the target centre z_c the residual
1579 *
1580 * r = beam - track = c + s * (z0 - z_c)
1581 *
1582 * with s the track slope. ponytail: the beam slope (about 1e-3) is left out of
1583 * s; its mean goes into c, its spread times z0 - z_c is a few 1e-3 cm. One
1584 * weighted least squares over all vertex tracks gives z0 together with the
1585 * offsets c, one per projection and per sign of the slope: the halves of an
1586 * unaligned tracker are shifted against each other, and the slope sign tells
1587 * which half a track goes to. With one offset per projection the step between
1588 * the halves would be taken for a slope dependence. Before the alignment the
1589 * residuals are wider than the line errors, by a different factor in x and y,
1590 * so the variances are scaled per projection by the pull width (MAD), and the
1591 * terms far off the line are left out, step by step.
1592 *
1593 * The tracks are the free lines through the tracker hits in the geometry of
1594 * the last result, the nominal one without it. The vertex tracks are the ones
1595 * whose vertex hit the vertex hit test accepts; the test is run here, and the
1596 * hit states it leaves behind are the only change this method makes.
1597 *
1598 * The fit is a linear least squares in five parameters,
1599 *
1600 * theta = ( c(x, s < 0), c(x, s >= 0), c(y, s < 0), c(y, s >= 0), z0 - z_c )
1601 *
1602 * Each term is one track in one projection p: the measurement r with weight
1603 * w = 1 / sigma^2 and the model r = c_k + s * (z0 - z_c), where k = Offset(p, s)
1604 * picks the offset of its projection and slope sign. Its derivative row g has
1605 * two non-zero entries only: 1 at k and s at iDZ. So a term adds w g g^T to the
1606 * normal matrix N and w g r to the right-hand side b at three places of N and
1607 * two of b:
1608 *
1609 * N(k, k) += w N(k, iDZ) += w s N(iDZ, iDZ) += w s^2
1610 * b(k) += w r b(iDZ) += w s r
1611 *
1612 * The offsets share no term, so N has an arrow shape: a diagonal 4x4 block
1613 * (the weight sum of each group), coupled to the others only through the last
1614 * row and column (the sums of w s, and of w s^2):
1615 *
1616 * | W0 . . . S0 |
1617 * | . W1 . . S1 |
1618 * | . . W2 . S2 |
1619 * | . . . W3 S3 |
1620 * | S0 S1 S2 S3 Q |
1621 *
1622 * Solution: theta = N^-1 b, and N^-1 is its covariance; the error of z0 is
1623 * sqrt(N^-1(iDZ, iDZ)), with the weights scaled by the measured pull widths.
1624 */
1626{
1627 const Int_t targetID{fpDetModel->TargetID()};
1628 if (targetID < 0) {
1629 LOG(error) << " <!> BmnAligner::FitTargetZ: the detector model has no target element";
1630 return kFALSE;
1631 }
1632 if (!fHierarchy.Ready()) {
1633 LOG(error) << " <!> BmnAligner::FitTargetZ: no parameter layout, PrepareData() must run first";
1634 return kFALSE;
1635 }
1636 const BmnDetectorModel::Layer& target{fpDetModel->Target()};
1637 const Double_t zC{0.5 * (target.zStart + target.zEnd)};
1638
1639 const Bool_t blank{fIterationResults.empty()};
1640 if (blank)
1643
1644 std::vector<VertexTerm_t> terms;
1645 terms.reserve(fTotalTracks);
1647 Int_t iTrack{0};
1648 fpProgressBar->Init();
1649 for (itr.ResetAll(); !itr.EndOfTracks(); itr.NextTrack(), iTrack++) {
1650 // the vertex hit comes first, and a disabled one has zero weights
1651 if (!fpTrackUsable->at(iTrack) || itr.EndOfHits() || itr.HitDetectorID() != targetID || itr.HitWx() <= 0.0
1652 || itr.HitWy() <= 0.0)
1653 continue;
1654 const SVect3 vertex{itr.HitX(), itr.HitY(), itr.HitZ()};
1655 BmnWeightedLine lineX, lineY;
1656 for (itr.NextHit(); !itr.EndOfHits(); itr.NextHit()) {
1657 SVect3 hit{itr.HitX(), itr.HitY(), itr.HitZ()};
1658 fpMeasureModel->AlignHitApproximately(hit, fpResultLast->A(fpDetModel->Idx(itr.HitDetectorID())));
1659 lineX.Add(hit(iZ), hit(iX), itr.HitWx());
1660 lineY.Add(hit(iZ), hit(iY), itr.HitWy());
1661 }
1662 if (lineX.Det() <= 0.0 || lineY.Det() <= 0.0)
1663 continue;
1664 terms.push_back({{vertex(iX) - lineX.At(vertex(iZ)), vertex(iY) - lineY.At(vertex(iZ))},
1665 {lineX.Slope(), lineY.Slope()},
1666 {lineX.Var(vertex(iZ)), lineY.Var(vertex(iZ))}});
1667 }
1668 fpProgressBar->Clear();
1669 if (blank)
1671 LOG(info) << Form(" %zu vertex tracks in the target z fit", terms.size());
1672
1674 typedef RM::SVector<Double_t, 5> SVectZ0;
1675 constexpr Int_t iDZ{4};
1676 auto Offset = [](Int_t p, Double_t s) { return 2 * p + (s >= 0.0 ? 1 : 0); };
1677 auto Residual = [&](const VertexTerm_t& t, Int_t p, const SVectZ0& th) {
1678 return t.r[p] - th(Offset(p, t.s[p])) - th(iDZ) * t.s[p];
1679 };
1680
1681 SVectZ0 theta;
1682 SMatrZ0 cov;
1683 Double_t scale[2]{1.0, 1.0}, // pull width per projection
1684 window{TMath::Infinity()};
1685 Int_t used{0}, usedPrev{-1}, steps{0};
1686 Bool_t fitted{kFALSE}, converged{kFALSE};
1687 VecDouble_t pulls;
1688 pulls.reserve(terms.size());
1689 for (; steps < Z0_MAX_STEPS && !converged; steps++) {
1690 SMatrZ0 normal;
1691 SVectZ0 rhs;
1692 used = 0;
1693 for (const VertexTerm_t& t : terms)
1694 for (Int_t p = 0; p < 2; p++) { // loop over {X, Y}
1695 const Double_t sigma{scale[p] * std::sqrt(t.var[p])};
1696 if (std::fabs(Residual(t, p, theta)) > window * sigma)
1697 continue;
1698 const Double_t w{1.0 / (sigma * sigma)};
1699 const Int_t k{Offset(p, t.s[p])};
1700 // CAUTION: N is symmetric storage, N(k, iDZ) and N(iDZ, k) are one element: add once
1701 normal(k, k) += w;
1702 normal(k, iDZ) += w * t.s[p];
1703 normal(iDZ, iDZ) += w * t.s[p] * t.s[p];
1704 rhs(k) += w * t.r[p];
1705 rhs(iDZ) += w * t.s[p] * t.r[p];
1706 used++;
1707 }
1708 cov = normal;
1709 fitted = used >= Z0_MIN_TERMS && cov.InvertChol(); // cov now contains N^-1, N is positive definite
1710 if (!fitted)
1711 break;
1712
1713 const Double_t dzPrev{theta(iDZ)};
1714 theta = cov * rhs;
1715 // the first fit takes every term, so it never counts as converged:
1716 // the window has to be applied once at least
1717 converged = std::fabs(theta(iDZ) - dzPrev) < Z0_TOLERANCE && used == usedPrev && steps > 0;
1718 usedPrev = used;
1719 for (Int_t p = 0; p < 2; p++) {
1720 pulls.clear();
1721 for (const VertexTerm_t& t : terms)
1722 pulls.push_back(std::fabs(Residual(t, p, theta)) / std::sqrt(t.var[p]));
1723 const auto mid{pulls.begin() + pulls.size() / 2};
1724 std::nth_element(pulls.begin(), mid, pulls.end());
1725 scale[p] = MAD_TO_SIGMA * *mid;
1726 }
1727 window = Z0_WINDOW;
1728 }
1729 if (!fitted) {
1730 LOG(error) << " <!> BmnAligner::FitTargetZ: " << used
1731 << " vertex track terms only, or a singular fit: z0 is undetermined";
1732 return kFALSE;
1733 }
1734
1735 z0 = zC + theta(iDZ);
1736 z0Err = std::sqrt(cov(iDZ, iDZ));
1737 LOG(info) << Form(" %.3f +- %.3f cm : z0, where the tracks meet the beam; target from %.3f to %.3f cm", z0,
1738 z0Err, target.zStart, target.zEnd);
1739 LOG(info) << Form(" beam - track offsets at z_c (cm), slope < 0 / >= 0 : x %+.3f / %+.3f, y %+.3f / %+.3f",
1740 theta(0), theta(1), theta(2), theta(3));
1741 LOG(info) << Form(" %d of %zu terms used, pull width x %.2f, y %.2f, %d fit(s)", used, 2 * terms.size(),
1742 scale[0], scale[1], steps);
1743 LOG_IF(warning, !converged) << " ! the z0 fit did not settle in " << Z0_MAX_STEPS
1744 << " fits: terms near the window edge keep changing";
1745 // CAUTION: FAIR_LOG_IF does not parenthesize its condition, an unwrapped || never stops its loop
1746 LOG_IF(warning, (z0 < target.zStart || z0 > target.zEnd)) << " ! z0 lies outside the target of the geometry file";
1747 return kTRUE;
1748}
1749
1750/*
1751 * Leave-one-out residuals of the current track: every hit against the line
1752 * through the other hits. A line fitted with the tested hit is pulled towards
1753 * it, which shrinks the very residual being tested - the more, the larger the
1754 * share of the hit in the fit (its leverage): a precise hit at the end of a
1755 * short track hides its own outlier almost completely.
1756 *
1757 * The variance of such a residual is the hit variance plus the variance of the
1758 * line extrapolated to the hit. Both go into the pull, so that a good hit has
1759 * a pull of unit width wherever it sits on the track; without the second term
1760 * the end hits, extrapolated the furthest, would look worse than they are.
1761 *
1762 * The lines are fitted to the aligned hits, once per track: the line without
1763 * hit i is the full line with hit i removed. A disabled hit has zero weight,
1764 * so it takes no part in the line of the others, and its own pull is NaN.
1765 * Leaves pItr past the last hit of the track.
1766 */
1768{
1769 auto Aligned = [this, pItr]() {
1770 SVect3 hit{pItr->HitX(), pItr->HitY(), pItr->HitZ()};
1771 fpMeasureModel->AlignHitApproximately(hit, fpResultLast->A(fpDetModel->Idx(pItr->HitDetectorID())));
1772 return hit;
1773 };
1774 hits.clear();
1775 BmnWeightedLine lineX, lineY;
1776 for (; !pItr->EndOfHits(); pItr->NextHit()) {
1777 const SVect3 hit{Aligned()};
1778 lineX.Add(hit(iZ), hit(iX), pItr->HitWx());
1779 lineY.Add(hit(iZ), hit(iY), pItr->HitWy());
1780 }
1781 for (pItr->ResetHits(); !pItr->EndOfHits(); pItr->NextHit()) {
1782 const SVect3 hit{Aligned()};
1783 const Double_t wx{pItr->HitWx()}, wy{pItr->HitWy()};
1784 BmnWeightedLine restX{lineX}, restY{lineY};
1785 restX.Remove(hit(iZ), hit(iX), wx);
1786 restY.Remove(hit(iZ), hit(iY), wy);
1787 LooHit_t& loo{hits.emplace_back()};
1788 loo.detID = pItr->HitDetectorID();
1789 if (restX.Det() <= 0.0 || restY.Det() <= 0.0) {
1790 loo.rx = loo.ry = loo.px = loo.py = TMath::QuietNaN();
1791 continue;
1792 }
1793 const SVectLC lc{restX.At0(), restX.Slope(), restY.At0(), restY.Slope()};
1794 const SVectGL& gl{fpResultLast->A(fpDetModel->Idx(loo.detID))};
1795 const Double_t z{pItr->HitZ()};
1796 loo.rx = pItr->HitX() - fpMeasureModel->X(z, gl, lc);
1797 loo.ry = pItr->HitY() - fpMeasureModel->Y(z, gl, lc);
1798 loo.px = wx > 0.0 ? loo.rx / std::sqrt(1.0 / wx + restX.Var(hit(iZ))) : TMath::QuietNaN();
1799 loo.py = wy > 0.0 ? loo.ry / std::sqrt(1.0 / wy + restY.Var(hit(iZ))) : TMath::QuietNaN();
1800 }
1801}
1802
1803/*
1804 * The outlier test of the tracks. A track is usable when every pull of its
1805 * tracker hits lies within OUTLIER_FACTOR MAD-sigmas of the median pull in
1806 * both projections, and rejected otherwise. Every track is tested again, the
1807 * rejected ones too, so the test can be repeated on a better geometry: a track
1808 * rejected only because it crossed an element still far off comes back.
1809 *
1810 * The test works on leave-one-out hit pulls (see LeaveOneOut()), not on raw
1811 * residuals. The hit errors differ by element and by projection: one window on
1812 * raw residuals rejects the tracks through the less precise elements far more
1813 * often and cuts the tails of their distributions, which leaves the errors of
1814 * the solution underestimated and the solution biased. The width is a MAD, not
1815 * an RMS: the outliers themselves widen an RMS, and the window with it.
1816 *
1817 * The vertex hits have a test of their own, see SelectVertexHits().
1818 */
1820{
1821 VecDouble_t px(fTotalHits, TMath::QuietNaN()), // NaN: the hit takes no part
1823 LOG(info) << " hit pulls calculation";
1824 fpProgressBar->Init();
1826 fpProgressBar->Clear();
1827
1828 VecDouble_t buffer;
1829 buffer.reserve(fTotalHits);
1830 const auto [cx, sx]{MedianAndSigma(px, buffer)};
1831 const auto [cy, sy]{MedianAndSigma(py, buffer)};
1832 LOG(info) << Form(" %.2e, %.2e : median hit pull in X, Y", cx, cy);
1833 LOG(info) << Form(" %.2e, %.2e : MAD-sigma of hit pulls in X, Y", sx, sy);
1834
1835 Int_t rejected{0}, changed{0};
1836 for (Int_t iTrack{0}; iTrack < fTotalTracks; iTrack++) {
1837 Bool_t accept{kTRUE};
1838 for (Int_t iHit{fFirstHits[iTrack]}; iHit < fFirstHits[iTrack + 1] && accept; iHit++)
1839 accept =
1840 std::isnan(px[iHit]) || std::isnan(py[iHit])
1841 || (std::abs(px[iHit] - cx) <= OUTLIER_FACTOR * sx && std::abs(py[iHit] - cy) <= OUTLIER_FACTOR * sy);
1842 rejected += !accept;
1843 changed += fpTrackUsable->at(iTrack) != accept;
1844 fpTrackUsable->at(iTrack) = accept;
1845 }
1846 fTracksUsableCnt = fTotalTracks - rejected;
1847 LOG(info) << Form(" %d (%.1f%%) tracks with outlier rejected; %d changed state", rejected,
1848 100.0 * rejected / fTotalTracks, changed);
1849 if (changed)
1850 LinregAlphaMSE(); // the next iteration compares MSE on the new track set
1851 return changed;
1852}
1853
1854// every track, the rejected ones too: SelectOutliers() judges them all again
1856{
1857 const Int_t targetID{fpDetModel->TargetID()};
1858 VecLooHits_t hits;
1859 Int_t iTrack;
1860 BmnRamIterator* pItr;
1861 SelectIterator(threadNum, iTrack, pItr);
1862 for (pItr->ResetAll(); !pItr->EndOfTracks(); pItr->NextTrack(), iTrack++) {
1863 LeaveOneOut(pItr, hits);
1864 // each thread writes the hits of its own range of tracks, so no lock;
1865 // LeaveOneOut() gives the hits in their fHits order
1866 for (size_t k{0}; k < hits.size(); k++) {
1867 if (hits[k].detID == targetID)
1868 continue;
1869 (*pPx)[fFirstHits[iTrack] + k] = hits[k].px;
1870 (*pPy)[fFirstHits[iTrack] + k] = hits[k].py;
1871 }
1872 }
1873}
1874
1876{
1877 // check number of requested threads
1878 LOG(info) << " " << fThreadsCnt << " threads requested";
1879 Int_t max_threads = fTotalTracks / MIN_TRACKS_PER_THREAD;
1880 if (!max_threads)
1881 max_threads = 1;
1882 if (max_threads < fThreadsCnt) {
1883 LOG(warning) << " ! too many threads requested for the size of dataset, using " << max_threads
1884 << " threads instead of " << fThreadsCnt;
1885 fThreadsCnt = max_threads;
1886 }
1887 LOG(info) << " " << fThreadsCnt << " threads approved";
1888
1889 if (fThreadsCnt > 1) {
1890 // create separate RamIterator for each thread
1892 fpIterators.resize(fThreadsCnt);
1893 Int_t tracksPerThread = fTotalTracks / fThreadsCnt;
1894 for (Int_t i = 0, iTrack = 0; i < fThreadsCnt; i++, iTrack += tracksPerThread) {
1895 fFirstTracksIdx[i] = iTrack;
1897 iTrack,
1898 i == fThreadsCnt - 1 // last thread case
1899 ? fTotalTracks - tracksPerThread * i // the rest of tracks for the last thread
1900 : tracksPerThread));
1901 }
1902 } else {
1903 fFirstTracksIdx.resize(1);
1904 fpIterators.resize(1);
1905 fFirstTracksIdx[0] = 0;
1907 }
1908}
std::vector< Double_t > VecDouble_t
std::vector< Bool_t > VecBool_t
RM::SVector< Double_t, 3 > SVect3
@ idZ
RM::SVector< Double_t, BMN_LOCAL_PARAMS_PT > SVectLC
RM::SVector< Double_t, BMN_GLOBAL_PARAMS_PD > SVectGL
std::vector< Int_t > VecInt_t
RM::SMatrix< Double_t, BMN_GLOBAL_PARAMS_PD, BMN_GLOBAL_PARAMS_PD > SMatrGL
RM::SMatrix< Double_t, BMN_GLOBAL_PARAMS_PD, BMN_LOCAL_PARAMS_PT > SMatrGP
@ iZ
@ iX
@ iY
RM::SMatrix< Double_t, BMN_LOCAL_PARAMS_PT, BMN_LOCAL_PARAMS_PT, RM::MatRepSym< Double_t, BMN_LOCAL_PARAMS_PT > > SMatrLC
#define BMN_LOCAL_PARAMS_PT
#define BMN_GLOBAL_PARAMS_PD
TrackFilter_t BmnDefaultTrackFilter(Bool_t wholeTrackOnly=kTRUE)
constexpr const char * BMN_VERTEX_CUT_STR
HitFilter_t BmnDefaultHitFilter(const BmnDetectorModel &model)
constexpr const char * BMN_HITS_CUT_STR
constexpr const char * BMN_TRACKS_CUT_STR
#define BMN_BEAM_BRANCH_NAME
#define BMN_TRACKS_BRANCH_NAME
#define BMN_HITS_BRANCH_NAME
__m128 v
Definition P4_F32vec4.h:1
int i
Definition P4_F32vec4.h:22
__m128 m
Definition P4_F32vec4.h:27
bool Bool_t
int Int_t
constexpr Bool_t kFALSE
double Double_t
constexpr Bool_t kTRUE
constexpr Int_t kBreak
Int_t gErrorIgnoreLevel
TMatrixTSym< Double_t > TMatrixDSym
TMatrixTSub< Double_t > TMatrixDSub
TMatrixT< Double_t > TMatrixD
R__EXTERN TRandom * gRandom
char * Form(const char *fmt,...)
TVectorT< Double_t > TVectorD
static Bool_t LoadConstraints(const char *jsonPath, const BmnAlignHierarchy &hierarchy, BmnAlignPriors &priors)
static Bool_t WriteSolution(const char *jsonPath, const BmnAlignHierarchy &hierarchy, const BmnAlignResult &result, Int_t totalTracks, Bool_t withAlpha)
static Bool_t LoadPresigmas(const char *jsonPath, const BmnAlignHierarchy &hierarchy, BmnAlignPriors &priors)
static Bool_t ReadSolution(const char *jsonPath, const BmnAlignHierarchy &hierarchy, Solution &solution)
SVectGL & A(Int_t index) noexcept
void AddBlankSolution()
Definition BmnAligner.h:226
VecHitRecs_t fHits
indexed by hit, the same way as fHits
Definition BmnAligner.h:159
VecDouble_t fLeafZsum
Definition BmnAligner.h:142
void LeaveOneOut(BmnRamIterator *pItr, VecLooHits_t &hits) const
void DoneInTime(TStopwatch &timer, const char *stage)
Definition BmnAligner.h:252
BmnAlignResult * fpResultPrev
Definition BmnAligner.h:165
VecBool_t * fpTrackUsable
Definition BmnAligner.h:133
BmnRamIterator * fpRamIterator
Definition BmnAligner.h:154
void VertexResidualsPart(VecDouble_t *pRx, VecDouble_t *pRy, Int_t threadNum)
BmnAligner(const BmnMeasureModel *measureModel, BmnDetectorModel *modelDetector, const char *filesListPath, const char *constraintsPath=nullptr, const char *presigmaPath=nullptr, Int_t nThreads=1, Bool_t withProgressBar=kTRUE)
Double_t CalculateMSE(const TVectorD &solution)
RM::BrentMinimizer1D fBrent
Definition BmnAligner.h:143
std::vector< BmnRamIterator * > fpIterators
Definition BmnAligner.h:174
void CalculateMSEpart(Bool_t withResiduals, Int_t threadNum)
BmnDetectorModel * fpDetModel
Definition BmnAligner.h:117
UInt_t fMSEclcCounter
Definition BmnAligner.h:128
VecInt_t fFirstTracksIdx
Definition BmnAligner.h:175
UInt_t fMSEclcTick
Definition BmnAligner.h:129
const BmnAlignResult & ResultLast() const
Definition BmnAligner.h:272
Bool_t SolveGlobal(const TMatrixD &mCL, const TVectorD &vBL, Bool_t optimStep=kFALSE)
BmnSimpleProgressBar * fpProgressBar
Definition BmnAligner.h:124
Int_t fIteration
Definition BmnAligner.h:131
void DropLastResult()
Definition BmnAligner.h:236
const char * fpPresigmaPath
Definition BmnAligner.h:121
VecDouble_t fLeafZmax
Definition BmnAligner.h:142
const BmnMeasureModel * fpMeasureModel
Definition BmnAligner.h:116
void HitPullsPart(VecDouble_t *pPx, VecDouble_t *pPy, Int_t threadNum)
Bool_t fInitialized
Definition BmnAligner.h:125
Double_t fMaxZvalue
Definition BmnAligner.h:170
std::mutex fMutexGlobal
Definition BmnAligner.h:176
Bool_t fAlphaReady
Definition BmnAligner.h:127
Int_t fTracksUsableCnt
Definition BmnAligner.h:135
VecInt_t fHitsPerDetector
Definition BmnAligner.h:138
Bool_t IterateAlignment()
BmnRootIterator * fpRootIterator
Definition BmnAligner.h:153
void InitIterators()
Results_t fIterationResults
Definition BmnAligner.h:167
Bool_t CheckInit(const char *stage)
Definition BmnAligner.h:200
Int_t SelectOutliers()
Int_t SelectVertexHits()
Int_t fTotalHits
Definition BmnAligner.h:137
Bool_t fForceRegular
Definition BmnAligner.h:126
Bool_t fMSEclcSlow
Definition BmnAligner.h:125
VecDouble_t fLeafZmin
Definition BmnAligner.h:142
Bool_t LoadSolution(const char *jsonPath)
std::vector< LooHit_t > VecLooHits_t
Definition BmnAligner.h:99
BmnAlignResult * fpResultLast
Definition BmnAligner.h:166
BmnAlignHierarchy fHierarchy
Definition BmnAligner.h:118
void SelectIterator(Int_t threadNum, Int_t &trackIdx, BmnRamIterator *&pItr)
Definition BmnAligner.h:215
BmnAlignPriors fPriors
Definition BmnAligner.h:119
void LinregAlphaMSE()
Definition BmnAligner.h:209
Int_t Elements() const noexcept
Definition BmnAligner.h:83
Int_t fThreadsCnt
Definition BmnAligner.h:177
Bool_t Align(Double_t zeroRand=0.0, Int_t maxRounds=3)
Int_t fRegularIters
Definition BmnAligner.h:132
Bool_t PrepareData(const char *dumpPath=nullptr, Bool_t fitTargetZ=kTRUE)
void RunThreads(Method method, Args... args)
Definition BmnAligner.h:180
void CalculateLocals(TVectorD *pvDA, Int_t threadNum)
void ProcessTracks(TVectorD *pvB_dash, TMatrixD *pmC_dash, Int_t threadNum)
VecAlphaRecs_t fAlphaRecs
Definition BmnAligner.h:158
const char * fpConstraintsPath
Definition BmnAligner.h:120
void RandomizeSolution(BmnAlignResult &solution, TVectorD *pStdDevLeaf, TVectorD *pStdDevComp)
Bool_t SaveSolution(const char *jsonPath, Bool_t withAlpha=kFALSE)
VecInt_t fFirstHits
hits of all tracks, stored track by track
Definition BmnAligner.h:160
Bool_t FitTargetZ(Double_t &z0, Double_t &z0Err)
void LinRegressionAlphaPart(Int_t threadNum)
Int_t fTotalTracks
Definition BmnAligner.h:136
Bool_t EndOfTracks() const noexcept
Bool_t EndOfHits() const noexcept
Bool_t Initialized() const
const std::string & Description() const
Bool_t IsEnabled() const noexcept
void SetEnabled(Bool_t enabled) noexcept
virtual const char * Description() const noexcept=0
virtual void NextHit() override
const BmnHitRecord & GetHit() const noexcept
virtual void ResetAll() override
virtual Double_t HitY() const override
virtual Double_t HitX() const override
virtual Int_t HitDetectorID() const override
virtual Double_t HitWy() const override
virtual void ResetHits() override
virtual Double_t HitWx() const override
virtual void NextTrack() override
virtual Double_t HitZ() const override
CbmStsTrack Track_t
Double_t Det() const noexcept
Double_t At0() const noexcept
Double_t Var(Double_t z) const noexcept
Double_t At(Double_t z) const noexcept
void Add(Double_t z, Double_t v, Double_t w=1.0) noexcept
Double_t Slope() const noexcept
void Remove(Double_t z, Double_t v, Double_t w=1.0) noexcept
Int_t GetSensorNr() const
Definition CbmStsHit.h:72
virtual Int_t GetStationNr() const
Definition CbmStsHit.h:67
Int_t GetSectorNr() const
Definition CbmStsHit.h:68
Int_t GetSystemId() const
Accessors.
Definition CbmStsHit.h:66
void SetStsHits(TArrayI &hitsArr)
Definition CbmStsTrack.h:89
void SetFunction(const ROOT::Math::IGenFunction &f, double xlow, double xup)
bool Minimize(int maxIter, double absTol=1.E-8, double relTol=1.E-10) override
double XMinimum() const override
void SetElements(InputIterator begin, InputIterator end, bool triang=false, bool lower=true)
const T * Array() const
void SetElements(InputIterator begin, InputIterator end)
void Set(Int_t n) override
Double_t GetXmax() const
Double_t GetXmin() const
void Delete(Option_t *option="") override
TMatrixD Invert()
Bool_t Decompose() override
const TVectorD & GetSig()
const TMatrixD & GetV()
Bool_t Decompose() override
TVectorD Solve(const TVectorD &b, Bool_t &ok) override
Bool_t cd() override
Int_t Write(const char *name=nullptr, Int_t opt=0, Int_t bufsize=0) const override
void Close(Option_t *option="") override
static void StatOverflows(Bool_t flag=kTRUE)
virtual Int_t GetNbinsY() const
static void AddDirectory(Bool_t add=kTRUE)
TAxis * GetXaxis()
virtual Int_t GetNbinsX() const
TAxis * GetYaxis()
virtual Int_t Fill(const char *name, Double_t w)
virtual Int_t Fill(const char *namex, const char *namey, Double_t w)
TMatrixT< Element > GetSub(Int_t row_lwb, Int_t row_upb, Int_t col_lwb, Int_t col_upb, Option_t *option="S") const
const TMatrixT< Element > & Use(const TMatrixT< Element > &a) const
TMatrixTBase< Element > & ResizeTo(const TMatrixT< Element > &m)
TMatrixTBase< Element > & SetSub(Int_t row_lwb, Int_t col_lwb, const TMatrixTBase< Element > &source) override
Int_t GetEntriesFast() const
TObject * At(Int_t idx) const override
R__ALWAYS_INLINE Bool_t IsZombie() const
Double_t RealTime()
void Start(Bool_t reset=kTRUE)
Double_t CpuTime()
void Stop()
void Reset()
const char * Data() const
static TString Format(const char *fmt,...)
virtual Int_t Fill()
virtual void SetDirectory(TDirectory *dir)
virtual Int_t Branch(const char *folder, Int_t bufsize=32000, Int_t splitlevel=99)
Int_t GetNrows() const
TVectorT< Element > & SetSub(Int_t row_lwb, const TVectorT< Element > &source)
Int_t NonZeros() const
TVectorT< Element > & ResizeTo(const TVectorT< Element > &v)
Element * GetMatrixArray()
TVectorT< Element > GetSub(Int_t row_lwb, Int_t row_upb, Option_t *option="S") const
Expr< TensorMulOp< SVector< T, D1 >, SVector< T, D2 > >, T, D1, D2 > TensorProd(const SVector< T, D1 > &lhs, const SVector< T, D2 > &rhs)
RVec< PromoteType< T > > round(const RVec< T > &v)
double E(void *xp)
Expr< TransposeOp< Expr< A, T, D1, D2, R >, T, D1, D2 >, T, D2, D1, typename TranspPolicy< T, D1, D2, R >::RepType > Transpose(const Expr< A, T, D1, D2, R > &rhs)
Double_t QuietNaN()
Double_t Abs(Double_t d)
Double_t Infinity()
std::vector< NodeValues > composites
std::vector< NodeValues > leaves