CbmRoot
Loading...
Searching...
No Matches
TrackingChain.cxx
Go to the documentation of this file.
1/* Copyright (C) 2023-2024 GSI Helmholtzzentrum fuer Schwerionenforschung, Darmstadt
2 SPDX-License-Identifier: GPL-3.0-only
3 Authors: Sergei Zharko [committer] */
4
9
10#include "TrackingChain.h"
11
12#include "CaDefs.h"
13#include "CaHit.h"
14#include "CaInitManager.h"
15#include "CaParameters.h"
16#include "ParFiles.h"
17#include "compat/OpenMP.h"
18#include "yaml/Yaml.h"
19
20#include <boost/archive/binary_oarchive.hpp>
21
22#include <fstream>
23#include <set>
24#include <unordered_map>
25
26#include <fmt/format.h>
27#include <xpu/host.h>
28
37using cbm::algo::ca::constants::clrs::CL; // clear text
38using cbm::algo::ca::constants::clrs::GNb; // grin bald text
39
40// ---------------------------------------------------------------------------------------------------------------------
41//
42TrackingChain::TrackingChain(std::shared_ptr<cbm::algo::HistogramSender> histoSender) : fQa(Qa(histoSender)) {}
43
44// ---------------------------------------------------------------------------------------------------------------------
45//
47{
48 if (fpSetup.get() == nullptr) {
49 throw std::runtime_error("Tracking Chain: TrackingSetup object was not registered");
50 }
51
52
53 // ------ Read tracking chain parameters from the config
54 ParFiles parFiles(Opts().RunId());
56
57 // ------ Read parameters from binary
58 auto geomCfgFile = (Opts().ParamsDir() / fConfig.fsGeomConfig).string();
59 auto setupCfgFile = (Opts().ParamsDir() / fConfig.fsSetupFilename).string();
60 auto mainCfgFile = (Opts().ParamsDir() / fConfig.fsMainConfig).string();
61 auto userCfgFile = fConfig.fsUserConfig;
62
63 L_(info) << "Tracking Chain: reading geometry from CA parameters file " << GNb << geomCfgFile << CL << '\n';
64 L_(info) << "Tracking Chain: reading geometry setup file " << GNb << setupCfgFile << CL << '\n';
65 L_(info) << "Tracking Chain: reading parameters from CA main config " << GNb << mainCfgFile << CL << '\n';
66 auto manager = InitManager{};
68 manager.SetConfigMain(mainCfgFile);
69 if (!userCfgFile.empty()) {
70 L_(info) << "Tracking Chain: applying user configuration from " << GNb << userCfgFile << CL << '\n';
71 manager.SetConfigUser(userCfgFile);
72 }
73 manager.ReadParametersObject(geomCfgFile); // geometry setup
74 manager.ReadInputConfigs();
75 manager.ReadGeometrySetup(setupCfgFile);
76 auto parameters = manager.TakeParameters();
77 L_(info) << "Tracking Chain: parameters object: \n" << parameters.ToString(1) << '\n';
78
79 // ------ Used detector subsystem flags
80 fbDetUsed.fill(false);
81 fbDetUsed[EDetectorID::kSts] = Opts().Has(fles::Subsystem::STS) && parameters.IsActive(EDetectorID::kSts);
82 fbDetUsed[EDetectorID::kTof] = Opts().Has(fles::Subsystem::TOF) && parameters.IsActive(EDetectorID::kTof);
83 fbDetUsed[EDetectorID::kTrd] = Opts().Has(fles::Subsystem::TRD) && parameters.IsActive(EDetectorID::kTrd);
84
85 // ------ Initialize CA framework
87 fCaFramework.SetNofThreads(Opts().NumOMPThreads() == std::nullopt ? openmp::GetMaxThreads()
88 : *(Opts().NumOMPThreads()));
89 fCaFramework.ReceiveParameters(std::move(parameters));
91
92 // ------ Initialize QA modules
93 if (fQa.IsSenderDefined()) {
95 fQa.Init();
96 }
97}
98
99// ---------------------------------------------------------------------------------------------------------------------
100//
102{
103 xpu::scoped_timer t_("CA"); // TODO: pass timings to monitoring for throughput?
106
107 // ----- Init input data ---------------------------------------------------------------------------------------------
109 this->PrepareInput(recoResults);
111
112 // ----- Run reconstruction ------------------------------------------------------------------------------------------
116
117 // ----- Init output data --------------------------------------------------------------------------------------------
118 return PrepareOutput();
119}
120
121// ---------------------------------------------------------------------------------------------------------------------
122//
124{
125 L_(info) << fCaMonitor.ToString();
127 auto fileName = "./" + fConfig.fsMoniOutName;
128 std::ofstream ofs(fileName);
129 boost::archive::binary_oarchive oa(ofs);
130 oa << fCaMonitor;
131 }
132}
133
134// ---------------------------------------------------------------------------------------------------------------------
135//
137{
138 fNofHitKeys = 0;
139 int nHitsTot = recoResults.stsHits.NElements() + recoResults.tofHits.NElements() + recoResults.trdHits.NElements();
140 L_(debug) << "Tracking chain: input has " << nHitsTot << " hits";
142 faHitExternalIndices.clear();
144 if (fbDetUsed[EDetectorID::kSts]) {
146 }
147 if (fbDetUsed[EDetectorID::kTrd]) {
149 }
150 if (fbDetUsed[EDetectorID::kTof]) {
152 }
153 faHitExternalIndices.shrink_to_fit();
155 L_(debug) << "Tracking chain: " << fCaDataManager.GetNofHits() << " hits will be passed to the ca::Framework";
157}
158
159// ---------------------------------------------------------------------------------------------------------------------
160//
162{
163 Output_t output;
164 output.tracks = std::move(fCaFramework.fRecoTracks);
165 int nTracks = output.tracks.size();
166
167 output.stsHitIndices.reset(nTracks);
168 output.tofHitIndices.reset(nTracks);
169 output.trdHitIndices.reset(nTracks);
170
171 int trackFirstHit = 0;
172 for (int iTrk = 0; iTrk < nTracks; ++iTrk) {
173 output.stsHitIndices[iTrk].clear();
174 output.tofHitIndices[iTrk].clear();
175 output.trdHitIndices[iTrk].clear();
176 int nHits = output.tracks[iTrk].fNofHits;
177 for (int iHit = 0; iHit < nHits; ++iHit) {
178 int iHitInternal = fCaFramework.GetInputData().GetHit(fCaFramework.fRecoHits[trackFirstHit + iHit]).Id();
179 const auto [detID, iPartition, iPartHit] = faHitExternalIndices[iHitInternal];
180 switch (detID) {
181 case ca::EDetectorID::kSts: output.stsHitIndices[iTrk].push_back(std::make_pair(iPartition, iPartHit)); break;
182 case ca::EDetectorID::kTof: output.tofHitIndices[iTrk].push_back(std::make_pair(iPartition, iPartHit)); break;
183 case ca::EDetectorID::kTrd: output.trdHitIndices[iTrk].push_back(std::make_pair(iPartition, iPartHit)); break;
184 default: break;
185 }
186 }
190
191 trackFirstHit += nHits;
192 }
193
194 L_(info) << "TrackingChain: Timeslice contains " << fCaMonitorData.GetCounterValue(ca::ECounter::RecoTrack)
195 << " tracks, with " << fCaMonitorData.GetCounterValue(ca::ECounter::RecoStsHit) << " sts hits, "
198 << "; the FindTracks routine ran " << fCaMonitorData.GetTimer(ca::ETimer::FindTracks).GetTotal() << " s";
199
200
201 // QA
202 if (fQa.IsSenderDefined()) {
205 fQa.RegisterTracks(&output.tracks);
207 fQa.Exec();
209 }
210
212
213 if constexpr (kDEBUG) { // Monitor data per TS
216 auto fileName = fmt::format("./ca_monitor_nth_{}_ts{}.dat", fCaFramework.GetNofThreads(), tsIndex);
217 std::ofstream ofs(fileName);
218 boost::archive::binary_oarchive oa(ofs);
219 ca::TrackingMonitor monitorPerTS;
220 monitorPerTS.AddMonitorData(fCaMonitorData);
221 oa << monitorPerTS;
222 }
223 }
224
227
228 return output;
229}
230
231// ---------------------------------------------------------------------------------------------------------------------
232//
233template<EDetectorID DetID>
235{
236 int nSt = fCaFramework.GetParameters().GetNstationsActive();
237
238 using Hit_t = ca::HitTypes_t::at<DetID>;
239 constexpr bool IsMvd = (DetID == EDetectorID::kMvd);
240 constexpr bool IsSts = (DetID == EDetectorID::kSts);
241 constexpr bool IsMuch = (DetID == EDetectorID::kMuch);
242 constexpr bool IsTrd = (DetID == EDetectorID::kTrd);
243 constexpr bool IsTof = (DetID == EDetectorID::kTof);
244
245 xpu::t_add_bytes(hits.NElements() * sizeof(Hit_t)); // Assumes call from Run, for existence of timer!
246
247 int64_t dataStreamDet = static_cast<int64_t>(DetID) << 60; // detector part of the data stream
248 int64_t dataStream = 0;
249 for (size_t iPartition = 0; iPartition < hits.NPartitions(); ++iPartition, ++dataStream) {
250 const auto& [vHits, extHitAddress] = hits.Partition(iPartition);
251 // ---- Define data stream and station index
252 //int64_t dataStream = dataStreamDet | extHitAddress;
253 int iStLocal = fpSetup->GetTrackingStation<ca::ToFlesSubsystem<DetID>()>(extHitAddress);
254 if (iStLocal < 0) {
255 continue; // Station is not used for tracking (e.g. TOF SMtype 5)
256 }
257
258 int iStActive = fCaFramework.GetParameters().GetStationIndexActive(iStLocal, DetID);
259
260 //size_t iOffset = hits.Offsets()[iPartition];
261 if (iStActive < 0) {
262 continue; // legit
263 }
264 if (iStActive >= nSt) {
265 L_(error) << "TrackingChain: found hit with wrong active station index above the upper limit: " << iStActive
266 << ", detector: " << ca::kDetName[DetID];
267 continue;
268 }
269 double lastTime = -1e9;
270 //double prevTime = -1;
271 ca::HitKeyIndex_t firstHitKey = fNofHitKeys;
272 for (size_t iPartHit = 0; iPartHit < vHits.size(); ++iPartHit) {
273 const auto& hit = vHits[iPartHit];
274
275 //if constexpr (IsTrd) {
276 // switch (extHitAddress) {
277 // case 0x5:
278 // if (!(fabs(hit.Z() - 116.77) < 10)) {
279 // L_(info) << "DBG! " << extHitAddress << ' ' << hit.Z();
280 // }
281 // break;
282 // case 0x15:
283 // if (!(fabs(hit.Z() - 163.8) < 10)) {
284 // L_(info) << "DBG! " << extHitAddress << ' ' << hit.Z();
285 // }
286 // break;
287 // case 0x25:
288 // if (!(fabs(hit.Z() - 190.8) < 10)) {
289 // L_(info) << "DBG! " << extHitAddress << ' ' << hit.Z();
290 // }
291 // break;
292 // }
293 //}
294
295
296 //int iHitExt = iOffset + iPartHit;
297 // ---- Fill ca::Hit
298 ca::Hit caHit;
299 if constexpr (IsSts) {
300 caHit.SetFrontKey(firstHitKey + hit.fFrontClusterId);
301 caHit.SetBackKey(firstHitKey + hit.fBackClusterId);
302 //L_(info) << ", hit=" << iHitExt << ", f=" << hit.fFrontClusterId << ", b=" << hit.fBackClusterId;
303 }
304 else {
305 caHit.SetFrontKey(firstHitKey + iPartHit);
306 caHit.SetBackKey(caHit.FrontKey());
307 }
308 caHit.SetX(hit.X());
309 caHit.SetY(hit.Y());
310 caHit.SetZ(hit.Z());
311 caHit.SetT(hit.Time());
312 caHit.SetDx2(hit.Dx() * hit.Dx() + fCaFramework.GetParameters().GetMisalignmentXsq(DetID));
313 caHit.SetDy2(hit.Dy() * hit.Dy() + fCaFramework.GetParameters().GetMisalignmentYsq(DetID));
314 if constexpr (IsSts) caHit.SetDxy(hit.fDxy);
315 caHit.SetDt2(hit.TimeError() * hit.TimeError() + fCaFramework.GetParameters().GetMisalignmentTsq(DetID));
317 //out << iStLocal << " " << extHitAddress << " " << hit.Z() << '\n';
318 caHit.SetRangeX(3.5 * hit.Dx());
319 caHit.SetRangeY(3.5 * hit.Dy());
320 caHit.SetRangeT(3.5 * hit.TimeError());
321 if constexpr (IsTrd) {
322 if (iStLocal == 0) {
323 caHit.SetRangeX(1.7);
324 caHit.SetRangeY(3.5);
325 caHit.SetRangeT(200.);
326 }
327 else if (iStLocal == 1) {
328 caHit.SetRangeY(sqrt(3.) * hit.Dy());
329 }
330 else {
331 caHit.SetRangeX(sqrt(3.) * hit.Dx());
332 }
333 }
334 caHit.SetStation(iStActive);
336 if (caHit.Check()) {
337 if ((caHit.T() < lastTime - 1000.) && (dataStream < 100000)) {
338 dataStream++;
339 }
340 lastTime = caHit.T();
341 fCaDataManager.PushBackHit(caHit, dataStreamDet | dataStream);
342 faHitExternalIndices.push_back(std::make_tuple(DetID, iPartition, iPartHit));
343 if (fNofHitKeys <= caHit.FrontKey()) {
344 fNofHitKeys = caHit.FrontKey() + 1;
345 }
346 if (fNofHitKeys <= caHit.BackKey()) {
347 fNofHitKeys = caHit.BackKey() + 1;
348 }
349 }
350 else {
351 if constexpr (IsMvd) {
353 }
354 if constexpr (IsSts) {
356 }
357 if constexpr (IsMuch) {
359 }
360 if constexpr (IsTrd) {
362 }
363 if constexpr (IsTof) {
365 }
366 }
367 //prevTime = caHit.T();
368 // ---- Update number of hit keys
369 } // iPartHit
370 } // iPartition
371}
#define L_(level)
Compile-time constants definition for the CA tracking algorithm.
A generic hit for the CA tracker (header)
Input data management class for the CA tracking algorithm (header)
static vector< vector< QAHit > > hits
friend fvec sqrt(const fvec &a)
This file contains the definition of the ParFiles class.
A chain class to execute CA tracking algorithm in online reconstruction (header)
fs::path ParamsDir() const
bool Has(fles::Subsystem detector) const
const Options & Opts() const
Definition SubChain.h:20
A chain for tracking algorithm.
Output_t Run(Input_t recoResults)
Provides action for a given time-slice.
std::shared_ptr< TrackingSetup > fpSetup
setup interface
ca::Framework fCaFramework
CA framework instance.
void ReadHits(PartitionedSpan< const ca::HitTypes_t::at< DetID > > hits)
Reads from different detector subsystems.
Output_t PrepareOutput()
Prepares output data.
ca::TrackingMonitorData fCaMonitorData
CA monitor data object.
ca::Qa fQa
CA QA builder.
void PrepareInput(Input_t recoResults)
Prepares input data.
void Init()
Provides action in the initialization of the run.
ca::DataManager fCaDataManager
CA data manager.
TrackingChain(std::shared_ptr< HistogramSender > histoSender=nullptr)
Constructor from parameters.
ca::Vector< std::tuple< ca::EDetectorID, uint32_t, uint32_t > > faHitExternalIndices
External indices of used hits.
TrackingChainConfig fConfig
Tracking config.
static constexpr bool kDEBUG
Debug mode.
ca::HitKeyIndex_t fNofHitKeys
Current number of hit keys (aux)
ca::TrackingMonitor fCaMonitor
CA internal monitor (debug purposes)
void Finalize()
Provides action in the end of the run.
ca::DetIdArray_t< bool > fbDetUsed
Flags of detector subsystems used in tracking.
void SetNhitKeys(int nKeys)
Sets the number of hit keys.
void PushBackHit(const Hit &hit, int64_t streamId)
Pushes back a hit.
InputData && TakeInputData()
Takes (moves) the instance of the input data object.
void ResetInputData(HitIndex_t nHits=0) noexcept
Resets the input data block.
int GetNofHits()
Gets number of hits stored.
const TrackingMonitorData & GetMonitorData() const
Gets monitor data.
int GetNofThreads() const
Gets number of threads.
const InputData & GetInputData() const
Gets pointer to input data object for external access.
Definition CaFramework.h:96
Vector< Track > fRecoTracks
reconstructed tracks
void SetNofThreads(int nThreads)
Sets number of threads.
void ReceiveParameters(Parameters< fvec > &&parameters)
Receives tracking parameters.
Vector< ca::HitIndex_t > fRecoHits
packed hits of reconstructed tracks
void ReceiveInputData(InputData &&inputData)
Receives input data.
void SetMonitorData(const TrackingMonitorData &monitorData)
Sets monitor data.
void Init(const TrackingMode mode)
const Parameters< fvec > & GetParameters() const
Gets a pointer to the Framework parameters object.
Definition CaFramework.h:87
ca::Hit class describes a generic hit for the CA tracker
Definition CaHit.h:32
void SetX(fscal x)
Set the X coordinate.
Definition CaHit.h:54
HitKeyIndex_t BackKey() const
Get the back key index.
Definition CaHit.h:99
void SetRangeT(fscal rangeT)
Set the +/- range of uncertainty of time.
Definition CaHit.h:84
void SetDt2(fscal dt2)
Set the uncertainty of time.
Definition CaHit.h:75
void SetDy2(fscal dy2)
Set the uncertainty of Y coordinate.
Definition CaHit.h:69
void SetRangeY(fscal rangeY)
Set the +/- range of uncertainty of Y coordinate.
Definition CaHit.h:81
void SetStation(int station)
Set the station index.
Definition CaHit.h:90
void SetDx2(fscal dx2)
Set the uncertainty of X coordinate.
Definition CaHit.h:66
void SetRangeX(fscal rangeX)
Set the +/- range of uncertainty of X coordinate.
Definition CaHit.h:78
void SetZ(fscal z)
Set the Z coordinate.
Definition CaHit.h:60
void SetBackKey(HitKeyIndex_t key)
Set the back key index.
Definition CaHit.h:51
void SetFrontKey(HitKeyIndex_t key)
Set the front key index.
Definition CaHit.h:48
void SetId(HitIndex_t id)
Set the hit id.
Definition CaHit.h:87
bool Check() const
Checks, if the hit is defined.
Definition CaHit.h:199
HitKeyIndex_t FrontKey() const
Get the front key index.
Definition CaHit.h:96
fscal T() const
Get the time.
Definition CaHit.h:111
void SetT(fscal t)
Set the time.
Definition CaHit.h:63
HitIndex_t Id() const
Get the hit id.
Definition CaHit.h:135
void SetDxy(fscal dxy)
Set the X/Y covariance.
Definition CaHit.h:72
void SetY(fscal y)
Set the Y coordinate.
Definition CaHit.h:57
A CA Parameters object initialization class.
void SetDetectorNames(const std::array< const char *, Size > &container)
Sets detector names.
const Hit & GetHit(HitIndex_t index) const
Gets reference to hit by its index.
Definition CaInputData.h:55
int GetCounterValue(ECounterKey key) const
Gets counter value.
void Reset()
Resets all the counters and timers.
void StopTimer(ETimerKey key)
Stops timer.
void IncrementCounter(ECounterKey key)
Increments key counter by 1.
void StartTimer(ETimerKey key)
Starts timer.
const Timer & GetTimer(ETimerKey key) const
Gets timer.
std::string ToString() const
Prints counters summary to string.
Definition CaMonitor.h:167
void Reset()
Resets the counters.
Definition CaMonitor.h:107
void AddMonitorData(const MonitorData< ECounterKey, ETimerKey > &data, bool parallel=false)
Adds the other monitor data to this.
Definition CaMonitor.h:70
int GetCounterValue(ECounterKey key) const
Gets counter value.
Definition CaMonitor.h:81
A container for all external parameters of the CA tracking algorithm.
void Exec()
QA execution function.
Definition CaQa.cxx:305
void RegisterParameters(const Parameters< fvec > *pParameters)
Registers tracking parameters object.
Definition CaQa.h:107
void Init()
Initializes the QA.
Definition CaQa.cxx:54
bool IsSenderDefined() const
Checks, if the histogram sender is defined.
Definition CaQa.h:91
void RegisterRecoHitIndices(const Vector< HitIndex_t > *pvRecoHits)
Registers reco hits indices vector.
Definition CaQa.h:103
void RegisterInputData(const InputData *pInputData)
Registers tracking input data object.
Definition CaQa.h:95
void RegisterTracks(const Vector< Track > *pvTracks)
Registers track vector.
Definition CaQa.h:99
double GetTotal() const
Gets total time [s].
Definition CaTimer.h:77
Class representing an output track in the CA tracking algorithm.
A monitor specialization for cbm::algo::ca::Framework class.
void push_back(Tinput value)
Pushes back a value to the vector.
Definition CaVector.h:176
void reserve(std::size_t count)
Reserves a new size for the vector.
Definition CaVector.h:162
void reset(std::size_t count, Tinput... value)
Clears vector and resizes it to the selected size with selected values.
Definition CaVector.h:121
constexpr char GNb[]
bold green
Definition CaDefs.h:155
constexpr char CL[]
clear
Definition CaDefs.h:132
unsigned int HitKeyIndex_t
Index of the hit key (e.g. front / back cluster id for STS)
Definition CaHit.h:28
@ RecoTrack
number of reconstructed tracks
@ RecoStsHit
number of STS hits in tracks
@ UndefinedTofHit
number of undefined TOF hits
@ TrackingCall
number of the routine calls
@ UndefinedTrdHit
number of undefined TRD hits
@ RecoTrdHit
number of TRD hits in tracks
@ UndefinedMvdHit
number of undefined MVD hits
@ RecoTofHit
number of TOF hits in tracks
@ UndefinedMuchHit
number of undefined MuCh hits
@ UndefinedStsHit
number of undefined STS hits
constexpr DetIdArray_t< const char * > kDetName
Detector subsystem names.
EDetectorID
Enumeration for the tracking detector subsystems in CBM-CA.
Definition CbmDefs.h:176
constexpr fles::Subsystem ToFlesSubsystem()
int GetMaxThreads()
Definition OpenMP.h:46
T ReadFromFile(fs::path path)
Definition Yaml.h:51
Class to hold the paths to the parameter files for the different detectors.
Definition ParFiles.h:21
struct cbm::algo::ParFiles::@4 ca
fs::path mainConfig
Definition ParFiles.h:52
std::string fsGeomConfig
Tracking geometry file name (TMP: includes all other settings, but the settings are rewritten)
std::string fsUserConfig
User configuration file (full path)
std::string fsSetupFilename
Geometry setup input file.
std::string fsMainConfig
Main configuration file (rel path in online parameters directory)
bool fbStoreMonitor
Stores monitor snapshot.
std::string fsMoniOutName
Monitor output file name.
Input to the TrackingChain.
PartitionedSpan< trd::Hit > trdHits
PartitionedSpan< sts::Hit > stsHits
PartitionedSpan< tof::Hit > tofHits
Output from the TrackingChain.
ca::Vector< ca::Track > tracks
Reconstructed tracks.
ca::TrackingMonitorData monitorData
Monitor data.
ca::Vector< std::vector< std::pair< uint32_t, uint32_t > > > trdHitIndices
TRD hit indices.
ca::Vector< std::vector< std::pair< uint32_t, uint32_t > > > tofHitIndices
TOF hit indices.
ca::Vector< std::vector< std::pair< uint32_t, uint32_t > > > stsHitIndices
STS hit indices.
Array of types, indexed by EDetectorID.
std::tuple_element_t< static_cast< std::size_t >(DetID), std::tuple< Types... > > at