FairShip
Loading...
Searching...
No Matches
test_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"""Tests for reading the CaloScoringPlane PID file (python/caloScoringPlanePID.py).
5
6The numerical checks (rows summing to 1, energies increasing, ...) are done in
7C++ by CaloScoringPlanePID::Set() and tested in tests/test_calo_scoring_plane_pid.cxx;
8the tests at the end check that their errors reach Python with the file name.
9"""
10
11import os
12
13import pytest
14import yaml
15from caloScoringPlanePID import SPECIES, PIDConfigError, load, parse
16
17SHIPPED = os.path.join(os.path.dirname(__file__), "..", "geometry", "caloScoringPlane_pid_provided.yaml")
18IDENTITY = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
19
20
21def config(**extra):
22 return {"points": [{"energy": 1, "matrix": IDENTITY}], **extra}
23
24
26 assert SPECIES == ("electron", "hadron", "muon")
27
28
30 model = parse(config())
31 assert model.energies == [1.0]
32 assert model.matrices == [1, 0, 0, 0, 1, 0, 0, 0, 1]
33 assert model.overrides == {}
34 assert not model.log_interpolation
35
36
38 # file order muon, electron, hadron; P(mu -> mu) = 0.7, P(mu -> hadron) = 0.3
39 model = parse(
40 {
41 "species": ["muon", "electron", "hadron"],
42 "points": [{"energy": 1, "matrix": [[0.7, 0.0, 0.3], [0, 1, 0], [0, 0, 1]]}],
43 }
44 )
45 e, h, mu = 0, 1, 2
46 m = model.matrices
47 assert m[3 * mu + mu] == 0.7
48 assert m[3 * mu + h] == 0.3
49 assert m[3 * e + e] == 1.0
50 assert m[3 * h + h] == 1.0
51
52
54 model = parse(
55 {
56 "interpolation": "log",
57 "points": [{"energy": 3, "matrix": IDENTITY}, {"energy": 100.0, "matrix": IDENTITY}],
58 }
59 )
60 assert model.log_interpolation
61 assert model.energies == [3.0, 100.0]
62 assert len(model.matrices) == 18
63
64
66 # the sign is folded by CaloScoringPlanePID::Set(), which can then reject conflicts
67 model = parse(config(pdg_overrides={22: "electron", -211: "none", 130: "muon"}))
68 assert model.overrides == {22: 0, -211: -1, 130: 2}
69
70
72 # "pdg_overrides:" with every entry commented out parses as None
73 assert parse(yaml.safe_load("pdg_overrides:\n" + yaml.safe_dump(config()))).overrides == {}
74
75
76@pytest.mark.parametrize(
77 ("cfg", "message"),
78 [
79 ([1, 2], "top level must be a mapping"),
80 (config(energies=[1]), "unknown key(s) energies"),
81 (config(species=["electron", "electron", "muon"]), "'species' must be a permutation"),
82 (config(species=["electron", "pion", "muon"]), "'species' must be a permutation"),
83 (config(interpolation="spline"), "'interpolation' must be linear or log"),
84 ({"points": []}, "'points' must be a non-empty list"),
85 ({"species": list(SPECIES)}, "'points' must be a non-empty list"),
86 ({"points": [{"energy": 1}]}, "points[0] must have exactly the keys"),
87 ({"points": [{"energy": 1, "matrix": IDENTITY, "x": 2}]}, "points[0] must have exactly the keys"),
88 ({"points": [{"energy": 1, "matrix": [[1, 0], [0, 1], [0, 0]]}]}, "points[0].matrix must be 3 rows"),
89 ({"points": [{"energy": 1, "matrix": [[1, 0, 0], [0, 1, 0]]}]}, "points[0].matrix must be 3 rows"),
90 ({"points": [{"energy": "high", "matrix": IDENTITY}]}, "points[0].energy must be a number"),
91 ({"points": [{"energy": 1, "matrix": [[1, 0, 0], [0, "a", 0], [0, 0, 1]]}]}, "points[0].matrix[1][1]"),
92 ({"points": [{"energy": 1, "matrix": [[True, 0, 0], [0, 1, 0], [0, 0, 1]]}]}, "must be a number"),
93 (config(pdg_overrides=[22]), "'pdg_overrides' must map PDG codes"),
94 (config(pdg_overrides={"gamma": "electron"}), "keys must be PDG codes"),
95 (config(pdg_overrides={22: "photon"}), "pdg_overrides[22] must be one of"),
96 (config(pdg_overrides={22: ["electron"]}), "pdg_overrides[22] must be one of"),
97 ],
98)
100 with pytest.raises(PIDConfigError) as error:
101 parse(cfg, "pid.yaml")
102 assert str(error.value).startswith("pid.yaml: ")
103 assert message in str(error.value)
104
105
106def test_missing_file(tmp_path):
107 with pytest.raises(PIDConfigError, match="cannot read the PID file"):
108 load(str(tmp_path / "missing.yaml"))
109
110
111def test_invalid_yaml(tmp_path):
112 path = tmp_path / "broken.yaml"
113 path.write_text("points: [\n")
114 with pytest.raises(PIDConfigError, match="not valid YAML"):
115 load(str(path))
116
117
119 (tmp_path / "pid.yaml").write_text(yaml.safe_dump(config()))
120 monkeypatch.setenv("PID_TEST_DIR", str(tmp_path))
121 assert load("$PID_TEST_DIR/pid.yaml").energies == [1.0]
122
123
125 model = load(SHIPPED)
126 assert model.log_interpolation
127 assert model.energies == sorted(model.energies)
128 assert len(model.matrices) == 9 * len(model.energies)
129
130
131# --- through the C++ class (needs the compiled CaloScoringPlane library) ---
132
133
134@pytest.fixture
135def ROOT(root_with_calo_scoring_plane):
136 return root_with_calo_scoring_plane
137
138
140 from caloScoringPlanePID import load_pid
141
142 pid = load_pid(SHIPPED)
143 assert list(pid.GetEnergies()) == load(SHIPPED).energies
144 assert pid.IsLogInterpolation()
145
146
148 from caloScoringPlanePID import load_pid
149
150 pid = load_pid(None)
151 assert pid.Identify(13, 5.0, 0.99) == ROOT.CaloScoringPlanePID.kMuon
152
153
155 from caloScoringPlanePID import load_pid
156
157 path = tmp_path / "pid.yaml"
158 path.write_text(yaml.safe_dump({"points": [{"energy": 1, "matrix": [[0.5, 0.4, 0], [0, 1, 0], [0, 0, 1]]}]}))
159 with pytest.raises(PIDConfigError) as error:
160 load_pid(str(path))
161 assert str(error.value).startswith(f"{path}: energy point 0")
162 assert "true electron row sums to 0.9" in str(error.value)
163
164
166 from caloScoringPlanePID import load_pid
167
168 path = tmp_path / "pid.yaml"
169 path.write_text("points:\n - energy: .nan\n matrix: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n")
170 with pytest.raises(PIDConfigError, match="not finite"):
171 load_pid(str(path))
172
173
175 from caloScoringPlanePID import make_pid
176
177 pid = make_pid(parse(config(pdg_overrides={-211: "muon"})))
178 assert pid.TrueSpecies(211) == ROOT.CaloScoringPlanePID.kMuon
179 assert pid.TrueSpecies(-211) == ROOT.CaloScoringPlanePID.kMuon
180
181
183 from caloScoringPlanePID import load_pid
184
185 path = tmp_path / "pid.yaml"
186 path.write_text(yaml.safe_dump(config(pdg_overrides={211: "hadron", -211: "muon"})))
187 with pytest.raises(PIDConfigError) as error:
188 load_pid(str(path))
189 assert str(path) in str(error.value)
190 assert "conflicting overrides" in str(error.value)
191
192
194 from caloScoringPlanePID import PIDModel, make_pid
195
196 with pytest.raises(TypeError):
197 make_pid(PIDModel(energies=["1"], matrices=[0.0] * 9)) # pyrefly: ignore[bad-argument-type]
test_conflicting_overrides_are_rejected(ROOT, tmp_path)
test_numerical_errors_name_the_file(ROOT, tmp_path)
ROOT(root_with_calo_scoring_plane)
test_nan_in_the_file_is_rejected(ROOT, tmp_path)
test_environment_variables_are_expanded(tmp_path, monkeypatch)