BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
BmnAlignerTest.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 BmnAlignerTest class implementation
9*/
10
11/*
12 === DEPRECATION NOTICE =========================================
13 Due to complex changes in BmnAligner, this class requires rework
14 ================================================================
15*/
16
17#include "BmnAlignerTest.h"
18
19#include "BmnAlignDefines.h"
20#include "Math/Functions.h"
21#include "TGraph.h"
22#include "TStopwatch.h"
23#include "fairlogger/Logger.h"
24
25#include <fstream>
26#include <nlohmann/json.hpp>
27
29 const BmnATestDetector* modelDetector,
30 Int_t nTracks,
31 const char* constraintsPath,
32 Int_t nThreads)
33 : BmnAligner(measureModel, modelDetector, constraintsPath, nThreads)
34 , fpDetectors(modelDetector)
35{
36 LOG(state) << " > BmnAlignerTest : initialization started";
37
38 // BmnAligner protected fields initialization
39 fTotalTracks = nTracks;
40 fTracksUsableCnt = nTracks;
41 // each track penetrates every (infinite) detector plane
42 fTotalHits = fTotalTracks * BMN_MODULE_COUNT;
43 LOG(detail) << " total hits: " << fTotalHits << ", " << sizeof(BmnATestHit) << " bytes per hit";
44 auto ram_size = fTotalHits * sizeof(BmnATestHit);
45 LOG(info) << " RAM required: " << ram_size / 1073741824.0 << " GB, ";
46 if (ram_size > BMN_MAX_HIT_RAM_SIZE) {
47 LOG(error) << "<!> required RAM size is too large for test:" << std::endl
48 << "<!> decrease number of tracks or detector planes" << std::endl
49 << "<!> max RAM allowed: " << BMN_MAX_HIT_RAM_SIZE / 1073741824.0 << " GB";
50 return;
51 }
52 // all dynamic memory allocated here is released in BmnAligner destructor
53 fpFirstHits = new Int_t[fTotalTracks + 1]; // one extra element for iterator convenience
54 fpTrackUsable = new std::vector<Bool_t>(fTracksUsableCnt, kTRUE);
55 fpHitsData = new Byte_t[ram_size];
56 fpHits = reinterpret_cast<BmnATestHit*>(fpHitsData);
57 fpRamIterator = new BmnRamIterator(fpHits, fpFirstHits, fTotalTracks);
58 fpIteratorMain = fpRamIterator;
59
60 // prepare set of iterators for parallelization by data
62
64 LOG(state) << " < BmnAlignerTest : initialization completed";
65}
66
68{
70 delete[] fpTestTracksData;
71 // the rest of dynamic memory is released in BmnAligner destructor
72}
73
74Bool_t BmnAlignerTest::PrepareData(const char* tracksPath) // virtual override
75{
76 LOG(state) << " > BmnAlignerTest : data preparation started";
77 if (!fInitialized) {
78 LOG(error) << " <!> BmnAlignerTest is not initialized";
79 return kFALSE;
80 }
81 TStopwatch Timer;
82 Bool_t loadTracks{tracksPath && std::filesystem::exists(tracksPath)};
83
84 // tracks data preparation
85 if (loadTracks) {
86 if (!LoadTracks(tracksPath)) {
87 LOG(error) << " <!> failed to load tracks from file " << tracksPath;
88 return kFALSE;
89 }
90 } else {
91 LOG(info) << " Generating random tracks";
93 fpTestTracks = reinterpret_cast<BmnATestTrack*>(fpTestTracksData);
94 for (auto iTrack = 0; iTrack < fTotalTracks; iTrack++)
95 new (fpTestTracks + iTrack)
96 BmnATestTrack(BMN_TEST_ALPHA1_SIGMA, BMN_TEST_ALPHA2_MIN, BMN_TEST_ALPHA2_MAX,
97 BMN_MODULE_COUNT // in test procedure each track penetrates every detector plane
98 );
99 if (tracksPath && !SaveTracks(tracksPath))
100 LOG(warning) << " failed to save tracks to file " << tracksPath;
101 }
102
103 // calculate hits as intersections of track and detector planes
104 SVect3 HitPoint, HitPointLocal;
105 Double_t Z;
106 Int_t iTrack, iHit{0};
107 for (iTrack = 0; iTrack < fTotalTracks; iTrack++) {
108 fpFirstHits[iTrack] = iHit;
109 BmnATestTrack& Track = fpTestTracks[iTrack];
110 for (Int_t iDet = 0; iDet < BMN_MODULE_COUNT; iDet++, iHit++) {
111 const BmnATestDetectorPlane& Detector = fpDetectors->GetDetectors()[iDet];
112 // generate true hit in lab coordinates
113 Z = (-Detector.GetConst() - ROOT::Math::Dot(Detector.GetNormal(), Track.GetVertex()))
114 / ROOT::Math::Dot(Detector.GetNormal(), Track.GetDirection());
115 HitPoint = {Track.X(Z), Track.Y(Z), Z};
116 // recalculate hit to local coordinates of detector
117 HitPointLocal = Detector.GetCrdInvRotation() * (HitPoint - Detector.GetCrdShift());
118 LOG_IF(error, HitPointLocal(2) > BMN_CLOSE_TO_ZERO)
119 << " <!> non-zero local z coordinate of test hit: " << HitPointLocal(2);
120 // store hit as data measured by detector
121 auto pHit = new (fpHits + iHit)
122 BmnATestHit(HitPointLocal(0) + BMN_RND.Gaus(0.0, BMN_TEST_AVERAGE_DX), // x measurement + noise
123 HitPointLocal(1) + BMN_RND.Gaus(0.0, BMN_TEST_AVERAGE_DY), // y measurement + noise
124 Detector.GetPosition(), // z = nominal position of detector
125 BMN_TEST_AVERAGE_DX, BMN_TEST_AVERAGE_DY, &Detector);
126 Track.AddHit(*pHit); // tracks should remember its hits for visualization purposes
127 } // for iDet
128
129 } // for iTrack
130 fpFirstHits[iTrack] = iHit; // last syntetic element for iterator convenience
131
132 // calculate zero approximation of linear tracks
133 std::vector<SVectLC> arrAlpha(fTotalTracks);
134 for (iTrack = 0; iTrack < fTotalTracks; iTrack++) {
135 BmnATestHit &firstHit = fpHits[fpFirstHits[iTrack]], &lastHit = fpHits[fpFirstHits[iTrack + 1] - 1];
136 Double_t dX{lastHit.GetX() - firstHit.GetX()}, dY{lastHit.GetY() - firstHit.GetY()},
137 dZ{lastHit.GetZ() - firstHit.GetZ()}, AlphaX1{dX / dZ}, AlphaY1{dY / dZ};
138 arrAlpha[iTrack] = SVectLC(firstHit.GetX() - AlphaX1 * firstHit.GetZ(), AlphaX1,
139 firstHit.GetY() - AlphaY1 * firstHit.GetZ(), AlphaY1);
140 }
141
142 // MSE scale factors calculation
143 fOmegaScaleFactor = (BMN_TEST_AVERAGE_DX + BMN_TEST_AVERAGE_DY) * 0.5;
144 fOmegaScaleFactor *= fOmegaScaleFactor;
145
146 StoreZeroSolution(arrAlpha);
147
148 /*
149 // DEBUG : Test on precise solution
150 for (Int_t i = 0; i < BMN_MODULE_COUNT; i++)
151 fpResultCurrent->pA[i] = fpDetectors->GetDetectors()[i].GetAlignShift();
152 for (Int_t i = 0; i < fTotalTracks; i++)
153 fpResultCurrent->pAlpha[i] = fpTestTracks[i].GetAlpha();
154 CalculateMSE(kTRUE);
155 */
156
157 Timer.Stop();
158 LOG(info) << " " << fTotalTracks << " tracks ready, total hits: " << iHit << ", time spent: " << Timer.CpuTime()
159 << " s (CPU)";
160 LOG(state) << " < BmnAlignerTest : data preparation completed";
161 return LoadConstraints();
162}
163
165{
167 if (!success)
168 return kFALSE;
169
170 // monitor local parameters convergence
171 SVectLC delta;
172 for (auto i = 0; i < TotalTracks(); i++) {
173 const SVectLC& Alpha = GetResult()->Alpha(i);
174 delta += ROOT::Math::fabs(Alpha - GetTestTrack(i).GetAlpha());
175 }
176 delta /= TotalTracks();
177 LOG(info) << " === average local parameters convergence:";
178 LOG(info) << " error by X = (" << delta(iX0) << ", " << delta(iX1) << ")";
179 LOG(info) << " error by Y = (" << delta(iY0) << ", " << delta(iY1) << ")";
180
181 return kTRUE;
182}
183
184Bool_t BmnAlignerTest::SaveTracks(const char* path) const
185{
186 LOG(info) << " Saving tracks data to " << path;
187 if (!fpTestTracks || fTotalTracks <= 0)
188 return kFALSE;
189 std::ofstream ofs(path);
190 if (!ofs.good()) {
191 LOG(error) << " <!> failed to open JSON file " << path;
192 return kFALSE;
193 }
194
195 nlohmann::json j;
196 j["tracks"] = fTotalTracks;
197 j["alphas"] = nlohmann::json::array();
198 for (Int_t i = 0; i < fTotalTracks; i++) {
199 const auto& tr = fpTestTracks[i];
200 const auto& Alpha = tr.GetAlpha();
201 j["alphas"].push_back({Alpha(iX0), Alpha(iX1), Alpha(iY0), Alpha(iY1)});
202 }
203
204 ofs << j.dump(2);
205 return kTRUE;
206}
207
209{
210 LOG(info) << " Loading tracks data from " << path;
211 std::ifstream ifs(path);
212 if (!ifs.good()) {
213 LOG(error) << " <!> failed to open JSON file " << path;
214 return kFALSE;
215 }
216
217 nlohmann::json j;
218 ifs >> j;
219
220 // re-allocate new buffer and construct records
221 fTotalTracks = j.value("tracks", 0);
223 delete[] fpTestTracksData;
225 fpTestTracks = reinterpret_cast<BmnATestTrack*>(fpTestTracksData);
226
227 const auto& arr = j["alphas"];
228 for (Int_t i = 0; i < fTotalTracks; i++) {
229 const auto& a = arr[i];
230 SVectLC Alpha(a[iX0].get<double>(), a[iX1].get<double>(), a[iY0].get<double>(), a[iY1].get<double>());
231 new (fpTestTracks + i) BmnATestTrack(Alpha, BMN_MODULE_COUNT);
232 }
233 return kTRUE;
234}
235
236// visualization works in ROOT macro mode only
238{
239 PrepareDrawing();
240
241 // Draw tracks
242 fpPad3D->cd();
243 fpPad3D->SetTitle("Some random tracks");
244 const Double_t zMax = fpDetectors->GetMaxZ() * 1.1;
245 for (Int_t i = 0; i < BMN_MODULE_COUNT; i++)
246 fpDetectors->GetDetectors()[i].Draw();
247 TRandom trueRnd{0};
248 std::vector<Int_t> drawn_tracks(BMN_DRAW_TRACKS_CNT, -1);
249 for (Int_t i = 0, j; i < BMN_DRAW_TRACKS_CNT; i++) {
250 j = trueRnd.Uniform(0, TotalTracks());
251 if (drawn_tracks.end() == std::find(drawn_tracks.begin(), drawn_tracks.end(), j) && fpTrackUsable->at(i)) {
252 GetTestTrack(j).Draw(kTRUE, zMax);
253 BmnATestTrack trk(GetResult()->Alpha(j), BMN_MODULE_COUNT);
254 trk.Draw(kFALSE, zMax);
255 drawn_tracks[i] = j;
256 } else
257 i--;
258 }
259
260 double xValues[BMN_GLPARAMS_TOTAL];
261 for (auto i = 0; i < BMN_GLPARAMS_TOTAL; i++)
262 xValues[i] = static_cast<double>(i + 1);
263
264 // Draw solution
265 Double_t A[BMN_GLPARAMS_TOTAL];
266 for (Int_t i = 0, k = 0; i < BMN_MODULE_COUNT; i++)
267 for (Int_t j = 0; j < BMN_GLOBAL_PARAMS_PD; j++, k++)
268 A[k] = GetResult()->A(i)(j);
269 fpPadG1->cd();
270 fpPadG1->SetTitle("Solution");
271 TGraph* graphSolution = new TGraph(BMN_GLPARAMS_TOTAL, xValues, A);
272 graphSolution->SetTitle("Alignment values");
273 graphSolution->SetFillColor(kRed);
274 graphSolution->SetMinimum(-0.25); // DEBUG
275 graphSolution->SetMaximum(0.35); // DEBUG
276 graphSolution->GetXaxis()->SetRangeUser(xValues[0], xValues[BMN_GLPARAMS_TOTAL - 1]);
277 graphSolution->Draw("AB");
278 Double_t T[BMN_GLPARAMS_TOTAL];
279 for (Int_t i = 0, k = 0; i < BMN_MODULE_COUNT; i++)
280 for (Int_t j = 0; j < BMN_GLOBAL_PARAMS_PD; j++, k++)
281 T[k] = fpDetectors->GetTestA()[i](j);
282 TGraph* graphTest = new TGraph(BMN_GLPARAMS_TOTAL, xValues, T);
283 graphTest->SetLineColor(kBlack);
284 graphTest->Draw("*SAME");
285
286 /*
287 // Draw SVD singularity values
288 TVectorD SVDsig {GetResult()->SVDSig()};
289 fpPadG4->cd();
290 fpPadG4->SetTitle("SVD singularity values");
291 fpPadG4->SetLogy();
292 TGraph* graphSVD = new TGraph(
293 BMN_GLPARAMS_TOTAL,
294 xValues,
295 SVDsig.GetMatrixArray()
296 );
297 // narrow drawing range to interesting part
298 Int_t SVDdrawIdx;
299 for (SVDdrawIdx = 0; SVDdrawIdx < SVDsig.GetNrows(); SVDdrawIdx++)
300 if (SVDsig(SVDdrawIdx) <= BMN_SVD_LOW) break;
301 SVDdrawIdx = std::max(
302 0,
303 std::min(
304 SVDdrawIdx,
305 BMN_GLPARAMS_TOTAL - 10
306 )
307 );
308 graphSVD->GetXaxis()->SetRangeUser(
309 static_cast<Double_t>(SVDdrawIdx),
310 static_cast<Double_t>(BMN_GLPARAMS_TOTAL)
311 );
312 graphSVD->SetTitle("SVD singularity values (tale)");
313 graphSVD->SetFillColor(kGray);
314 graphSVD->Draw("AB");
315 */
316
317 DrawResiduals();
318}
319
321{
323 const SVectGL* Atest{fpDetectors->GetTestA()};
324 BmnAlignResult *pBeforeResult{GetResult(kFALSE)}, *pAfterResult{GetResult(kTRUE)};
325 Double_t beforeValue{0.0}, afterValue{0.0};
326 for (Int_t i = 0; i < BMN_MODULE_COUNT; i++) {
327 beforeValue += ROOT::Math::Mag2(Atest[i] - pBeforeResult->A(i));
328 afterValue += ROOT::Math::Mag2(Atest[i] - pAfterResult->A(i));
329 }
330 LOG(info) << " === distance to test A before/after alignment: " << std::sqrt(beforeValue) << " / "
331 << std::sqrt(afterValue);
332}
333
335{
336 fpResultCurrent->ResetValueMSE();
337 if (withResiduals) {
338 fpResultCurrent->ResidualsX().Reset();
339 fpResultCurrent->ResidualsY().Reset();
340 }
341 for (Int_t iTrack = 0; iTrack < fTotalTracks; iTrack++) {
342 if (!fpTrackUsable->at(iTrack))
343 continue;
344 fpTestTracks[iTrack].AddMSE(this, withResiduals);
345 }
346 return fpResultCurrent->GetValueMSE();
347}
@ iY1
@ iY0
@ iX1
@ iX0
RM::SVector< Double_t, 3 > SVect3
RM::SVector< Double_t, BMN_LOCAL_PARAMS_PT > SVectLC
RM::SVector< Double_t, BMN_GLOBAL_PARAMS_PD > SVectGL
#define BMN_GLOBAL_PARAMS_PD
int i
Definition P4_F32vec4.h:22
bool Bool_t
int Int_t
unsigned char Byte_t
constexpr Bool_t kFALSE
double Double_t
constexpr Bool_t kTRUE
kRed
kBlack
const SVect3 & GetNormal() const noexcept
const SVect3 & GetCrdShift() const noexcept
Double_t GetPosition() const noexcept
const SMatr3x3 & GetCrdInvRotation() const noexcept
Double_t GetConst() const noexcept
const SVect3 & GetVertex() const noexcept
Double_t Y(Double_t z) const noexcept
Double_t X(Double_t z) const noexcept
void Draw(Bool_t solid=kTRUE, Double_t maxZ=BMN_TEST_TRACK_DEF_MAX_Z) const
const SVect3 & GetDirection() const noexcept
void AddHit(BmnATestHit &hit)
SVectGL & A(Int_t index) noexcept
BmnATestTrack * fpTestTracks
virtual void ReportResults() const override
virtual Double_t CalculateMSE(Bool_t withResiduals) override
virtual Bool_t PrepareData(const char *tracksPath=nullptr) override
virtual Bool_t IterateAlignment() override
virtual ~BmnAlignerTest()
virtual void Draw() override
BmnAlignerTest()=delete
const BmnATestDetector * fpDetectors
Bool_t LoadTracks(const char *path)
Byte_t * fpTestTracksData
Bool_t SaveTracks(const char *path) const
const BmnATestTrack & GetTestTrack(Int_t trackID) const noexcept
BmnRamIterator * fpRamIterator
Definition BmnAligner.h:154
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)
Bool_t IterateAlignment()
Int_t TotalTracks() const noexcept
Definition BmnAligner.h:67
Double_t GetY() const noexcept
Double_t GetX() const noexcept
Double_t GetZ() const noexcept
virtual void SetFillColor(Color_t fcolor)
virtual void SetLineColor(Color_t lcolor)
virtual void SetRangeUser(Double_t ufirst, Double_t ulast)
virtual void SetMaximum(Double_t maximum=-1111)
void Draw(Option_t *chopt="") override
TAxis * GetXaxis() const
void SetTitle(const char *title="") override
virtual void SetMinimum(Double_t minimum=-1111)
virtual Double_t Uniform(Double_t x1, Double_t x2)
T Mag2(const SVector< T, D > &rhs)
T Dot(const SVector< T, D > &lhs, const SVector< T, D > &rhs)
Expr< UnaryOp< Fabs< T >, Expr< A, T, D, D2, R >, T >, T, D, D2, R > fabs(const Expr< A, T, D, D2, R > &rhs)