FairShip
Loading...
Searching...
No Matches
CaloScoringPlanePID.cxx
Go to the documentation of this file.
1// SPDX-License-Identifier: LGPL-3.0-or-later
2// SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP
3// Collaboration
4
6
7#include <algorithm>
8#include <array>
9#include <cmath>
10#include <cstdlib>
11#include <map>
12#include <sstream>
13#include <stdexcept>
14#include <string>
15#include <utility>
16#include <vector>
17
19#include "FairLogger.h"
20#include "TDatabasePDG.h"
21#include "TParticlePDG.h"
22#include "TRandom.h"
23
24namespace {
25
26constexpr Double_t kRowSumTolerance = 1e-6;
27
28[[noreturn]] void Invalid(const std::string& what) {
29 throw std::invalid_argument("CaloScoringPlanePID::Set: " + what);
30}
31
32// PDG Monte Carlo numbering scheme: mesons and baryons have a non-zero quark
33// digit n_q2 (hundreds). Codes >= 9900000 are generator-specific or BSM
34// (e.g. HNL 9900015), codes >= 1e9 are nuclei.
35bool IsHadronCode(Int_t pdg) {
36 const Int_t a = std::abs(pdg);
37 if (a >= 9900000) return false;
38 return (a / 100) % 10 != 0;
39}
40
41using Species = CaloScoringPlanePID::Species;
42using Row = std::array<Double_t, CaloScoringPlanePID::kNSpecies>;
43
44void RequireFinite(Double_t energy) {
45 if (!std::isfinite(energy)) {
46 std::ostringstream os;
47 os << "CaloScoringPlanePID: energy must be finite, not " << energy;
48 throw std::invalid_argument(os.str());
49 }
50}
51
52// The only outcome of a matrix row, or kUnknown if more than one is possible
53// and a number has to be drawn.
54Species OnlyOutcome(const Row& row) {
55 Species only = CaloScoringPlanePID::kUnknown;
56 for (Int_t j = 0; j < CaloScoringPlanePID::kNSpecies; ++j) {
57 if (row[j] <= 0.) continue;
60 only = static_cast<Species>(j);
61 }
62 return only;
63}
64
65// Outcome of the row of true species s for the uniform number u.
66Species Draw(const Row& row, Species s, Double_t u) {
67 double cumulative = 0.;
68 Int_t last = s;
69 for (Int_t j = 0; j < CaloScoringPlanePID::kNSpecies; ++j) {
70 const double p = row[j];
71 if (p <= 0.) continue;
72 last = j;
73 cumulative += p;
74 if (u < cumulative) return static_cast<Species>(j);
75 }
76 // u at (or, through rounding, above) the row total: last non-empty outcome.
77 return static_cast<Species>(last);
78}
79
80} // namespace
81
83
85 fEnergies = {1.0};
86 fMatrices.assign(9, 0.);
87 for (Int_t i = 0; i < kNSpecies; ++i) fMatrices[3 * i + i] = 1.;
88 fOverrides.clear();
89 fLogInterpolation = kFALSE;
90}
91
92void CaloScoringPlanePID::Set(const std::vector<Double_t>& energies,
93 const std::vector<Double_t>& matrices,
94 const std::map<Int_t, Int_t>& overrides,
95 Bool_t logInterpolation) {
96 // Validate everything before changing the model, so that a rejected model
97 // leaves the previous one in place.
98 const size_t n = energies.size();
99 if (n == 0) Invalid("no energy points");
100 if (matrices.size() != 9 * n) {
101 Invalid("expected " + std::to_string(9 * n) +
102 " matrix values (9 per energy point), got " +
103 std::to_string(matrices.size()));
104 }
105 for (size_t k = 0; k < n; ++k) {
106 std::ostringstream where;
107 where << "energy point " << k << " (" << energies[k] << " GeV)";
108 if (!std::isfinite(energies[k])) Invalid(where.str() + ": not finite");
109 if (k > 0 && energies[k] <= energies[k - 1]) {
110 Invalid(where.str() + ": energies must be strictly increasing");
111 }
112 if (logInterpolation && energies[k] <= 0.) {
113 Invalid(where.str() + ": log interpolation needs positive energies");
114 }
115 for (Int_t i = 0; i < kNSpecies; ++i) {
116 const std::string row = where.str() + ", true " + SpeciesName(i) + " row";
117 double sum = 0.;
118 for (Int_t j = 0; j < kNSpecies; ++j) {
119 const double x = matrices[9 * k + static_cast<size_t>(3 * i + j)];
120 if (!std::isfinite(x)) Invalid(row + ": entry not finite");
121 if (x < 0.) Invalid(row + ": negative entry");
122 sum += x;
123 }
124 if (std::fabs(sum - 1.) > kRowSumTolerance) {
125 std::ostringstream os;
126 os << row << " sums to " << sum << ", expected 1";
127 Invalid(os.str());
128 }
129 }
130 }
131 std::map<Int_t, Int_t> byAbsPdg;
132 for (const auto& [pdg, species] : overrides) {
133 if (species < kUnknown || species >= kNSpecies) {
134 Invalid("override for PDG code " + std::to_string(pdg) + ": species " +
135 std::to_string(species) +
136 " is not -1 (unknown), 0 (electron), 1 (hadron) or 2 (muon)");
137 }
138 const auto [it, inserted] = byAbsPdg.emplace(std::abs(pdg), species);
139 if (!inserted && it->second != species) {
140 Invalid("conflicting overrides for |PDG code| " +
141 std::to_string(std::abs(pdg)));
142 }
143 }
144 fEnergies = energies;
145 fMatrices = matrices;
146 fOverrides = std::move(byAbsPdg);
147 fLogInterpolation = logInterpolation;
148}
149
151 const Int_t a = std::abs(pdg);
152 if (auto it = fOverrides.find(a); it != fOverrides.end()) {
153 return static_cast<Species>(it->second);
154 }
155 if (a == 11) return kElectron;
156 if (a == 13) return kMuon;
157 if (IsHadronCode(a)) return kHadron;
158 return kUnknown;
159}
160
162 Double_t energy, Int_t trueSpecies) const {
163 // A NaN would pass both clamps below and make upper_bound return end().
164 RequireFinite(energy);
165 Row row{};
166 const auto rowAt = [&](size_t k) {
167 for (Int_t j = 0; j < kNSpecies; ++j) row[j] = At(k, trueSpecies, j);
168 return row;
169 };
170 const size_t n = fEnergies.size();
171 if (n == 1 || energy <= fEnergies.front()) return rowAt(0);
172 if (energy >= fEnergies.back()) return rowAt(n - 1);
173 const auto hi = static_cast<size_t>(
174 std::upper_bound(fEnergies.begin(), fEnergies.end(), energy) -
175 fEnergies.begin());
176 const size_t lo = hi - 1;
177 const double w =
179 ? std::log(energy / fEnergies[lo]) /
180 std::log(fEnergies[hi] / fEnergies[lo])
181 : (energy - fEnergies[lo]) / (fEnergies[hi] - fEnergies[lo]);
182 for (Int_t j = 0; j < kNSpecies; ++j) {
183 row[j] = (1. - w) * At(lo, trueSpecies, j) + w * At(hi, trueSpecies, j);
184 }
185 return row;
186}
187
188std::vector<Double_t> CaloScoringPlanePID::Matrix(Double_t energy) const {
189 std::vector<Double_t> m(9);
190 for (Int_t i = 0; i < kNSpecies; ++i) {
191 const Row row = InterpolatedRow(energy, i);
192 std::copy(row.begin(), row.end(), m.begin() + 3L * i);
193 }
194 return m;
195}
196
198 Species recoSpecies,
199 Double_t energy) const {
200 for (const Int_t s :
201 {static_cast<Int_t>(trueSpecies), static_cast<Int_t>(recoSpecies)}) {
202 if (s < kUnknown || s >= kNSpecies) {
203 throw std::out_of_range("CaloScoringPlanePID: species " +
204 std::to_string(s) + " out of range");
205 }
206 }
207 RequireFinite(energy);
208 if (trueSpecies == kUnknown) return recoSpecies == kUnknown ? 1. : 0.;
209 if (recoSpecies == kUnknown) return 0.;
210 return InterpolatedRow(energy, trueSpecies)[recoSpecies];
211}
212
214 Double_t energy,
215 Double_t u) const {
216 const Species s = TrueSpecies(pdg);
217 if (s == kUnknown || !std::isfinite(energy)) return kUnknown;
218 return Draw(InterpolatedRow(energy, s), s, u);
219}
220
222 Double_t energy,
223 TRandom& rng) const {
224 const Species s = TrueSpecies(pdg);
225 if (s == kUnknown || !std::isfinite(energy)) return kUnknown;
226 const Row row = InterpolatedRow(energy, s);
227 // Draw only when the outcome can vary, so that a fixed outcome leaves the
228 // generator's sequence untouched.
229 if (const Species only = OnlyOutcome(row); only != kUnknown) return only;
230 return Draw(row, s, rng.Rndm());
231}
232
234 const CaloScoringPlanePoint& point, TRandom& rng) const {
235 // Skip the energy (a TDatabasePDG lookup) for photons, nuclei, ...
236 if (TrueSpecies(point.PdgCode()) == kUnknown) return kUnknown;
237 return Identify(point.PdgCode(), Energy(point), rng);
238}
239
241 const double p2 = point.GetPx() * point.GetPx() +
242 point.GetPy() * point.GetPy() +
243 point.GetPz() * point.GetPz();
244 double mass = 0.;
245 if (const TParticlePDG* particle =
246 TDatabasePDG::Instance()->GetParticle(point.PdgCode())) {
247 mass = particle->Mass();
248 }
249 return std::sqrt(p2 + mass * mass);
250}
251
252const char* CaloScoringPlanePID::SpeciesName(Int_t species) {
253 switch (species) {
254 case kElectron:
255 return "electron";
256 case kHadron:
257 return "hadron";
258 case kMuon:
259 return "muon";
260 default:
261 return "unknown";
262 }
263}
264
266 LOG(info) << "CaloScoringPlanePID: " << fEnergies.size()
267 << " energy point(s), " << (fLogInterpolation ? "log" : "linear")
268 << " interpolation; rows = true, columns = identified "
269 "(electron, hadron, muon)";
270 for (size_t k = 0; k < fEnergies.size(); ++k) {
271 for (Int_t i = 0; i < kNSpecies; ++i) {
272 LOG(info) << " E = " << fEnergies[k] << " GeV " << SpeciesName(i)
273 << ": " << At(k, i, 0) << " " << At(k, i, 1) << " "
274 << At(k, i, 2);
275 }
276 }
277 for (const auto& [pdg, s] : fOverrides) {
278 LOG(info) << " override |pdg| " << pdg << " -> " << SpeciesName(s);
279 }
280}
constexpr Double_t m
std::vector< Double_t > fEnergies
GeV, strictly increasing.
static constexpr Int_t kNSpecies
Double_t Probability(Species trueSpecies, Species recoSpecies, Double_t energy) const
static Double_t Energy(const CaloScoringPlanePoint &point)
std::vector< Double_t > fMatrices
9 per energy, row-major, internal order
std::array< Double_t, kNSpecies > Row
Double_t At(size_t iEnergy, Int_t i, Int_t j) const
static const char * SpeciesName(Int_t species)
std::vector< Double_t > Matrix(Double_t energy) const
Row InterpolatedRow(Double_t energy, Int_t trueSpecies) const
std::map< Int_t, Int_t > fOverrides
|pdg| -> Species
void Set(const std::vector< Double_t > &energies, const std::vector< Double_t > &matrices, const std::map< Int_t, Int_t > &overrides={}, Bool_t logInterpolation=kFALSE)
Species Identify(Int_t pdg, Double_t energy, Double_t u) const
Species TrueSpecies(Int_t pdg) const
Int_t PdgCode() const