FairShip
Loading...
Searching...
No Matches
test_field_maps.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"""Check that every shipped field map is stored the way ShipBFieldMap reads it.
5
6The reader streams the ``Data`` tree sequentially and indexes it as
7``(iX*Ny + iY)*Nz + iZ``. Nothing in the file states that ordering, and when
8``Nx == Ny`` with matching x and y ranges a transposed map still has the right
9number of entries, so it is read mirrored about the x = y plane without a
10single complaint. That is what happened to the default spectrometer map.
11
12Two things pin the ordering down. The stored node coordinates say what the
13writer intended, and the divergence of the field says what is actually in the
14file: a physical field has div B = 0, and no transposition survives that.
15"""
16
17from pathlib import Path
18
19import fieldMapTools as fmt
20import numpy as np
21import pytest
22
23MAP_DIRECTORY = Path(__file__).resolve().parent.parent / "files"
24
25# Per map: the component that dominates on the beam axis, how much better the
26# divergence has to be than the transposed reading, and how large the
27# divergence may be next to the local gradient scale.
28#
29# The shield maps sit inside iron on a coarse grid, so their numerical
30# divergence is large and only weakly discriminating; their node coordinates
31# carry the check instead. The measured values are roughly 50x / 0.015 for the
32# spectrometer maps, 3.7x / 0.29 for the older one, and 2.2x / 0.9 for the
33# shield maps.
34EXPECTED = {
35 "2026_09_28_SHiP_SpectrometerField_ECN3_MgB2": ("Bx", 10.0, 0.1),
36 "2026_09_28_MainSpectrometerField_V13_3500": ("Bx", 10.0, 0.1),
37 "2026_09_28_MainSpectrometerField_V21_2000": ("Bx", 10.0, 0.1),
38 "2026_09_28_MainSpectrometerField_V21_3000": ("Bx", 10.0, 0.1),
39 "2026_07_02_MainSpectrometerField_V21_2455": ("Bx", 10.0, 0.1),
40 "MainSpectrometerField": ("Bx", 2.0, 0.5),
41 "TRY_2026": ("By", 1.4, 1.2),
42}
43
44
46 with path.open("rb") as handle:
47 return handle.read(40).startswith(b"version https://git-lfs")
48
49
51 """Every readable field map in files/.
52
53 Unfetched git-lfs pointers are dropped one by one rather than taken as a
54 reason to skip the lot, so a partly fetched checkout still checks the maps
55 it does have.
56 """
57 if not MAP_DIRECTORY.is_dir():
58 return []
59 candidates = sorted(MAP_DIRECTORY.glob("*.root"))
60 return [path for path in candidates if not _is_lfs_pointer(path) and fmt.is_field_map(path)]
61
62
63MAPS = _discover()
64
65pytestmark = pytest.mark.skipif(not MAPS, reason="no field maps in files/ (git-lfs objects not fetched?)")
66
67
68@pytest.fixture(scope="module")
69def loaded():
70 """Every map read once, as ``{stem: (range, field)}``."""
71 return {path.stem: (fmt.read_range(path), fmt.read_field(path)) for path in MAPS}
72
73
74def expectation(stem):
75 """What this map should look like, or a skip if nobody has said."""
76 if stem not in EXPECTED:
77 pytest.skip(f"{stem} is not listed in EXPECTED (see test_map_is_expected)")
78 return EXPECTED[stem]
79
80
81@pytest.mark.parametrize("path", MAPS, ids=lambda path: path.stem)
83 """A new map has to be added to EXPECTED deliberately, not by accident."""
84 assert path.stem in EXPECTED, (
85 f"{path.name} is not listed in EXPECTED. Work out which component it is "
86 "meant to produce and how clean its divergence is, then add it."
87 )
88
89
90@pytest.mark.parametrize("path", MAPS, ids=lambda path: path.stem)
92 rng = fmt.read_range(path)
93 assert min(rng.dx, rng.dy, rng.dz) > 0.0
94 assert min(rng.Nx, rng.Ny, rng.Nz) >= 2
95 # Limits that are not a whole number of bins apart would put every node
96 # away from where the interpolation looks for it.
97 assert max(rng.extent_mismatch()) < 1e-2
98 assert fmt.entry_count(path) == rng.N
99
100
101@pytest.mark.parametrize("path", MAPS, ids=lambda path: path.stem)
103 """The regression test: a transposed map is off by tens of bins here."""
104 rng = fmt.read_range(path)
105 residuals = fmt.coord_residuals(path, rng)
106 assert residuals is not None, (
107 f"{path.name} stores no x,y,z branches, so its ordering cannot be "
108 "verified. Repack it with field/canonicaliseFieldMap.py."
109 )
110 # The builtin max() skips a NaN that is not first, so check explicitly.
111 assert np.all(np.isfinite(residuals)), f"{path.name} stores non-finite node coordinates: residuals {residuals}"
112 assert max(residuals) < 0.5, (
113 f"{path.name} is stored in {fmt.infer_data_order(path, rng)} order, not "
114 "the ascending z,y,x order ShipBFieldMap assumes."
115 )
116
117
118@pytest.mark.parametrize("path", MAPS, ids=lambda path: path.stem)
120 """div B = 0 only holds for the reading that matches the file."""
121 _, minimum_ratio, maximum_relative = expectation(path.stem)
122 rng, field = loaded[path.stem]
123 as_stored, scale = fmt.div_b_rms(field, rng)
124 transposed, _ = fmt.div_b_rms(fmt.transpose_xy(field), rng)
125 assert as_stored * minimum_ratio < transposed
126 assert as_stored < maximum_relative * scale
127
128
129@pytest.mark.parametrize("path", MAPS, ids=lambda path: path.stem)
131 """Catches a Bx/By column swap, which leaves div B untouched."""
132 dominant = expectation(path.stem)[0]
133 rng, field = loaded[path.stem]
134 peaks = np.abs(fmt.on_axis(field, rng)).max(axis=0)
135 index = fmt.FIELD_BRANCHES.index(dominant)
136 others = np.delete(peaks, index).max()
137 assert peaks[index] > 5.0 * others
test_coordinates_follow_the_assumed_order(path)
test_divergence_prefers_the_stored_order(path, loaded)
test_binning_is_consistent(path)
test_expected_component_dominates_on_axis(path, loaded)