FairShip
Loading...
Searching...
No Matches
canonicaliseFieldMap.py
Go to the documentation of this file.
1#!/bin/python
2# SPDX-License-Identifier: LGPL-3.0-or-later
3# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
4
5"""Rewrite a FairShip ROOT field map in the ordering ShipBFieldMap expects.
6
7``ShipBFieldMap`` reads the ``Data`` tree sequentially and indexes it as
8``(iX*Ny + iY)*Nz + iZ``: z is increased first, then y, then x. A map written
9in any other order is read transposed, and when ``Nx == Ny`` with matching x
10and y ranges even the entry count still adds up, so nothing complains.
11
12This script reorders the field into that convention and writes the node
13coordinates alongside it, so the map states its own ordering and FairShip can
14check it at startup.
15
16The input order can be inferred two ways, and the script uses both. The stored
17``x``, ``y`` and ``z`` branches say what the writer thought it was doing, and
18the divergence of the field says what is actually there: a physical field has
19div B = 0, which no transposition survives. When the two disagree the file is
20internally inconsistent and the order has to be given on the command line.
21"""
22
23import argparse
24import hashlib
25import sys
26
27import fieldMapTools as fmt
28import numpy as np
29
30
31def checksum(path):
32 """Hash of the field components, to tell a repack from a rewrite."""
33 field = fmt.read_field(path).ravel()
34 return hashlib.sha256(field.tobytes()).hexdigest()[:16]
35
36
37#: How much cleaner one reading's divergence has to be before it counts as
38#: the answer. A field symmetric about the x = y plane scores the same either
39#: way up to rounding, and the weakest real map here separates by 1.6.
40DIVERGENCE_MARGIN = 1.1
41
42
43def divergence_order(field, rng):
44 """The ordering whose div B is smaller, with both values and the scale.
45
46 The order is None when the two are too close to choose between, so a
47 symmetric map is reported as undecided instead of arbitrarily transposed.
48 """
49 as_read, scale = fmt.div_b_rms(field, rng)
50 transposed, _ = fmt.div_b_rms(fmt.transpose_xy(field), rng)
51 lower, upper = sorted((as_read, transposed))
52 if upper <= lower * DIVERGENCE_MARGIN:
53 order = None
54 else:
55 order = "xslow" if as_read < transposed else "yslow"
56 return order, as_read, transposed, scale
57
58
59def describe(path, rng, field):
60 """Print what the file says about itself and what the field says."""
61 residuals = fmt.coord_residuals(path, rng)
62 print(f" grid {rng.Nx} x {rng.Ny} x {rng.Nz} = {rng.N} nodes")
63 print(f" extent mismatch {tuple(float(round(e, 4)) for e in rng.extent_mismatch())} bins")
64 if residuals is None:
65 print(" coordinates absent")
66 else:
67 print(
68 f" coordinates off by {tuple(float(round(r, 3)) for r in residuals)} bins "
69 f"from canonical order -> {fmt.infer_data_order(path, rng) or 'neither'}"
70 )
71 order, as_read, transposed, scale = divergence_order(field, rng)
72 print(
73 f" RMS(div B) xslow {as_read:.3e}, yslow {transposed:.3e} "
74 f"(gradient scale {scale:.3e}) -> {order or 'too close to call'}"
75 )
76 on_axis = fmt.on_axis(field, rng)
77 peaks = [float(np.abs(on_axis[:, i]).max()) for i in range(3)]
78 print(f" peak on axis Bx {peaks[0]:.4f}, By {peaks[1]:.4f}, Bz {peaks[2]:.4f} T")
79 return order
80
81
82def resolve_order(path, rng, field, requested):
83 """Settle on the input ordering, or explain why it cannot be settled."""
84 from_field = divergence_order(field, rng)[0]
85 from_coords = fmt.infer_data_order(path, rng)
86
87 if requested != "auto":
88 if from_field is not None and requested != from_field:
89 print(
90 f"Warning: --data-order {requested} disagrees with the divergence "
91 f"of the field, which points at {from_field}.",
92 file=sys.stderr,
93 )
94 return requested
95
96 if from_field is not None and from_coords is not None and from_coords != from_field:
97 raise SystemExit(
98 f"{path} is internally inconsistent: its coordinates are written in "
99 f"{from_coords} order but its field is only divergence-free read as "
100 f"{from_field}. Pass --data-order explicitly once you know which is "
101 "right; the coordinates are regenerated either way."
102 )
103 if from_coords is not None:
104 return from_coords
105 if from_field is not None:
106 print(f"Using {from_field} from the divergence of the field; the map stores no usable coordinates.")
107 return from_field
108 raise SystemExit(
109 f"{path} does not say what order it is in: its coordinates match neither "
110 "layout, and its divergence is the same read either way. Pass "
111 "--data-order explicitly."
112 )
113
114
115def main():
116 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
117 parser.add_argument("input", help="field map to read")
118 parser.add_argument("-o", "--output", help="field map to write (omit to only report)")
119 parser.add_argument(
120 "--data-order",
121 choices=("auto", *fmt.ORDERS),
122 default="auto",
123 help="ordering of the input; auto requires the coordinates and the field to agree",
124 )
125 parser.add_argument(
126 "--check-only",
127 action="store_true",
128 help="report on the input and exit non-zero unless it is already canonical",
129 )
130 args = parser.parse_args()
131
132 rng = fmt.read_range(args.input)
133 field = fmt.read_field(args.input, rng=rng)
134
135 print(f"{args.input}:")
136 from_field = describe(args.input, rng, field)
137
138 if args.check_only:
139 residuals = fmt.coord_residuals(args.input, rng)
140 # An undecided divergence leaves the coordinates as the authority.
141 canonical = from_field != "yslow" and residuals is not None and max(residuals) < 0.5
142 print(" verdict " + ("canonical" if canonical else "NEEDS REPACKING"))
143 return 0 if canonical else 1
144
145 if not args.output:
146 parser.error("give --output, or --check-only to just report")
147
148 order = resolve_order(args.input, rng, field, args.data_order)
149 print(f"Reading {args.input} as {order} and writing {args.output}")
150 fmt.canonicalise(args.input, args.output, order=order, rng=rng)
151
152 print(f"{args.output}:")
153 written = fmt.read_field(args.output)
154 describe(args.output, fmt.read_range(args.output), written)
155 before, after = checksum(args.input), checksum(args.output)
156 print(f" field contents {before} -> {after} ({'unchanged' if before == after else 'reordered'})")
157 return 0
158
159
160if __name__ == "__main__":
161 sys.exit(main())
describe(path, rng, field)
resolve_order(path, rng, field, requested)