multipolePDM 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. multipolepdm/__init__.py +3 -0
  2. multipolepdm/__main__.py +32 -0
  3. multipolepdm/cli.py +127 -0
  4. multipolepdm/config/common.py +7 -0
  5. multipolepdm/config/p_ado.py +3 -0
  6. multipolepdm/config/p_dco.py +10 -0
  7. multipolepdm/config/pdco.py +13 -0
  8. multipolepdm/contracts.py +222 -0
  9. multipolepdm/examples/README.md +56 -0
  10. multipolepdm/examples/example.json +45 -0
  11. multipolepdm/examples/example_PDCO.json +55 -0
  12. multipolepdm/examples/example_P_DCO.json +55 -0
  13. multipolepdm/examples/example_batch.json +159 -0
  14. multipolepdm/gui/results.py +191 -0
  15. multipolepdm/gui/self_test.py +89 -0
  16. multipolepdm/gui/window.py +560 -0
  17. multipolepdm/io/export.py +255 -0
  18. multipolepdm/io/input.py +115 -0
  19. multipolepdm/jobs/manager.py +186 -0
  20. multipolepdm/jobs/workers.py +26 -0
  21. multipolepdm/models/p_ado.py +5 -0
  22. multipolepdm/models/p_dco.py +5 -0
  23. multipolepdm/models/pdco.py +5 -0
  24. multipolepdm/models/registry.py +88 -0
  25. multipolepdm/pdm/mapping.py +200 -0
  26. multipolepdm/pdm/observations.py +63 -0
  27. multipolepdm/pdm/statistics.py +229 -0
  28. multipolepdm/physics/amplitudes.py +99 -0
  29. multipolepdm/physics/joint.py +131 -0
  30. multipolepdm/physics/populations.py +52 -0
  31. multipolepdm/physics/propagation.py +43 -0
  32. multipolepdm/physics/symmetries.py +34 -0
  33. multipolepdm/plotting/__init__.py +16 -0
  34. multipolepdm/plotting/export.py +86 -0
  35. multipolepdm/plotting/intervals.py +199 -0
  36. multipolepdm/plotting/overview.py +229 -0
  37. multipolepdm/plotting/style.py +94 -0
  38. multipolepdm-0.1.0.dist-info/METADATA +40 -0
  39. multipolepdm-0.1.0.dist-info/RECORD +43 -0
  40. multipolepdm-0.1.0.dist-info/WHEEL +5 -0
  41. multipolepdm-0.1.0.dist-info/entry_points.txt +3 -0
  42. multipolepdm-0.1.0.dist-info/licenses/LICENSE +21 -0
  43. multipolepdm-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,200 @@
1
+ """Numerical change of variables on a supplied response grid."""
2
+
3
+ import numpy as np
4
+ from scipy.integrate import trapezoid
5
+
6
+ from multipolepdm.contracts import JobRequest, MappingResult, ResponseGrid
7
+
8
+ from .observations import observation_density
9
+
10
+
11
+ _NEAR_SINGULAR = 1e-12
12
+ _SIGMA_EPS_MULTIPLIER = 64
13
+ _EDGE_WIDTH_FRACTION = 0.05
14
+ _EDGE_MASS_WARNING = 0.10
15
+ _EDGE_DENSITY_WARNING = 0.10
16
+
17
+
18
+ def _grid_axis(values: np.ndarray, name: str) -> np.ndarray:
19
+ axis = np.asarray(values, dtype=float)
20
+ if axis.ndim != 1 or axis.size < 3 or not np.isfinite(axis).all():
21
+ raise ValueError(
22
+ f"{name} must be a finite one-dimensional axis with at least three points."
23
+ )
24
+ widths = np.diff(axis)
25
+ if not np.isfinite(widths).all() or not np.all(widths > 0):
26
+ raise ValueError(f"{name} must be strictly increasing with finite spacings.")
27
+ return axis
28
+
29
+
30
+ def _differentiate(
31
+ values: np.ndarray, coordinates: np.ndarray, axis: int
32
+ ) -> np.ndarray:
33
+ """Use three-point stencils. NaN propagates through any incomplete stencil."""
34
+ samples = np.moveaxis(values, axis, -1)
35
+ widths = np.diff(coordinates)
36
+ slopes = np.diff(samples, axis=-1) / widths
37
+ stencil_widths = widths[:-1] + widths[1:]
38
+ left_fraction = widths[:-1] / stencil_widths
39
+ right_fraction = widths[1:] / stencil_widths
40
+
41
+ derivative = np.empty_like(samples)
42
+ derivative[..., 1:-1] = (
43
+ right_fraction * slopes[..., :-1] + left_fraction * slopes[..., 1:]
44
+ )
45
+ derivative[..., 0] = slopes[..., 0] + left_fraction[0] * (
46
+ slopes[..., 0] - slopes[..., 1]
47
+ )
48
+ derivative[..., -1] = slopes[..., -1] + right_fraction[-1] * (
49
+ slopes[..., -1] - slopes[..., -2]
50
+ )
51
+ return np.moveaxis(derivative, -1, axis)
52
+
53
+
54
+ def _has_resolved_sigma_variation(values: np.ndarray, valid: np.ndarray) -> bool:
55
+ """Compare each xi column's sigma range with the scale of the whole response field."""
56
+ lower = np.min(values, axis=0, where=valid, initial=np.inf)
57
+ upper = np.max(values, axis=0, where=valid, initial=-np.inf)
58
+ scale = max(upper.max(), -lower.min())
59
+ if scale <= 0:
60
+ return False
61
+ relative_span = upper / scale - lower / scale
62
+ return bool(np.any(relative_span > _SIGMA_EPS_MULTIPLIER * np.finfo(float).eps))
63
+
64
+
65
+ def _edge_warnings(
66
+ coordinates: np.ndarray, density: np.ndarray, name: str
67
+ ) -> list[str]:
68
+ lower, upper = coordinates[0], coordinates[-1]
69
+ width = (upper - lower) * _EDGE_WIDTH_FRACTION
70
+ peak = density.max()
71
+ warnings = []
72
+ for side, start, stop, endpoint in (
73
+ ("lower", lower, lower + width, density[0]),
74
+ ("upper", upper - width, upper, density[-1]),
75
+ ):
76
+ interior = coordinates[(coordinates > start) & (coordinates < stop)]
77
+ edge = np.concatenate(([start], interior, [stop]))
78
+ mass = trapezoid(np.interp(edge, coordinates, density), edge)
79
+ endpoint_fraction = endpoint / peak
80
+ if mass >= _EDGE_MASS_WARNING or endpoint_fraction >= _EDGE_DENSITY_WARNING:
81
+ warnings.append(
82
+ f"{name} {side} grid edge indicates possible sensitivity to the finite scan bounds. "
83
+ f"The endpoint density is {endpoint_fraction:.1%} of the marginal peak and the outer 5% "
84
+ f"of the span contains {mass:.1%} of the in-grid mass."
85
+ )
86
+ return warnings
87
+
88
+
89
+ def map_density(job: JobRequest, response: ResponseGrid) -> MappingResult:
90
+ """Map independent measurement densities to a finite (xi_rad, sigma) grid.
91
+
92
+ The Jacobian is its absolute determinant, with NaN for undefined stencils.
93
+ Invalid observation nodes and undefined parameter-density nodes have zero
94
+ density for quadrature.
95
+ """
96
+ if len(job.target.multipoles) == 1:
97
+ raise ValueError(
98
+ "A pure one-component target has no mixing-angle degree of freedom. "
99
+ "Use the forward-only path for this target. A two-dimensional PDM PDF is undefined."
100
+ )
101
+ if job.reference_spin <= 0:
102
+ raise ValueError(
103
+ "I_ref=0 requires the forward-only path. A two-dimensional PDM PDF is undefined."
104
+ )
105
+ if (
106
+ response.reference_spin != job.reference_spin
107
+ or response.ratio_name != job.ratio_name
108
+ ):
109
+ raise ValueError(
110
+ "Response reference spin and angular-ratio name must match the job."
111
+ )
112
+
113
+ xi = _grid_axis(response.xi_rad, "xi_rad")
114
+ sigma = _grid_axis(response.sigma, "sigma")
115
+ if xi[0] <= -np.pi / 2 or xi[-1] >= np.pi / 2:
116
+ raise ValueError("xi_rad must lie strictly inside (-pi/2, pi/2).")
117
+ shape = (sigma.size, xi.size)
118
+ polar = np.asarray(response.polarization, dtype=float)
119
+ ratio = np.asarray(response.angular_ratio, dtype=float)
120
+ valid = np.asarray(response.valid, dtype=bool)
121
+ if polar.shape != shape or ratio.shape != shape or valid.shape != shape:
122
+ raise ValueError("Response arrays must have shape (n_sigma, n_xi).")
123
+ valid = valid & np.isfinite(polar) & np.isfinite(ratio)
124
+ polar = np.where(valid, polar, np.nan)
125
+ ratio = np.where(valid, ratio, np.nan)
126
+ with np.errstate(over="ignore", invalid="ignore"):
127
+ jacobian = np.abs(
128
+ _differentiate(polar, xi, axis=1) * _differentiate(ratio, sigma, axis=0)
129
+ - _differentiate(polar, sigma, axis=0) * _differentiate(ratio, xi, axis=1)
130
+ )
131
+ defined = np.isfinite(jacobian)
132
+ if not defined.any():
133
+ raise ValueError(
134
+ "No finite Jacobian on the grid. Check the response mask and derivative stencils."
135
+ )
136
+ jacobian[~defined] = np.nan
137
+ if not np.any(jacobian[defined] > 0):
138
+ raise ValueError(
139
+ "The Jacobian is zero at every defined grid point. A two-dimensional PDM PDF is undefined."
140
+ )
141
+ if not (
142
+ _has_resolved_sigma_variation(polar, valid)
143
+ or _has_resolved_sigma_variation(ratio, valid)
144
+ ):
145
+ raise ValueError(
146
+ "No resolved sigma variation in either response field on this grid "
147
+ f"(within {_SIGMA_EPS_MULTIPLIER} machine epsilons relative to each field's scale). "
148
+ "A two-dimensional PDM PDF is numerically unresolved."
149
+ )
150
+
151
+ observations = np.zeros(shape)
152
+ observations[valid] = observation_density(
153
+ polar[valid], ratio[valid], job.polarization, job.angular_ratio
154
+ )
155
+ parameter_density = np.zeros(shape)
156
+ with np.errstate(over="ignore", invalid="ignore"):
157
+ np.multiply(
158
+ observations,
159
+ jacobian,
160
+ out=parameter_density,
161
+ where=defined & (jacobian > 0),
162
+ )
163
+ normalization = float(
164
+ trapezoid(trapezoid(parameter_density, xi, axis=1), sigma)
165
+ )
166
+ if not np.isfinite(normalization) or normalization <= 0:
167
+ raise ValueError(
168
+ "The mapped grid has no positive finite normalization. Check the scan and observation scales."
169
+ )
170
+ parameter_density /= normalization
171
+
172
+ warnings = [
173
+ "Observation density assumes independent polarization and angular-ratio errors. "
174
+ "Asymmetric errors use a median-centered normal transform with a density jump at the median."
175
+ ]
176
+ if not defined.all():
177
+ warnings.append(
178
+ f"Jacobian undefined at {np.count_nonzero(~defined)} grid points. "
179
+ "Invalid responses and incomplete derivative stencils contribute zero density."
180
+ )
181
+ near_singular = np.count_nonzero(jacobian <= _NEAR_SINGULAR)
182
+ if near_singular:
183
+ warnings.append(
184
+ f"Near-singular Jacobian (<= {_NEAR_SINGULAR:g} in xi_rad, sigma) at {near_singular} grid points."
185
+ )
186
+ warnings.extend(
187
+ _edge_warnings(xi, trapezoid(parameter_density, sigma, axis=0), "xi_rad")
188
+ )
189
+ warnings.extend(
190
+ _edge_warnings(sigma, trapezoid(parameter_density, xi, axis=1), "sigma")
191
+ )
192
+ return MappingResult(
193
+ job,
194
+ response,
195
+ observations,
196
+ jacobian,
197
+ parameter_density,
198
+ normalization,
199
+ tuple(warnings),
200
+ )
@@ -0,0 +1,63 @@
1
+ """Independent polarization and angular-ratio measurement densities."""
2
+
3
+ from math import log, pi
4
+
5
+ import numpy as np
6
+
7
+ from multipolepdm.contracts import Measurement
8
+
9
+
10
+ def _log_measurement_density(
11
+ values: np.ndarray, measurement: Measurement
12
+ ) -> np.ndarray:
13
+ values = np.asarray(values, dtype=float)
14
+ scale = np.where(
15
+ values < measurement.value, measurement.err_minus, measurement.err_plus
16
+ )
17
+ with np.errstate(over="ignore"):
18
+ standardized = (values - measurement.value) / scale
19
+ return -0.5 * standardized**2 - np.log(scale) - 0.5 * log(2 * pi)
20
+
21
+
22
+ def measurement_density(values: np.ndarray, measurement: Measurement) -> np.ndarray:
23
+ """Evaluate the density of a standard normal scaled separately on each side.
24
+
25
+ Each side carries probability 1/2. The center is the median, and the
26
+ lower and upper error endpoints are the Phi(-1) and Phi(1) quantiles.
27
+ Unequal scales cause a jump at the median. The value there is the
28
+ right-hand limit.
29
+ """
30
+ return np.exp(_log_measurement_density(values, measurement))
31
+
32
+
33
+ def observation_density(
34
+ polarization: np.ndarray,
35
+ angular_ratio: np.ndarray,
36
+ polarization_measurement: Measurement,
37
+ ratio_measurement: Measurement,
38
+ ) -> np.ndarray:
39
+ """Evaluate the product density under the independent-error approximation."""
40
+ return np.exp(
41
+ _log_measurement_density(polarization, polarization_measurement)
42
+ + _log_measurement_density(angular_ratio, ratio_measurement)
43
+ )
44
+
45
+
46
+ def observation_mesh(polarization_measurement, ratio_measurement, points=257):
47
+ """Regular observed-space coordinates; distinct from response-grid samples."""
48
+
49
+ def axis(measurement):
50
+ return np.linspace(
51
+ measurement.value - 5 * measurement.err_minus,
52
+ measurement.value + 5 * measurement.err_plus,
53
+ points,
54
+ )
55
+
56
+ polar, ratio = axis(polarization_measurement), axis(ratio_measurement)
57
+ return (
58
+ polar,
59
+ ratio,
60
+ observation_density(
61
+ polar[:, None], ratio[None, :], polarization_measurement, ratio_measurement
62
+ ),
63
+ )
@@ -0,0 +1,229 @@
1
+ """Marginal densities and intervals on the displayed coordinates."""
2
+
3
+ from collections.abc import Iterable
4
+
5
+ import numpy as np
6
+ from scipy.integrate import trapezoid
7
+
8
+ from multipolepdm.contracts import Interval, MappingResult, MarginalSummary, Summary
9
+
10
+
11
+ _DELTA_AREA_TOLERANCE = 2e-7
12
+
13
+
14
+ def _delta_curve(xi: np.ndarray, density: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
15
+ """Interpolate in xi and refine the transformed piecewise-linear PDF.
16
+
17
+ Compare the trapezoid in delta against the exact xi mass on each half
18
+ segment, with an error budget apportioned by xi width.
19
+ """
20
+ area_budget = _DELTA_AREA_TOLERANCE * trapezoid(density, xi) / (xi[-1] - xi[0])
21
+ delta = np.tan(xi)
22
+ if not np.all(np.diff(delta) > 0):
23
+ raise ValueError(
24
+ "xi_rad must transform to strictly increasing delta coordinates."
25
+ )
26
+ transformed = density * np.cos(xi) ** 2
27
+ while True:
28
+ widths = np.diff(xi)
29
+ midpoint = xi[:-1] + widths / 2
30
+ left_xi_width = midpoint - xi[:-1]
31
+ right_xi_width = xi[1:] - midpoint
32
+ mid_density = density[:-1] + (density[1:] - density[:-1]) * (
33
+ left_xi_width / widths
34
+ )
35
+ mid_delta = np.tan(midpoint)
36
+ left_width = mid_delta - delta[:-1]
37
+ right_width = delta[1:] - mid_delta
38
+ linear_mid = transformed[:-1] + (transformed[1:] - transformed[:-1]) * (
39
+ left_width / (left_width + right_width)
40
+ )
41
+ left_error = np.abs(
42
+ (
43
+ left_width * (transformed[:-1] + linear_mid)
44
+ - left_xi_width * (density[:-1] + mid_density)
45
+ )
46
+ / 2
47
+ )
48
+ right_error = np.abs(
49
+ (
50
+ right_width * (linear_mid + transformed[1:])
51
+ - right_xi_width * (mid_density + density[1:])
52
+ )
53
+ / 2
54
+ )
55
+ split = np.flatnonzero(
56
+ (left_error + right_error > area_budget * widths)
57
+ & (left_xi_width > 0)
58
+ & (right_xi_width > 0)
59
+ & (left_width > 0)
60
+ & (right_width > 0)
61
+ )
62
+ if split.size == 0:
63
+ return delta, transformed
64
+ xi = np.insert(xi, split + 1, midpoint[split])
65
+ density = np.insert(density, split + 1, mid_density[split])
66
+ delta = np.insert(delta, split + 1, mid_delta[split])
67
+ transformed = np.insert(
68
+ transformed, split + 1, mid_density[split] * np.cos(midpoint[split]) ** 2
69
+ )
70
+
71
+
72
+ def _quantile(
73
+ coordinate: np.ndarray,
74
+ density: np.ndarray,
75
+ cumulative: np.ndarray,
76
+ probability: float,
77
+ ) -> float:
78
+ target = probability * cumulative[-1]
79
+ upper = int(np.searchsorted(cumulative, target))
80
+ if upper == 0 or target == cumulative[upper]:
81
+ return float(coordinate[upper])
82
+ lower = upper - 1
83
+ mass_fraction = (target - cumulative[lower]) / (
84
+ cumulative[upper] - cumulative[lower]
85
+ )
86
+ left, right = density[lower : upper + 1] / max(density[lower], density[upper])
87
+ root = np.sqrt((1 - mass_fraction) * left**2 + mass_fraction * right**2)
88
+ position = mass_fraction * (left + right) / (left + root)
89
+ return float(coordinate[lower] + position * (coordinate[upper] - coordinate[lower]))
90
+
91
+
92
+ def _hdi(
93
+ coordinate: np.ndarray, density: np.ndarray, mass: float
94
+ ) -> tuple[tuple[tuple[float, float], ...], float]:
95
+ """Find the density threshold and integrate the clipped linear segments."""
96
+ widths = np.diff(coordinate)
97
+ left, right = density[:-1], density[1:]
98
+ low, high = np.minimum(left, right), np.maximum(left, right)
99
+ cell_mass = widths * (left + right) / 2
100
+ target = mass * cell_mass.sum()
101
+ flat_heights = np.unique(low[(low == high) & (low > 0)])
102
+
103
+ def mass_at_or_above(height: float) -> float:
104
+ partial = (low < height) & (high > height)
105
+ fraction = (high[partial] - height) / (high[partial] - low[partial])
106
+ return float(
107
+ cell_mass[low >= height].sum()
108
+ + np.sum(widths[partial] * fraction * (high[partial] + height) / 2)
109
+ )
110
+
111
+ lower, upper = 0.0, float(density.max())
112
+ while True:
113
+ threshold = lower + (upper - lower) / 2
114
+ if threshold == lower or threshold == upper:
115
+ break
116
+ if mass_at_or_above(threshold) >= target:
117
+ lower = threshold
118
+ else:
119
+ upper = threshold
120
+
121
+ threshold = lower
122
+ plateau = np.searchsorted(flat_heights, lower)
123
+ if plateau < flat_heights.size and flat_heights[plateau] <= upper:
124
+ threshold = float(flat_heights[plateau])
125
+
126
+ above = high > threshold
127
+ starts, stops = coordinate[:-1].copy(), coordinate[1:].copy()
128
+ rising = above & (left < threshold)
129
+ falling = above & (right < threshold)
130
+ starts[rising] += (
131
+ widths[rising] * (threshold - left[rising]) / (right[rising] - left[rising])
132
+ )
133
+ stops[falling] -= (
134
+ widths[falling]
135
+ * (threshold - right[falling])
136
+ / (left[falling] - right[falling])
137
+ )
138
+
139
+ tied = (low == threshold) & (high == threshold) & (threshold > 0)
140
+ if tied.any():
141
+ remaining = target - (mass_at_or_above(threshold) - cell_mass[tied].sum())
142
+ for index in np.flatnonzero(tied):
143
+ if remaining <= 0:
144
+ break
145
+ if remaining < cell_mass[index]:
146
+ stops[index] = starts[index] + remaining / threshold
147
+ above[index] = True
148
+ remaining -= cell_mass[index]
149
+
150
+ intervals = []
151
+ for start, stop in zip(starts[above], stops[above]):
152
+ if stop <= start:
153
+ continue
154
+ if intervals and start <= intervals[-1][1]:
155
+ intervals[-1] = (intervals[-1][0], float(stop))
156
+ else:
157
+ intervals.append((float(start), float(stop)))
158
+ return tuple(intervals), threshold
159
+
160
+
161
+ def _summarize(
162
+ coordinate: np.ndarray, density: np.ndarray, masses: tuple[float, ...]
163
+ ) -> MarginalSummary:
164
+ widths = np.diff(coordinate)
165
+ if not np.all(widths > 0):
166
+ raise ValueError("Marginal coordinates must be strictly increasing.")
167
+ area = float(trapezoid(density, coordinate))
168
+ if not np.isfinite(area) or area <= 0:
169
+ raise ValueError("A marginal must have positive finite mass.")
170
+ density = density / area
171
+ cumulative = np.concatenate(
172
+ ([0.0], np.cumsum(widths * (density[:-1] + density[1:]) / 2))
173
+ )
174
+
175
+ intervals = []
176
+ for mass in masses:
177
+ tail = (1 - mass) / 2
178
+ eti = (
179
+ _quantile(coordinate, density, cumulative, tail),
180
+ _quantile(coordinate, density, cumulative, 1 - tail),
181
+ )
182
+ hdi, threshold = _hdi(coordinate, density, mass)
183
+ intervals.append(Interval(mass, eti, hdi, threshold))
184
+ return MarginalSummary(
185
+ coordinate,
186
+ density,
187
+ _quantile(coordinate, density, cumulative, 0.5),
188
+ float(coordinate[np.argmax(density)]),
189
+ tuple(intervals),
190
+ )
191
+
192
+
193
+ def summarize_density(
194
+ result: MappingResult, masses: Iterable[float] = (0.68, 0.95)
195
+ ) -> Summary:
196
+ """Marginalize the core PDF and summarize it in delta and sigma/I_ref.
197
+
198
+ ETI and HDI use the returned piecewise-linear curves. At an HDI threshold
199
+ plateau, ties are taken from left to right to attain the requested mass.
200
+ """
201
+ masses = tuple(float(mass) for mass in masses)
202
+ if any(not 0 < mass < 1 for mass in masses):
203
+ raise ValueError("Interval masses must lie strictly between zero and one.")
204
+ response = result.response
205
+ spin = response.reference_spin
206
+ if not np.isfinite(spin) or spin <= 0:
207
+ raise ValueError(
208
+ "A finite positive I_ref is required to summarize sigma/I_ref."
209
+ )
210
+ xi, sigma = (
211
+ np.asarray(response.xi_rad, dtype=float),
212
+ np.asarray(response.sigma, dtype=float),
213
+ )
214
+ density = np.asarray(result.parameter_density, dtype=float)
215
+ if (
216
+ density.shape != (sigma.size, xi.size)
217
+ or not np.isfinite(density).all()
218
+ or np.any(density < 0)
219
+ ):
220
+ raise ValueError(
221
+ "Parameter density must be finite and nonnegative with shape (n_sigma, n_xi)."
222
+ )
223
+ xi_density = trapezoid(density, sigma, axis=0)
224
+ sigma_density = trapezoid(density, xi, axis=1)
225
+ delta, delta_density = _delta_curve(xi, xi_density)
226
+ return Summary(
227
+ delta=_summarize(delta, delta_density, masses),
228
+ sigma_over_i=_summarize(sigma / spin, spin * sigma_density, masses),
229
+ )
@@ -0,0 +1,99 @@
1
+ """Unit-total-radiation photon amplitudes in a declared helicity basis.
2
+
3
+ Rows are daughter m, columns are parent m; helicity order is (+1, -1).
4
+ The analyzer uses electric-field axes e_theta (parallel) and e_phi (perp).
5
+ All angles accepted here are radians. The (-1)^L basis phase makes the input
6
+ E2/M1 ratio the KS/Droste radiation amplitude ratio (D96 Eqs.3/5/7), not the
7
+ opposite-signed bare CG/D basis ratio.
8
+ """
9
+
10
+ from functools import lru_cache
11
+
12
+ import numpy as np
13
+ from scipy.linalg import expm
14
+ from sympy import Rational
15
+ from sympy.physics.wigner import clebsch_gordan
16
+
17
+ from multipolepdm.physics.populations import substates
18
+
19
+
20
+ @lru_cache(maxsize=256)
21
+ def coupling_matrices(ji, jf, rank):
22
+ mi, mf = substates(ji), substates(jf)
23
+ result = np.zeros((2 * rank + 1, len(mf), len(mi)))
24
+ a, b = Rational(round(2 * jf), 2), Rational(round(2 * ji), 2)
25
+ for f, m_f in enumerate(mf):
26
+ for i, m_i in enumerate(mi):
27
+ q = m_i - m_f
28
+ if abs(q) <= rank and q == round(q):
29
+ result[int(q + rank), f, i] = float(
30
+ clebsch_gordan(
31
+ a,
32
+ rank,
33
+ b,
34
+ Rational(round(2 * m_f), 2),
35
+ int(q),
36
+ Rational(round(2 * m_i), 2),
37
+ )
38
+ )
39
+ result.setflags(write=False)
40
+ return result
41
+
42
+
43
+ @lru_cache(maxsize=512)
44
+ def small_d(rank, theta):
45
+ m = np.arange(-rank, rank + 1)
46
+ raising = np.diag(np.sqrt((rank - m[:-1]) * (rank + m[:-1] + 1)), -1)
47
+ value = expm((raising.T - raising) * (theta / 2))
48
+ value.setflags(write=False)
49
+ return value
50
+
51
+
52
+ @lru_cache(maxsize=1024)
53
+ def pure_amplitudes(ji, jf, multipole, theta, phi):
54
+ rank = int(multipole[1:])
55
+ couplings = coupling_matrices(ji, jf, rank)
56
+ q = np.arange(-rank, rank + 1)
57
+ d = small_d(rank, float(theta))
58
+ amplitudes = []
59
+ for helicity in (1, -1):
60
+ angular = np.exp(1j * q * phi) * d[:, helicity + rank]
61
+ electric = helicity if multipole.startswith("E") else 1
62
+ source_phase = (-1) ** rank
63
+ amplitudes.append(
64
+ source_phase
65
+ * electric
66
+ * np.sqrt((2 * rank + 1) / (8 * np.pi))
67
+ * np.einsum("q,qfi->fi", angular, couplings)
68
+ )
69
+ value = np.asarray(amplitudes)
70
+ value.setflags(write=False)
71
+ return value
72
+
73
+
74
+ def emission_amplitudes(transition, theta, phi=0.0, xi_rad=None):
75
+ parts = [
76
+ pure_amplitudes(
77
+ transition.spin_initial, transition.spin_final, p, float(theta), float(phi)
78
+ )
79
+ for p in transition.multipoles
80
+ ]
81
+ if len(parts) == 1:
82
+ return parts[0]
83
+ xi = np.arctan(transition.delta) if xi_rad is None else xi_rad
84
+ return np.cos(xi) * parts[0] + np.sin(xi) * parts[1]
85
+
86
+
87
+ def analyzer_amplitudes(helicity):
88
+ plus, minus = helicity
89
+ return (plus + minus) / np.sqrt(2), (plus - minus) / (1j * np.sqrt(2))
90
+
91
+
92
+ def emit(rho, amplitudes):
93
+ """Sum specified polarization channels without renormalizing gate weights."""
94
+ amplitudes = np.asarray(amplitudes)
95
+ if amplitudes.ndim == 2:
96
+ amplitudes = amplitudes[None, ...]
97
+ return np.einsum(
98
+ "afi,...ij,agj->...fg", amplitudes, rho, amplitudes.conj(), optimize=True
99
+ )