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

Classes

class  MapRange

Functions

 read_range (path)
 is_field_map (path)
 branches (path)
 entry_count (path)
 has_coords (path)
 _columns (path, names)
 read_field (path, order="xslow", rng=None)
 transpose_xy (field)
 read_coords (path)
 _residuals (coords, rng, order)
 coord_residuals (path, rng=None, order="xslow")
 infer_data_order (path, rng=None)
 core_slices (rng, xy_fraction=0.3, z_fraction=0.25)
 div_b_rms (field, rng, region=None)
 on_axis (field, rng)
 canonicalise (in_path, out_path, order="xslow", rng=None)

Variables

tuple FIELD_BRANCHES = ("Bx", "By", "Bz")
tuple COORD_BRANCHES = ("x", "y", "z")
tuple ORDERS = ("xslow", "yslow")

Detailed Description

Helpers for reading, validating and repacking FairShip magnetic field maps.

A FairShip ROOT field map holds two trees. ``Range`` has a single entry with
the coordinate limits and bin widths (cm), and ``Data`` has ``Nx*Ny*Nz``
entries with the field components (Tesla), optionally accompanied by the node
coordinates.

``ShipBFieldMap`` reads ``Data`` sequentially and only imposes the grid
structure at lookup time, through ``index = (iX*Ny + iY)*Nz + iZ``: z is
increased first, then y, then x. Nothing in the file states the ordering, so a
map written in a different order is read transposed. When ``Nx == Ny`` and the
x and y ranges agree, even the entry count still matches and the mistake is
silent. The functions here make the ordering checkable, from both the stored
coordinates and from the field itself.

Function Documentation

◆ _columns()

fieldMapTools._columns ( path,
names )
protected

Definition at line 155 of file fieldMapTools.py.

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

◆ _residuals()

fieldMapTools._residuals ( coords,
rng,
order )
protected
Per-axis deviation of the stored coordinates from ``order``, in bins.

Definition at line 189 of file fieldMapTools.py.

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

◆ branches()

fieldMapTools.branches ( path)
Names of the branches of the ``Data`` tree.

Definition at line 140 of file fieldMapTools.py.

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

◆ canonicalise()

fieldMapTools.canonicalise ( in_path,
out_path,
order = "xslow",
rng = None )
Write a field map in canonical order, with matching node coordinates.

``order`` is the order the *input* is in. The output is always
``(iX*Ny + iY)*Nz + iZ`` with freshly generated ``x``, ``y`` and ``z``
branches, so ``ShipBFieldMap`` can verify it.

Definition at line 278 of file fieldMapTools.py.

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

◆ coord_residuals()

fieldMapTools.coord_residuals ( path,
rng = None,
order = "xslow" )
Largest deviation of a stored coordinate from the node ``order`` puts it at.

Returned per axis, in bin widths, over every entry. A map in the given
order sits within a fraction of a bin; a permuted one is off by tens of
bins. ``None`` if the map stores no coordinates.

Definition at line 198 of file fieldMapTools.py.

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

◆ core_slices()

fieldMapTools.core_slices ( rng,
xy_fraction = 0.3,
z_fraction = 0.25 )
Slices selecting the middle of the map, away from coils and yoke.

Definition at line 233 of file fieldMapTools.py.

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

◆ div_b_rms()

fieldMapTools.div_b_rms ( field,
rng,
region = None )
RMS of div B over the core of the map, and the local gradient scale.

A physical field has div B = 0, so an ordering that scrambles neighbouring
nodes shows up as a large residual. The gradient scale is the RMS of the
three diagonal derivatives, which is what the residual should be compared
against: it is the size div B would have if the derivatives did not cancel.

Definition at line 256 of file fieldMapTools.py.

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

◆ entry_count()

fieldMapTools.entry_count ( path)
Number of entries in the ``Data`` tree.

Definition at line 145 of file fieldMapTools.py.

145def entry_count(path):
146 """Number of entries in the ``Data`` tree."""
147 return int(ROOT.RDataFrame("Data", str(path)).Count().GetValue())
148
149

◆ has_coords()

fieldMapTools.has_coords ( path)
Whether the map stores the node coordinates alongside the field.

Definition at line 150 of file fieldMapTools.py.

150def has_coords(path):
151 """Whether the map stores the node coordinates alongside the field."""
152 return set(COORD_BRANCHES) <= branches(path)
153
154

◆ infer_data_order()

fieldMapTools.infer_data_order ( path,
rng = None )
Guess the data order from the stored coordinates.

Returns ``"xslow"``, ``"yslow"``, or ``None`` when the map stores no
coordinates or matches neither ordering.

Definition at line 214 of file fieldMapTools.py.

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

◆ is_field_map()

fieldMapTools.is_field_map ( path)
Whether the file holds both trees a FairShip field map needs.

False for anything ROOT cannot open, an unfetched git-lfs pointer
included. PyROOT raises OSError there rather than handing back a null
file, so checking the returned handle would never catch it.

Definition at line 122 of file fieldMapTools.py.

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

◆ on_axis()

fieldMapTools.on_axis ( field,
rng )
Field along z at the grid node closest to x = y = 0.

Definition at line 272 of file fieldMapTools.py.

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

◆ read_coords()

fieldMapTools.read_coords ( path)
Read the stored node coordinates, or ``None`` if the map has none.

Definition at line 182 of file fieldMapTools.py.

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

◆ read_field()

fieldMapTools.read_field ( path,
order = "xslow",
rng = None )
Read the field as an ``(Nx, Ny, Nz, 3)`` array of Tesla.

``order`` says how the flat entries map onto the grid: ``xslow`` is the
canonical ``(iX*Ny + iY)*Nz + iZ``, ``yslow`` its x/y transpose.

Definition at line 160 of file fieldMapTools.py.

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

◆ read_range()

fieldMapTools.read_range ( path)
Read the ``Range`` tree of a field map.

Definition at line 113 of file fieldMapTools.py.

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

◆ transpose_xy()

fieldMapTools.transpose_xy ( field)
The same field read with x and y swapped.

Definition at line 177 of file fieldMapTools.py.

177def transpose_xy(field):
178 """The same field read with x and y swapped."""
179 return field.transpose(1, 0, 2, 3)
180
181

Variable Documentation

◆ COORD_BRANCHES

tuple fieldMapTools.COORD_BRANCHES = ("x", "y", "z")

Definition at line 31 of file fieldMapTools.py.

◆ FIELD_BRANCHES

tuple fieldMapTools.FIELD_BRANCHES = ("Bx", "By", "Bz")

Definition at line 27 of file fieldMapTools.py.

◆ ORDERS

tuple fieldMapTools.ORDERS = ("xslow", "yslow")

Definition at line 34 of file fieldMapTools.py.