ATLAS Offline Software
Loading...
Searching...
No Matches
TrackTruthMatchingBaseAlg.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
3*/
5
9
10// for pdg_id -> name
11#include "HepPDT/ParticleDataTable.hh"
12
13#include <iomanip>
14#include <cmath>
15#include <type_traits>
16#include <typeinfo>
17#include <numeric>
18
19namespace {
20 template <typename T, std::size_t N>
21 void accumulateTo(typename std::vector<std::array<T,N> >::const_iterator src_begin,
22 typename std::vector<std::array<T,N> >::const_iterator src_end,
23 std::array<T,N> &dest) {
24 for (typename std::vector<std::array<T,N> >::const_iterator src_iter = src_begin;
25 src_iter != src_end;
26 ++src_iter) {
27 for (unsigned int elm_i=0; elm_i<dest.size(); ++elm_i) {
28 assert( elm_i < src_iter->size() );
29 dest[elm_i] += (*src_iter)[elm_i];
30 }
31 }
32 }
33
34 template <typename T, bool LastRowOnly=false>
35 void accumulateToLastColumnRow(std::size_t n_rows, std::size_t n_cols, std::vector<T> &stat) {
36 assert(n_cols > 0);
37 assert(n_rows > 0);
38 auto stat_begin_iter = stat.begin();
39 if (n_rows>1) {
40 auto stat_total_row_begin_iter = stat.begin() + (n_rows-1) * n_cols;
41 assert( static_cast<std::size_t>(stat_total_row_begin_iter - stat_begin_iter) < stat.size());
42
43 for (std::size_t row_i = 0; row_i < n_rows-1; ++row_i) {
44 auto stat_end_iter = stat_begin_iter + n_cols - 1 ;
45 assert(static_cast<std::size_t>(stat_end_iter - stat.begin()) < stat.size());
46 auto stat_total_row_iter = stat_total_row_begin_iter;
47 if constexpr(!LastRowOnly) {
48 accumulateTo(stat_begin_iter, stat_end_iter, *stat_end_iter );
49 }
50
51 ++stat_end_iter; // now also consider the total eta bin.
52 for (; stat_begin_iter != stat_end_iter; ++stat_begin_iter, ++stat_total_row_iter) {
53 assert(static_cast<std::size_t>(stat_begin_iter - stat.begin()) < stat.size());
54 assert(static_cast<std::size_t>(stat_total_row_iter - stat.begin()) < stat.size());
55 for (unsigned int idx=0; idx < stat_total_row_iter->size(); ++idx) {
56 stat_total_row_iter->at(idx) += stat_begin_iter->at(idx);
57 }
58 }
59 }
60 }
61 else if constexpr(!LastRowOnly) {
62 auto stat_end_iter = stat_begin_iter + n_cols - 1 ;
63 accumulateTo(stat_begin_iter, stat_end_iter, *stat_end_iter );
64 }
65 }
66
67 template <typename T>
68 void accumulateToLastRow(std::size_t n_rows, std::size_t n_cols, std::vector<T> &stat) {
69 accumulateToLastColumnRow<T,true>(n_rows, n_cols, stat);
70 }
71
72 template <typename T, std::size_t N>
73 void addStat(const std::vector<std::array<T,N> > &src, std::vector<std::array<T,N> > &dest) {
74 assert( src.size() == dest.size());
75 unsigned int idx=0;
76 for (const std::array<T,N> &src_elm : src) {
77 assert( idx < dest.size());
78 std::array<T,N> &dest_elm = dest[idx];
79 unsigned val_i=0;
80 for (const T &val : src_elm) {
81 assert( val_i < dest_elm.size());
82 dest_elm[val_i] += val;
83 ++val_i;
84 }
85 ++idx;
86 }
87 }
88
89 inline double sqr(double a) { return a*a; }
90 // computate ratio and its statistical uncertainty
91 inline std::array<float, 2> computeRatio(unsigned int numerator_counts, unsigned int denominator_counts) {
92 double inv_denominator_counts = denominator_counts > 0 ? 1./denominator_counts : 0.;
93 return std::array<float, 2> {
94 static_cast<float>(numerator_counts * inv_denominator_counts),
95 static_cast<float>(sqrt( numerator_counts * (denominator_counts-numerator_counts)
96 * inv_denominator_counts * sqr(inv_denominator_counts) ))
97 };
98 }
99
100 std::string hfill(const std::string &head, const std::string &tail, std::size_t width) {
101 width=std::max(width, head.size() + tail.size()) - head.size() - tail.size();
102 std::stringstream out;
103 out << head << std::setw(width) << " " << tail;
104 return out.str();
105
106 }
107
108 std::string dumpCounts(const ActsTrk::HitCounterArray &counts) {
109 std::stringstream out;
110 for (uint8_t val : counts) {
111 out << " " << std::setw(2) << static_cast<int>(val);
112 }
113 return out.str();
114 }
115}
116namespace ActsTrk
117{
118 // to dump
119 inline MsgStream &operator<<(MsgStream &out, const ActsUtils::Stat &stat) {
120 ActsUtils::dumpStat(out, stat);
121 return out;
122 }
123
125 ISvcLocator *pSvcLocator)
126 : AthReentrantAlgorithm(name, pSvcLocator)
127 {
128 }
129
131 {
132 ATH_CHECK( m_truthSelectionTool.retrieve());
133 ATH_CHECK( m_truthHitCounts.initialize() );
135 return checkMatchWeights();
136 }
137
138 template <bool IsDebug>
139 template <class T_OutStream>
141 if constexpr(IsDebug) {
142 out << "Weighted measurement sum per truth particle without associated counts :" << m_measPerTruthParticleWithoutCounts << std::endl
143 << m_measPerTruthParticleWithoutCounts.histogramToString() << std::endl
144 << "Match probability of best match :" << m_bestMatchProb << std::endl
145 << m_bestMatchProb.histogramToString() << std::endl
146 << "Match probability of next-to-best match :" << m_nextToBestMatchProb << std::endl
147 << m_nextToBestMatchProb.histogramToString() << std::endl;
148 }
149 }
150
151 template <bool IsDebug>
153 if constexpr(IsDebug) {
154 std::lock_guard<std::mutex> lock(m_mutex);
155 m_measPerTruthParticleWithoutCounts.add(weighted_measurement_sum);
156 }
157 }
158 template <bool IsDebug>
159 inline void TrackTruthMatchingBaseAlg::DebugCounter<IsDebug>::fillTruthMatchProb(const std::array<float,2> &best_match_prob) const {
160 if constexpr(IsDebug) {
161 std::lock_guard<std::mutex> lock(m_mutex);
162 m_bestMatchProb.add(best_match_prob[0]);
163 m_nextToBestMatchProb.add(best_match_prob[1]);
164 }
165 }
166
167
169 {
170 if (msgLvl(MSG::INFO)) {
172 m_debugCounter.dumpStatistics(msg());
173 }
174 msg(MSG::INFO) << "Truth selection cuts: " << std::endl;
175 unsigned int cut_i=0;
176 std::size_t total = std::accumulate ( m_detailedStat.m_truthSelectionCuts.m_histogram.begin(),
177 m_detailedStat.m_truthSelectionCuts.m_histogram.end(), 0u);
178 msg() << std::setw(3) << "" << " " << std::setw(20) << total << " total" << std::endl;
179 if (m_detailedStat.m_truthSelectionCuts.m_histogram.at(cut_i) > 0) {
180 msg() << std::setw(3) << "" << " "
181 << std::setw(20) << (total - m_detailedStat.m_truthSelectionCuts.m_histogram.at(cut_i))
182 << " underflow" << std::endl;
183 }
184 total -= m_detailedStat.m_truthSelectionCuts.m_histogram.at(cut_i++);
185 for (const std::string &name : m_truthSelectionTool->names()) {
186 total -= m_detailedStat.m_truthSelectionCuts.m_histogram.at(cut_i);
187 msg() << std::setw(3) << cut_i << " " << std::setw(20) << total << " " << name << std::endl;
188 ++cut_i;
189 }
190 total -= m_detailedStat.m_truthSelectionCuts.m_histogram.at(cut_i);
191 if (total>0) {
192 msg() << std::setw(3) << "" << " " << std::setw(20) << total << " overflow" << std::endl;
193 }
194 if (msgLvl(MSG::DEBUG)) {
195 msg() << m_detailedStat.m_truthSelectionCuts.histogramToString();
196 }
197 msg() << endmsg;
198 }
200 return StatusCode::SUCCESS;
201 }
202
205 const HitCountsPerTrack &track_hit_counts,
206 TrackTruthMatchingBaseAlg::EventStat &event_stat) const
207 {
208 TruthMatchResult ret{};
209 std::array<unsigned int,2> best_match_i{std::numeric_limits<unsigned int>::max(),std::numeric_limits<unsigned int>::max()};
210 std::array<float,2> best_match_prob {};
211
212 std::array<unsigned int,2> best_match_i_nonoise{std::numeric_limits<unsigned int>::max(),std::numeric_limits<unsigned int>::max()};
213 std::array<float,2> best_match_prob_nonoise{};
214
215 const HitCounterArray &total_counts = track_hit_counts.totalCounts();
216 const HitCounterArray &noise_counts = track_hit_counts.noiseCounts();
217
218 double total_sum=weightedCountSum(total_counts, m_weights.value() );
219 double total_sum_for_prob=weightedCountSum(total_counts, m_weightsForProb.value() );
220 double noise_sum=noiseCorrection(noise_counts, m_weightsForProb.value() );
221 double total_sum_for_prob_nonoise=total_sum_for_prob;
222 total_sum_for_prob += noise_sum;
224 if (total_sum_for_prob>0.) {
225 // compute total hit count per truth particle and remember the highest and second highest
226 // count per truth particle.
227 // The match probability is then max_counter / sum_{i in associated truth particles} counts_i
228 unsigned int truth_i=0;
229 --truth_i;
230 for (const std::pair<const xAOD::TruthParticle *, HitCounterArray > &
231 hit_counts_for_associated_truth_particle : track_hit_counts.countsPerTruthParticle() ) {
232 ++truth_i;
233 double truth_sum_for_prob=weightedCountSum(hit_counts_for_associated_truth_particle.second, m_weightsForProb.value() );
234 float match_prob_nonoise = truth_sum_for_prob /total_sum_for_prob_nonoise;
235 float match_prob = truth_sum_for_prob /total_sum_for_prob;
236 if (match_prob>1 || match_prob<0.) {
237 ATH_MSG_ERROR("Negative or too large truth match \"probability\". This should not happen."
238 << " Track hits: " << dumpCounts(total_counts)
239 << " noise hits of those: " << dumpCounts(noise_counts)
240 << " truth hits: " << dumpCounts(hit_counts_for_associated_truth_particle.second));
241 } // remember the highest and next-to-highest hit count per truth particle
242 if (match_prob>best_match_prob[1]) {
243 int dest_i=match_prob<best_match_prob[0];
244 best_match_i[1]=best_match_i[0];
245 best_match_prob[1]=best_match_prob[0];
246 best_match_prob[dest_i]=match_prob;
247 best_match_i[dest_i]=truth_i;
248 }
249 if (match_prob_nonoise>best_match_prob_nonoise[1]) {
250 int dest_i=match_prob_nonoise<best_match_prob_nonoise[0];
251 best_match_i_nonoise[1]=best_match_i_nonoise[0];
252 best_match_prob_nonoise[1]=best_match_prob_nonoise[0];
253 best_match_prob_nonoise[dest_i]=match_prob_nonoise;
254 best_match_i_nonoise[dest_i]=truth_i;
255 }
256
257 }
258 }
259
260 if (best_match_i_nonoise[0] != best_match_i[0]) {
262 }
263 if ( best_match_i[0] < track_hit_counts.countsPerTruthParticle().size()
264 && track_hit_counts.countsPerTruthParticle()[ best_match_i[0] ].first) {
265 ret.m_truthParticle = track_hit_counts.countsPerTruthParticle()[ best_match_i[0] ].first;
266 ret.m_matchProbability = best_match_prob[0];
267
268 const xAOD::TruthParticle *best_match = track_hit_counts.countsPerTruthParticle()[ best_match_i[0] ].first;
269 const IAthSelectionTool::CutResult accept = m_truthSelectionTool->accept(best_match);
270 event_stat.m_truthSelectionCuts.add( event_stat.m_nTruthCuts - accept.missingCuts() );
271 if (accept) {
272
273 double common_truth_sum=weightedCountSum(track_hit_counts.countsPerTruthParticle()[ best_match_i[0] ].second, m_weights.value() );
274
275 float hit_efficiency = 0.;
276 std::unordered_map<const xAOD::TruthParticle *,HitCounterArray>::const_iterator
277 best_truth_particle_counts_iter = truth_particle_hit_counts.find( best_match );
278
279 if (best_truth_particle_counts_iter != truth_particle_hit_counts.end()) {
280 double truth_sum=weightedCountSum(best_truth_particle_counts_iter->second, m_weights.value() );
281 // in principle truth_measuremnts should always be larger than 0
282 hit_efficiency = truth_sum > 0u ? (common_truth_sum/truth_sum) : 0.;
283 }
284 else {
285 // this can happen if the total number of hits are below threshold for
286 // accepting a truth particle
288 m_debugCounter.fillMeasForTruthParticleWithoutCount(total_sum);
289 }
290
291 // in principle a track matched to a truth particle should always have n_total > 0
292 // but the hits could be filtered out.
293 if (total_sum>0.) {
294 float hit_purity = common_truth_sum / total_sum;
295 ret.m_hitPurity = hit_purity;
296 ret.m_hitEfficiency = hit_efficiency;
297 m_debugCounter.fillTruthMatchProb(best_match_prob);
298
300 float best_match_pt = best_match->pt();
301 std::size_t eta_category_i = getPtEtaStatCategory(best_match_pt, best_match->eta());
302 std::size_t pdg_id_category_i = getPtPdgIdStatCategory(best_match_pt, best_match->pdg_id());
303 event_stat.fill( eta_category_i, pdg_id_category_i, hit_efficiency, hit_purity, best_match_prob[0], best_match );
304 }
305 }
306 }
307 else {
309 }
310 }
311 else {
312 // no eta, pdg_id for tracks without associated truth particle
313 // could use eta of track but not available to the algorithm
314
316 if (!track_hit_counts.countsPerTruthParticle().empty()) {
317 ATH_MSG_ERROR("Failed to select best matching truth particle out of " << track_hit_counts.countsPerTruthParticle().size()
318 << ". This should not happen." );
319 }
320 }
321 return ret;
323
325
327 std::size_t n_tracks,
328 TrackTruthMatchingBaseAlg::EventStat &event_stat) const
329 {
330 if constexpr(EventStat::doDetail) {
331 if (m_computeTrackRecoEfficiency.value()) {
332 for(const std::pair<const xAOD::TruthParticle * const,ActsTrk::HitCounterArray> &truth_particle : truth_particle_hit_counts) {
333 const IAthSelectionTool::CutResult accept = m_truthSelectionTool->accept(truth_particle.first);
334 if (accept) {
335 double truth_sum=weightedCountSum(truth_particle.second, m_weights.value() );
336 if (truth_sum>0.) {
337 float truth_particle_pt = truth_particle.first->pt();
338 std::size_t eta_category_i = getPtEtaStatCategory(truth_particle_pt, truth_particle.first->eta());
339 std::size_t pdg_id_category_i = getPtPdgIdStatCategory(truth_particle_pt, truth_particle.first->pdg_id());
340 event_stat.incrementTotal(eta_category_i, pdg_id_category_i);
341 }
342 }
343 }
344 }
345 }
346
347 // update total statistic counter
348 {
349 std::lock_guard<std::mutex> lock(m_statMutex);
354 m_counter[NTracksTotal]+=n_tracks;
355 m_counter[NTruthWithCountsTotal]+=truth_particle_hit_counts.size();
356
357 if constexpr(EventStat::doDetail) {
358 m_detailedStat += event_stat;
359 }
360 }
361 }
362
363 inline std::size_t TrackTruthMatchingBaseAlg::getPtEtaStatCategory(float pt, float eta) const
364 {
365 std::vector<float>::const_iterator pt_bin_iter = std::upper_bound(m_statPtBins.begin(),
366 m_statPtBins.end(),
367 pt);
368 std::vector<float>::const_iterator eta_bin_iter = std::upper_bound(m_statEtaBins.begin(),
369 m_statEtaBins.end(),
370 m_useAbsEtaForStat ? std::abs(eta) : eta);
371 return (m_statEtaBins.size()+2u) * static_cast<std::size_t>(pt_bin_iter - m_statPtBins.begin())
372 + static_cast<std::size_t>(eta_bin_iter - m_statEtaBins.begin());
373 }
374 std::size_t TrackTruthMatchingBaseAlg::getPtPdgIdStatCategory(float pt, int pdg_id) const {
375 std::vector<float>::const_iterator pt_bin_iter = std::upper_bound(m_statPtBins.begin(),
376 m_statPtBins.end(),
377 pt);
378 int abs_pdg_id = std::min(std::abs(pdg_id), s_pdgIdMax);
379 std::vector< int >::const_iterator iter = std::find(m_pdgId.begin(), m_pdgId.end(), abs_pdg_id);
380 if (iter == m_pdgId.end()){
381 if (m_pdgId.size() < m_pdgId.capacity()) {
382 std::lock_guard<std::mutex> lock(m_statMutex); // @TODO pdg id list specific mutex ?
383 // make sure that the pdg id still does not exist.
384 iter = std::find(m_pdgId.begin(), m_pdgId.end(), abs_pdg_id);
385 if (iter == m_pdgId.end()){
386 m_pdgId.push_back(abs_pdg_id);
387 iter = m_pdgId.end()-1;
388 }
389 }
390 else {
391 iter=m_pdgId.begin();
392 }
393 }
394 return (m_pdgId.capacity()) * static_cast<std::size_t>(pt_bin_iter - m_statPtBins.begin())
395 + (iter - m_pdgId.begin());
396 }
397
398 void TrackTruthMatchingBaseAlg::checkBinOrder( const std::vector<float> &bin_edges, const std::string &bin_label) const {
399 if (!bin_edges.empty())
400 {
401 float last_eta = bin_edges[0];
402 for (float eta : bin_edges)
403 {
404 if (eta < last_eta)
405 {
406 ATH_MSG_FATAL(bin_label + " bins for statistics counter not in ascending order.");
407 }
408 last_eta = eta;
409 }
410 }
411 }
413 {
414 if (!m_statEtaBins.empty())
415 {
417 checkBinOrder(m_statEtaBins.value(),"Eta");
418 }
419 checkBinOrder(m_statPtBins.value(),"Pt");
420
421
422 unsigned int max_pdg_id_slots=( m_pdgIdCategorisation.value() ? 20 : 1 );
423
424 // last element in statPerEta and counterPerEta will be used accumulate statistics of all eta bins
425 m_detailedStat.reset( *m_truthSelectionTool,
426 (m_statPtBins.size() + 2) * (m_statEtaBins.size() + 2),
427 (m_statPtBins.size() + 2) * max_pdg_id_slots);
428
429 m_pdgId.reserve(max_pdg_id_slots);
430 m_pdgId.push_back(1000000000);
431 }
432
433 template <bool DetailEnabled>
436 if constexpr(DetailEnabled) {
437 addStat(event_stat.m_counterPerEta,m_counterPerEta);
438 addStat(event_stat.m_statPerEta, m_statPerEta);
439 addStat(event_stat.m_counterPerPdgId,m_counterPerPdgId);
440 addStat(event_stat.m_statPerPdgId, m_statPerPdgId);
441 }
443 return *this;
444 }
445
446 template <bool DetailEnabled>
448 const std::vector<float> &statPtBins,
449 const std::vector<float> &statEtaBins,
450 std::vector< int > &pdgId,
451 bool printDetails,
452 bool pdgIdCategorisation,
453 bool useAbsEtaForStat) {
454 if constexpr(DetailEnabled) {
455 static constexpr bool rotate=true;// row : eta/PDG ID; column: pt
456 std::vector<std::string> counter_labels { std::string("Truth particles"),
457 std::string("with asso. track"),
458 std::string("with >1 asso. tracks"),
459 std::string("total tracks")};
460 std::vector<std::string> pt_labels;
461 pt_labels.reserve(statPtBins.size() + 2);
462 unsigned int pt_precision=0;
463 for (float pt : statPtBins) {
464 if (pt<1.) {
465 pt_precision=1;
466 break;
467 }
468 }
469 for (std::size_t bin_i = 0; bin_i < statPtBins.size() + 2; ++bin_i) {
470 pt_labels.push_back(TableUtils::makeBinLabel("pt",statPtBins, bin_i, true, pt_precision));
471 }
472 // statistics eta-bins
473 {
474 std::vector<std::string> eta_labels;
475 eta_labels.reserve(statEtaBins.size() + 2);
476 for (std::size_t eta_bin_i = 0; eta_bin_i < statEtaBins.size() + 2; ++eta_bin_i) {
477 eta_labels.push_back(TableUtils::makeEtaBinLabel(statEtaBins, eta_bin_i, useAbsEtaForStat));
478 }
479
480 accumulateToLastColumnRow(statPtBins.size()+2,statEtaBins.size()+2, m_statPerEta);
481 accumulateToLastColumnRow(statPtBins.size()+2,statEtaBins.size()+2, m_counterPerEta);
482
483 if (statPtBins.empty() || printDetails) {
484 parent.printCategories(pt_labels, eta_labels, counter_labels, m_statPerEta, m_counterPerEta,
485 (!statPtBins.empty()
486 ? hfill("pt ",
487 "eta",
489 +TableUtils::maxLabelWidth(eta_labels))
490 : std::string("eta") ),
491 !statPtBins.empty());
492 }
493 if (!statPtBins.empty()) {
494 parent.printData2D(pt_labels, eta_labels,
495 rotate
496 ? hfill("eta","\\ pt", TableUtils::maxLabelWidth(eta_labels))
497 : hfill("pt","\\ eta", TableUtils::maxLabelWidth(pt_labels)),
500 rotate);
501 }
502 }
503
504 // statistics in PDG ID bins.
505 if (pdgIdCategorisation) {
506 std::vector<std::string> pdg_id_labels;
507 pdg_id_labels.reserve( pdgId.size());
508 pdg_id_labels.push_back("Other");
509 for (unsigned int pdg_i=1; pdg_i < pdgId.size(); ++pdg_i) {
510 std::stringstream a_label;
511 a_label << HepPID::particleName(pdgId[pdg_i]) << " [" << pdgId[pdg_i] << "]";
512 pdg_id_labels.push_back( a_label.str() );
513 }
514 unsigned int max_pdg_id_slots=m_statPerPdgId.size()/(statPtBins.size()+2);
515 assert( m_statPerPdgId.size() % (statPtBins.size()+2) == 0 );
516 // also the unused columns are projected, but that does not harm :
517 accumulateToLastRow(statPtBins.size()+2,max_pdg_id_slots, m_statPerPdgId);
518 accumulateToLastRow(statPtBins.size()+2,max_pdg_id_slots, m_counterPerPdgId);
519
520 if (statPtBins.empty() || printDetails) {
521 parent.printCategories(pt_labels, pdg_id_labels, counter_labels, m_statPerPdgId, m_counterPerPdgId,
522 (!statPtBins.empty()
523 ? hfill("pt ",
524 "PDG-id",
526 +TableUtils::maxLabelWidth(pdg_id_labels))
527 : std::string("eta")),
528 !statPtBins.empty());
529 }
530 if (!statPtBins.empty()) {
531 parent.printData2D(pt_labels, pdg_id_labels,
532 rotate
533 ? hfill("PDG ID","\\ pt", TableUtils::maxLabelWidth(pdg_id_labels))
534 : hfill("pt","\\ PDG ID", TableUtils::maxLabelWidth(pt_labels)),
537 rotate);
538 }
539 }
540 }
541 }
542
544 {
545 if (msgLvl(MSG::INFO))
546 {
547 msg() << MSG::INFO << std::endl;
548 m_detailedStat.printStatTables( *this, m_statPtBins, m_statEtaBins, m_pdgId, m_printDetails.value(), m_pdgIdCategorisation.value(), m_useAbsEtaForStat );
549 {
550 std::array<std::string, kNCounter> counter_labels { std::string("Number of tracks"),
551 std::string("Number of truth particles with hit counts"),
552 std::string("Associated truth particles without hit counts"),
553 std::string("Tracks without associated truth particle"),
554 std::string("Tracks without selected, associated truth particle"),
555 std::string("Best truth particle without noise correction mismatch")
556 };
557 msg() << makeTable( m_counter, counter_labels) << std::endl;
558 }
559 msg() << endmsg;
560 }
561 }
562
563
564
565 void TrackTruthMatchingBaseAlg::printCategories(const std::vector<std::string> &row_category_labels,
566 const std::vector<std::string> &col_category_labels,
567 std::vector<std::string> &counter_labels,
568 std::vector< std::array< ActsUtils::Stat, kNCategorisedStat> > &stat_per_category,
569 std::vector< std::array< std::size_t, kNCategorisedCounter> > &counts_per_category,
570 const std::string &top_left,
571 bool print_sub_categories) const {
572 if (!row_category_labels.empty() && !col_category_labels.empty()) {
573 if (row_category_labels.size() * col_category_labels.size() > counts_per_category.size() ) {
574 ATH_MSG_ERROR( "Mismatch between category labels and number of counters (logic error -> fix needed):"
575 << row_category_labels.size() << " * " << col_category_labels.size()
576 << " > " << counts_per_category.size() );
577 }
578 constexpr std::size_t stat_column_width=14*4 + 3*3+4 + 9; // floats + seperators + integer of Stat output
579 assert( stat_per_category.size() == counts_per_category.size());
580 const unsigned int n_rows = row_category_labels.size();
581 const unsigned int n_cols = stat_per_category.size() / n_rows; // some columns at the end of a row might not have labels
582 // and are to be ignored
583
584 assert( stat_per_category.size() % n_rows == 0 );
585 for(unsigned int row_i=(print_sub_categories ? 0 : n_rows-1); row_i<n_rows; ++row_i) {
586 {
587 std::vector<std::string> stat_labels { std::string("Hit Efficiency") };
588 msg() << makeTable( stat_per_category, row_i*n_cols, kNCategorisedStat, kHitEfficiency, 1u, col_category_labels, stat_labels, top_left)
589 .columnWidth(stat_column_width)
590 .labelPrefix(row_category_labels.at(row_i)+" ")
591 .precision(std::vector<unsigned int>{3})
592 << std::endl;
593 }
594 {
595 std::vector<std::string> stat_labels { std::string("Hit Purity") };
596 msg() << makeTable( stat_per_category, row_i*n_cols, kNCategorisedStat, kHitPurity, 1u, col_category_labels, stat_labels, top_left)
597 .columnWidth(stat_column_width)
598 .labelPrefix(row_category_labels.at(row_i)+" ")
599 .precision(std::vector<unsigned int>{3})
600 << std::endl;
601 }
602 {
603 std::vector<std::string> stat_labels { std::string("Match probability") };
604 msg() << makeTable( stat_per_category, row_i*n_cols, kNCategorisedStat, kMatchProbability, 1u, col_category_labels, stat_labels, top_left)
605 .columnWidth(stat_column_width)
606 .labelPrefix(row_category_labels.at(row_i)+" ")
607 .precision(std::vector<unsigned int>{3})
608 << std::endl;
609 }
610 if (m_showRawCounts.value()) {
611 msg() << makeTable( counts_per_category, row_i*n_cols, kNCategorisedCounter, 0u, 1u, col_category_labels, counter_labels, top_left)
612 .labelPrefix(row_category_labels.at(row_i)+" ")
613 << std::endl;
614 }
615
616 if (m_computeTrackRecoEfficiency.value()) {
617 std::vector< std::array< float, 2> > eff;
618 eff.reserve(m_pdgId.size());
619 for (unsigned int category_i=0; category_i< col_category_labels.size(); ++category_i) {
620 eff.push_back( computeRatio( counts_per_category[category_i+row_i*n_cols][kNParticleWithAssociatedTrack],
621 counts_per_category[category_i+row_i*n_cols][kNTotalParticles] ) );
622 }
623 std::vector<std::string> eff_labels { std::string("reco efficiency"),
624 std::string("stat. uncertainty") };
625 msg() << makeTable( eff, 0u, eff.begin()->size(),0u,1u, col_category_labels, eff_labels, top_left)
626 .labelPrefix(row_category_labels.at(row_i)+" ")
627 .precision(std::vector<unsigned int>{3,3})
628 << std::endl;
629 }
630 }
631 }
632 }
633
634 namespace {
635 // helper to prevent temporary table data from beeing destructed too early
636 template <typename T>
637 struct TablePlusData {
638 TablePlusData(std::vector<T> &&values,
639 const std::vector<std::string> &row_labels,
640 const std::vector<std::string> &col_labels,
641 const std::string &top_left_label)
642 : m_data(std::move(values)),
643 m_assocTable({
644 TableUtils::Range2D<T>{m_data.data(),
645 row_labels.size(), // n-rows
646 col_labels.size(), // n-columns
647 col_labels.size(), // offset between rows
648 0u, // first column index
649 1u}, // offset between columns
650 TableUtils::Range<std::string> {row_labels.data(), row_labels.size()},
651 TableUtils::Range<std::string> {col_labels.data(), col_labels.size()},
652 top_left_label
653 })
654 {}
655 std::vector<T> m_data;
656 TableUtils::MultiColumnTable<T> m_assocTable;
657 TablePlusData &columnWidth(std::size_t value) { m_assocTable.columnWidth(value); return *this;}
658 TablePlusData &minLabelWidth(std::size_t value) { m_assocTable.minLabelWidth(value); return *this;}
659 TablePlusData &dumpHeader(bool value=true) { m_assocTable.dumpHeader(value); return *this;}
660 TablePlusData &dumpFooter(bool value=true) { m_assocTable.dumpFooter(value); return *this;}
661 TablePlusData &separateLastRow(bool value=true) { m_assocTable.separateLastRow(value); return *this;}
662 TablePlusData &labelPrefix(const std::string& value) { m_assocTable.labelPrefix(value); return *this;}
663 TablePlusData &precision(std::vector<unsigned int> &&precision) { m_assocTable.precision(std::move(precision)); return *this;}
664 };
665
666 template <typename T>
667 inline MsgStream &operator<<(MsgStream &out, const TablePlusData<T> &table) {
668 out << table.m_assocTable;
669 return out;
670 }
671
672 template <typename T>
673 inline std::ostream &operator<<(std::ostream &out, const TablePlusData<T> &table) {
674 out << table.m_assocTable;
675 return out;
676 }
677
678 template <class T_Container, class T_Function, typename T=double>
679 TablePlusData<T>
680 create2DTable(const std::vector<std::string> &row_category_labels,
681 const std::vector<std::string> &col_category_labels,
682 const std::string &top_left_label,
683 T_Container container,
684 T_Function function,
685 bool rotate) {
686 const unsigned int n_rows = row_category_labels.size();
687 const unsigned int n_cols = col_category_labels.size();
688 const unsigned int n_cols_total = container.size() / n_rows; // some columns at the end of a row might not have labels
689 std::vector< T > values;
690 values.reserve( n_rows * n_cols );
691 if (rotate) {
692 for (unsigned int col_i=0; col_i< n_cols; ++col_i) {
693 for (unsigned int row_i=0; row_i< n_rows; ++row_i) {
694 values.push_back( function(container.at( row_i * n_cols_total + col_i )) );
695 }
696 }
697 }
698 else {
699 for (unsigned int row_i=0; row_i< n_rows; ++row_i) {
700 for (unsigned int col_i=0; col_i< n_cols; ++col_i) {
701 values.push_back( function(container.at( row_i * n_cols_total + col_i )) );
702 }
703 }
704 }
705 return TablePlusData<T>(std::move(values),
706 rotate ? col_category_labels : row_category_labels, // rows
707 rotate ? row_category_labels : col_category_labels, // columns
708 top_left_label);
709 }
710 }
711
712 void TrackTruthMatchingBaseAlg::printData2D(const std::vector<std::string> &row_category_labels,
713 const std::vector<std::string> &col_category_labels,
714 const std::string &top_left_label,
715 std::vector< std::array< ActsUtils::Stat, kNCategorisedStat> > &stat_per_category,
716 std::vector< std::array< std::size_t, kNCategorisedCounter> > &counts_per_category,
717 bool rotate) const
718 {
719 if (!row_category_labels.empty() && !col_category_labels.empty()) {
720 if (row_category_labels.size() * col_category_labels.size() > counts_per_category.size() ) {
721 ATH_MSG_ERROR( "Mismatch between category labels and number of counters (logic error -> fix needed):"
722 << row_category_labels.size() << " * " << col_category_labels.size()
723 << " > " << counts_per_category.size() );
724 }
725 std::vector<unsigned int> column_precision;
726 column_precision.resize( rotate ? row_category_labels.size() : col_category_labels.size(), 3u);
727 assert( stat_per_category.size() == counts_per_category.size());
728 msg() << "Hit efficiency : contributing hits over all hits of best matching truth particle" << std::endl
729 << create2DTable( row_category_labels, col_category_labels, top_left_label, stat_per_category,
730 [](const std::array< ActsUtils::Stat, kNCategorisedStat> &stat) {
731 return stat.at(kHitEfficiency).mean();
732 },
733 rotate)
734 .columnWidth(10)
735 .precision(std::vector<unsigned int>(column_precision))
736 << std::endl;
737 msg() << "Hit purity : contributing hits of best matching truth particle over all hits on track" << std::endl
738 << create2DTable( row_category_labels, col_category_labels, top_left_label, stat_per_category,
739 [](const std::array< ActsUtils::Stat, kNCategorisedStat> &stat) {
740 return stat.at(kHitPurity).mean();
741 },
742 rotate)
743 .columnWidth(10)
744 .precision(std::vector<unsigned int>(column_precision))
745 << std::endl;
746 msg() << "Match probability : weighted common hit sum of best matching truth particle over total track weighted hit sum" << std::endl
747 << create2DTable( row_category_labels, col_category_labels, top_left_label, stat_per_category,
748 [](const std::array< ActsUtils::Stat, kNCategorisedStat> &stat) {
749 return stat.at(kMatchProbability).mean();
750 },
751 rotate)
752 .columnWidth(10)
753 .precision(std::vector<unsigned int>(column_precision))
754 << std::endl;
755
756 if (m_computeTrackRecoEfficiency.value()) {
757 msg() << "Reco efficiency : tracks with assoc. truth particle over all selected truth particles with assoc. measurements."
758 << std::endl
759 << create2DTable( row_category_labels, col_category_labels, top_left_label, counts_per_category,
760 [](const std::array< std::size_t, kNCategorisedCounter> &counter) {
761 return computeRatio( counter[kNParticleWithAssociatedTrack],
762 counter[kNTotalParticles] )[0];
763 },
764 rotate)
765 .columnWidth(10)
766 .precision(std::move(column_precision))
767 << std::endl;
768 }
769 }
770 }
771
773 if (m_weights.size() != s_NMeasurementTypes) {
774 ATH_MSG_FATAL( "There must be exactly one weight per measurement type. But got "
775 << m_weights.size() << " != " << s_NMeasurementTypes);
776 return StatusCode::FAILURE;
777 }
779 ATH_MSG_FATAL( "There must be exactly one weight for computing the matching probability per measurement type. But got "
780 << m_weightsForProb.size() << " != " << s_NMeasurementTypes);
781 return StatusCode::FAILURE;
782 }
783 for (unsigned int type_i=0; type_i<s_NMeasurementTypes; ++type_i) {
784 if (m_weightsForProb[type_i]<0. || m_weights[type_i]<0. || (m_weights[type_i]>0) != (m_weightsForProb[type_i]>0.)) {
785 ATH_MSG_FATAL( "Invalid weights (should be positive) or inconsistency of weights which are zero (match prob. weights, weights):"
786 << m_weightsForProb[type_i] << " vs " << m_weights[type_i]);
787 return StatusCode::FAILURE;
788 }
789 }
790 return StatusCode::SUCCESS;
791 }
792
794 const std::vector<float> &weights) {
795 assert( weights.size() == counts.size());
796 double sum=0.;
797 for (unsigned int count_i=0; count_i < counts.size(); ++count_i) {
798 sum += counts[count_i] * weights[count_i];
799 }
800 return sum;
801 }
802
804 const std::vector<float> &weights) {
805 assert( weights.size() == noise_counts.size());
806 double sum=0.;
807 for (unsigned int count_i=0; count_i < noise_counts.size(); ++count_i) {
808 sum -= weights[count_i] * noise_counts[count_i] - noise_counts[count_i];
809 }
810 return sum;
811 }
812}
Scalar eta() const
pseudorapidity method
#define endmsg
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_ERROR(x)
#define ATH_MSG_FATAL(x)
virtual void lock()=0
Interface to allow an object to lock itself when made const in SG.
static Double_t a
#define sqr(t)
size_t size() const
Number of registered mappings.
void rotate(double angler, GeoTrf::Vector2D &vector)
const double width
TableUtils::StatTable< T > makeTable(const std::array< T, N > &counter, const std::array< std::string, N > &label)
Definition TableUtils.h:543
Container for hit counts per track Contains hit counts per associated truth particle and the total hi...
const container & countsPerTruthParticle() const
vector with counts per associated truth particle (read only)
HitCounterArray & noiseCounts()
Noise hit counts per track.
HitCounterArray & totalCounts()
Total hit counts per track.
void checkBinOrder(const std::vector< float > &bin_edges, const std::string &bin_label) const
check that bins are in increasing order.
static constexpr unsigned int s_NMeasurementTypes
void printData2D(const std::vector< std::string > &row_category_labels, const std::vector< std::string > &col_category_labels, const std::string &top_left_label, std::vector< std::array< ActsUtils::Stat, kNCategorisedStat > > &stat_per_category, std::vector< std::array< std::size_t, kNCategorisedCounter > > &counts_per_category, bool rotate) const
SG::ReadHandleKey< TruthParticleHitCounts > m_truthHitCounts
TruthMatchResult analyseTrackTruth(const TruthParticleHitCounts &truth_particle_hit_counts, const HitCountsPerTrack &track_hit_counts, EventStat &event_stat) const
DebugCounter< TrackFindingValidationDebugHists > m_debugCounter
void printCategories(const std::vector< std::string > &pt_category_labels, const std::vector< std::string > &eta_category_labels, std::vector< std::string > &counter_labels, std::vector< std::array< ActsUtils::Stat, kNCategorisedStat > > &stat_per_category, std::vector< std::array< std::size_t, kNCategorisedCounter > > &counts_per_category, const std::string &top_left_label, bool print_sub_categories) const
EventStatBase< TrackFindingValidationDetailedStat > EventStat
static double noiseCorrection(const ActsTrk::HitCounterArray &noise_counts, const std::vector< float > &weights)
std::size_t getPtPdgIdStatCategory(float pt, int pdg_id) const
Return the category based on the PDG ID.
static double weightedCountSum(const ActsTrk::HitCounterArray &counts, const std::vector< float > &weights)
Property< std::vector< float > > m_statPtBins
void postProcessEventStat(const TruthParticleHitCounts &truth_particle_hit_counts, std::size_t n_tracks, EventStat &event_stat) const
Gaudi::Property< std::vector< float > > m_weightsForProb
std::size_t getPtEtaStatCategory(float pt, float eta) const
Return the category based on the provided eta value.
TrackTruthMatchingBaseAlg(const std::string &name, ISvcLocator *pSvcLocator)
Property< std::vector< float > > m_statEtaBins
Gaudi::Property< std::vector< float > > m_weights
ToolHandle< IAthSelectionTool > m_truthSelectionTool
void add(double val)
Gather statistics and fill the histogram if not disabled.
Definition StatUtils.h:117
bool msgLvl(const MSG::Level lvl) const
An algorithm that can be simultaneously executed in multiple threads.
int pdg_id() const
PDG ID code.
virtual double pt() const override final
The transverse momentum ( ) of the particle.
virtual double eta() const override final
The pseudorapidity ( ) of the particle.
std::string tail(std::string s, const std::string &pattern)
tail of a string
std::string head(std::string s, const std::string &pattern)
head of a string
The AlignStoreProviderAlg loads the rigid alignment corrections and pipes them through the readout ge...
std::unordered_map< const xAOD::TruthParticle *, HitCounterArray > TruthParticleHitCounts
constexpr bool TrackFindingValidationDetailedStat
std::ostream & operator<<(std::ostream &ostr, const DetectorType type)
constexpr bool TrackFindingValidationDebugHists
void dumpStat(T_Stream &out, const Stat &stat)
Dump the given statistics object to the given output stream.
Definition StatUtils.h:63
const SG::AuxVectorData * container() const
Return the container holding this element.
float computeRatio(std::size_t numerator, std::size_t denominator)
Definition TableUtils.h:434
std::size_t maxLabelWidth(const T_Collection &col)
Definition TableUtils.h:310
std::string makeEtaBinLabel(const std::vector< float > &eta_bins, std::size_t eta_bin_i, bool abs_eta=false)
Definition TableUtils.h:534
std::string makeBinLabel(const std::string &variable_name, const std::vector< float > &bins, std::size_t bin_i, bool abs_value=false, int precision=1)
Definition TableUtils.h:505
STL namespace.
TruthParticle_v1 TruthParticle
Typedef to implementation.
void incrementTotal(unsigned int eta_category_i, unsigned int pdg_id_category_i)
BaseStat< DetailEnabled > & operator+=(const BaseStat< DetailEnabled > &event_stat)
void printStatTables(const TrackTruthMatchingBaseAlg &parent, const std::vector< float > &statPtBins, const std::vector< float > &statEtaBins, std::vector< int > &pdgId, bool printDetails, bool pdgIdCategorisation, bool useAbsEtaForStat)
void fillMeasForTruthParticleWithoutCount(double weighted_measurement_sum) const
void fillTruthMatchProb(const std::array< float, 2 > &best_match_prob) const
void fill(unsigned int eta_category_i, unsigned int pdg_id_category_i, float hit_efficiency, float hit_purity, float match_prob, const xAOD::TruthParticle *best_match)
float m_hitPurity
fraction of hits originting from best match over total reco hits
float m_matchProbability
the matching probability based on weighted hit sums
float m_hitEfficiency
fraction of hits originting from best match over total best match hits
const xAOD::TruthParticle * m_truthParticle
best matching truth particle or nullptr