BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
BmnAlignerApply.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 BmnAlignerApply class implementation
9*/
10
11#include "BmnAlignerApply.h"
12
13#include "BmnAlignConfig.h"
15#include "BmnVSPStationSet.h"
16#include "CbmStsHit.h"
17#include "DigiRunHeader.h"
18#include "DstEventHeader.h"
19#include "FairRootManager.h"
20#include "FairRunAna.h"
21#include "TFile.h"
22#include "TKey.h"
23#include "TSystem.h"
24#include "fairlogger/Logger.h"
25
26#include <iostream>
27#include <memory>
28#include <set>
29
31{
32 for (auto& station : fhLorCorX)
33 for (auto& [isec, h2] : station)
34 delete h2;
35 for (auto& station : fhLorCorY)
36 for (auto& [isec, h2] : station)
37 delete h2;
38}
39
41{
42 FairRootManager* ioman = FairRootManager::Instance();
43 if (!ioman) {
44 LOG(error) << " <!> BmnAlignerApply::Init : FairRootManager not found";
45 SetActive(kFALSE);
46 return kERROR;
47 }
48 fpStsHitsArray = (TClonesArray*)ioman->GetObject("StsHit");
49 if (!fpStsHitsArray) {
50 LOG(error) << " <!> BmnAlignerApply::Init : Failed to get StsHit array";
51 SetActive(kFALSE);
52 return kERROR;
53 }
54 try {
56 fCorrections.assign(fpDetModel->Alignables(), SVectGL());
57 if (!fHierarchy.BuildFlat(*fpDetModel)) {
58 LOG(error) << " <!> BmnAlignerApply::Init : Failed init alignment hierarchy";
59 SetActive(kFALSE);
60 return kERROR;
61 }
63 LOG(error) << " <!> BmnAlignerApply::Init : Failed to load alignment solution from file " << fAlignFilePath;
64 SetActive(kFALSE);
65 return kERROR;
66 }
67 for (const BmnAlignConfig::NodeValues& leaf : solution.leaves)
68 fCorrections[leaf.node] = leaf.values;
69 } catch (std::exception& e) {
70 LOG(error) << " <!> BmnAlignerApply::Init : " << e.what();
71 SetActive(kFALSE);
72 return kERROR;
73 } catch (...) {
74 LOG(error) << " <!> BmnAlignerApply::Init : Unknown exception";
75 SetActive(kFALSE);
76 return kERROR;
77 }
78
79 LOG(info) << "BmnAlignerApply::Init : detector alignment model '" << fpDetModel->Description() << "'";
80 LOG_IF(warning, fpDetModel->IgnoresSome())
81 << "BmnAlignerApply::Init : this model is incomplete - some hits will be left as is";
82
84 SetActive(kTRUE);
85 return kSUCCESS;
86 }
87 InitStatus statusL{LorentzCorrectionInit()};
88 SetActive(statusL == kSUCCESS);
89 return statusL;
90}
91
93{
94 /*
95 * Lorentz corrections section-----------------------------------------------------------------
96 *
97 * The code below is taken from BmnToCbmHitConverter::Init() and
98 * BmnToCbmHitConverter::FillLorentzHistos(int). It implements the Lorentz correction of hit
99 * positions and was not revised, except few lines marked with tag PLV. Commented-out lines of
100 * the original are dropped. Indentation is kept as in the original code.
101 */
102
103 FairField* mField = FairRunAna::Instance()->GetField();
104 fieldFlag = (TMath::Abs(mField->GetBy(0, 0, 135)) > 0.5) ? kTRUE : kFALSE;
105
106 // PLV : begin
107 // the corrections are applied with the field on only (AZ-280826), so without it no tables are needed
108 if (!fieldFlag)
109 return kSUCCESS;
110
111 // the station sets are local: only the Si and VSP module counts are needed, and only here;
112 // the configuration files are those that run_reco_bmn.C sets for BmnToCbmHitConverter
113 FairRootManager* ioman = FairRootManager::Instance();
114 auto digiRunHeader = static_cast<DigiRunHeader*>(ioman->GetInFile()->Get("DigiRunHeader"));
115 uint64_t period{digiRunHeader ? digiRunHeader->GetPeriodId() : 0};
116 TString gPathConfig{gSystem->Getenv("VMCWORKDIR")};
117 std::unique_ptr<BmnSiliconStationSet> SilStationSet{new BmnSiliconStationSet(
118 gPathConfig + "/parameters/silicon/XMLConfigs/" + (period > 8 ? "SiliconRun9.xml" : "SiliconRun8.xml"))};
119 std::unique_ptr<BmnVSPStationSet> VspStationSet;
120 if (period > 8)
121 VspStationSet.reset(new BmnVSPStationSet(gPathConfig + "/parameters/vsp/XMLConfigs/VSP_Run9.xml"));
122
123 UInt_t irun{((DstEventHeader*)ioman->GetObject("DstEventHeader."))->GetRunId()};
124 if (irun == 0) {
125 LOG(error) << " <!> BmnAlignerApply::Init : no run number to select Lorentz corrections";
126 return kERROR;
127 }
128
129 // TFile::Open() below moves gDirectory away from the output file; restore it on return
130 TDirectory::TContext dirContext;
131 // PLV : end
132
133 TString fileName = gSystem->ExpandPathName("$VMCWORKDIR");
134 fileName += "/parameters/reco/LorentzCorr.histo.root";
135
136 TFile* histFile = TFile::Open(fileName);
137 if (histFile == nullptr) {
138 // PLV : begin
139 // a failed task init instead of exit(1)
140 LOG(error) << " <!> BmnAlignerApply::Init : Lorentz correction file " << fileName << " not found";
141 return kERROR;
142 // PLV : end
143 }
144
145 // Get runs with silicon and GEM histograms
146 set<int> runs[2];
147
148 TList* keyList = histFile->GetListOfKeys();
149 TIter next(keyList);
150 TObject* obj = nullptr;
151 TKey *key = nullptr, *key1 = nullptr;
152
153 while ((obj = next())) {
154 key = (TKey*)obj;
155 if (key->IsFolder()) {
156 TDirectory* dir = (TDirectory*)key->ReadObj();
157 TIter nextHist(dir->GetListOfKeys());
158
159 while ((key1 = (TKey*)nextHist())) {
160 if (TString(key1->GetName()).Contains("hSil"))
161 runs[0].insert(stoi(key->GetName())); // run name
162 else if (TString(key1->GetName()).Contains("hGem"))
163 runs[1].insert(stoi(key->GetName())); // run name
164 }
165 }
166 }
167
168 for (int igem = 0; igem < 2; ++igem) {
169 auto iter = runs[igem].upper_bound(irun);
170 if (iter != runs[igem].begin())
171 --iter;
172 cout << " ---> Using corrections for run " << *iter << " " << igem << endl;
173 int ifirst = 0;
174
175 TDirectory* dir = (TDirectory*)histFile->Get(TString::Itoa(*iter, 10));
176 TIter nextHist(dir->GetListOfKeys());
177
178 while ((key = (TKey*)nextHist())) {
179 TString hName = key->GetName();
180 if (igem == 0 && !hName.Contains("hSil"))
181 continue;
182 if (igem == 1 && !hName.Contains("hGem"))
183 continue;
184 TH2D* hist = (TH2D*)key->ReadObj();
185 TString cXY = (hName.Contains("X")) ? "X" : "Y";
186 int ipos = hName.First("_");
187 TString stat = hName(ipos + 1, hName.Length() - ipos);
188 int ista = stat.Atoi() - 1;
189
190 // Split histogram into 2 halves for GEM (upper and lower) and modules for Si
191 int nx = hist->GetNbinsX(), ny = hist->GetNbinsY(), ny12 = ny / 2;
192 Double_t xmin = hist->GetXaxis()->GetXmin(), xmax = hist->GetXaxis()->GetXmax();
193 Double_t ymin = hist->GetYaxis()->GetXmin(), ymax = hist->GetYaxis()->GetXmax();
194 if (TMath::Abs(ymax + ymin) > 0.1)
195 Fatal("FillLorentzHistost", "!!! Different ymin and ymax %f %f ", ymin, ymax);
196 if (ifirst == 0) {
197 ifirst = 1;
198 Double_t dx = (xmax - xmin) / nx, dy = (ymax - ymin) / ny;
199 cout << " Bin size: " << dx << "x" << dy << " cm" << endl;
200 }
201
202 if (igem) {
203 // GEM
204
205 for (int iupl = 0; iupl < 2; ++iupl) {
206 TString hName12 = hName;
207 TString upl = to_string(iupl);
208 hName12.Insert(ipos - 1, upl);
209 TH2D* hnew = new TH2D(hName12, "", nx, xmin, xmax, ny12, 0, ymax);
210 hnew->SetDirectory(nullptr); // AZ-010926
211 if (cXY == "X")
212 fhLorCorX[ista][iupl] = hnew;
213 else
214 fhLorCorY[ista][iupl] = hnew;
215 int iyb = ny12 + 1, iye = ny;
216 if (iupl) {
217 iyb = 1;
218 iye = ny12;
219 }
220
221 // Fill histo
222 for (int iy = iyb; iy <= iye; ++iy) {
223 for (int ix = 1; ix <= nx; ++ix) {
224 Double_t cont = hist->GetBinContent(ix, iy);
225 int iy1 = (iupl == 0) ? iy - ny12 : ny12 - iy + 1;
226 hnew->SetBinContent(ix, iy1, cont);
227 }
228 }
229 }
230 } else {
231 // Silicon
232 int nsec = 2, nxsi = 0;
233 Double_t rangex = xmax - xmin;
234 if (ista == 0 && VspStationSet)
235 nsec = VspStationSet->GetStation(ista)->GetNModules();
236 else {
237 int ista1 = ista;
238 if (VspStationSet)
239 --ista1;
240 nsec = SilStationSet->GetStation(ista1)->GetNModules();
241 }
242 nxsi = nx / (nsec / 2);
243 rangex = (xmax - xmin) / (nsec / 2);
244 Double_t xend = xmax + rangex; // sectors are counted from positive X
245
246 for (int isec = 0; isec < nsec; ++isec) {
247 TString hName12 = hName;
248 TString sec = to_string(isec);
249 hName12.Insert(ipos, sec);
250 if (isec == nsec / 2)
251 xend = xmax + rangex;
252 xend -= rangex;
253 TH2D* hnew = new TH2D(hName12, "", nxsi, xend - rangex, xend, ny12, 0, ymax);
254 hnew->SetDirectory(nullptr); // AZ-010926
255 auto& hLorCor = (cXY == "X") ? fhLorCorX[ista] : fhLorCorY[ista];
256 hLorCor[isec] = hnew;
257 }
258
259 // Fill histos
260
261 for (int iy = ny; iy > 0; --iy) {
262 int iy1 = (iy > ny12) ? iy - ny12 : ny12 - iy + 1;
263
264 for (int ix = 1; ix <= nx; ++ix) {
265 int isec = (ix - 1) / nxsi;
266 isec = nsec / 2 - isec - 1;
267 if (iy <= ny12)
268 isec += (nsec / 2);
269 int ix1 = (ix - 1) % nxsi + 1;
270 Double_t cont = hist->GetBinContent(ix, iy);
271 TH2D* hnew = (cXY == "X") ? fhLorCorX[ista][isec] : fhLorCorY[ista][isec];
272 hnew->SetBinContent(ix1, iy1, cont);
273 }
274 }
275 } // if (igem)
276 } // while ((key = (TKey*) nextHist()))
277 } // for (int igem = 0; igem < 2;
278 // PLV : begin
279 // the file object is deleted, not only closed
280 delete histFile; // AZ-010926
281 // PLV : end
282
283 /*
284 * End of Lorentz corrections section ---------------------------------------------------------
285 */
286 return kSUCCESS;
287}
288
290{
291 Int_t totalHits{fpStsHitsArray->GetEntriesFast()}, alignedHits{0}, failedHits{0};
292 for (Int_t i = 0; i < totalHits; i++) {
293 CbmStsHit* hit = static_cast<CbmStsHit*>(fpStsHitsArray->At(i));
294
295 // check if detector element of the hit is included in model
296 Int_t hitDetID = hit->GetDetectorID();
297 if (fpDetModel->IgnoreHit(hitDetID))
298 continue;
299
300 // check if detector ID of the hit is valid for the model
301 Int_t modelDetID = fpDetModel->IDfromHit(hitDetID);
302 if (fpDetModel->UnknownID(modelDetID)) {
303 failedHits++;
304 LOG(error) << " <!> BmnAlignerApply::Exec : unknown detector ID " << hitDetID << " ("
305 << fpDetModel->DecodeID(hitDetID) << ")";
306 continue;
307 }
308
309 const SVectGL& align = fCorrections[fpDetModel->Idx(modelDetID)];
310 // keep alignment application code inside BmnMeasureModel
311 // to prevent inconsistency in sign selection and rotation sequence
312 if (fpMeasureModel->AlignHit(*hit, align))
313 alignedHits++;
314 else {
315 failedHits++;
316 LOG(error) << " <!> BmnAlignerApply::Exec : hit alignment skipped due to rotation matrix inversion failure";
317 }
318 // as in BmnToCbmHitConverter: Lorentz corrections with the field on only (AZ-280826)
320 continue;
321
322 /*
323 * Lorentz corrections section-----------------------------------------------------------------
324 *
325 * The code below is taken from BmnToCbmHitConverter::ApplyLorentzCorr(CbmStsHit*).
326 * It implements the Lorentz correction of hit positions and was not revised, except few
327 * lines marked with tag PLV. Commented-out lines and the disabled `if (0)` block of the
328 * original are dropped. Indentation is kept as in the original code.
329 */
330
331 int ista = hit->GetStationNr() - 1;
332 int isec = hit->GetSectorNr() - 1;
333 const Double_t scale = 0.95; // AZ-290826
334
335 if (fieldFlag && hit->GetSystemId() == kGEM) {
336 // Lorentz corrections
337 int iupd = isec / 4;
338 Double_t xh = hit->GetX(), yh = TMath::Abs(hit->GetY()), xh1 = xh, yh1 = yh;
339 TH2D* h2 = fhLorCorX[ista][iupd];
340 if (h2 == nullptr)
341 // PLV : begin
342 // in case of non-initialized h2 we must proceed to the next hit
343 // original code:
344 // return;
345 // modified code:
346 continue;
347 // PLV : end
348 TAxis *ax = h2->GetXaxis(), *ay = h2->GetYaxis();
349 Double_t xmin = ax->GetXmin(), xmax = ax->GetXmax();
350 Double_t ymin = ay->GetXmin(), ymax = ay->GetXmax();
351 if (xh1 >= xmax)
352 xh1 = xmax - 0.1;
353 else if (xh1 < xmin)
354 xh1 = xmin + 0.1;
355 if (yh1 >= ymax)
356 yh1 = ymax - 0.1;
357 else if (yh1 < ymin)
358 yh1 = ymin + 0.1;
359 Double_t dx = h2->Interpolate(xh1, yh1);
360 hit->SetX(xh - dx * scale);
361 h2 = fhLorCorY[ista][iupd];
362 Double_t dy = h2->Interpolate(xh1, yh1);
363 if (iupd)
364 dy = -dy;
365 Double_t ynew = yh - dy * scale;
366 if (iupd)
367 ynew = -ynew;
368 hit->SetY(ynew);
369 } else if (hit->GetSystemId() != kGEM) {
370 TH2D* h2 = fhLorCorX[ista][isec];
371 // PLV : begin
372 // the original has no check here; a missing table must not crash, as in the GEM branch
373 if (h2 == nullptr)
374 continue;
375 // PLV : end
376 Double_t xh = hit->GetX(), yh = TMath::Abs(hit->GetY()), xh1 = xh, yh1 = yh;
377 TAxis *ax = h2->GetXaxis(), *ay = h2->GetYaxis();
378 Double_t xmin = ax->GetXmin(), xmax = ax->GetXmax();
379 Double_t ymin = ay->GetXmin(), ymax = ay->GetXmax();
380 if (xh1 >= xmax)
381 xh1 = xmax - 0.1;
382 else if (xh1 < xmin)
383 xh1 = xmin + 0.1;
384 if (yh1 >= ymax)
385 yh1 = ymax - 0.1;
386 else if (yh1 < ymin)
387 yh1 = ymin + 0.1;
388 Double_t dx = h2->Interpolate(xh1, yh1);
389 hit->SetX(xh - dx * scale);
390 h2 = fhLorCorY[ista][isec];
391 Double_t dy = h2->Interpolate(xh1, yh1);
392 int nsec = fhLorCorY[ista].size();
393 int iupd = isec / (nsec / 2);
394 if (iupd)
395 dy = -dy;
396 Double_t ynew = yh - dy * scale;
397 if (iupd)
398 ynew = -ynew;
399 hit->SetY(ynew);
400 }
401
402 /*
403 * End of Lorentz corrections section ---------------------------------------------------------
404 */
405
406 } // end of loop over hits
407
408 fHitsAligned += alignedHits;
409 fHitsFailed += failedHits;
410 fHitsIgnored += totalHits - alignedHits - failedHits;
411 LOG(info) << "BmnAlignerApply: " << alignedHits << " hits aligned, " << totalHits - alignedHits << " hits ignored";
412 LOG_IF(warning, failedHits) << " <!> BmnAlignerApply: " << failedHits << " hits failed to be aligned";
413}
414
416{
417 LOG(info) << " BmnAlignerApply::Finish : " << fHitsAligned << " hits aligned";
418 LOG(info) << " BmnAlignerApply::Finish : " << fHitsIgnored << " hits ignored";
419 LOG_IF(warning, fHitsFailed) << " <!> BmnAlignerApply::Finish : " << fHitsFailed << " hits failed to be aligned";
420}
RM::SVector< Double_t, BMN_GLOBAL_PARAMS_PD > SVectGL
@ kGEM
int i
Definition P4_F32vec4.h:22
int Int_t
constexpr Bool_t kFALSE
double Double_t
constexpr Bool_t kTRUE
const char Option_t
void Fatal(const char *location, const char *msgfmt,...)
R__EXTERN TSystem * gSystem
static Bool_t ReadSolution(const char *jsonPath, const BmnAlignHierarchy &hierarchy, Solution &solution)
const BmnMeasureModel * fpMeasureModel
std::map< int, TH2D * > fhLorCorX[17]
const char * fAlignFilePath
TClonesArray * fpStsHitsArray
std::map< int, TH2D * > fhLorCorY[17]
virtual void Exec(Option_t *opt)
virtual void Finish()
const BmnDetectorModel * fpDetModel
VecSVectGL_t fCorrections
BmnAlignHierarchy fHierarchy
const Bool_t fLorentzCorrectionApply
virtual InitStatus Init()
InitStatus LorentzCorrectionInit()
virtual ~BmnAlignerApply()
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
Double_t GetXmax() const
Double_t GetXmin() const
T * Get(const char *namecycle)
TList * GetListOfKeys() const override
virtual TList * GetListOfKeys() const
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
virtual void SetDirectory(TDirectory *dir)
virtual Int_t GetNbinsY() const
TAxis * GetXaxis()
virtual Int_t GetNbinsX() const
TAxis * GetYaxis()
void SetBinContent(Int_t bin, Double_t content) override
Double_t Interpolate(Double_t x, Double_t y) const override
virtual Double_t GetBinContent(Int_t bin) const
Bool_t IsFolder() const override
virtual TObject * ReadObj()
const char * GetName() const override
Ssiz_t Length() const
TString & Insert(Ssiz_t pos, const char *s)
Int_t Atoi() const
Ssiz_t First(char c) const
static TString Itoa(Int_t value, Int_t base)
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Double_t Abs(Double_t d)
std::vector< NodeValues > leaves