BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
BmnAligner.h
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 declaration
9 Alignment algorithm itself
10*/
11
12#ifndef BMNALIGNER_H
13#define BMNALIGNER_H
14
15#include "BmnAlignDefines.h"
16#include "BmnAlignHierarchy.h"
17#include "BmnAlignPriors.h"
18#include "BmnAlignResult.h"
19#include "BmnDetectorModel.h"
20#include "BmnHitRecord.h"
21#include "BmnMeasureModel.h"
22#include "BmnParamLayout.h"
23#include "BmnRamIterator.h"
24#include "BmnRootIterator.h"
26#include "BmnWeightedLine.h" // IWYU pragma: keep -- include here to put it into the dictionary, for the macros
27
29#include <TStopwatch.h>
30#include <deque>
31#include <mutex>
32#include <thread>
33#include <vector>
34
36{
37 public:
38 // the only way to build one: a task plus the data to solve it on. The detector
39 // model is not const: PrepareData() may move its target, see there
40 BmnAligner(const BmnMeasureModel* measureModel,
41 BmnDetectorModel* modelDetector,
42 const char* filesListPath,
43 const char* constraintsPath = nullptr,
44 const char* presigmaPath = nullptr,
45 Int_t nThreads = 1,
46 Bool_t withProgressBar = kTRUE);
48
49 // user interface methods
50 Bool_t Align(Double_t zeroRand = 0.0, Int_t maxRounds = 3);
51 Bool_t PrepareData(const char* dumpPath = nullptr, Bool_t fitTargetZ = kTRUE);
52 Bool_t SaveSolution(const char* jsonPath, Bool_t withAlpha = kFALSE);
53 Bool_t LoadSolution(const char* jsonPath);
55 TVectorD* pStdDevLeaf, // element own share, per parameter
56 TVectorD* pStdDevComp // composite own share, null to skip
57 );
58 inline void AddBlankSolution();
59 inline void DropLastResult();
60 inline void LinregAlphaMSE();
61 Int_t SelectVertexHits(); // returns how many hits changed state
62 Bool_t FitTargetZ(Double_t& z0, Double_t& z0Err); // where the tracks meet the beam
63
64 // getters
65 typedef std::deque<BmnAlignResult> Results_t;
66 Bool_t Initialized() const noexcept { return fInitialized; }
67 Int_t TotalTracks() const noexcept { return fTotalTracks; }
68 Int_t TotalHits() const noexcept { return fTotalHits; }
69 Results_t& Results() noexcept { return fIterationResults; }
70 const Results_t& Results() const noexcept { return fIterationResults; }
71 const BmnAlignHierarchy& Hierarchy() const noexcept { return fHierarchy; }
72 const BmnParamLayout& Layout() const noexcept { return fHierarchy.Layout(); }
73 const BmnDetectorModel* DetectorModel() const noexcept { return fpDetModel; }
74 const BmnMeasureModel* MeasureModel() const noexcept { return fpMeasureModel; }
76 BmnRamIterator* RamIterator() const noexcept { return fpRamIterator; }
77 const BmnAlignPriors& Priors() const noexcept { return fPriors; }
78 const char* ConstraintsPath() const noexcept { return fpConstraintsPath; }
79 Double_t TotalCpuTime() const noexcept { return fTotalCpuTime; }
80 Double_t TotalRealTime() const noexcept { return fTotalRealTime; }
81 Double_t MaxZvalue() const noexcept { return fMaxZvalue; }
82 Int_t TracksUsable() const noexcept { return fTracksUsableCnt; }
83 Int_t Elements() const noexcept { return fpDetModel->Alignables(); }
84 const VecBool_t* TrackUsable() const noexcept { return fpTrackUsable; }
85 BmnSimpleProgressBar* ProgressBar() const noexcept { return fpProgressBar; }
86 const BmnAlignResult& ResultLast() const;
88 const BmnAlignResult& ResultZero() const;
90
91 protected:
92 // a hit against the line through the other hits of its track, see LeaveOneOut()
93 struct LooHit_t
94 {
96 Double_t rx, ry, // residual, measured minus line (cm); NaN if no line is left
97 px, py; // pull, residual over its standard deviation; NaN if undefined
98 };
99 typedef std::vector<LooHit_t> VecLooHits_t;
100
101 // main internal methods -- see implementation for details
103 Double_t CalculateMSE(const TVectorD& solution); // does not store result
104 Double_t CalculateMSE(Bool_t withResiduals); // stores result in fResultCurrent
105 Bool_t SolveGlobal(const TMatrixD& mCL, const TVectorD& vBL, Bool_t optimStep = kFALSE);
106 Int_t SelectOutliers(); // returns how many tracks changed state
107 void LeaveOneOut(BmnRamIterator* pItr, VecLooHits_t& hits) const;
108 // internal service methods
110 inline void MarkTime(TStopwatch& timer);
111 inline void DoneInTime(TStopwatch& timer, const char* stage);
112 inline Bool_t CheckInit(const char* stage);
113 inline void CheckResults() const;
114
115 // alignment task definition elements
116 const BmnMeasureModel* fpMeasureModel; // observables measurement model
117 BmnDetectorModel* fpDetModel; // detector structure and encoding model
118 BmnAlignHierarchy fHierarchy; // structure of the alignment parametrization
119 BmnAlignPriors fPriors; // aprior knowledge -- constraints and presigmas
120 const char* fpConstraintsPath{nullptr};
121 const char* fpPresigmaPath{nullptr};
122
123 // service variables
126 fForceRegular{kFALSE}, // against quasi-Newton devergence
127 fAlphaReady{kFALSE}; // indicates completeness of local parameters calculation
128 UInt_t fMSEclcCounter{0u}, // CLI output counter
129 fMSEclcTick{1u}; // CLI output parameter
131 Int_t fIteration{-1}, // global iteration counter
132 fRegularIters{0}; // regularized iterations counter
133 VecBool_t* fpTrackUsable{nullptr}; // runtime tracks rejection flags, see SelectOutliers()
134 // TODO: replace with TBits, move into the iterator
135 Int_t fTracksUsableCnt{0}, // runtime tracks usable count
136 fTotalTracks{0}, // global track count
137 fTotalHits{0}; // global hit count
138 VecInt_t fHitsPerDetector; // per-detector hit count
139 // per-element hit z statistics, collected by PrepareData(). The mean gives
140 // the nominal element z the hierarchy pivots rest on; the spread tells how
141 // well the hit-independent Jacobian assumption holds (see BmnAlignHierarchy)
144 // data storage implementation
146 { // data necessary for final Alpha calculation (one record per hit)
147 SMatrGP mGGammaInv; // one matrix term -- part of C_12 * C_22^-1 _VBCK_ (4)
148 Int_t paramIdx; // offset of the element's first parameter in the leaf layout,
149 // negative if the hit takes no part in the global section
150 };
151 typedef std::vector<AlphaData_t> VecAlphaRecs_t;
152 typedef std::vector<BmnHitRecord> VecHitRecs_t;
153 BmnRootIterator* fpRootIterator{nullptr}; // iterator over ROOT files
154 BmnRamIterator* fpRamIterator{nullptr}; // iterator over RAM storage
155 // CAUTION: fpRamIterator and all its slices keep raw pointers into fHits and fFirstHits, aquired
156 // from std::vectors. Therefore, both fHits and fFirstHits must get their final capacity once
157 // in BmnAligner constructor and never reallocate after that.
158 VecAlphaRecs_t fAlphaRecs; //! indexed by hit, the same way as fHits
159 VecHitRecs_t fHits; //! hits of all tracks, stored track by track
160 VecInt_t fFirstHits; // indexes of first hit of each track
161 // The "//!" marks keep rootcling from generating collection dictionaries: they need a default
162 // constructor (BmnHitRecord has none) and a public element type (AlphaData_t is protected).
163
164 // iteration results storage
165 BmnAlignResult *fpResultPrev{nullptr}, // link to result of previous iteration
166 *fpResultLast{nullptr}; // link to result of latest iteration
167 Results_t fIterationResults; // all results of calculations
168 // largest hit z in the data, collected by PrepareData(); the solution
169 // carries it, and BmnAlignDraw scales the 3D view by it
171
172 // multithreading implementation
173 private:
174 std::vector<BmnRamIterator*> fpIterators; // one iterator per thread
175 VecInt_t fFirstTracksIdx; // first track to process for each thread
176 std::mutex fMutexGlobal;
178 inline void SelectIterator(Int_t threadNum, Int_t& trackIdx, BmnRamIterator*& pItr);
179 template<typename Method, typename... Args>
180 void RunThreads(Method method, Args... args)
181 {
182 std::vector<std::thread> threads;
183 threads.reserve(fThreadsCnt);
184 for (Int_t i = 0; i < fThreadsCnt; i++)
185 threads.emplace_back(method, this, args..., i);
186 for (std::thread& thread : threads)
187 thread.join();
188 }
189 // thread functions
190 void ProcessTracks(TVectorD* pvB_dash, TMatrixD* pmC_dash, Int_t threadNum);
191 void CalculateLocals(TVectorD* pvDA, Int_t threadNum);
192 void CalculateMSEpart(Bool_t withResiduals, Int_t threadNum);
194 void HitPullsPart(VecDouble_t* pPx, VecDouble_t* pPy, Int_t threadNum);
196};
197
198// === inline implementation ====================================================
199
200inline Bool_t BmnAligner::CheckInit(const char* stage)
201{
202 if (!fInitialized) {
203 LOG(error) << "<!> BmnAligner is not initialized";
204 LOG(state) << " < BmnAligner : " << stage << " terminated";
205 }
206 return fInitialized;
207}
208
214
215inline void BmnAligner::SelectIterator(Int_t threadNum, Int_t& trackIdx, BmnRamIterator*& pItr)
216{
217 if (threadNum == -1) { // single-thread computation
218 trackIdx = 0;
219 pItr = fpRamIterator;
220 } else { // multi-thread computation
221 trackIdx = fFirstTracksIdx[threadNum];
222 pItr = fpIterators[threadNum];
223 }
224}
225
227{
228 fIterationResults.emplace_back(fTotalTracks, fMaxZvalue, fpDetModel->Alignables(),
229 // before PrepareData() has built the hierarchy the layout is flat
230 fHierarchy.Ready() ? fHierarchy.AllParams()
231 : fpDetModel->Alignables() * BMN_GLOBAL_PARAMS_PD);
234}
235
237{
238 if (fIterationResults.empty())
239 return;
240 fIterationResults.pop_back();
241 fpResultLast = fIterationResults.empty() ? nullptr : &fIterationResults.back();
242 fpResultPrev = fIterationResults.size() < 2 ? nullptr : &fIterationResults[fIterationResults.size() - 2];
243}
244
246{
247 timer.Stop();
248 fTotalCpuTime += timer.CpuTime();
249 fTotalRealTime += timer.RealTime();
250}
251
252inline void BmnAligner::DoneInTime(TStopwatch& timer, const char* stage)
253{
254 MarkTime(timer);
255 LOG(state) << Form(" < BmnAligner : %s completed in %.1fs (REAL) / %.1fs (CPU)", stage, timer.RealTime(),
256 timer.CpuTime());
257 LOG(state) << " ---";
258}
259
260inline void BmnAligner::CheckResults() const
261{
262 if (fIterationResults.empty())
263 throw std::runtime_error("BmnAligner: no results");
264}
265
267{
268 CheckResults();
269 return fIterationResults.back();
270}
271
273{
274 CheckResults();
275 return fIterationResults.back();
276}
277
279{
280 CheckResults();
281 return fIterationResults.front();
282}
283
285{
286 CheckResults();
287 return fIterationResults.front();
288}
289
290#endif // BMNALIGNER_H
std::vector< Double_t > VecDouble_t
std::vector< Bool_t > VecBool_t
std::vector< Int_t > VecInt_t
RM::SMatrix< Double_t, BMN_GLOBAL_PARAMS_PD, BMN_LOCAL_PARAMS_PT > SMatrGP
#define BMN_GLOBAL_PARAMS_PD
int i
Definition P4_F32vec4.h:22
bool Bool_t
int Int_t
unsigned int UInt_t
constexpr Bool_t kFALSE
double Double_t
constexpr Bool_t kTRUE
TMatrixT< Double_t > TMatrixD
char * Form(const char *fmt,...)
TVectorT< Double_t > TVectorD
void AddBlankSolution()
Definition BmnAligner.h:226
void LeaveOneOut(BmnRamIterator *pItr, VecLooHits_t &hits) const
BmnSimpleProgressBar * ProgressBar() const noexcept
Definition BmnAligner.h:85
std::deque< BmnAlignResult > Results_t
Definition BmnAligner.h:65
void DoneInTime(TStopwatch &timer, const char *stage)
Definition BmnAligner.h:252
BmnAlignResult * fpResultPrev
Definition BmnAligner.h:165
void CheckResults() const
Definition BmnAligner.h:260
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
Double_t TotalCpuTime() const noexcept
Definition BmnAligner.h:79
const Results_t & Results() const noexcept
Definition BmnAligner.h:70
Double_t MaxZvalue() const noexcept
Definition BmnAligner.h:81
std::vector< BmnRamIterator * > fpIterators
Definition BmnAligner.h:174
void CalculateMSEpart(Bool_t withResiduals, Int_t threadNum)
BmnDetectorModel * fpDetModel
Definition BmnAligner.h:117
const BmnDetectorModel * DetectorModel() const noexcept
Definition BmnAligner.h:73
Bool_t Initialized() const noexcept
Definition BmnAligner.h:66
Int_t TracksUsable() const noexcept
Definition BmnAligner.h:82
Int_t TotalHits() const noexcept
Definition BmnAligner.h:68
const BmnAlignResult & ResultLast() const
Definition BmnAligner.h:272
BmnAlignResult & ResultLast()
Definition BmnAligner.h:266
Bool_t SolveGlobal(const TMatrixD &mCL, const TVectorD &vBL, Bool_t optimStep=kFALSE)
BmnSimpleProgressBar * fpProgressBar
Definition BmnAligner.h:124
void DropLastResult()
Definition BmnAligner.h:236
const char * fpPresigmaPath
Definition BmnAligner.h:121
const BmnMeasureModel * fpMeasureModel
Definition BmnAligner.h:116
const VecBool_t * TrackUsable() const noexcept
Definition BmnAligner.h:84
void HitPullsPart(VecDouble_t *pPx, VecDouble_t *pPy, Int_t threadNum)
Double_t CalculateMSE(Bool_t withResiduals)
std::vector< BmnHitRecord > VecHitRecs_t
Definition BmnAligner.h:152
const char * ConstraintsPath() const noexcept
Definition BmnAligner.h:78
void MarkTime(TStopwatch &timer)
Definition BmnAligner.h:245
BmnRamIterator * RamIterator() const noexcept
Definition BmnAligner.h:76
Bool_t IterateAlignment()
BmnRootIterator * fpRootIterator
Definition BmnAligner.h:153
void InitIterators()
Bool_t CheckInit(const char *stage)
Definition BmnAligner.h:200
Results_t & Results() noexcept
Definition BmnAligner.h:69
Int_t SelectOutliers()
Int_t SelectVertexHits()
const BmnMeasureModel * MeasureModel() const noexcept
Definition BmnAligner.h:74
Bool_t fMSEclcSlow
Definition BmnAligner.h:125
Bool_t LoadSolution(const char *jsonPath)
const BmnParamLayout & Layout() const noexcept
Definition BmnAligner.h:72
BmnRootIterator * RootIterator() noexcept
Definition BmnAligner.h:75
std::vector< LooHit_t > VecLooHits_t
Definition BmnAligner.h:99
BmnAlignResult * fpResultLast
Definition BmnAligner.h:166
const BmnAlignResult & ResultZero() const
Definition BmnAligner.h:284
BmnAlignHierarchy fHierarchy
Definition BmnAligner.h:118
Int_t TotalTracks() const noexcept
Definition BmnAligner.h:67
void SelectIterator(Int_t threadNum, Int_t &trackIdx, BmnRamIterator *&pItr)
Definition BmnAligner.h:215
BmnAlignResult & ResultZero()
Definition BmnAligner.h:278
void LinregAlphaMSE()
Definition BmnAligner.h:209
Int_t Elements() const noexcept
Definition BmnAligner.h:83
Bool_t Align(Double_t zeroRand=0.0, Int_t maxRounds=3)
Bool_t PrepareData(const char *dumpPath=nullptr, Bool_t fitTargetZ=kTRUE)
std::vector< AlphaData_t > VecAlphaRecs_t
Definition BmnAligner.h:151
const BmnAlignPriors & Priors() const noexcept
Definition BmnAligner.h:77
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)
const BmnAlignHierarchy & Hierarchy() const noexcept
Definition BmnAligner.h:71
Bool_t FitTargetZ(Double_t &z0, Double_t &z0Err)
Double_t TotalRealTime() const noexcept
Definition BmnAligner.h:80
void LinRegressionAlphaPart(Int_t threadNum)
Double_t RealTime()
Double_t CpuTime()
void Stop()