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