CbmRoot
Loading...
Searching...
No Matches
CaInitManager.cxx
Go to the documentation of this file.
1/* Copyright (C) 2022 GSI Helmholtzzentrum fuer Schwerionenforschung, Darmstadt
2 SPDX-License-Identifier: GPL-3.0-only
3 Authors: Sergey Gorbunov, Sergei Zharko [committer] */
4
9
10#include "CaInitManager.h"
11
12#include "CaConfigReader.h"
13#include "KfSetupBuilder.h"
14
15#include <boost/archive/binary_iarchive.hpp>
16#include <boost/archive/binary_oarchive.hpp>
17#include <boost/archive/text_iarchive.hpp>
18
19#include <algorithm>
20#include <fstream>
21#include <sstream>
22
23namespace cbm::algo::ca
24{
25 // --------------------------------------------------------------------------------------------------------------------
26 //
27 void InitManager::AddStation(const StationInitializer& inStation) { fvStationInfo.push_back(inStation); }
28
29 // --------------------------------------------------------------------------------------------------------------------
30 //
32 {
35 fbConfigIsRead = false;
37 }
38
39 // --------------------------------------------------------------------------------------------------------------------
40 //
42 {
43 // Clear stations set and a thickness map
44 fvStationInfo.clear();
46
47 // Set number of stations do default values
48 this->ClearStationLayout();
49
50 // Clear field info
51 fParameters.fVertexFieldRegion = kf::FieldRegion<fvec>();
52 fParameters.fVertexFieldValue = kf::FieldValue<fvec>();
54
55 // Clear target position
56 fParameters.fTargetPos.fill(Undef<float>);
57 fTargetZ = 0.;
59
60 // Clear field function
61 fFieldFunction = FieldFunction_t([](const double(&)[3], double(&)[3]) {});
63
64 // Clear other flags
65 fParameters.fRandomSeed = 1;
66 fParameters.fGhostSuppression = 0;
69
70 fParameters.fMisalignmentX.fill(0.);
71 fParameters.fMisalignmentY.fill(0.);
72 fParameters.fMisalignmentT.fill(0.);
73
74 fParameters.fDevIsIgnoreHitSearchAreas = false;
75 fParameters.fDevIsUseOfOriginalField = false;
76 fParameters.fDevIsMatchDoubletsViaMc = false;
77 fParameters.fDevIsMatchTripletsViaMc = false;
78 fParameters.fDevIsExtendTracksViaMc = false;
79 fParameters.fDevIsSuppressOverlapHitsViaMc = false;
80 fParameters.fDevIsParSearchWUsed = false;
81 }
82
83 // --------------------------------------------------------------------------------------------------------------------
84 //
92
93 // --------------------------------------------------------------------------------------------------------------------
94 // NOTE: this function should be called once in the SendParameters
96 {
97 // Read configuration files
98 this->ReadInputConfigs();
99 if (!fbConfigIsRead) { // Check config reading status
100 return false;
101 }
102
103 if (!fParameters.fDevIsParSearchWUsed) {
105 }
106
107 // Apply magnetic field to the station info objects
108 std::for_each(fvStationInfo.begin(), fvStationInfo.end(), [&](auto& st) { st.SetFieldFunction(fFieldFunction); });
109
110 // Check initialization
111 this->CheckInit();
112
114 LOG(error) << "ca::InitManager: Attempt to form parameters container before all necessary fields were initialized"
116 return false;
117 }
118
119 { // Form array of stations
120 auto destIt = fParameters.fStations.begin();
121 for (const auto& station : fvStationInfo) {
122 if (!station.GetTrackingStatus()) {
123 continue;
124 }
125 *destIt = station.GetStation();
126 ++destIt;
127 }
128 }
129
130 // Check the consistency of the parameters object. If object inconsistent, it throws std::logic_error
131 try {
132 fParameters.CheckConsistency();
133 }
134 catch (const std::logic_error& err) {
135 LOG(error) << "ca::InitManager: parameters container consistency check failed. Reason: " << err.what();
136 return false;
137 }
138
139 return true;
140 }
141
142 // --------------------------------------------------------------------------------------------------------------------
143 //
145 {
147 std::stringstream msg;
148 msg << "ca::InitManager: number of active stations cannot be accessed until the station layout is initialized";
149 throw std::runtime_error(msg.str());
150 }
151 return fParameters.GetNstationsActive();
152 }
153
154 // --------------------------------------------------------------------------------------------------------------------
155 //
157 {
159 std::stringstream msg;
160 msg << "ca::InitManager: number of active stations cannot be accessed until the station layout is initialized";
161 throw std::runtime_error(msg.str());
162 }
163 return fParameters.GetNstationsActive(detectorID);
164 }
165
166 // --------------------------------------------------------------------------------------------------------------------
167 //
169 {
171 std::stringstream msg;
172 msg << "ca::InitManager: number of geometry stations cannot be accessed until the station layout is initialized";
173 throw std::runtime_error(msg.str());
174 }
175 return fParameters.GetNstationsGeometry();
176 }
177
178 // --------------------------------------------------------------------------------------------------------------------
179 //
181 {
183 std::stringstream msg;
184 msg << "ca::InitManager: number of geometry stations cannot be accessed until the station layout is initialized";
185 throw std::runtime_error(msg.str());
186 }
187 return fParameters.GetNstationsGeometry(detectorID);
188 }
189
190 // --------------------------------------------------------------------------------------------------------------------
191 //
192 std::vector<StationInitializer>& InitManager::GetStationInfo()
193 {
195 std::stringstream msg;
196 msg << "ca::InitManager: station info container cannot be accessed until the station layout is initialized";
197 throw std::runtime_error(msg.str());
198 }
199 return fvStationInfo;
200 }
201
202
203 // --------------------------------------------------------------------------------------------------------------------
204 //
206 {
207 LOG(info) << "ca::InitManager::InitStationLayout(): ....";
208 this->ClearStationLayout();
209 std::sort(fvStationInfo.begin(), fvStationInfo.end());
210
211 for (const auto& aStation : fvStationInfo) {
212 ++fParameters.fvFirstGeoId[static_cast<int>(aStation.GetDetectorID()) + 1];
213 }
214 for (int iDet = 1; iDet < static_cast<int>(fParameters.fvFirstGeoId.size()) - 1; ++iDet) {
215 fParameters.fvFirstGeoId[iDet + 1] += fParameters.fvFirstGeoId[iDet];
216 }
217
218 fParameters.fNstationsActiveTotal = 0;
219 for (int iStGeo = 0; iStGeo < static_cast<int>(fvStationInfo.size()); ++iStGeo) {
220 const auto& aStation = fvStationInfo[iStGeo];
221 int iDet = static_cast<int>(aStation.GetDetectorID());
222 int iStLocal = aStation.GetStationID();
223 // Fill local -> geo map
224 fParameters.fvGeoToLocalIdMap[iStGeo] = std::make_pair(aStation.GetDetectorID(), iStLocal);
225 // Fill geo -> local map
226 fParameters.fvLocalToGeoIdMap[fParameters.fvFirstGeoId[iDet] + iStLocal] = iStGeo;
227 // Fill geo <-> active map
228 int iStActive = aStation.GetTrackingStatus() ? fParameters.fNstationsActiveTotal++ : -1;
229 fParameters.fvGeoToActiveMap[iStGeo] = iStActive;
230 if (iStActive > -1) {
231 fParameters.fvActiveToGeoMap[iStActive] = iStGeo;
232 }
233 }
235
236 for (auto& aStation : fvStationInfo) {
237 aStation.SetGeoLayerID(fParameters.GetStationIndexGeometry(aStation.GetStationID(), aStation.GetDetectorID()));
238 }
239 }
240
241 // --------------------------------------------------------------------------------------------------------------------
242 //
244 {
246 LOG(warn) << "ca::InitManager::InitTargetField: attempt to reinitialize the field value and field region "
247 << "near target. Ignore";
248 return;
249 }
250
251 // Check for field function
253 std::stringstream msg;
254 msg << "Attempt to initialize the field value and field region near target before initializing field function";
255 throw std::runtime_error(msg.str());
256 }
257 // Check for target defined
259 std::stringstream msg;
260 msg << "Attempt to initialize the field value and field region near target before the target position"
261 << "initialization";
262 throw std::runtime_error(msg.str());
263 }
264 constexpr int nDimensions{3};
265 constexpr int nPointsNodal{3};
266
267 std::array<double, nPointsNodal> inputNodalZ{fTargetZ, fTargetZ + zStep, fTargetZ + 2. * zStep};
268 std::array<kf::FieldValue<fvec>, nPointsNodal> B{};
269 std::array<fvec, nPointsNodal> z{};
270 // loop over nodal points
271 for (int idx = 0; idx < nPointsNodal; ++idx) {
272 double point[nDimensions]{0., 0., inputNodalZ[idx]};
273 double field[nDimensions]{};
274 fFieldFunction(point, field);
275 z[idx] = inputNodalZ[idx];
276 B[idx].Set(field[0], field[1], field[2]);
277 } // loop over nodal points: end
278 fParameters.fVertexFieldRegion.Set(B[0], z[0], B[1], z[1], B[2], z[2]);
279 fParameters.fVertexFieldValue = B[0];
280
282 }
283
284 // --------------------------------------------------------------------------------------------------------------------
285 //
287 {
288 // TODO: probably some checks must be inserted here (S.Zharko)
290 std::stringstream msg;
291 msg << "Attempt to push back a CA track finder iteration before the number of iterations was defined";
292 throw std::runtime_error(msg.str());
293 }
294 fParameters.fCAIterations.push_back(iteration);
295 }
296
297 // -------------------------------------------------------------------------------------------------------------------
298 //
300 {
301 if (!fbConfigIsRead) {
302 LOG(info) << "ca::InitManager: reading parameter configuration ...";
303 try {
304 auto configReader = ConfigReader(this, 4);
305 configReader.SetMainConfigPath(fsConfigInputMain);
306 configReader.SetUserConfigPath(fsConfigInputUser);
307 configReader.SetGeometryLock(fbGeometryConfigLock);
308 configReader.Read();
309 fbConfigIsRead = true;
310 LOG(info) << "ca::InitManager: reading parameter configuration ... \033[1;32mdone\033[0m";
311 }
312 catch (const std::runtime_error& err) {
313 LOG(error) << "ca::InitManager: reading parameter configuration ... \033[1;31mfail\033[0m. Reason: "
314 << err.what();
315 }
316 }
317 }
318
319 // -------------------------------------------------------------------------------------------------------------------
320 //
321 void InitManager::ReadGeometrySetup(const std::string& fileName)
322 {
323 // Open input binary file
325 }
326
327 // -------------------------------------------------------------------------------------------------------------------
328 //
329 void InitManager::ReadParametersObject(const std::string& fileName)
330 {
331 using namespace constants;
332 // clrs::CL - end colored log
333 // clrs::GNb - bold green log
334 // clrs::RDb - bold red log
335
336 // Open input binary file
337 std::ifstream ifs(fileName, std::ios::binary);
338 if (!ifs) {
339 std::stringstream msg;
340 msg << "ca::InitManager: parameters data file \"" << clrs::GNb << fileName << clrs::CL << "\" was not found";
341 throw std::runtime_error(msg.str());
342 }
343
344 // Get L1InputData object
345 try {
346 boost::archive::binary_iarchive ia(ifs);
347 ia >> fParameters;
349 }
350 catch (const std::exception&) {
351 std::stringstream msg;
352 msg << "ca::InitManager: parameters file \"" << clrs::GNb << fileName << clrs::CL
353 << "\" has incorrect data format or was corrupted";
354 throw std::runtime_error(msg.str());
355 }
356
360 }
361
362 // -------------------------------------------------------------------------------------------------------------------
363 //
364 void InitManager::ReadSearchWindows(const std::string& fileName)
365 {
366 // Open input binary file
367 std::ifstream ifs(fileName);
368 if (!ifs) {
369 std::stringstream msg;
370 msg << "ca::InitManager: search window file \"" << fileName << "\" was not found";
371 throw std::runtime_error(msg.str());
372 }
373
374 try {
375 boost::archive::text_iarchive ia(ifs);
376 int nPars = -1;
377 int nWindows = -1;
378 ia >> nPars;
379 assert(nPars == 1); // Currently only the constant windows are available
380 ia >> nWindows;
381 std::stringstream errMsg;
382 for (int iW = 0; iW < nWindows; ++iW) {
383 SearchWindow swBuffer;
384 ia >> swBuffer;
385 int iStationID = swBuffer.GetStationID();
386 int iTrackGrID = swBuffer.GetTrackGroupID();
387 if (iStationID < 0 || iStationID > constants::size::MaxNstations) {
388 errMsg << "\t- wrong station id for entry " << iW << ": " << iStationID << " (should be between 0 and "
390 }
391 if (iTrackGrID < 0 || iTrackGrID > constants::size::MaxNtrackGroups) {
392 errMsg << "\t- wrong track group id for entry " << iW << ": " << iTrackGrID << " (should be between 0 and "
394 }
395 fParameters.fSearchWindows[iTrackGrID * constants::size::MaxNstations + iStationID] = swBuffer;
396 }
397 if (errMsg.str().size()) {
398 std::stringstream msg;
399 msg << "ca::InitManager: some errors occurred while reading search windows: " << errMsg.str();
400 throw std::runtime_error(msg.str());
401 }
402 }
403 catch (const std::exception& err) {
404 std::stringstream msg;
405 msg << "search windows file \"" << fileName << "\" has incorrect data format or was corrupted. ";
406 msg << "Exception catched: " << err.what();
407 throw std::runtime_error(msg.str());
408 }
409
411 }
412
413 // --------------------------------------------------------------------------------------------------------------------
414 //
416 {
417 fCAIterationsNumberCrosscheck = nIterations;
418 auto& iterationsContainer = fParameters.fCAIterations;
419
420 // NOTE: should be called to prevent multiple copies of objects between the memory reallocations
421 iterationsContainer.reserve(nIterations);
423 }
424
425 // --------------------------------------------------------------------------------------------------------------------
426 //
428 {
430 fFieldFunction = fieldFunction;
432 }
433 else {
434 LOG(warn) << "ca::InitManager::SetFieldFunction: attempt to reinitialize the field function. Ignored";
435 }
436 }
437
438 // --------------------------------------------------------------------------------------------------------------------
439 //
440 void InitManager::SetGhostSuppression(int ghostSuppression)
441 {
443 LOG(warn)
444 << "ca::InitManager::SetGhostSuppression: attempt of reinitializating the ghost suppresion flag. Ignore";
445 return;
446 }
447 fParameters.fGhostSuppression = ghostSuppression;
449 }
450
451 // --------------------------------------------------------------------------------------------------------------------
452 //
453 void InitManager::SetRandomSeed(unsigned int seed)
454 {
456 LOG(warn) << "ca::InitManager::SetRandomSeed: attempt of reinitializating the random seed. Ignore";
457 return;
458 }
459 fParameters.fRandomSeed = seed;
461 }
462
463 // --------------------------------------------------------------------------------------------------------------------
464 //
465 void InitManager::SetTargetPosition(double x, double y, double z)
466 {
468 LOG(warn) << "ca::InitManager::SetTargetPosition: attempt to reinitialize the target position. Ignore";
469 return;
470 }
471
473 fParameters.fTargetPos[0] = x;
474 fParameters.fTargetPos[1] = y;
475 fParameters.fTargetPos[2] = z;
477 fTargetZ = z;
479 }
480
481 // --------------------------------------------------------------------------------------------------------------------
482 //
484
485 // --------------------------------------------------------------------------------------------------------------------
486 //
487 void InitManager::WriteParametersObject(const std::string& fileName) const
488 {
491 // Open output binary file
492 std::ofstream ofs(fileName, std::ios::binary);
493 if (!ofs) {
494 std::stringstream msg;
495 msg << "ca::InitManager: failed opening file \"" << GNb << fileName << CL << "\" to write parameters object";
496 throw std::runtime_error(msg.str());
497 }
498
499 LOG(info) << "ca::InitManager: writing CA parameters object to file \"" << GNb << fileName << '\"' << CL;
500
501 // Serialize L1Parameters object and write
502 boost::archive::binary_oarchive oa(ofs);
503 oa << fParameters;
504 }
505
506 // --------------------------------------------------------------------------------------------------------------------
507 //
509 {
510 bool ifInitPassed = true;
512 int nIterationsActual = fParameters.fCAIterations.size();
513 int nIterationsExpected = fCAIterationsNumberCrosscheck;
514 if (nIterationsActual != nIterationsExpected) {
515 LOG(warn) << "ca::InitManager::CheckCAIterations: incorrect number of iterations registered: "
516 << nIterationsActual << " of " << nIterationsExpected << " expected";
517 ifInitPassed = false;
518 }
519 }
521 }
522
523 // --------------------------------------------------------------------------------------------------------------------
524 // TODO: REWRITE! and add const qualifier (S.Zharko)
526 {
527 bool ifInitPassed = true;
529 // (1) Check the stations themselves
530 bool bStationsFinalized = std::all_of(fvStationInfo.begin(), fvStationInfo.end(),
531 [](const auto& st) { return st.GetInitController().IsFinalized(); });
532 if (!bStationsFinalized) {
533 std::stringstream msg;
534 msg << "ca::InitManager: At least one of the StationInitializer objects is not finalized";
535 }
536
537 // (2) Check for maximum allowed number of stations
538 if (fParameters.GetNstationsGeometry() > constants::size::MaxNstations) {
539 std::stringstream msg;
540 msg << "Actual total number of registered stations in geometry (" << fParameters.GetNstationsGeometry()
541 << ") is larger then possible (" << constants::size::MaxNstations
542 << "). Please, select another set of active tracking detectors or recompile the code with enlarged"
543 << " constants::size::MaxNstations value";
544 throw std::runtime_error(msg.str());
545 }
546 }
548 }
549
550 // -------------------------------------------------------------------------------------------------------------------
551 //
553 {
554 fParameters.fvFirstGeoId.fill(0);
555 fParameters.fvLocalToGeoIdMap.fill(0);
556 fParameters.fvGeoToLocalIdMap.fill(std::make_pair(static_cast<EDetectorID>(0), -1));
557 fParameters.fvGeoToActiveMap.fill(-1); // Note: by default all the stations are inactive
558 fParameters.fvActiveToGeoMap.fill(0);
559 fParameters.fNstationsActiveTotal = -1;
561 }
562} // namespace cbm::algo::ca
Configuration parameter file reader for the CA tracking algorithm (header)
Input data management class for the CA tracking algorithm (header)
A base KF-Setup initialization class (source)
A reader for the CA parameters from the YAML configuration files.
std::vector< StationInitializer > & GetStationInfo()
Gets a reference to the stations array.
void SetTargetPosition(double x, double y, double z)
Sets target position.
void ClearStationLayout()
Returns station layout into undefined condition.
void SetFieldFunction(const FieldFunction_t &fieldFcn)
Sets a magnetic field function, which will be applied for all the stations.
InitController_t fInitController
Initialization flags.
void ReadSearchWindows(const std::string &fileName)
Reads search windows from file.
void InitTargetField(double zStep)
Calculates kf::FieldValue and L1FieldReference values for a selected step in z-axis from the target p...
Parameters< fvec > fParameters
CA parameters object.
int fCAIterationsNumberCrosscheck
Number of iterations to be passed (must be used for cross-checks)
bool fbConfigIsRead
Flag, if configuration file was read.
void SetCAIterationsNumberCrosscheck(int nIterations)
Sets a number of CA track finder iterations to provide initialization cross-check.
void ReadGeometrySetup(const std::string &fileName)
Reads geometry setup from file.
int GetNstationsGeometry() const
Gets total number of stations, provided by setup geometry.
void ClearCAIterations()
Clears vector of CA track finder iterations.
void InitStationLayout()
Initializes station layout.
Parameters< fvec > && TakeParameters()
Takes parameters object from the init-manager instance.
bool fbGeometryConfigLock
Lock geometry initialization.
void SetGeometrySetup(const cbm::algo::kf::Setup< DataT > &setup)
Sets setup.
void ReadParametersObject(const std::string &fileName)
Reads parameters object from boost-serialized binary file.
std::function< void(const double(&xyz)[3], double(&B)[3])> FieldFunction_t
void SetGhostSuppression(int ghostSuppression)
Sets the flag to enable/disable the ghost suppression routine.
void CheckCAIterationsInit()
Checker for Iteration container initialization (sets EInitKey::kCAIterations)
void ClearSetupInfo()
Clears vector of base setup.
void WriteParametersObject(const std::string &fileName) const
Writes parameters object from boost-serialized binary file.
double fTargetZ
Target position z component in double precision.
void SetRandomSeed(unsigned int seed)
Sets pseudo-random numbers generator seed.
std::string fsConfigInputMain
name for the input configuration file
void ReadInputConfigs()
Reads main and user parameters configs.
FieldFunction_t fFieldFunction
A function which returns magnetic field vector B in a radius-vector xyz.
int GetNstationsActive() const
Gets total number of active stations.
void PushBackCAIteration(const Iteration &iteration)
Pushes an CA track finder iteration into a sequence of iteration using reference.
std::vector< StationInitializer > fvStationInfo
Vector of StationInitializer objects (active + inactive)
void AddStation(const StationInitializer &station)
Adds a tracking station to the geometry.
void CheckInit()
Provides final checks of the parameters object.
@ kSearchWindows
6) If the hit search windows were initialized
@ kFieldFunction
0) If magnetic field getter function is set
@ kTargetPos
1) If target position was defined
@ kCAIterationsNumberCrosscheck
4) If the number of CA track finder is initialized
@ kStationLayoutInitialized
9) If stations layout is initialized
@ kRandomSeed
8) If the random seed is provided
@ kStationsInfo
3) If all the planned stations were added to the manager
@ kPrimaryVertexField
2) If magnetic field value and region defined at primary vertex
@ kCAIterations
5) If the CA track finder iterations were initialized
bool FormParametersContainer()
Forms parameters container.
void CheckStationsInfoInit()
Checker for StationInitializer set initialization (sets EInitKey::kStationsInfo)
std::string fsConfigInputUser
name for the input configuration file
A set of parameters for the CA Track finder iteration.
bool GetFlag(InitKeyEnum bitKey) const
void SetFlag(InitKeyEnum bitKey, bool newStatus=true)
bool IsFinalized() const
Checks, if the object is finalized, i.e. all its fields were set up.
std::string ToString(int indentLevel=0) const
A container for all external parameters of the CA tracking algorithm.
Class L1SearchWindow defines a parameterisation of hits search window for CA tracking algorithm TODO:...
int GetStationID() const
Gets station id.
int GetTrackGroupID() const
Gets track group id.
A base class which provides interface to L1Algo station geometry.
Magnetic field region, corresponding to a hit triplet.
Magnetic flux density vector.
static Setup< T > Load(const std::string &fileName)
Loads a serialized setup from a file.
constexpr char GNb[]
bold green
Definition CaDefs.h:155
constexpr char CL[]
clear
Definition CaDefs.h:132
constexpr int MaxNstations
Max number of stations, 2^6 = 64.
Definition CaDefs.h:44
constexpr int MaxNtrackGroups
Definition CaDefs.h:51
TODO: SZh 8.11.2022: add selection of parameterisation.
Definition CaBranch.h:14
EDetectorID
Enumeration for the tracking detector subsystems in CBM-CA.
Definition CbmDefs.h:176