FairShip
Loading...
Searching...
No Matches
caloScoringPlanePID Namespace Reference

Classes

class  PIDConfigError
class  PIDModel

Functions

float _number (Any value, str where, str source)
PIDModel parse (Any config, str source="<string>")
PIDModel load (str path)
Any make_pid (PIDModel model, str source="<model>")
Any load_pid (str|None path)

Variables

tuple SPECIES = ("electron", "hadron", "muon")
dict _OVERRIDE_SPECIES = {"electron": 0, "hadron": 1, "muon": 2, "none": -1}
dict _KEYS = {"species", "interpolation", "points", "pdg_overrides"}

Detailed Description

Read the CaloScoringPlane particle-identification file.

The file holds energy-dependent electron / hadron / muon confusion matrices
(format: CaloScoringPlane/README.md, example:
geometry/caloScoringPlane_pid_provided.yaml). parse() checks its structure and
returns a PIDModel in the species order of the C++ class; make_pid() hands it
to CaloScoringPlanePID::Set(), which checks the numbers (finite, non-negative,
rows summing to 1, energies increasing) and that the overrides for +pdg and
-pdg agree. A PIDModel from parse() alone is therefore not fully validated.
load_pid() does both for a file.

Function Documentation

◆ _number()

float caloScoringPlanePID._number ( Any value,
str where,
str source )
protected

Definition at line 45 of file caloScoringPlanePID.py.

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

◆ load()

PIDModel caloScoringPlanePID.load ( str path)
Read and parse a PID file; environment variables and ~ are expanded.

Definition at line 106 of file caloScoringPlanePID.py.

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

◆ load_pid()

Any caloScoringPlanePID.load_pid ( str | None path)
CaloScoringPlanePID from a PID file, or perfect identification without one.

Definition at line 141 of file caloScoringPlanePID.py.

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)))

◆ make_pid()

Any caloScoringPlanePID.make_pid ( PIDModel model,
str source = "<model>" )
Build a CaloScoringPlanePID from a model; numbers are checked in C++.

Definition at line 119 of file caloScoringPlanePID.py.

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

◆ parse()

PIDModel caloScoringPlanePID.parse ( Any config,
str source = "<string>" )
Check the structure of a parsed PID file and reorder it to SPECIES.

Definition at line 52 of file caloScoringPlanePID.py.

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

Variable Documentation

◆ _KEYS

dict caloScoringPlanePID._KEYS = {"species", "interpolation", "points", "pdg_overrides"}
protected

Definition at line 28 of file caloScoringPlanePID.py.

◆ _OVERRIDE_SPECIES

dict caloScoringPlanePID._OVERRIDE_SPECIES = {"electron": 0, "hadron": 1, "muon": 2, "none": -1}
protected

Definition at line 27 of file caloScoringPlanePID.py.

◆ SPECIES

tuple caloScoringPlanePID.SPECIES = ("electron", "hadron", "muon")

Definition at line 26 of file caloScoringPlanePID.py.