FairShip
Loading...
Searching...
No Matches
fieldMapTools.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"""Helpers for reading, validating and repacking FairShip magnetic field maps.
5
6A FairShip ROOT field map holds two trees. ``Range`` has a single entry with
7the coordinate limits and bin widths (cm), and ``Data`` has ``Nx*Ny*Nz``
8entries with the field components (Tesla), optionally accompanied by the node
9coordinates.
10
11``ShipBFieldMap`` reads ``Data`` sequentially and only imposes the grid
12structure at lookup time, through ``index = (iX*Ny + iY)*Nz + iZ``: z is
13increased first, then y, then x. Nothing in the file states the ordering, so a
14map written in a different order is read transposed. When ``Nx == Ny`` and the
15x and y ranges agree, even the entry count still matches and the mistake is
16silent. The functions here make the ordering checkable, from both the stored
17coordinates and from the field itself.
18"""
19
20import os
21from dataclasses import dataclass
22
23import numpy as np
24import ROOT
25
26#: Field component branch names, in the order they are stored.
27FIELD_BRANCHES = ("Bx", "By", "Bz")
28
29#: Node coordinate branch names, written when a map is converted with
30#: ``storeCoords``.
31COORD_BRANCHES = ("x", "y", "z")
32
33#: Supported data orderings. ``xslow`` is the one FairShip assumes.
34ORDERS = ("xslow", "yslow")
35
36
37@dataclass(frozen=True)
39 """Coordinate limits and binning of a field map, in cm."""
40
41 xMin: float
42 xMax: float
43 dx: float
44 yMin: float
45 yMax: float
46 dy: float
47 zMin: float
48 zMax: float
49 dz: float
50
51 @staticmethod
52 def _bins(lo, hi, step):
53 # Same arithmetic as ShipBFieldMap::setLimits(): the 1.5 rounds up to
54 # the nearest integer while counting both endpoints.
55 if step <= 0.0:
56 raise ValueError(f"Non-positive bin width {step}")
57 return int((hi - lo) / step + 1.5)
58
59 @property
60 def Nx(self):
61 return self._bins(self.xMin, self.xMax, self.dx)
62
63 @property
64 def Ny(self):
65 return self._bins(self.yMin, self.yMax, self.dy)
66
67 @property
68 def Nz(self):
69 return self._bins(self.zMin, self.zMax, self.dz)
70
71 @property
72 def N(self):
73 return self.Nx * self.Ny * self.Nz
74
75 @property
76 def shape(self):
77 return (self.Nx, self.Ny, self.Nz)
78
79 def axis_values(self):
80 """Nominal node coordinates along each axis."""
81 return (
82 self.xMin + self.dx * np.arange(self.Nx),
83 self.yMin + self.dy * np.arange(self.Ny),
84 self.zMin + self.dz * np.arange(self.Nz),
85 )
86
87 def node_indices(self, entries, order="xslow"):
88 """Grid indices (iX, iY, iZ) of the given entry numbers."""
89 entries = np.asarray(entries)
90 iZ = entries % self.Nz
91 if order == "xslow":
92 return entries // (self.Ny * self.Nz), (entries // self.Nz) % self.Ny, iZ
93 if order == "yslow":
94 return (entries // self.Nz) % self.Nx, entries // (self.Nx * self.Nz), iZ
95 raise ValueError(f"Unknown data order {order!r}, expected one of {ORDERS}")
96
97 def extent_mismatch(self):
98 """Deviation of each axis extent from a whole number of bins, in bins.
99
100 A non-zero value means the limits and the bin width disagree, so the
101 node coordinates drift away from the nominal grid.
102 """
103 return tuple(
104 abs((n - 1) * d - (hi - lo)) / d
105 for n, d, lo, hi in (
106 (self.Nx, self.dx, self.xMin, self.xMax),
107 (self.Ny, self.dy, self.yMin, self.yMax),
108 (self.Nz, self.dz, self.zMin, self.zMax),
109 )
110 )
111
112
113def read_range(path):
114 """Read the ``Range`` tree of a field map."""
115 columns = ROOT.RDataFrame("Range", str(path)).AsNumpy(
116 ["xMin", "xMax", "dx", "yMin", "yMax", "dy", "zMin", "zMax", "dz"]
117 )
118 values = {name: float(column[0]) for name, column in columns.items()}
119 return MapRange(**values)
120
121
122def is_field_map(path):
123 """Whether the file holds both trees a FairShip field map needs.
124
125 False for anything ROOT cannot open, an unfetched git-lfs pointer
126 included. PyROOT raises OSError there rather than handing back a null
127 file, so checking the returned handle would never catch it.
128 """
129 try:
130 handle = ROOT.TFile.Open(str(path))
131 except OSError:
132 return False
133 try:
134 trees = {key.GetName() for key in handle.GetListOfKeys()}
135 finally:
136 handle.Close()
137 return {"Range", "Data"} <= trees
138
139
140def branches(path):
141 """Names of the branches of the ``Data`` tree."""
142 return {str(name) for name in ROOT.RDataFrame("Data", str(path)).GetColumnNames()}
143
144
145def entry_count(path):
146 """Number of entries in the ``Data`` tree."""
147 return int(ROOT.RDataFrame("Data", str(path)).Count().GetValue())
148
149
150def has_coords(path):
151 """Whether the map stores the node coordinates alongside the field."""
152 return set(COORD_BRANCHES) <= branches(path)
153
154
155def _columns(path, names):
156 data = ROOT.RDataFrame("Data", str(path)).AsNumpy(list(names))
157 return [np.asarray(data[name], dtype=np.float64) for name in names]
158
159
160def read_field(path, order="xslow", rng=None):
161 """Read the field as an ``(Nx, Ny, Nz, 3)`` array of Tesla.
162
163 ``order`` says how the flat entries map onto the grid: ``xslow`` is the
164 canonical ``(iX*Ny + iY)*Nz + iZ``, ``yslow`` its x/y transpose.
165 """
166 if order not in ORDERS:
167 raise ValueError(f"Unknown data order {order!r}, expected one of {ORDERS}")
168 rng = rng or read_range(path)
169 field = np.stack(_columns(path, FIELD_BRANCHES), axis=-1)
170 if len(field) != rng.N:
171 raise ValueError(f"{path}: expected {rng.N} entries but found {len(field)}")
172 if order == "xslow":
173 return field.reshape(rng.Nx, rng.Ny, rng.Nz, 3)
174 return field.reshape(rng.Ny, rng.Nx, rng.Nz, 3).transpose(1, 0, 2, 3)
175
176
177def transpose_xy(field):
178 """The same field read with x and y swapped."""
179 return field.transpose(1, 0, 2, 3)
180
181
182def read_coords(path):
183 """Read the stored node coordinates, or ``None`` if the map has none."""
184 if not has_coords(path):
185 return None
186 return _columns(path, COORD_BRANCHES)
187
188
189def _residuals(coords, rng, order):
190 """Per-axis deviation of the stored coordinates from ``order``, in bins."""
191 nodes = rng.node_indices(np.arange(rng.N), order)
192 limits = ((rng.xMin, rng.dx), (rng.yMin, rng.dy), (rng.zMin, rng.dz))
193 return tuple(
194 np.abs(stored - (lo + node * step)).max() / step for stored, node, (lo, step) in zip(coords, nodes, limits)
195 )
196
197
198def coord_residuals(path, rng=None, order="xslow"):
199 """Largest deviation of a stored coordinate from the node ``order`` puts it at.
200
201 Returned per axis, in bin widths, over every entry. A map in the given
202 order sits within a fraction of a bin; a permuted one is off by tens of
203 bins. ``None`` if the map stores no coordinates.
204 """
205 coords = read_coords(path)
206 if coords is None:
207 return None
208 rng = rng or read_range(path)
209 if len(coords[0]) != rng.N:
210 raise ValueError(f"{path}: expected {rng.N} entries but found {len(coords[0])}")
211 return _residuals(coords, rng, order)
212
213
214def infer_data_order(path, rng=None):
215 """Guess the data order from the stored coordinates.
216
217 Returns ``"xslow"``, ``"yslow"``, or ``None`` when the map stores no
218 coordinates or matches neither ordering.
219 """
220 coords = read_coords(path)
221 if coords is None:
222 return None
223 rng = rng or read_range(path)
224 if len(coords[0]) != rng.N:
225 return None
226 # Check every node against both candidates rather than watch a single
227 # transition: a layout that is neither has to come back unknown, or
228 # canonicalise() would reorder from a premise that does not hold.
229 matching = [order for order in ORDERS if max(_residuals(coords, rng, order)) < 0.5]
230 return matching[0] if len(matching) == 1 else None
231
232
233def core_slices(rng, xy_fraction=0.3, z_fraction=0.25):
234 """Slices selecting the middle of the map, away from coils and yoke."""
235 xs, ys, zs = rng.axis_values()
236
237 def middle(values, fraction):
238 centre = 0.5 * (values[0] + values[-1])
239 half = fraction * 0.5 * (values[-1] - values[0])
240 (inside,) = np.nonzero(np.abs(values - centre) <= half)
241 if not inside.size:
242 # Too few nodes for the fraction to reach one of them. Take the
243 # node nearest the centre so the caller gets a region, not an
244 # IndexError.
245 nearest = int(np.abs(values - centre).argmin())
246 return slice(nearest, nearest + 1)
247 return slice(inside[0], inside[-1] + 1)
248
249 return (
250 middle(xs, xy_fraction),
251 middle(ys, xy_fraction),
252 middle(zs, z_fraction),
253 )
254
255
256def div_b_rms(field, rng, region=None):
257 """RMS of div B over the core of the map, and the local gradient scale.
258
259 A physical field has div B = 0, so an ordering that scrambles neighbouring
260 nodes shows up as a large residual. The gradient scale is the RMS of the
261 three diagonal derivatives, which is what the residual should be compared
262 against: it is the size div B would have if the derivatives did not cancel.
263 """
264 region = region or core_slices(rng)
265 terms = [np.gradient(field[..., axis], step, axis=axis) for axis, step in enumerate((rng.dx, rng.dy, rng.dz))]
266 dBx, dBy, dBz = (term[region] for term in terms)
267 divergence = dBx + dBy + dBz
268 scale = sum(float((term**2).mean()) for term in (dBx, dBy, dBz))
269 return float(np.sqrt((divergence**2).mean())), float(np.sqrt(scale))
270
271
272def on_axis(field, rng):
273 """Field along z at the grid node closest to x = y = 0."""
274 xs, ys, _ = rng.axis_values()
275 return field[np.abs(xs).argmin(), np.abs(ys).argmin()]
276
277
278def canonicalise(in_path, out_path, order="xslow", rng=None):
279 """Write a field map in canonical order, with matching node coordinates.
280
281 ``order`` is the order the *input* is in. The output is always
282 ``(iX*Ny + iY)*Nz + iZ`` with freshly generated ``x``, ``y`` and ``z``
283 branches, so ``ShipBFieldMap`` can verify it.
284 """
285 # Snapshot recreates the output, and the Range tree is copied out of the
286 # input afterwards, so writing over the input would lose it.
287 if os.path.exists(out_path) and os.path.samefile(in_path, out_path):
288 raise ValueError(f"{out_path} is the input; write the repacked map somewhere else")
289
290 rng = rng or read_range(in_path)
291 field = read_field(in_path, order=order, rng=rng).reshape(rng.N, 3)
292
293 xs, ys, zs = rng.axis_values()
294 x, y, z = (grid.ravel() for grid in np.meshgrid(xs, ys, zs, indexing="ij"))
295
296 columns = {
297 "x": x.astype(np.float32),
298 "y": y.astype(np.float32),
299 "z": z.astype(np.float32),
300 }
301 columns.update({name: field[:, i].astype(np.float32) for i, name in enumerate(FIELD_BRANCHES)})
302 ROOT.RDF.FromNumpy(columns).Snapshot("Data", str(out_path))
303
304 # Snapshot writes a fresh file, so copy the Range tree over afterwards.
305 source = ROOT.TFile.Open(str(in_path))
306 destination = ROOT.TFile.Open(str(out_path), "UPDATE")
307 destination.cd()
308 source.Get("Range").CloneTree(-1, "fast").Write()
309 destination.Close()
310 source.Close()
node_indices(self, entries, order="xslow")
infer_data_order(path, rng=None)
_columns(path, names)
canonicalise(in_path, out_path, order="xslow", rng=None)
on_axis(field, rng)
coord_residuals(path, rng=None, order="xslow")
core_slices(rng, xy_fraction=0.3, z_fraction=0.25)
read_field(path, order="xslow", rng=None)
_residuals(coords, rng, order)
div_b_rms(field, rng, region=None)