delphi-edm4hep
DELPHI SDST/FDST -> EDM4hep converter
Loading...
Searching...
No Matches
delphi_btag_check.cpp
Go to the documentation of this file.
1// delphi_btag_check — validate the b-tag payload of a converted file.
2//
3// delphi_btag_check [--source sDST|fDST] <input.edm4hep.root> <run|data>
4//
5// The second argument states what the run numbers should look like: `data`
6// for positive run numbers, or `mc` for the negative ones AABTAG uses to pick
7// its simulation calibration.
8//
9// Both b-tags are emitted on every file, so this checks that both are there
10// and that the recalculated one is self-consistent: the per-track rows match
11// the track count AABTAG reports, each row links to a particle, the values sit
12// in their allowed ranges, and the vertex agrees with the number of tracks it
13// says it fitted.
14//
15// Exit 0 when everything checks out, 2 otherwise. The single status line is
16// meant to be greppable from CI.
17
19
20#include <edm4hep/ParticleIDCollection.h>
21#include <edm4hep/TrackCollection.h>
22#include <edm4hep/TrackState.h>
23#include <edm4hep/VertexCollection.h>
24#include <podio/Frame.h>
25#include <podio/ROOTReader.h>
26
27#include <cstdint>
28#include <exception>
29#include <iostream>
30#include <limits>
31#include <optional>
32#include <string>
33#include <string_view>
34#include <vector>
35
37
38namespace {
39
40// CHI2TR is a truncated quadratic form, so it rounds slightly below zero for a
41// track sitting on the vertex. Observed floor over 3459 attached tracks is
42// -0.03, against a median of 1.4.
43constexpr float kChi2RoundGuard = 0.1f;
44
45
46struct Stats {
47 std::uint64_t entries = 0;
48 std::uint64_t framesChecked = 0;
49 std::uint64_t frameReadFailures = 0;
50 std::uint64_t missingParameters = 0;
51 std::uint64_t missingCollections = 0;
52 std::uint64_t sourcePrefixFailures = 0;
53 std::uint64_t runSignFailures = 0;
54 std::uint64_t probabilityFailures = 0;
55 std::uint64_t tagRowCountFailures = 0;
56 std::uint64_t tagParamCountFailures = 0;
57 // Rows the layout check rejected, and whose domain checks therefore never
58 // ran. Reported separately so a skipped row cannot be read as a passed one.
59 std::uint64_t tagRowsUnchecked = 0;
60 std::uint64_t tagDomainFailures = 0;
61 std::uint64_t unresolvedParticles = 0;
62 std::uint64_t impactStateCountFailures = 0;
63 std::uint64_t impactDomainFailures = 0;
64 std::uint64_t vertexFailures = 0;
65 std::uint64_t attachedConsistencyFailures = 0;
66 std::uint64_t beamspotErrorEvents = 0;
67
68 std::uint64_t failures() const {
69 return frameReadFailures + missingParameters + missingCollections +
70 sourcePrefixFailures + runSignFailures + probabilityFailures +
71 tagRowCountFailures + tagParamCountFailures + tagDomainFailures +
72 impactStateCountFailures + impactDomainFailures + vertexFailures +
73 attachedConsistencyFailures;
74 }
75};
76
77void usage(const char* argv0) {
78 std::cerr << "usage: " << argv0
79 << " [--source sDST|fDST] <input.edm4hep.root> <data|mc>\n";
80}
81
82// A value computed in single precision can land one ULP outside a closed
83// bound: a thrust of exactly 1, which is physical, comes back as 1 + 2^-23.
84constexpr float kBoundSlack = std::numeric_limits<float>::epsilon();
85
86// A probability is either the not-computed sentinel (NaN) or in [0, 1].
87bool okProbability(float v) {
88 return std::isnan(v) ||
89 (domain::isFinite(v) && v >= -kBoundSlack && v <= 1.f + kBoundSlack);
90}
91
92// A thrust-axis component is a direction cosine, so it spans [-1, 1].
93bool okCosine(float v) {
94 return std::isnan(v) || (domain::isFinite(v) &&
95 v >= -1.f - kBoundSlack && v <= 1.f + kBoundSlack);
96}
97
98} // namespace
99
100int main(int argc, char** argv) {
101 std::string source = "sDST";
102 std::vector<std::string> positional;
103 for (int i = 1; i < argc; ++i) {
104 const std::string arg = argv[i];
105 if (arg == "--source") {
106 if (++i >= argc) { std::cerr << "error: --source requires sDST or fDST\n"; return 1; }
107 source = argv[i];
108 } else if (arg.rfind("--source=", 0) == 0) {
109 source = arg.substr(std::string("--source=").size());
110 } else if (arg.rfind("--", 0) == 0) {
111 std::cerr << "error: unknown option: " << arg << "\n";
112 return 1;
113 } else {
114 positional.push_back(arg);
115 }
116 }
117 if (positional.size() != 2) { usage(argv[0]); return 1; }
118 if (source != "sDST" && source != "fDST") {
119 std::cerr << "error: --source must be sDST or fDST, got: " << source << "\n";
120 return 1;
121 }
122 const std::string& input = positional[0];
123 const std::string& kind = positional[1];
124 if (kind != "data" && kind != "mc") {
125 std::cerr << "error: expected data or mc, got: " << kind << "\n";
126 usage(argv[0]);
127 return 1;
128 }
129 const bool expectNegativeRun = (kind == "mc");
130
131 const std::string cfg = source + "_BTAGCFG_";
132 const std::string aa = source + "_AABTAG_";
133 const std::string btg = source + "_BTG_";
134 // Identity parameters stay under the sDST prefix in both passes: pass 2
135 // copies them and has no fDST_EVT_ domain of its own.
136 const std::string evt = "sDST_EVT_";
137
138 Stats stats;
139 try {
140 podio::ROOTReader reader;
141 reader.openFile(input);
142 stats.entries = reader.getEntries("events");
143
144 for (std::uint64_t i = 0; i < stats.entries; ++i) {
145 podio::Frame frame(reader.readEntry("events", i));
146 ++stats.framesChecked;
147
148 // ---- provenance that still varies ----
149 const auto prefix = frame.getParameter<std::string>(cfg + "SourcePrefix");
150 if (!prefix) ++stats.missingParameters;
151 else if (*prefix != source) ++stats.sourcePrefixFailures;
152
153 const auto beamspot = frame.getParameter<int>(cfg + "BeamSpotErrorCode");
154 if (!beamspot) ++stats.missingParameters;
155 else if (*beamspot != 0) ++stats.beamspotErrorEvents;
156
157 // AABTAG selects its calibration by the sign of the run number, so a
158 // simulation file converted as data is a real error, not cosmetics.
159 const auto run = frame.getParameter<int>(evt + "runNumber");
160 if (!run) ++stats.missingParameters;
161 else if ((*run < 0) != expectNegativeRun) ++stats.runSignFailures;
162
163 // ---- both tags present, both in range ----
164 for (const std::string& tag : {btg, aa}) {
165 for (const char* name : {"ProbNegIP", "ProbPosIP", "ProbAllIP", "ThrustAxis"}) {
166 const auto v = frame.getParameter<std::vector<float>>(tag + name);
167 if (!v) { ++stats.missingParameters; continue; }
168 if (v->size() != 3) { ++stats.probabilityFailures; continue; }
169 const bool cosine = std::string_view(name) == "ThrustAxis";
170 for (const float x : *v) {
171 if (cosine ? !okCosine(x) : !okProbability(x)) ++stats.probabilityFailures;
172 }
173 }
174 const auto thrust = frame.getParameter<float>(tag + "ThrustValue");
175 if (!thrust) ++stats.missingParameters;
176 else if (!okProbability(*thrust)) ++stats.probabilityFailures;
177 }
178
179 const auto nTracks = frame.getParameter<int>(aa + "NTracks");
180 const auto nAttached = frame.getParameter<int>(aa + "NTracksAttached");
181 const auto valid = frame.getParameter<int>(aa + "Valid");
182 if (!nTracks || !nAttached || !valid) { ++stats.missingParameters; continue; }
183
184 const auto names = frame.getAvailableCollections();
185 const auto has = [&](const std::string& n) {
186 for (const auto& x : names) if (x == n) return true;
187 return false;
188 };
189
190 // ---- per-track rows ----
191 const std::string tagName = aa + "TrackTag";
192 if (!has(tagName)) { ++stats.missingCollections; continue; }
193 const auto& tags = frame.get<edm4hep::ParticleIDCollection>(tagName);
194 if (static_cast<int>(tags.size()) != *nTracks) ++stats.tagRowCountFailures;
195
196 std::uint64_t attachedRows = 0;
197 for (const auto& tag : tags) {
198 const auto params = tag.getParameters();
199 if (params.size() != domain::kTrCount) {
200 ++stats.tagParamCountFailures;
201 ++stats.tagRowsUnchecked;
202 continue;
203 }
204 if (!okProbability(params[domain::kTrProb]) ||
205 !okProbability(params[domain::kTrProbZ])) ++stats.tagDomainFailures;
206 if (!domain::isNonnegativeFinite(params[domain::kTrChi2Vd])) ++stats.tagDomainFailures;
207 // CHI2TR is defined only where AABTAG attached the track; the
208 // converter emits NaN elsewhere, and the checker holds it to that.
209 const bool attached =
210 static_cast<std::int32_t>(params[domain::kTrAttached]) == 1;
211 if (attached) {
212 if (!domain::isFinite(params[domain::kTrChi2Tr]) ||
213 params[domain::kTrChi2Tr] < -kChi2RoundGuard)
214 ++stats.tagDomainFailures;
215 } else if (!std::isnan(params[domain::kTrChi2Tr])) {
216 ++stats.tagDomainFailures;
217 }
218 if (!domain::isPositiveFinite(params[domain::kTrMomentum])) ++stats.tagDomainFailures;
219 if (!domain::isValidSignedCount(static_cast<std::int32_t>(params[domain::kTrNVdp]), domain::kMaxVdHits) ||
220 !domain::isValidSignedCount(static_cast<std::int32_t>(params[domain::kTrNVdpz]), domain::kMaxVdHits) ||
221 !domain::isValidSignedCount(static_cast<std::int32_t>(params[domain::kTrNLay]), domain::kMaxVdLayers) ||
222 !domain::isValidSignedCount(static_cast<std::int32_t>(params[domain::kTrNLayz]), domain::kMaxVdLayers))
223 ++stats.tagDomainFailures;
224 if (!domain::isValidUsedForTag(static_cast<std::int32_t>(params[domain::kTrIsrt]))) ++stats.tagDomainFailures;
225 if (!domain::isValidAttachedFlag(static_cast<std::int32_t>(params[domain::kTrAttached]))) ++stats.tagDomainFailures;
226 // The AAJETS / AASCND / AAJESV words. Each bound below comes from the
227 // algorithm -- an array cap or the list of codes a variable is
228 // assigned in aabtagxx.car -- rather than from the range a sample
229 // happens to show, so a failure here is corruption and not a tail.
230 if (!domain::isValidJetIndex(static_cast<std::int32_t>(params[domain::kTrIjet])) ||
231 !domain::isValidJetIndex(static_cast<std::int32_t>(params[domain::kTrIjsv])))
232 ++stats.tagDomainFailures;
233 if (!domain::isValidHemisphere(static_cast<std::int32_t>(params[domain::kTrIthr]))) ++stats.tagDomainFailures;
234 if (!domain::isUnitSign(params[domain::kTrPhivSign])) ++stats.tagDomainFailures;
235 if (!domain::isValidInsv(static_cast<std::int32_t>(params[domain::kTrInsv]))) ++stats.tagDomainFailures;
236 if (!domain::isValidTrackStatus(static_cast<std::int32_t>(params[domain::kTrIst]))) ++stats.tagDomainFailures;
237 if (!domain::isFinite(params[domain::kTrRpdt])) ++stats.tagDomainFailures;
238 // DISTJ / ERRTJ / the PHIV length are a measurement or a placeholder
239 // together, so NaN is expected and only the pairing is enforced: a
240 // finite distance must be non-negative and carry a positive error.
243 ++stats.tagDomainFailures;
244 if (!std::isnan(params[domain::kTrDistj]) &&
248 ++stats.tagDomainFailures;
249 // ILUND is deliberately unchecked: the value indexes a JETSET record
250 // this converter does not ship, so any bound would be a guess.
251 if (attached) ++attachedRows;
252 if (!tag.getParticle().isAvailable()) ++stats.unresolvedParticles;
253 }
254
255 // ---- impact parameters, which ride on the track ----
256 const std::string trackName = source + "_TRAC_Tracks";
257 if (!has(trackName)) { ++stats.missingCollections; continue; }
258 int atVertex = 0;
259 for (const auto& track : frame.get<edm4hep::TrackCollection>(trackName)) {
260 for (const auto& state : track.getTrackStates()) {
261 if (state.location != edm4hep::TrackState::AtVertex) continue;
262 ++atVertex;
263 if (!domain::isFinite(state.D0) || !domain::isFinite(state.Z0))
264 ++stats.impactDomainFailures;
265 // Only the two measured variances are filled; the rest are NaN.
266 const float vD0 = state.covMatrix[0];
267 const float vZ0 = state.covMatrix[9];
269 ++stats.impactDomainFailures;
270 }
271 }
272 if (atVertex != *nTracks) ++stats.impactStateCountFailures;
273
274 // ---- the vertex AABTAG fitted ----
275 const std::string pvName = aa + "PrimaryVertex";
276 if (!has(pvName)) { ++stats.missingCollections; continue; }
277 const auto& pvs = frame.get<edm4hep::VertexCollection>(pvName);
278 const std::size_t expectedPvs = (*valid == 1) ? 1u : 0u;
279 if (pvs.size() != expectedPvs) ++stats.vertexFailures;
280 for (const auto& pv : pvs) {
281 if (!pv.isPrimary() ||
282 pv.getAlgorithmType() != domain::kPrimaryVertexAlgorithmType ||
283 !domain::isFinite(pv.getPosition().x) ||
284 !domain::isFinite(pv.getPosition().y) ||
285 !domain::isFinite(pv.getPosition().z) ||
287 ++stats.vertexFailures;
288 }
289 // chi2 is only meaningful where a fit happened. AABTAG leaves a
290 // numerically-zero value on the beamspot-only vertices it reports
291 // with ndf 0.
292 if (pv.getNdf() > 0 && !domain::isNonnegativeFinite(pv.getChi2())) {
293 ++stats.vertexFailures;
294 }
295 // The vertex relation and the per-track flag are independent routes to
296 // the same number; they must agree.
297 if (static_cast<int>(pv.getParticles().size()) != *nAttached)
298 ++stats.attachedConsistencyFailures;
299 }
300 if (attachedRows != static_cast<std::uint64_t>(*nAttached))
301 ++stats.attachedConsistencyFailures;
302 }
303 } catch (const std::exception& error) {
304 std::cerr << "error: validation failed: " << error.what() << "\n";
305 ++stats.frameReadFailures;
306 }
307
308 const bool ok = stats.failures() == 0;
309 std::cout << "status=" << (ok ? "PASS" : "FAIL")
310 << " entries=" << stats.entries
311 << " source=" << source
312 << " expected=" << kind
313 << " frames_checked=" << stats.framesChecked
314 << " failures=" << stats.failures()
315 << " frame_read_failures=" << stats.frameReadFailures
316 << " missing_parameters=" << stats.missingParameters
317 << " missing_collections=" << stats.missingCollections
318 << " source_prefix_failures=" << stats.sourcePrefixFailures
319 << " run_sign_failures=" << stats.runSignFailures
320 << " probability_failures=" << stats.probabilityFailures
321 << " tag_row_count_failures=" << stats.tagRowCountFailures
322 << " tag_param_count_failures=" << stats.tagParamCountFailures
323 << " tag_rows_unchecked=" << stats.tagRowsUnchecked
324 << " tag_domain_failures=" << stats.tagDomainFailures
325 << " impact_state_count_failures=" << stats.impactStateCountFailures
326 << " impact_domain_failures=" << stats.impactDomainFailures
327 << " vertex_failures=" << stats.vertexFailures
328 << " attached_consistency_failures=" << stats.attachedConsistencyFailures
329 << " unresolved_particles=" << stats.unresolvedParticles
330 << " beamspot_error_events=" << stats.beamspotErrorEvents
331 << "\n";
332 return ok ? 0 : 2;
333}
int main(int argc, char **argv)
static void usage(const char *argv0)
bool isValidAttachedFlag(std::int32_t value)
constexpr int kPrimaryVertexAlgorithmType
bool isValidHemisphere(std::int32_t value)
constexpr std::int32_t kMaxVdLayers
bool isNonnegativeFinite(float value)
bool isValidSignedCount(std::int32_t value, std::int32_t maximum)
constexpr std::int32_t kMaxVdHits
bool isValidJetIndex(std::int32_t value)
bool isConsistentPlaceholder(float phivDist, float distj)
bool isValidUsedForTag(std::int32_t value)
bool isValidInsv(std::int32_t value)
bool isValidTrackStatus(std::int32_t value)
bool isSensiblePrimaryVertexNdf(int value)
@ kTrInsv
INSV SV hypothesis using the track (+100 flags)
@ kTrIthr
ITHR thrust hemisphere (1 or 2)
@ kTrProbZ
TRPRZ the same, using z
@ kTrIsrt
ISRT 0 if the track was not used by the tag
@ kTrErrtj
ERRTJ error on kTrDistj, mm; NaN on the same rows
@ kTrAttached
1 if AABTAG attached the track to its primary vertex
@ kTrChi2Tr
CHI2TR track-to-vertex chi2; NaN unless kTrAttached
@ kTrProb
TRPR lifetime probability
@ kTrCount
number of slots; the expected parameters size
@ kTrNLayz
NLAYZ of which carry z
@ kTrIjsv
IJSV jet after the SV redefinition
@ kTrChi2Vd
CHI2VD chi2 of the VD hits on the track
@ kTrIst
IST track-quality code (AASTRK / AASLCT / AAIMPC)
@ kTrNLay
NLAY VD layers touched
@ kTrRpdt
RPDT track rapidity with respect to its jet
@ kTrDistj
DISTJ 3-D track-jet distance, mm; NaN if not computed
@ kTrMomentum
PMOM track momentum, GeV
@ kTrNVdpz
NVDPZ of which carry z
@ kTrIjet
IJET AABTAG_CombinedTagRow row, 1-based
bool isPositiveFinite(float value)