FairShip
Loading...
Searching...
No Matches
plotFieldMap.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"""Plot the components of a FairShip field map, straight from the file.
6
7``ShipFieldMaker::plotField`` also draws the three components, but it needs a
8built geometry and samples the field through it. This reads the map on its own,
9so it can be pointed at a file before anything is simulated, and it can show
10the same file read two ways.
11
12The panels are chosen to make an x/y transposition obvious: a dipole aperture
13is not square, so the x and y profiles and the aperture outline disagree at a
14glance when the two axes are swapped.
15"""
16
17import argparse
18import sys
19
20import fieldMapTools as fmt
21import matplotlib
22import numpy as np
23
24matplotlib.use("Agg")
25import matplotlib.pyplot as plt
26
27#: Nominal half-aperture of the SHiP spectrometer, in cm.
28APERTURE = (200.0, 300.0)
29
30
31def bending_power(field, rng):
32 """Integral of Bx along z at every (x, y), in T cm.
33
34 Trapezoidal, so the integral covers the intervals between nodes rather
35 than counting the two end nodes as whole steps.
36 """
37 return np.trapezoid(field[..., 0], dx=rng.dz, axis=2)
38
39
40def draw(axes, rng, field, label, aperture):
41 xs, ys, zs = rng.axis_values()
42 centre = np.abs(zs).argmin()
43 i0, j0 = np.abs(xs).argmin(), np.abs(ys).argmin()
44
45 slice_xy = field[:, :, centre, 0].T
46 limit = np.abs(slice_xy).max()
47 mesh = axes[0].pcolormesh(xs, ys, slice_xy, cmap="RdBu_r", vmin=-limit, vmax=limit)
48 axes[0].figure.colorbar(mesh, ax=axes[0], label="$B_x$ [T]")
49 if aperture:
50 axes[0].add_patch(
51 plt.Rectangle(
52 (-aperture[0], -aperture[1]),
53 2 * aperture[0],
54 2 * aperture[1],
55 fill=False,
56 linestyle="--",
57 edgecolor="k",
58 )
59 )
60 axes[0].set(xlabel="x [cm]", ylabel="y [cm]", title=f"{label}: $B_x$ at z = {zs[centre]:.0f} cm")
61 axes[0].set_aspect("equal")
62
63 axes[1].plot(xs, field[:, j0, centre, 0], label="along x, y = 0")
64 axes[1].plot(ys, field[i0, :, centre, 0], label="along y, x = 0")
65 # Clip to the aperture field so the coil and yoke return flux, which is an
66 # order of magnitude larger, does not flatten the profiles.
67 on_axis = abs(field[i0, j0, centre, 0])
68 axes[1].set_ylim(-1.5 * on_axis, 1.5 * on_axis)
69 axes[1].axhline(0.0, color="k", linewidth=0.5)
70 axes[1].legend()
71 axes[1].grid(alpha=0.3)
72 axes[1].set(xlabel="x or y [cm]", ylabel="$B_x$ [T]", title=f"{label}: transverse profiles")
73
74 integral = bending_power(field, rng).T
75 limit = np.abs(integral).max()
76 mesh = axes[2].pcolormesh(xs, ys, integral, cmap="RdBu_r", vmin=-limit, vmax=limit)
77 axes[2].figure.colorbar(mesh, ax=axes[2], label=r"$\int B_x \mathrm{d}z$ [T cm]")
78 axes[2].set(xlabel="x [cm]", ylabel="y [cm]", title=f"{label}: bending power")
79 axes[2].set_aspect("equal")
80
81 axes[3].plot(zs, field[i0, j0, :, 0], label="$B_x$")
82 axes[3].plot(zs, field[i0, j0, :, 1], label="$B_y$")
83 axes[3].plot(zs, field[i0, j0, :, 2], label="$B_z$")
84 axes[3].legend()
85 axes[3].grid(alpha=0.3)
86 axes[3].set(xlabel="z [cm]", ylabel="B [T]", title=f"{label}: on the beam axis")
87
88
89def main():
90 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
91 parser.add_argument("input", help="field map to plot")
92 parser.add_argument("-o", "--output", default="fieldMap.pdf", help="file to write")
93 parser.add_argument(
94 "--data-order",
95 choices=fmt.ORDERS,
96 default="xslow",
97 help="how to unroll the entries; xslow is what ShipBFieldMap assumes",
98 )
99 parser.add_argument(
100 "--compare-orders",
101 action="store_true",
102 help="draw both unrollings side by side",
103 )
104 parser.add_argument(
105 "--no-aperture",
106 action="store_true",
107 help="leave out the nominal spectrometer aperture outline",
108 )
109 parser.add_argument(
110 "--probe",
111 nargs=2,
112 type=float,
113 action="append",
114 metavar=("X", "Y"),
115 help="also print the bending power at this (x, y), repeatable",
116 )
117 args = parser.parse_args()
118
119 rng = fmt.read_range(args.input)
120 field = fmt.read_field(args.input, order=args.data_order, rng=rng)
121 aperture = None if args.no_aperture else APERTURE
122
123 readings = [(args.data_order, field)]
124 if args.compare_orders:
125 other = "yslow" if args.data_order == "xslow" else "xslow"
126 readings.append((other, fmt.transpose_xy(field)))
127
128 figure, grid = plt.subplots(4, len(readings), figsize=(7 * len(readings), 20), squeeze=False, layout="constrained")
129 for column, (label, values) in enumerate(readings):
130 draw([grid[row][column] for row in range(4)], rng, values, label, aperture)
131 figure.suptitle(args.input)
132 figure.savefig(args.output)
133 print(f"Wrote {args.output}")
134
135 if args.probe:
136 xs, ys, _ = rng.axis_values()
137 for label, values in readings:
138 integral = bending_power(values, rng)
139 for x, y in args.probe:
140 i, j = np.abs(xs - x).argmin(), np.abs(ys - y).argmin()
141 print(f" {label}: int Bx dz at ({xs[i]:.0f}, {ys[j]:.0f}) cm = {integral[i, j]:.3f} T cm")
142 return 0
143
144
145if __name__ == "__main__":
146 sys.exit(main())
draw(axes, rng, field, label, aperture)
bending_power(field, rng)