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.
- multipolepdm/__init__.py +3 -0
- multipolepdm/__main__.py +32 -0
- multipolepdm/cli.py +127 -0
- multipolepdm/config/common.py +7 -0
- multipolepdm/config/p_ado.py +3 -0
- multipolepdm/config/p_dco.py +10 -0
- multipolepdm/config/pdco.py +13 -0
- multipolepdm/contracts.py +222 -0
- multipolepdm/examples/README.md +56 -0
- multipolepdm/examples/example.json +45 -0
- multipolepdm/examples/example_PDCO.json +55 -0
- multipolepdm/examples/example_P_DCO.json +55 -0
- multipolepdm/examples/example_batch.json +159 -0
- multipolepdm/gui/results.py +191 -0
- multipolepdm/gui/self_test.py +89 -0
- multipolepdm/gui/window.py +560 -0
- multipolepdm/io/export.py +255 -0
- multipolepdm/io/input.py +115 -0
- multipolepdm/jobs/manager.py +186 -0
- multipolepdm/jobs/workers.py +26 -0
- multipolepdm/models/p_ado.py +5 -0
- multipolepdm/models/p_dco.py +5 -0
- multipolepdm/models/pdco.py +5 -0
- multipolepdm/models/registry.py +88 -0
- multipolepdm/pdm/mapping.py +200 -0
- multipolepdm/pdm/observations.py +63 -0
- multipolepdm/pdm/statistics.py +229 -0
- multipolepdm/physics/amplitudes.py +99 -0
- multipolepdm/physics/joint.py +131 -0
- multipolepdm/physics/populations.py +52 -0
- multipolepdm/physics/propagation.py +43 -0
- multipolepdm/physics/symmetries.py +34 -0
- multipolepdm/plotting/__init__.py +16 -0
- multipolepdm/plotting/export.py +86 -0
- multipolepdm/plotting/intervals.py +199 -0
- multipolepdm/plotting/overview.py +229 -0
- multipolepdm/plotting/style.py +94 -0
- multipolepdm-0.1.0.dist-info/METADATA +40 -0
- multipolepdm-0.1.0.dist-info/RECORD +43 -0
- multipolepdm-0.1.0.dist-info/WHEEL +5 -0
- multipolepdm-0.1.0.dist-info/entry_points.txt +3 -0
- multipolepdm-0.1.0.dist-info/licenses/LICENSE +21 -0
- multipolepdm-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Joint intensities and their exact quadratic dependence on target mixing."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from multipolepdm.physics.amplitudes import (
|
|
6
|
+
analyzer_amplitudes,
|
|
7
|
+
emission_amplitudes,
|
|
8
|
+
emit,
|
|
9
|
+
)
|
|
10
|
+
from multipolepdm.physics.populations import initial_population
|
|
11
|
+
from multipolepdm.physics.propagation import propagate_path, propagate_unobserved
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
AZIMUTH_NODES = np.arange(9) * (2 * np.pi / 9)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def azimuth_mean_channels(job, xi_rad, rho, target_direction, gate_theta):
|
|
18
|
+
"""Average intensities at fixed gate polar angle, not polarization ratios.
|
|
19
|
+
|
|
20
|
+
Nine equispaced nodes integrate every azimuth harmonic of the supported
|
|
21
|
+
dipole/quadrupole photons exactly up to floating-point roundoff.
|
|
22
|
+
"""
|
|
23
|
+
return np.mean(
|
|
24
|
+
[
|
|
25
|
+
joint_channels(job, xi_rad, rho, target_direction, (gate_theta, phi))
|
|
26
|
+
for phi in AZIMUTH_NODES
|
|
27
|
+
],
|
|
28
|
+
axis=0,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def source_basis(job):
|
|
33
|
+
d = round(2 * job.reference_spin + 1)
|
|
34
|
+
basis = np.zeros((d, d, d), dtype=complex)
|
|
35
|
+
basis[np.arange(d), np.arange(d), np.arange(d)] = 1
|
|
36
|
+
return basis
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def joint_channels(job, xi_rad, rho, target_direction, gate_direction):
|
|
40
|
+
"""Return parallel/perp target intensities, summing gate polarization.
|
|
41
|
+
|
|
42
|
+
Directions are (theta_rad, phi_rad). rho may be unnormalized and batched.
|
|
43
|
+
No branch normalization is performed, including at intermediate levels.
|
|
44
|
+
"""
|
|
45
|
+
target = emission_amplitudes(job.target, *target_direction, xi_rad=xi_rad)
|
|
46
|
+
gate = emission_amplitudes(job.gate, *gate_direction)
|
|
47
|
+
result = []
|
|
48
|
+
for analyzer in analyzer_amplitudes(target):
|
|
49
|
+
if job.target_first:
|
|
50
|
+
state = emit(rho, analyzer)
|
|
51
|
+
state = propagate_path(state, job.intermediates)
|
|
52
|
+
state = emit(state, gate)
|
|
53
|
+
else:
|
|
54
|
+
state = emit(rho, gate)
|
|
55
|
+
state = propagate_path(state, job.intermediates)
|
|
56
|
+
state = emit(state, analyzer)
|
|
57
|
+
result.append(np.trace(state, axis1=-2, axis2=-1).real)
|
|
58
|
+
return np.asarray(result)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def single_channels(job, xi_rad, rho, direction):
|
|
62
|
+
if job.mode != "P_ADO" and not job.target_first:
|
|
63
|
+
rho = propagate_unobserved(rho, job.gate)
|
|
64
|
+
rho = propagate_path(rho, job.intermediates)
|
|
65
|
+
a = emission_amplitudes(job.target, *direction, xi_rad=xi_rad)
|
|
66
|
+
return np.asarray(
|
|
67
|
+
[
|
|
68
|
+
np.trace(emit(rho, t), axis1=-2, axis2=-1).real
|
|
69
|
+
for t in analyzer_amplitudes(a)
|
|
70
|
+
]
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def quadratic_coefficients(evaluator):
|
|
75
|
+
mm = evaluator(0.0)
|
|
76
|
+
ee = evaluator(np.pi / 2)
|
|
77
|
+
me = evaluator(np.pi / 4) - (mm + ee) / 2
|
|
78
|
+
return np.stack((mm, me, ee))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def evaluate_quadratic(coefficients, populations, xi_rad):
|
|
82
|
+
# coefficients: [MM, ME, EE] x channels x source-m; output: channels x sigma x xi
|
|
83
|
+
strengths = np.einsum("kcm,sm->kcs", coefficients, populations, optimize=True)
|
|
84
|
+
c, s = np.cos(xi_rad), np.sin(xi_rad)
|
|
85
|
+
return (
|
|
86
|
+
strengths[0, ..., None] * c**2
|
|
87
|
+
+ 2 * strengths[1, ..., None] * c * s
|
|
88
|
+
+ strengths[2, ..., None] * s**2
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def response_channels(job, xi_rad, sigma, conditional=False):
|
|
93
|
+
g = job.geometry
|
|
94
|
+
rad = np.deg2rad
|
|
95
|
+
source = source_basis(job)
|
|
96
|
+
pop = initial_population(job.reference_spin, sigma)
|
|
97
|
+
pdir = (rad(g.theta_p_deg), rad(g.phi_p_deg))
|
|
98
|
+
if conditional:
|
|
99
|
+
pgate = (rad(g.theta_gate_p_deg), rad(g.phi_gate_p_deg))
|
|
100
|
+
if g.polarization_gate_azimuth_average:
|
|
101
|
+
polar = lambda xi: azimuth_mean_channels(job, xi, source, pdir, pgate[0])
|
|
102
|
+
else:
|
|
103
|
+
polar = lambda xi: joint_channels(job, xi, source, pdir, pgate)
|
|
104
|
+
else:
|
|
105
|
+
polar = lambda xi: single_channels(job, xi, source, pdir)
|
|
106
|
+
a = (rad(g.theta_a_deg), 0.0)
|
|
107
|
+
b = (rad(g.theta_b_deg), rad(g.relative_phi_deg))
|
|
108
|
+
if job.mode == "P_ADO":
|
|
109
|
+
ratio = lambda xi: np.stack(
|
|
110
|
+
(
|
|
111
|
+
single_channels(job, xi, source, a).sum(axis=0),
|
|
112
|
+
single_channels(job, xi, source, b).sum(axis=0),
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
elif g.ratio_azimuth_average:
|
|
116
|
+
ratio = lambda xi: np.stack(
|
|
117
|
+
(
|
|
118
|
+
azimuth_mean_channels(job, xi, source, a, b[0]).sum(axis=0),
|
|
119
|
+
azimuth_mean_channels(job, xi, source, (b[0], 0.0), a[0]).sum(axis=0),
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
else:
|
|
123
|
+
ratio = lambda xi: np.stack(
|
|
124
|
+
(
|
|
125
|
+
joint_channels(job, xi, source, a, b).sum(axis=0),
|
|
126
|
+
joint_channels(job, xi, source, (b[0], 0.0), (a[0], b[1])).sum(axis=0),
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
cp = quadratic_coefficients(polar)
|
|
130
|
+
cr = quadratic_coefficients(ratio)
|
|
131
|
+
return evaluate_quadratic(cp, pop, xi_rad), evaluate_quadratic(cr, pop, xi_rad)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Axial Gaussian source populations; no gated-state Gaussian replacement."""
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from sympy import Rational
|
|
7
|
+
from sympy.physics.wigner import clebsch_gordan
|
|
8
|
+
|
|
9
|
+
from multipolepdm.contracts import spin
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def substates(j):
|
|
13
|
+
return np.arange(-spin(j), spin(j) + 1)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def initial_population(j, sigma):
|
|
17
|
+
sigma = np.asarray(sigma, dtype=float)
|
|
18
|
+
if np.any(~np.isfinite(sigma)) or np.any(sigma <= 0):
|
|
19
|
+
raise ValueError("sigma must be finite and positive.")
|
|
20
|
+
m = substates(j)
|
|
21
|
+
# Subtract the least m^2 before exponentiation, including half-integer spins.
|
|
22
|
+
offset = m * m - np.min(m * m)
|
|
23
|
+
# Minimal-|m| states retain unit relative weight if sigma squared underflows.
|
|
24
|
+
with np.errstate(over="ignore", under="ignore", divide="ignore", invalid="ignore"):
|
|
25
|
+
exponent = np.where(offset == 0, 0.0, -offset / (2 * sigma[..., None] ** 2))
|
|
26
|
+
weights = np.exp(exponent)
|
|
27
|
+
return weights / weights.sum(axis=-1, keepdims=True)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@lru_cache(maxsize=256)
|
|
31
|
+
def tensor_weights(j, rank):
|
|
32
|
+
jj = Rational(round(2 * spin(j)), 2)
|
|
33
|
+
return np.array(
|
|
34
|
+
[
|
|
35
|
+
float(
|
|
36
|
+
(-1) ** round(j - m)
|
|
37
|
+
* clebsch_gordan(
|
|
38
|
+
jj,
|
|
39
|
+
jj,
|
|
40
|
+
rank,
|
|
41
|
+
Rational(round(2 * m), 2),
|
|
42
|
+
Rational(round(-2 * m), 2),
|
|
43
|
+
0,
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
for m in substates(j)
|
|
47
|
+
]
|
|
48
|
+
) * np.sqrt(2 * j + 1)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def orientation_tensor(j, populations, rank):
|
|
52
|
+
return np.asarray(populations) @ tensor_weights(j, rank)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Exact full-direction, polarization-summed unobserved transition channel."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from multipolepdm.physics.amplitudes import coupling_matrices, emit
|
|
6
|
+
from multipolepdm.physics.populations import orientation_tensor, tensor_weights
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def propagate_unobserved(rho, transition):
|
|
10
|
+
angle = np.arctan(transition.delta)
|
|
11
|
+
weights = (
|
|
12
|
+
(1.0,)
|
|
13
|
+
if len(transition.multipoles) == 1
|
|
14
|
+
else (np.cos(angle) ** 2, np.sin(angle) ** 2)
|
|
15
|
+
)
|
|
16
|
+
value = 0
|
|
17
|
+
for multipole, weight in zip(transition.multipoles, weights):
|
|
18
|
+
value = value + weight * emit(
|
|
19
|
+
rho,
|
|
20
|
+
coupling_matrices(
|
|
21
|
+
transition.spin_initial, transition.spin_final, int(multipole[1:])
|
|
22
|
+
),
|
|
23
|
+
)
|
|
24
|
+
return value
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def propagate_path(rho, path):
|
|
28
|
+
for transition in path:
|
|
29
|
+
rho = propagate_unobserved(rho, transition)
|
|
30
|
+
return rho
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def deorientation_coefficient(transition, rank):
|
|
34
|
+
"""Transfer eigenvalue for normalized B_k, computed from the exact channel."""
|
|
35
|
+
if rank > 2 * min(transition.spin_initial, transition.spin_final):
|
|
36
|
+
return 0.0
|
|
37
|
+
before = tensor_weights(transition.spin_initial, rank)
|
|
38
|
+
rho = np.diag(before)
|
|
39
|
+
after = propagate_unobserved(rho, transition).diagonal().real
|
|
40
|
+
return float(
|
|
41
|
+
orientation_tensor(transition.spin_final, after, rank)
|
|
42
|
+
/ orientation_tensor(transition.spin_initial, before, rank)
|
|
43
|
+
)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Exact observable identities for the declared axial source and photon model."""
|
|
2
|
+
|
|
3
|
+
from fractions import Fraction
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def observable_identities(job):
|
|
7
|
+
g = job.geometry
|
|
8
|
+
# Compare declared decimal angles exactly, without an angular tolerance.
|
|
9
|
+
angle = lambda value: Fraction(str(value))
|
|
10
|
+
a, b = angle(g.theta_a_deg), angle(g.theta_b_deg)
|
|
11
|
+
unit_ratio = a == b or a + b == 180
|
|
12
|
+
p, gate_p = angle(g.theta_p_deg), angle(g.theta_gate_p_deg)
|
|
13
|
+
pole = lambda theta: theta == 0 or theta == 180
|
|
14
|
+
if job.mode != "PDCO":
|
|
15
|
+
zero_polarization = pole(p)
|
|
16
|
+
else:
|
|
17
|
+
zero_polarization = pole(p) and (
|
|
18
|
+
pole(gate_p) or g.polarization_gate_azimuth_average
|
|
19
|
+
)
|
|
20
|
+
delta_phi = (angle(g.phi_p_deg) - angle(g.phi_gate_p_deg)) % 360
|
|
21
|
+
collinear = (p == gate_p and delta_phi == 0) or (
|
|
22
|
+
p + gate_p == 180 and abs(delta_phi) == 180
|
|
23
|
+
)
|
|
24
|
+
final_spin = job.gate.spin_final if job.target_first else job.target.spin_final
|
|
25
|
+
# Collinear photons have total projection 0 or +/-2. If only 0 is
|
|
26
|
+
# allowed, tracing the gate helicity removes all linear polarization.
|
|
27
|
+
if (
|
|
28
|
+
not g.polarization_gate_azimuth_average
|
|
29
|
+
and not job.intermediates
|
|
30
|
+
and job.reference_spin + final_spin < 2
|
|
31
|
+
and collinear
|
|
32
|
+
):
|
|
33
|
+
zero_polarization = True
|
|
34
|
+
return unit_ratio, zero_polarization
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Shared scientific plotting and image export for PDM."""
|
|
2
|
+
|
|
3
|
+
from .export import save_overview, save_panel, supported_formats
|
|
4
|
+
from .overview import PreviewData, make_panel, make_preview
|
|
5
|
+
from .style import GUI_STYLE, REPORT_STYLE
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"GUI_STYLE",
|
|
9
|
+
"REPORT_STYLE",
|
|
10
|
+
"PreviewData",
|
|
11
|
+
"make_panel",
|
|
12
|
+
"make_preview",
|
|
13
|
+
"save_overview",
|
|
14
|
+
"save_panel",
|
|
15
|
+
"supported_formats",
|
|
16
|
+
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Save report-sized Matplotlib figures from PDM result data."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from tempfile import TemporaryDirectory
|
|
5
|
+
|
|
6
|
+
from matplotlib import rc_context
|
|
7
|
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
8
|
+
from matplotlib.colors import to_rgb
|
|
9
|
+
from matplotlib.figure import Figure
|
|
10
|
+
|
|
11
|
+
from multipolepdm.contracts import MappingResult, Summary
|
|
12
|
+
|
|
13
|
+
from .intervals import HDI_ARTIST_PREFIX
|
|
14
|
+
from .overview import make_panel, make_preview
|
|
15
|
+
from .style import EXPORT_DPI, HDI_ALPHA, HDI_COLOR, MATPLOTLIB_LOCK, MATPLOTLIB_STYLE
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def supported_formats() -> dict[str, str]:
|
|
19
|
+
"""Return backend formats that can be exported without a TeX toolchain."""
|
|
20
|
+
return {
|
|
21
|
+
extension: name
|
|
22
|
+
for extension, name in FigureCanvasAgg.get_supported_filetypes().items()
|
|
23
|
+
if extension != "pgf"
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _flatten_hdi_alpha(figure: Figure) -> None:
|
|
28
|
+
"""Use the equivalent opaque color for PostScript on a white background."""
|
|
29
|
+
color = tuple(1 - HDI_ALPHA * (1 - channel) for channel in to_rgb(HDI_COLOR))
|
|
30
|
+
for artist in figure.findobj():
|
|
31
|
+
key = artist.get_gid()
|
|
32
|
+
if key and key.startswith(HDI_ARTIST_PREFIX):
|
|
33
|
+
artist.set_alpha(1)
|
|
34
|
+
artist.set_facecolor(color)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _save(figure: Figure, path: str | Path, dpi: float) -> Path:
|
|
38
|
+
destination = Path(path)
|
|
39
|
+
if not destination.suffix:
|
|
40
|
+
destination = destination.with_suffix(".png")
|
|
41
|
+
extension = destination.suffix[1:].lower()
|
|
42
|
+
if extension not in supported_formats():
|
|
43
|
+
raise ValueError(f"Unsupported figure format: {extension!r}.")
|
|
44
|
+
if extension in ("eps", "ps"):
|
|
45
|
+
_flatten_hdi_alpha(figure)
|
|
46
|
+
with TemporaryDirectory(dir=destination.parent, prefix=".pdm-") as directory:
|
|
47
|
+
temporary = Path(directory) / destination.name
|
|
48
|
+
with MATPLOTLIB_LOCK, rc_context(MATPLOTLIB_STYLE):
|
|
49
|
+
figure.savefig(temporary, format=extension, dpi=dpi, facecolor="white")
|
|
50
|
+
temporary.replace(destination)
|
|
51
|
+
return destination
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def save_overview(
|
|
55
|
+
result: MappingResult,
|
|
56
|
+
summary: Summary,
|
|
57
|
+
path: str | Path,
|
|
58
|
+
*,
|
|
59
|
+
mass: float | None = None,
|
|
60
|
+
dpi: float = EXPORT_DPI,
|
|
61
|
+
focus_delta: bool = True,
|
|
62
|
+
) -> Path:
|
|
63
|
+
"""Save all four panels at report size, using the filename extension."""
|
|
64
|
+
return _save(
|
|
65
|
+
make_preview(result, summary, mass=mass, focus_delta=focus_delta).figure,
|
|
66
|
+
path,
|
|
67
|
+
dpi,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def save_panel(
|
|
72
|
+
result: MappingResult,
|
|
73
|
+
summary: Summary,
|
|
74
|
+
panel: str,
|
|
75
|
+
path: str | Path,
|
|
76
|
+
*,
|
|
77
|
+
mass: float | None = None,
|
|
78
|
+
dpi: float = EXPORT_DPI,
|
|
79
|
+
focus_delta: bool = True,
|
|
80
|
+
) -> Path:
|
|
81
|
+
"""Save one panel at report size, using the filename extension."""
|
|
82
|
+
return _save(
|
|
83
|
+
make_panel(result, summary, panel, mass=mass, focus_delta=focus_delta),
|
|
84
|
+
path,
|
|
85
|
+
dpi,
|
|
86
|
+
)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Draw marginal PDFs with interval boundaries in the PDF's coordinate."""
|
|
2
|
+
|
|
3
|
+
from math import isclose, isfinite
|
|
4
|
+
|
|
5
|
+
from matplotlib.axes import Axes
|
|
6
|
+
from matplotlib.patches import Patch
|
|
7
|
+
from matplotlib.transforms import ScaledTranslation
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from multipolepdm.contracts import Interval, MarginalSummary
|
|
11
|
+
|
|
12
|
+
from .style import ETI_COLOR, HDI_ALPHA, HDI_COLOR, PDF_COLOR, PlotStyle, style_axes
|
|
13
|
+
|
|
14
|
+
HDI_ARTIST_PREFIX = "pdm-hdi-"
|
|
15
|
+
DELTA_FOCUS_LABEL = "View: 95% ETI + HDI envelope"
|
|
16
|
+
DELTA_FOCUS_PADDING = 0.05
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _interval_at_mass(intervals: tuple[Interval, ...], mass: float) -> Interval | None:
|
|
20
|
+
return next(
|
|
21
|
+
(
|
|
22
|
+
interval
|
|
23
|
+
for interval in intervals
|
|
24
|
+
if isclose(interval.mass, mass, rel_tol=0, abs_tol=1e-9)
|
|
25
|
+
),
|
|
26
|
+
None,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _select_interval(
|
|
31
|
+
intervals: tuple[Interval, ...], mass: float | None
|
|
32
|
+
) -> Interval | None:
|
|
33
|
+
interval = _interval_at_mass(intervals, 0.68 if mass is None else mass)
|
|
34
|
+
if interval is not None:
|
|
35
|
+
return interval
|
|
36
|
+
if mass is not None:
|
|
37
|
+
raise ValueError(
|
|
38
|
+
f"The marginal does not contain a {mass:.6g} probability interval."
|
|
39
|
+
)
|
|
40
|
+
return intervals[0] if intervals else None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _interval_envelope(interval: Interval) -> tuple[float, float]:
|
|
44
|
+
endpoints = (
|
|
45
|
+
*interval.eti,
|
|
46
|
+
*(endpoint for branch in interval.hdi for endpoint in branch),
|
|
47
|
+
)
|
|
48
|
+
return min(endpoints), max(endpoints)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def delta_display_limits(marginal: MarginalSummary) -> tuple[float, float] | None:
|
|
52
|
+
"""Return the padded 95% ETI/HDI envelope, or None for a full-range view."""
|
|
53
|
+
interval = _interval_at_mass(marginal.intervals, 0.95)
|
|
54
|
+
if interval is None:
|
|
55
|
+
return None
|
|
56
|
+
lower, upper = _interval_envelope(interval)
|
|
57
|
+
span = upper - lower
|
|
58
|
+
if not isfinite(span) or span <= 0:
|
|
59
|
+
return None
|
|
60
|
+
domain_lower, domain_upper = (
|
|
61
|
+
float(marginal.coordinate[0]),
|
|
62
|
+
float(marginal.coordinate[-1]),
|
|
63
|
+
)
|
|
64
|
+
if not domain_lower <= lower < upper <= domain_upper:
|
|
65
|
+
return None
|
|
66
|
+
padding = DELTA_FOCUS_PADDING * span
|
|
67
|
+
limits = max(domain_lower, lower - padding), min(domain_upper, upper + padding)
|
|
68
|
+
return None if limits == (domain_lower, domain_upper) else limits
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _focus_delta_axes(
|
|
72
|
+
axes: Axes, marginal: MarginalSummary, selected: Interval, style: PlotStyle
|
|
73
|
+
) -> None:
|
|
74
|
+
limits = delta_display_limits(marginal)
|
|
75
|
+
lower, upper = _interval_envelope(selected)
|
|
76
|
+
if limits is None or lower < limits[0] or limits[1] < upper:
|
|
77
|
+
return
|
|
78
|
+
axes.set_xlim(*limits)
|
|
79
|
+
offset = ScaledTranslation(
|
|
80
|
+
0, -3.75 * style.axis_pt / 72, axes.figure.dpi_scale_trans
|
|
81
|
+
)
|
|
82
|
+
caption = axes.text(
|
|
83
|
+
0.5,
|
|
84
|
+
0,
|
|
85
|
+
DELTA_FOCUS_LABEL,
|
|
86
|
+
transform=axes.transAxes + offset,
|
|
87
|
+
ha="center",
|
|
88
|
+
va="top",
|
|
89
|
+
fontsize=style.tick_pt,
|
|
90
|
+
color="#4A4A4A",
|
|
91
|
+
)
|
|
92
|
+
axes.callbacks.connect(
|
|
93
|
+
"xlim_changed",
|
|
94
|
+
lambda changed_axes: caption.set_visible(changed_axes.get_xlim() == limits),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _segment(
|
|
99
|
+
coordinate: np.ndarray, density: np.ndarray, lower: float, upper: float
|
|
100
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
101
|
+
first = np.searchsorted(coordinate, lower, side="right")
|
|
102
|
+
last = np.searchsorted(coordinate, upper, side="left")
|
|
103
|
+
segment_coordinate = np.concatenate(([lower], coordinate[first:last], [upper]))
|
|
104
|
+
segment_density = np.concatenate(
|
|
105
|
+
(
|
|
106
|
+
[np.interp(lower, coordinate, density)],
|
|
107
|
+
density[first:last],
|
|
108
|
+
[np.interp(upper, coordinate, density)],
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
return segment_coordinate, segment_density
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def draw_marginal(
|
|
115
|
+
axes: Axes,
|
|
116
|
+
marginal: MarginalSummary,
|
|
117
|
+
xlabel: str,
|
|
118
|
+
style: PlotStyle,
|
|
119
|
+
mass: float | None,
|
|
120
|
+
*,
|
|
121
|
+
focus_delta: bool = False,
|
|
122
|
+
) -> None:
|
|
123
|
+
coordinate = np.asarray(marginal.coordinate)
|
|
124
|
+
density = np.asarray(marginal.density)
|
|
125
|
+
if (
|
|
126
|
+
coordinate.ndim != 1
|
|
127
|
+
or coordinate.size < 2
|
|
128
|
+
or not np.all(np.diff(coordinate) > 0)
|
|
129
|
+
):
|
|
130
|
+
raise ValueError("Marginal coordinates must be strictly increasing.")
|
|
131
|
+
if density.shape != coordinate.shape:
|
|
132
|
+
raise ValueError("Marginal density must have one value per coordinate.")
|
|
133
|
+
style_axes(axes, style, xlabel, "Probability density")
|
|
134
|
+
interval = _select_interval(marginal.intervals, mass)
|
|
135
|
+
handles = []
|
|
136
|
+
if interval is not None:
|
|
137
|
+
for index, (lower, upper) in enumerate(interval.hdi):
|
|
138
|
+
if lower < upper:
|
|
139
|
+
fill_x, fill_y = _segment(coordinate, density, lower, upper)
|
|
140
|
+
fill = axes.fill_between(
|
|
141
|
+
fill_x,
|
|
142
|
+
0,
|
|
143
|
+
fill_y,
|
|
144
|
+
color=HDI_COLOR,
|
|
145
|
+
alpha=HDI_ALPHA,
|
|
146
|
+
linewidth=0,
|
|
147
|
+
zorder=1,
|
|
148
|
+
)
|
|
149
|
+
fill.set_gid(f"{HDI_ARTIST_PREFIX}{axes.get_label()}-{index}")
|
|
150
|
+
percent = f"{100 * interval.mass:.6g}%"
|
|
151
|
+
handles.append(
|
|
152
|
+
Patch(
|
|
153
|
+
facecolor=HDI_COLOR,
|
|
154
|
+
alpha=HDI_ALPHA,
|
|
155
|
+
linewidth=0,
|
|
156
|
+
label=f"{percent} HDI",
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
lower, upper = interval.eti
|
|
160
|
+
handles.append(
|
|
161
|
+
axes.axvline(
|
|
162
|
+
lower,
|
|
163
|
+
color=ETI_COLOR,
|
|
164
|
+
linestyle="--",
|
|
165
|
+
linewidth=1.0,
|
|
166
|
+
zorder=2,
|
|
167
|
+
label=f"{percent} ETI",
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
axes.axvline(upper, color=ETI_COLOR, linestyle="--", linewidth=1.0, zorder=2)
|
|
171
|
+
median = axes.axvline(
|
|
172
|
+
marginal.median,
|
|
173
|
+
color=PDF_COLOR,
|
|
174
|
+
linestyle=":",
|
|
175
|
+
linewidth=1.0,
|
|
176
|
+
label="Median",
|
|
177
|
+
zorder=2,
|
|
178
|
+
)
|
|
179
|
+
handles.append(median)
|
|
180
|
+
axes.plot(coordinate, density, color=PDF_COLOR, linewidth=1.2, zorder=3)
|
|
181
|
+
axes.set_xlim(coordinate[0], coordinate[-1])
|
|
182
|
+
if focus_delta and interval is not None:
|
|
183
|
+
_focus_delta_axes(axes, marginal, interval, style)
|
|
184
|
+
axes.set_ylim(bottom=0)
|
|
185
|
+
legend = axes.legend(
|
|
186
|
+
handles=handles,
|
|
187
|
+
loc="lower left",
|
|
188
|
+
bbox_to_anchor=(0, 1.02),
|
|
189
|
+
ncols=len(handles),
|
|
190
|
+
frameon=False,
|
|
191
|
+
fontsize=style.tick_pt,
|
|
192
|
+
borderaxespad=0,
|
|
193
|
+
borderpad=0,
|
|
194
|
+
handlelength=1.45,
|
|
195
|
+
columnspacing=0.9,
|
|
196
|
+
handletextpad=0.4,
|
|
197
|
+
)
|
|
198
|
+
if interval is not None:
|
|
199
|
+
legend.get_patches()[0].set_gid(f"{HDI_ARTIST_PREFIX}{axes.get_label()}-key")
|