FairShip
Loading...
Searching...
No Matches
caloScoringPlanePID.py
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 Collaboration
3
4"""Read the CaloScoringPlane particle-identification file.
5
6The file holds energy-dependent electron / hadron / muon confusion matrices
7(format: CaloScoringPlane/README.md, example:
8geometry/caloScoringPlane_pid_provided.yaml). parse() checks its structure and
9returns a PIDModel in the species order of the C++ class; make_pid() hands it
10to CaloScoringPlanePID::Set(), which checks the numbers (finite, non-negative,
11rows summing to 1, energies increasing) and that the overrides for +pdg and
12-pdg agree. A PIDModel from parse() alone is therefore not fully validated.
13load_pid() does both for a file.
14"""
15
16from __future__ import annotations
17
18import os
19from dataclasses import dataclass, field
20from typing import Any
21
22import yaml
23from yaml.error import YAMLError
24
25# Order of CaloScoringPlanePID::Species (kElectron = 0, kHadron = 1, kMuon = 2).
26SPECIES = ("electron", "hadron", "muon")
27_OVERRIDE_SPECIES = {"electron": 0, "hadron": 1, "muon": 2, "none": -1}
28_KEYS = {"species", "interpolation", "points", "pdg_overrides"}
29
30
31class PIDConfigError(ValueError):
32 """The PID file is malformed; the message names the file and the entry."""
33
34
35@dataclass
37 """Confusion matrices in the species order of CaloScoringPlanePID."""
38
39 energies: list[float]
40 matrices: list[float] # 9 per energy, row-major: rows true, columns identified
41 overrides: dict[int, int] = field(default_factory=dict) # pdg -> species; Set() folds the sign
42 log_interpolation: bool = False
43
44
45def _number(value: Any, where: str, source: str) -> float:
46 # bool is an int subclass, but "true" is not a probability.
47 if isinstance(value, bool) or not isinstance(value, (int, float)):
48 raise PIDConfigError(f"{source}: {where} must be a number, not {value!r}")
49 return float(value)
50
51
52def parse(config: Any, source: str = "<string>") -> PIDModel:
53 """Check the structure of a parsed PID file and reorder it to SPECIES."""
54 if not isinstance(config, dict):
55 raise PIDConfigError(f"{source}: the top level must be a mapping")
56 unknown = sorted(str(k) for k in config if k not in _KEYS)
57 if unknown:
58 raise PIDConfigError(f"{source}: unknown key(s) {', '.join(unknown)}")
59
60 species = config.get("species", list(SPECIES))
61 if not isinstance(species, list) or sorted(map(str, species)) != sorted(SPECIES):
62 raise PIDConfigError(f"{source}: 'species' must be a permutation of {', '.join(SPECIES)}, not {species!r}")
63 order = [SPECIES.index(s) for s in species] # file row/column -> internal index
64
65 interpolation = config.get("interpolation", "linear")
66 if interpolation not in ("linear", "log"):
67 raise PIDConfigError(f"{source}: 'interpolation' must be linear or log, not {interpolation!r}")
68
69 points = config.get("points")
70 if not isinstance(points, list) or not points:
71 raise PIDConfigError(f"{source}: 'points' must be a non-empty list of {{energy, matrix}}")
72 energies: list[float] = []
73 matrices: list[float] = []
74 for k, point in enumerate(points):
75 where = f"points[{k}]"
76 if not isinstance(point, dict) or set(point) != {"energy", "matrix"}:
77 raise PIDConfigError(f"{source}: {where} must have exactly the keys 'energy' and 'matrix'")
78 energies.append(_number(point["energy"], f"{where}.energy", source))
79 rows = point["matrix"]
80 if not isinstance(rows, list) or len(rows) != 3 or any(not isinstance(r, list) or len(r) != 3 for r in rows):
81 raise PIDConfigError(f"{source}: {where}.matrix must be 3 rows of 3 numbers")
82 matrix = [0.0] * 9
83 for i, row in enumerate(rows):
84 for j, value in enumerate(row):
85 matrix[3 * order[i] + order[j]] = _number(value, f"{where}.matrix[{i}][{j}]", source)
86 matrices.extend(matrix)
87
88 overrides: dict[int, int] = {}
89 raw = config.get("pdg_overrides") or {} # an empty key (all entries commented out) is allowed
90 if not isinstance(raw, dict):
91 raise PIDConfigError(f"{source}: 'pdg_overrides' must map PDG codes to species")
92 for pdg, name in raw.items():
93 if isinstance(pdg, bool) or not isinstance(pdg, int):
94 raise PIDConfigError(f"{source}: 'pdg_overrides' keys must be PDG codes, not {pdg!r}")
95 if not isinstance(name, str) or name not in _OVERRIDE_SPECIES:
96 raise PIDConfigError(
97 f"{source}: pdg_overrides[{pdg}] must be one of {', '.join(_OVERRIDE_SPECIES)}, not {name!r}"
98 )
99 # Keep the sign: Set() applies the override to |pdg| and rejects
100 # conflicting entries for +pdg and -pdg.
101 overrides[pdg] = _OVERRIDE_SPECIES[name]
102
103 return PIDModel(energies, matrices, overrides, interpolation == "log")
104
105
106def load(path: str) -> PIDModel:
107 """Read and parse a PID file; environment variables and ~ are expanded."""
108 expanded = os.path.expanduser(os.path.expandvars(path))
109 try:
110 with open(expanded) as f:
111 config = yaml.safe_load(f)
112 except OSError as error:
113 raise PIDConfigError(f"cannot read the PID file {expanded}: {error.strerror}") from error
114 except YAMLError as error:
115 raise PIDConfigError(f"{expanded}: not valid YAML: {error}") from error
116 return parse(config, expanded)
117
118
119def make_pid(model: PIDModel, source: str = "<model>") -> Any:
120 """Build a CaloScoringPlanePID from a model; numbers are checked in C++."""
121 import ROOT
122
123 pid = ROOT.CaloScoringPlanePID()
124 overrides = ROOT.std.map("int", "int")()
125 for pdg, species in model.overrides.items():
126 overrides[pdg] = species
127 try:
128 pid.Set(
129 ROOT.std.vector("double")(model.energies),
130 ROOT.std.vector("double")(model.matrices),
131 overrides,
132 model.log_interpolation,
133 )
134 except ROOT.std.invalid_argument as error: # the model was rejected by Set()
135 # The class prefix helps C++ callers; in a file error it is noise.
136 message = error.what().removeprefix("CaloScoringPlanePID::Set: ")
137 raise PIDConfigError(f"{source}: {message}") from error
138 return pid
139
140
141def load_pid(path: str | None) -> Any:
142 """CaloScoringPlanePID from a PID file, or perfect identification without one."""
143 if not path:
144 import ROOT
145
146 return ROOT.CaloScoringPlanePID()
147 return make_pid(load(path), os.path.expanduser(os.path.expandvars(path)))
PIDModel parse(Any config, str source="<string>")
Any load_pid(str|None path)
Any make_pid(PIDModel model, str source="<model>")
PIDModel load(str path)
float _number(Any value, str where, str source)