mango-osc 0.3.0__tar.gz

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 (48) hide show
  1. mango_osc-0.3.0/LICENSE +27 -0
  2. mango_osc-0.3.0/PKG-INFO +602 -0
  3. mango_osc-0.3.0/README.md +573 -0
  4. mango_osc-0.3.0/mango/__init__.py +80 -0
  5. mango_osc-0.3.0/mango/constants.py +82 -0
  6. mango_osc-0.3.0/mango/decoherence.py +116 -0
  7. mango_osc-0.3.0/mango/earth.py +468 -0
  8. mango_osc-0.3.0/mango/eigensolve.py +76 -0
  9. mango_osc-0.3.0/mango/globes.py +483 -0
  10. mango_osc-0.3.0/mango/hamiltonian.py +90 -0
  11. mango_osc-0.3.0/mango/layers.py +82 -0
  12. mango_osc-0.3.0/mango/nonunitarity.py +288 -0
  13. mango_osc-0.3.0/mango/nsi.py +54 -0
  14. mango_osc-0.3.0/mango/nufast.py +176 -0
  15. mango_osc-0.3.0/mango/ode.py +161 -0
  16. mango_osc-0.3.0/mango/oscillator.py +368 -0
  17. mango_osc-0.3.0/mango/params.py +69 -0
  18. mango_osc-0.3.0/mango/pmns.py +42 -0
  19. mango_osc-0.3.0/mango/propagator.py +132 -0
  20. mango_osc-0.3.0/mango/solar.py +380 -0
  21. mango_osc-0.3.0/mango/stat.py +134 -0
  22. mango_osc-0.3.0/mango/sterile.py +118 -0
  23. mango_osc-0.3.0/mango_osc.egg-info/PKG-INFO +602 -0
  24. mango_osc-0.3.0/mango_osc.egg-info/SOURCES.txt +46 -0
  25. mango_osc-0.3.0/mango_osc.egg-info/dependency_links.txt +1 -0
  26. mango_osc-0.3.0/mango_osc.egg-info/requires.txt +12 -0
  27. mango_osc-0.3.0/mango_osc.egg-info/top_level.txt +1 -0
  28. mango_osc-0.3.0/pyproject.toml +40 -0
  29. mango_osc-0.3.0/setup.cfg +4 -0
  30. mango_osc-0.3.0/tests/test_api_validation.py +342 -0
  31. mango_osc-0.3.0/tests/test_atmospheric_solar.py +143 -0
  32. mango_osc-0.3.0/tests/test_backend_edge_cases.py +162 -0
  33. mango_osc-0.3.0/tests/test_backends.py +54 -0
  34. mango_osc-0.3.0/tests/test_chord_segmentation.py +266 -0
  35. mango_osc-0.3.0/tests/test_decoherence_nonunitarity.py +85 -0
  36. mango_osc-0.3.0/tests/test_geometry_grad.py +190 -0
  37. mango_osc-0.3.0/tests/test_globes.py +135 -0
  38. mango_osc-0.3.0/tests/test_globes_tilt.py +106 -0
  39. mango_osc-0.3.0/tests/test_grad.py +60 -0
  40. mango_osc-0.3.0/tests/test_mass_states.py +88 -0
  41. mango_osc-0.3.0/tests/test_nonunitarity_layered.py +249 -0
  42. mango_osc-0.3.0/tests/test_nsi_sterile.py +111 -0
  43. mango_osc-0.3.0/tests/test_nufast_reference.py +63 -0
  44. mango_osc-0.3.0/tests/test_ode.py +49 -0
  45. mango_osc-0.3.0/tests/test_oscprob_reference.py +72 -0
  46. mango_osc-0.3.0/tests/test_physics.py +89 -0
  47. mango_osc-0.3.0/tests/test_solar_production.py +331 -0
  48. mango_osc-0.3.0/tests/test_stat.py +57 -0
@@ -0,0 +1,27 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pgranger23
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ This distribution also incorporates third-party material whose copyright and
26
+ licence terms are retained in THIRD_PARTY_LICENSES.md, notably a JAX port of
27
+ NuFast-LBL, Copyright (c) 2024 Peter B. Denton, used under the MIT License.
@@ -0,0 +1,602 @@
1
+ Metadata-Version: 2.4
2
+ Name: mango-osc
3
+ Version: 0.3.0
4
+ Summary: MANGO: A Neutrino Gradient Oscillator in JAX (vacuum, constant density, PREM Earth, atmospheric, solar, NSI, sterile)
5
+ Author: pgranger23
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/pgranger23/mango-osc
8
+ Project-URL: Repository, https://github.com/pgranger23/mango-osc
9
+ Project-URL: Issues, https://github.com/pgranger23/mango-osc/issues
10
+ Keywords: neutrino,oscillation,jax,differentiable,PREM,atmospheric,matter effects,MSW,NSI,sterile neutrino
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Physics
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: jax>=0.4.20
20
+ Requires-Dist: numpy>=1.24
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7; extra == "test"
23
+ Provides-Extra: examples
24
+ Requires-Dist: matplotlib>=3.6; extra == "examples"
25
+ Requires-Dist: blackjax>=1.0; extra == "examples"
26
+ Provides-Extra: diffrax
27
+ Requires-Dist: diffrax>=0.5; extra == "diffrax"
28
+ Dynamic: license-file
29
+
30
+ <p align="center">
31
+ <img src="assets/logo.png" alt="MANGO Logo" width="440"/>
32
+ </p>
33
+
34
+ <h1 align="center">MANGO</h1>
35
+ <h3 align="center">MANGO: A Neutrino Gradient Oscillator</h3>
36
+
37
+ <p align="center">
38
+ <a href="https://github.com/pgranger23/mango-osc/actions/workflows/ci.yml"><img src="https://github.com/pgranger23/mango-osc/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
39
+ <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT"></a>
40
+ <a href="https://doi.org/10.5281/zenodo.21774110"><img src="https://zenodo.org/badge/DOI/10.5281/zenodo.21774110.svg" alt="DOI"></a>
41
+ </p>
42
+
43
+ **MANGO** (**A Neutrino Gradient Oscillator**) is an autodiff-first neutrino oscillation calculator in [JAX](https://docs.jax.dev).
44
+
45
+ `mango` computes neutrino oscillation probabilities in **vacuum**, **constant-density
46
+ matter**, **non-constant density** (the Earth via the PREM model, with an
47
+ atmospheric production height), arbitrary **user profiles**, and the **Sun**
48
+ (adiabatic MSW). Everything is `jit`-compilable, `vmap`-batchable, and
49
+ **differentiable end-to-end** — with respect to the oscillation parameters *and* the
50
+ geometry (zenith angle, baseline, energy). **Non-standard interactions (NSI)** and
51
+ **sterile neutrinos (3+N)** are first-class.
52
+
53
+ It is validated to machine precision against the established codes
54
+ [OscProb](https://github.com/joaoabcoelho/OscProb) and
55
+ [NuFast](https://github.com/PeterDenton), and reproduces the reference plots of the
56
+ [nu-waves](https://github.com/nadrino/nu-waves) library.
57
+
58
+ ![atmospheric oscillogram](examples/nuwaves/figures/matter_prem_test.jpg)
59
+
60
+ *Atmospheric oscillograms through the PREM Earth: ν/ν̄ × (μ→e, μ→μ) over
61
+ (energy, cos θ_z), showing the MSW resonance, the matter ν/ν̄ asymmetry, the
62
+ core–mantle boundary at cos θ_z ≈ −0.84, and near-horizon atmospheric oscillations.*
63
+
64
+ ---
65
+
66
+ ## Why another oscillation code?
67
+
68
+ The established fast codes (NuFast, OscProb, Prob3++, …) are excellent at forward
69
+ evaluation but are not differentiable. `mango` is built **autodiff-first**: you get
70
+ exact gradients of any probability with respect to any input for free, which is what
71
+ you want inside a JAX fitting / HMC / neural-network pipeline. The cost of all six
72
+ oscillation-parameter gradients is ~3–5× a single forward evaluation (vs ~12× noisy
73
+ evaluations for finite differences), and the same code runs batched on GPU/TPU.
74
+
75
+ ---
76
+
77
+ ## Showcase: oscillograds
78
+
79
+ An *oscillograd* ([arXiv:2512.16427](https://arxiv.org/abs/2512.16427)) is a map of
80
+ the **gradient** of an oscillation probability with respect to a parameter,
81
+ `∂P/∂ζ` — it shows where in parameter space a probability is most sensitive to ζ.
82
+ This is exactly what a differentiable simulator is for: `jax.jacrev` returns the
83
+ oscillograd for *every* parameter in a single reverse-mode pass.
84
+
85
+ ![atmospheric oscillograds](examples/oscillograds_atm.jpg)
86
+
87
+ *Atmospheric oscillograds of `P(νμ→νe)` through the PREM Earth: the probability and
88
+ its exact derivatives w.r.t. δ_CP, θ₂₃, θ₁₃ and Δm²₃₁ over (E, cos θ_z). θ₁₃ drives
89
+ the MSW resonance (~6 GeV), θ₂₃ sets the appearance amplitude, δ_CP sensitivity sits
90
+ at low energy — and the core–mantle boundary at cos θ_z ≈ −0.84 is visible in the
91
+ gradients. Computed through fully differentiable matter propagation.*
92
+
93
+ [`examples/oscillograds.py`](examples/oscillograds.py) generates these (and the
94
+ DUNE-baseline constant-density version, paper-style) and verifies every gradient
95
+ against central finite differences — agreement is **~1e−9** (constant density) and
96
+ **~1e−8** (PREM Earth), for all six parameters.
97
+
98
+ You can also differentiate w.r.t. the **Earth model** itself — the two-zone electron
99
+ fraction `Y_e` (∝ electron density `N_e = ρ Y_e N_A`) is a traced input of
100
+ `probability_earth(..., ye_core=, ye_mantle=)`:
101
+
102
+ ![core electron-density oscillograds](examples/oscillograds_density.jpg)
103
+
104
+ *`∂P/∂Y_e^core` (center) is **exactly zero** for mantle-only trajectories and turns
105
+ on only below the core-crossing threshold cos θ_z ≈ −0.84 — the autodiff gradient
106
+ correctly "knows" the chord geometry — while `∂P/∂Y_e^mantle` (right) is non-zero for
107
+ all up-going paths.*
108
+
109
+ For full control, a parametric `LayeredEarth` makes the **shell boundary radii**,
110
+ **densities** and **Y_e** all differentiable inputs:
111
+
112
+ ```python
113
+ model = mango.prem_layered(n_sub=3) # constant-density-shell Earth sampled from PREM
114
+ P = mango.probability_earth(params, E, cz, earth_model=model)
115
+ jac = jax.jacrev(lambda m: mango.probability_earth(params, E, cz, earth_model=m,
116
+ flavor_in=Flavor.MU, flavor_out=Flavor.E))(model)
117
+ # jac.outer -> dP/d(boundary radii), jac.density -> dP/d(shell densities), jac.ye -> ...
118
+ ```
119
+
120
+ ![Earth-model oscillograds](examples/oscillograds_earth_model.jpg)
121
+
122
+ *Differentiating w.r.t. the Earth structure itself: `∂P/∂R_cmb` (the core–mantle
123
+ boundary position, center) and `∂P/∂ρ` for a deep core shell at 1735 km (right).
124
+ Each is non-zero **only for trajectories that reach that radius** — the boundary
125
+ sensitivity below cos θ_z ≈ −0.84, the 1735 km shell only below ≈ −0.96 — so the
126
+ gradients exactly trace the radial geometry. (Matches finite differences to ~1e−8.)*
127
+
128
+ ## Application: DUNE long-baseline sensitivity
129
+
130
+ [`analyses/dune/`](analyses/dune) reproduces the **DUNE TDR oscillation analysis**
131
+ using mango for the oscillation probabilities and DUNE's official GLoBES
132
+ configuration (arXiv:2103.04797) for the flux, cross-sections, per-channel
133
+ migration matrices, efficiencies, and systematics. The far-detector spectra match
134
+ the reference essentially exactly, and the CP-violation and mass-ordering
135
+ sensitivities reproduce the DUNE curves (correct shapes, peak positions, and zeros)
136
+ — with the χ² profiled over ~15 parameters using the **exact gradient from mango**
137
+ (`jax.value_and_grad` → L-BFGS). See its [README](analyses/dune/README.md).
138
+
139
+ ## Installation
140
+
141
+ ```bash
142
+ git clone https://github.com/pgranger23/mango-osc.git
143
+ cd mango-osc
144
+ pip install -e . # core: jax + numpy
145
+ pip install -e ".[examples]" # + matplotlib for the example scripts
146
+ pip install -e ".[diffrax]" # + diffrax for the optional stiff ODE backend
147
+ pip install -e ".[test]" # + pytest
148
+ ```
149
+
150
+ > **Float64 is required** for oscillation phases (Δm² ~ 1e−3 eV²) and is enabled
151
+ > automatically on `import mango`.
152
+
153
+ ---
154
+
155
+ ## Quick start
156
+
157
+ ```python
158
+ import jax, jax.numpy as jnp
159
+ import mango
160
+ from mango import nufit_no, Flavor
161
+
162
+ params = nufit_no() # a NuFIT-like normal-ordering point
163
+ E = jnp.linspace(1.0, 25.0, 200) # GeV
164
+ cz = jnp.linspace(-1.0, -0.05, 150) # cos(zenith), up-going
165
+
166
+ # Atmospheric oscillogram P(νμ → νe) through the Earth, shape (n_cz, n_E)
167
+ P = mango.probability_earth(params, E, cz,
168
+ flavor_in=Flavor.MU, flavor_out=Flavor.E)
169
+
170
+ # Exact gradient w.r.t. every oscillation parameter (returns an OscParams of grads)
171
+ def loss(p):
172
+ return mango.probability_earth(p, jnp.asarray(4.0), jnp.asarray(-1.0),
173
+ flavor_in=Flavor.MU, flavor_out=Flavor.E)
174
+ grads = jax.grad(loss)(params) # grads.theta23, grads.dm31, grads.deltacp, ...
175
+ ```
176
+
177
+ Probability matrices have shape `(..., N, N)` indexed `P[β, α] = P(ν_α → ν_β)`;
178
+ pass `flavor_in` / `flavor_out` to select one channel. Antineutrinos: `anti=True`.
179
+ `Flavor.E, Flavor.MU, Flavor.TAU = 0, 1, 2` (sterile flavors are indices ≥ 3).
180
+
181
+ ### The five regimes
182
+
183
+ ```python
184
+ # vacuum
185
+ mango.probability_vacuum(params, E, baseline_km=295.0) # T2K-like
186
+
187
+ # constant-density matter
188
+ mango.probability_constant(params, E, baseline_km=1300.0, density=2.8, ye=0.5) # DUNE-like
189
+
190
+ # PREM Earth (+ optional atmosphere); single entrypoint
191
+ mango.probability_earth(params, E, cz,
192
+ ye_core=0.466, ye_mantle=0.494, # configurable two-zone Y_e
193
+ h_atm_km=15.0, # production height -> full cosz
194
+ n_sub=4, det_depth_km=0.0,
195
+ segmentation=None) # chord cut (default); "radial" = v0.2.x
196
+
197
+ # arbitrary piecewise-constant profile (source -> detector ordering)
198
+ mango.probability_profile(params, E, density_gcc=[...], ye=[...], length_km=[...])
199
+
200
+ # mass eigenstates entering instead of flavours (solar neutrinos at night): P[..., beta, i] = P(nu_i -> nu_beta)
201
+ mango.probability_earth(params, E, cz, mass_states=True)
202
+
203
+ # solar adiabatic MSW: vacuum mass-state fractions vs radius
204
+ prof = mango.solar.load_bs05("examples/data/bs05_agsop.dat")
205
+ F = mango.solar.adiabatic_mass_fractions(params, E_GeV, prof, r_km, r_emit_km)
206
+
207
+ # solar neutrinos from a production region: weights are production fractions per point of
208
+ # prof.r_over_rsun (integrated over each shell, e.g. from the model's flux table, not a density dPhi/dr);
209
+ # P(nu_e -> nu_beta) by day, and at night through the Earth on a (n_cz, n_E) grid (adiabatic; see
210
+ # solar.adiabaticity)
211
+ P_day = mango.probability_solar(params, E_GeV, prof, weights) # or method="convolution"
212
+ P_ee_night = mango.probability_solar(params, E_GeV, prof, weights, cos_zenith=cz, flavor_out=0)
213
+ # the mass-state fractions leaving the Sun, if needed on their own
214
+ c = mango.solar.production_mixing(params, E_GeV, prof, weights)
215
+ ```
216
+
217
+ ### NSI and sterile neutrinos
218
+
219
+ ```python
220
+ # matter NSI: an epsilon_{alpha beta} object on any probability function
221
+ P = mango.probability_constant(params, E, 1300.0, density=2.8,
222
+ nsi=mango.NSI(eps_emu=0.1 + 0.05j, eps_ee=0.05))
223
+
224
+ # 3+1 sterile (flavors e, mu, tau, s); the matter potential automatically gives
225
+ # sterile flavors only the relative neutral-current term; backend auto-switches to eigh
226
+ st = mango.Sterile3plus1(theta12, theta13, theta23, theta14, theta24, theta34,
227
+ delta13, delta24, dm21, dm31, dm41)
228
+ P = mango.probability_earth(st, E, cz) # (n_cz, n_E, 4, 4)
229
+
230
+ # arbitrary 3+N via the generic builder
231
+ U = mango.pmns_nflavor(5, [(3, 4, 0.1), (2, 4, 0.05), ..., (0, 1, theta12)])
232
+ params5 = mango.NFlavorParams(U=U, msq=jnp.array([0, dm21, dm31, dm41, dm51]), n_active=3)
233
+ ```
234
+
235
+ Both NSI and sterile parameters are differentiable leaves — `jax.grad` works through
236
+ `NSI(...)` and `Sterile3plus1(...)`.
237
+
238
+ ### Decoherence and non-unitary mixing
239
+
240
+ ```python
241
+ # Lindblad decoherence Gamma_ij = gamma_ij (E/E0)^n, or wave-packet separation
242
+ P = mango.decoherence.probability(params, E, L, mango.Decoherence(gamma21=1e-14, n=0),
243
+ density=2.8)
244
+ P = mango.decoherence.probability(params, E, L, mango.WavePacket(sigma_x_m=2e-13))
245
+
246
+ # non-unitary mixing N = (1 - alpha) U: zero-distance effect + non-cancelling
247
+ # NC matter term included
248
+ P = mango.nonunitarity.probability(params, mango.NonUnitarity(alpha21=0.02 + 0.01j),
249
+ E, L, density=2.8)
250
+ ```
251
+
252
+ Both are validated against their exact limits (γ→0 / α→0 reproduce the standard
253
+ probabilities to ~1e-15; full damping gives the interference-averaged rates; the
254
+ L→0 flavor violation matches the analytic zero-distance formula) and are
255
+ differentiable through `gamma` / `sigma_x` / `alpha` — decoherence and
256
+ unitarity-violation sensitivity forecasts are one `jax.grad` away.
257
+
258
+ ![decoherence](examples/decoherence.jpg)
259
+
260
+ *Left: Lindblad damping washes the DUNE-baseline νμ survival oscillations out
261
+ toward the interference-averaged rate as γL grows. Right: the classic reactor
262
+ wave-packet signature at a JUNO-like baseline — the fast Δm²₃₁ wiggles disappear
263
+ as σ_x shrinks while the slow solar oscillation survives.
264
+ ([examples/decoherence_plot.py](examples/decoherence_plot.py))*
265
+
266
+ ![non-unitarity](examples/nonunitarity.jpg)
267
+
268
+ *Left: |α₂₁| = 0.02 shifts the DUNE appearance probability with a phase φ₂₁
269
+ dependence that mimics δ_CP (the NU–CP degeneracy). Right: the zero-distance
270
+ effect — P(νμ→νe) plateaus at the analytic |(NN†)_eμ|² value (dotted) instead of
271
+ vanishing as L→0. ([examples/nonunitarity_plot.py](examples/nonunitarity_plot.py))*
272
+
273
+ ### Loading GLoBES experiments (a "differentiable GLoBES")
274
+
275
+ `mango.globes` parses a GLoBES/AEDL experiment definition — includes, channels,
276
+ rules, migration matrices or analytic Gaussian smearing, efficiencies,
277
+ normalization systematics, matter profile — and turns it into a differentiable
278
+ forward model:
279
+
280
+ ```python
281
+ exp = mango.globes.load("DUNE_GLoBES.glb", scale=1.21)
282
+ spectra = exp.spectra(params) # dict rule -> reco spectrum
283
+ chi2 = exp.chi2(params, xi, data) # Poisson + norm systematics
284
+ grad = jax.grad(lambda p: exp.spectra(p)["nue_app"].sum())(params)
285
+ ```
286
+
287
+ Validated end-to-end on the official DUNE TDR configuration (it reproduces the
288
+ bespoke DUNE analysis in `analyses/dune` to ~1e-5 — and parsing the file's
289
+ `@energy_window` even caught a hand-coded window bug in the bespoke version).
290
+ See the module docstring for the supported AEDL subset.
291
+
292
+ ![DUNE spectra from the GLoBES loader](examples/dune_globes.jpg)
293
+
294
+ *The classic DUNE TDR figure straight from `mango.globes.load`: νe / ν̄e
295
+ appearance for δ_CP = −π/2, 0, +π/2 (note the CP effect flipping sign between
296
+ neutrino and antineutrino modes), backgrounds shaded.
297
+ ([examples/dune_globes_plot.py](examples/dune_globes_plot.py))*
298
+
299
+ ### Fisher forecasts and Bayesian fits (`mango.stat`)
300
+
301
+ ```python
302
+ F = mango.stat.fisher_matrix(model, params) # exact Poisson Fisher via autodiff
303
+ F = F.with_prior("theta13", 0.002) # reactor constraint
304
+ F.sigma("deltacp") # marginalized 1-sigma forecast
305
+ F.fixed("dm31").sigma("deltacp") # conditional bound
306
+ ```
307
+
308
+ The Fisher matrix equals the Asimov-χ² curvature (tested), and pairs naturally
309
+ with gradient-based samplers: [examples/hmc_posterior.py](examples/hmc_posterior.py)
310
+ runs a blackjax **NUTS** posterior of (θ₂₃, θ₁₃, Δm²₃₁, δ_CP) for a DUNE-like
311
+ experiment using exact mango gradients and overlays the analytic Fisher ellipses:
312
+
313
+ ![HMC posterior vs Fisher](examples/hmc_posterior.jpg)
314
+
315
+ ---
316
+
317
+ ## Algorithm choices
318
+
319
+ This section documents *why* each numerical method was chosen.
320
+
321
+ ### Units and precision
322
+
323
+ The numerical core runs **entirely in natural units** (`ħ = c = 1`): energies in eV,
324
+ lengths in eV⁻¹, masses² in eV². Unit conversions (GeV, km, g/cm³) and the matter
325
+ potential happen only at the API boundary (`constants.py`), derived from
326
+ first-principles CODATA/PDG values — there are no opaque literals like `7.6e-14`.
327
+ The charged-current potential is `V_CC = √2 G_F N_e`; sterile neutrinos additionally
328
+ feel the relative neutral-current term `½√2 G_F N_n`. **float64/complex128** is
329
+ mandatory and set on import: at float32 the large oscillation phases lose precision
330
+ (float32 buys only ~1.06× on CPU and ~1e−6 accuracy loss — not worth it except
331
+ possibly on GPU).
332
+
333
+ ### Propagation backends
334
+
335
+ The evolution of a constant-density layer is `S = exp(−iHL)`; `P_{αβ} = |S_{βα}|²`.
336
+ Four backends, agreeing to ~1e−14:
337
+
338
+ | backend | method | used for |
339
+ |---------|--------|----------|
340
+ | **`nufast`** | analytic NuFast-LBL formula (default for constant density / vacuum) | single layer, standard 3-flavor |
341
+ | **`cayley`** | Cayley–Hamilton via Newton divided differences (default for the Earth path) | layered Earth, all cases |
342
+ | **`eigh`** | generic Hermitian eigendecomposition | any N (steriles), validation |
343
+ | **`expm`** | `jax.scipy.linalg.expm` | reference cross-check |
344
+
345
+ - **`nufast`** ports Parke & Denton's NuFast-LBL ("DMP Rosetta") algorithm: the
346
+ matter mixing-matrix magnitudes `|Uᵐ_{αi}|²` and the matter Jarlskog are computed
347
+ **analytically from the eigenvalues** and plugged straight into the standard `sin²`
348
+ probability formula — no eigenvectors, no matrix exponential, no matmuls. It is
349
+ exact (matches the matrix-exponential backends to ~5e−15), differentiable, and
350
+ several times faster, putting constant-density throughput on par with NuFast's C++.
351
+ It applies only to a single constant-density layer and standard 3-flavor, so it
352
+ **falls back automatically** to `cayley`/`eigh` when NSI or steriles are present.
353
+ - **`cayley`** is the default for the multi-layer Earth path because there you need
354
+ the evolution operator `S` (to chain across layers), not just probabilities. It
355
+ uses the **analytic 3×3 Hermitian eigenvalues** (stable trigonometric solution of
356
+ the characteristic cubic) and the **Newton divided-difference (Hermite) form** of
357
+ `exp(−iM)` — which is eigenvector-free, handles repeated / zero eigenvalues exactly
358
+ (so zero-length Earth segments collapse to identity cleanly), and avoids the
359
+ ill-conditioning of a naive Vandermonde solve (the raw Hamiltonian eigenvalues are
360
+ ~1e−13 eV, so it works with the dimensionless `M = HL` instead).
361
+ - **`eigh`** handles `N ≠ 3` (sterile models) and is the generic validation oracle.
362
+ The backend is auto-switched to `eigh` for `N ≠ 3` since the analytic kernels are
363
+ 3×3-specific.
364
+
365
+ ### Earth model and geometry (`earth.py`)
366
+
367
+ - **PREM** (Dziewonski & Anderson 1981) density as piecewise polynomials in radius;
368
+ a **two-zone `Y_e`** (core/mantle, boundary at 3480 km) that is user-configurable
369
+ (`ye_core` / `ye_mantle`) to match whatever convention you are comparing against.
370
+ - **One unified entrypoint** (`probability_earth` → `earth.chord_segments`) covers
371
+ up-going through the Earth, down-going, *and* the atmospheric production height
372
+ `h_atm_km` (so down-going / near-horizon directions get the correct vacuum
373
+ baseline). Geometry uses the distance-from-closest-approach coordinate
374
+ `d(r) = √(r²−r_min²)`; PREM shell boundaries are respected exactly.
375
+ - **Layer placement, NuFast-style.** Shells are allocated **proportional to radial
376
+ thickness** (not `n_sub` per PREM region), so resolution goes to the thick
377
+ core/mantle where the oscillation phase accumulates rather than to thin crust
378
+ layers; density is sampled at each segment's **path midpoint** (not the shell's
379
+ geometric midpoint). Together these converge ~3–5× faster in `n_sub`: e.g.
380
+ `n_sub=2` (25 shells) reaches ~3e−3 accuracy, better than naive uniform
381
+ subdivision at 121 shells.
382
+ - **Two ways to cut the chord** (`segmentation=`). `"radial"` (the v0.2.x
383
+ default) cuts at every sub-shell boundary. Each sub-shell radius is an angle at which the chord
384
+ grazes it, so `P(cosθ)` gets an artificial √-cusp there: the cusps shrink with
385
+ `n_sub` but their number grows, and pointwise `∂P/∂cosθ` converges slowly
386
+ (~`n_sub^-0.7`). `"chord"` cuts each PREM region's part of the chord into the
387
+ same number of equal-length pieces instead. Piece ends slide smoothly with
388
+ `cosθ`, so only the cusps at the real PREM discontinuities remain, and `P` and
389
+ `∂P/∂cosθ` converge as `n_sub^-2` at the same cost (at `n_sub=4`, 2–20 GeV either side of the
390
+ core threshold, the worst `∂P/∂cosθ` error drops from 14% to 0.05% of its peak).
391
+ `"chord"` is the default since v0.3.0; `"radial"` stays available to
392
+ reproduce v0.2.x numbers and the shell cut of OscProb / Prob3++. The two
393
+ coincide at the nadir for a surface detector. See `benchmarks/fig_nsub_convergence.py`.
394
+
395
+ ### Layer product (`layers.py`), device-aware
396
+
397
+ The per-layer operators are chained `S = S_N ⋯ S_1`. Two strategies, auto-selected:
398
+
399
+ - **CPU:** a sequential `lax.scan` — least total work and memory; fastest where there
400
+ is no parallel hardware to exploit.
401
+ - **GPU/TPU:** build all per-layer propagators with `vmap` (vectorized eigensolves,
402
+ hoisting the layer-independent vacuum Hamiltonian) and combine with
403
+ `lax.associative_scan` (parallel-prefix, O(log N) depth).
404
+
405
+ (The parallel-prefix product is *slower* on CPU because it computes all prefixes;
406
+ benchmarking confirmed the sequential scan wins on CPU, so it is the CPU default.)
407
+
408
+ ### Differentiability
409
+
410
+ - The `cayley` divided differences and the analytic eigensolver are **guarded with
411
+ double-`where`** so degenerate / zero-length segments carry no NaN gradients
412
+ (`sqrt` has an infinite derivative at 0).
413
+ - The Earth chord geometry uses a **gradient-safe `sqrt`** at the turning point
414
+ (closest approach), where the geometric vertical tangent would otherwise NaN
415
+ `dP/d cos θ_z`. Autodiff matches finite differences for parameters *and* geometry.
416
+ - Antineutrinos are a conjugation/sign flag (`U → U*`, `V → −V`, `ε → ε*`), not a
417
+ separate code path, so gradients flow identically.
418
+
419
+ ### Continuous (ODE) backend (`ode.py`)
420
+
421
+ For arbitrary smooth profiles (and as an independent cross-check of the layer
422
+ method), `mango.ode` integrates `dS/ds = −iH(s)S` directly. Two solvers: `odeint`
423
+ (default, no extra dependency) and an optional **diffrax** backend
424
+ (`backend="diffrax"`, `solver="dopri8"`/`"kvaerno5"`/…) with stiff/implicit solvers
425
+ and checkpointed adjoints — most useful for hard profiles (e.g. supernovae). The
426
+ diffrax path evolves a real `[Re S, Im S]` state (diffrax complex support is
427
+ experimental). These are only approximately unitary (RK drifts off the unitary
428
+ group), so they are *not* on the default path; the layer method is exact per layer.
429
+
430
+ ### Solar adiabatic MSW (`solar.py`)
431
+
432
+ A BS05-style standard-solar-model loader (or an analytic exponential profile) plus
433
+ the **averaged adiabatic** mass-state fractions
434
+ `F_i(r) = Σ_k |⟨ν_i^vac|ν_k^m(r)⟩|² · |⟨ν_k^m(r_emit)|ν_e⟩|²` — the textbook LMA-MSW
435
+ result (a ν_e produced in the dense core emerges predominantly as ν₂).
436
+
437
+ ---
438
+
439
+ ## Validation
440
+
441
+ `python run_tests.py` (or `pytest`) — **132 checks**, including:
442
+
443
+ - vacuum two-flavor analytic limit; unitarity in vacuum & matter; CP asymmetry; MSW;
444
+ - exact Earth chord geometry; oscillogram unitarity, no NaNs; down-going → vacuum;
445
+ - cross-backend agreement (`nufast` / `cayley` / `eigh` / `expm`) to ~1e−14;
446
+ - autodiff vs finite differences for oscillation parameters *and* `cos θ_z`; `jit`;
447
+ - NSI(0) → standard, sterile(θ_i4=0) → 3-flavor, reactor-sterile RAA depth,
448
+ 3+2 unitarity, gradients through NSI / sterile params;
449
+ - ODE (odeint & diffrax) vs the layer method.
450
+
451
+ **External cross-code validation** (see [validation/README.md](validation/README.md)):
452
+
453
+ | comparison | constant density | PREM Earth |
454
+ |---|---|---|
455
+ | vs **OscProb** (ROOT/Eigen) | ~1e−9 | ~1e−7 (identical path) |
456
+ | vs **NuFast** (C++) | 5e−13 (constants aligned) | ~1e−5 (converged) |
457
+
458
+ The residual vs NuFast is fully explained by NuFast's 6-significant-figure constants;
459
+ mango and OscProb (which share first-principles constants) agree to ~1e−9 despite
460
+ completely different propagators. Reference values are embedded as regression tests
461
+ (`tests/test_oscprob_reference.py`, `tests/test_nufast_reference.py`).
462
+
463
+ ### Reproductions of the nu-waves reference plots
464
+
465
+ [`examples/nuwaves/`](examples/nuwaves) reproduces all six figures from the nu-waves
466
+ README (vacuum PMNS, sterile + energy smearing, constant-density NO/IO, (E,L) maps,
467
+ the atmospheric oscillogram, solar adiabatic MSW) — five match essentially exactly;
468
+ the solar one reproduces the correct MSW physics (see that folder's README for the
469
+ convention note). [`examples/nsi_sterile.py`](examples/nsi_sterile.py) demonstrates
470
+ the NSI and sterile front-ends.
471
+
472
+ ---
473
+
474
+ ## Performance (Apple M3 Pro, CPU, float64)
475
+
476
+ | workload | mango | NuFast (C++) | OscProb (C++) |
477
+ |---|---|---|---|
478
+ | constant density, P(νμ→νe) | **37–94 Mevals/s** (`nufast` backend) | 28 | 14 |
479
+ | PREM Earth oscillogram | ~0.04–0.07 Mevals/s | 51 | 0.5 |
480
+ | all 6 param gradients | **2.9–5.4× a forward eval** (exact) | n/a (finite diff ≈ 12×) | n/a |
481
+
482
+ `mango` matches or beats the hand-optimized C++ for the constant-density/LBL case
483
+ (the `nufast` backend is a single analytic formula, no scan). For PREM Earth on CPU
484
+ it is much slower: the cost is XLA per-op overhead on the sequential scan of tiny 3×3
485
+ ops, not the algorithm — NuFast-Earth's analytic per-layer machinery is in a
486
+ different class on CPU. mango's Earth value is differentiability + GPU/TPU batching
487
+ (where the gap closes). See [DESIGN.md](DESIGN.md) §11 for the GPU-oriented
488
+ NuFast-Earth roadmap item.
489
+
490
+ ### Reproducing the paper's benchmark tables
491
+
492
+ [`benchmarks/`](benchmarks) has standalone, self-contained scripts (only
493
+ `mango`/`numpy`/`jax`/`matplotlib`) that reproduce every performance and
494
+ validation table in the accompanying paper, plus a README mapping each
495
+ script to the table/figure it reproduces. The paper's own absolute numbers
496
+ were measured on 8 cores of an AMD EPYC 7542 (CPU) and one NVIDIA A100 (GPU);
497
+ expect different absolute timings on other hardware, but the same relative
498
+ ordering of the backends.
499
+
500
+ ---
501
+
502
+ ## Module map
503
+
504
+ ```
505
+ mango/
506
+ constants.py physical constants + unit conversions + matter potentials
507
+ params.py OscParams PyTree (differentiable leaves) + a benchmark point
508
+ pmns.py generic N-flavor PMNS construction
509
+ hamiltonian.py vacuum + matter Hamiltonian (generic N, NSI + sterile)
510
+ eigensolve.py analytic 3x3 Hermitian eigenvalues
511
+ propagator.py exp(-iHL): cayley / eigh / expm
512
+ nufast.py fast analytic constant-density probability (NuFast-LBL port)
513
+ layers.py device-aware layered propagation
514
+ earth.py PREM + chord geometry + thickness-proportional shells
515
+ oscillator.py high-level API (vacuum / constant / earth / profile)
516
+ nsi.py non-standard interactions
517
+ sterile.py 3+N sterile front-end
518
+ decoherence.py Lindblad / wave-packet decoherence
519
+ nonunitarity.py non-unitary mixing (alpha parametrization)
520
+ globes.py generic GLoBES/AEDL experiment loader
521
+ stat.py Fisher information & chi2 utilities
522
+ solar.py solar profile + adiabatic MSW
523
+ ode.py continuous-density backend (odeint / diffrax)
524
+ ```
525
+
526
+ ---
527
+
528
+ ## Limitations & roadmap
529
+
530
+ - **3-flavor** is the core; **sterile (3+N)** and **matter NSI** are implemented.
531
+ - CPU Earth throughput is far below the specialized C++ codes (see Performance). A
532
+ **GPU-oriented NuFast-Earth propagator** (eigensystem caching across cos θ_z +
533
+ reduced-basis real per-shell amplitudes + symmetric-trajectory halving) is the
534
+ roadmap item to close that gap on accelerators — [DESIGN.md](DESIGN.md) §11.
535
+ - A **supernova module** would be the natural consumer of the diffrax stiff backend.
536
+
537
+ ---
538
+
539
+ ## References & acknowledgements
540
+
541
+ - **PREM.** Dziewonski & Anderson, *Phys. Earth Planet. Inter.* **25** (1981) 297.
542
+ `mango/earth.py` implements the PREM density as piecewise polynomials in
543
+ radius, from the coefficients tabulated in that paper.
544
+ - **NuFast / DMP.** Denton & Parke, *Phys. Rev. D* **110** (2024) 073005
545
+ (arXiv:2405.02400); see also Denton, Minakata & Parke (arXiv:1604.08167) for
546
+ the underlying "Rosetta" relations. `mango/nufast.py`'s `nufast` backend is a
547
+ **close, line-by-line JAX transcription of the reference C++ implementation**
548
+ that the authors publish alongside the paper as
549
+ [NuFast-LBL](https://github.com/PeterDenton/NuFast-LBL) — the intermediate
550
+ variable naming in `mango/nufast.py` tracks that source closely enough that
551
+ this is a port, not an independent re-derivation from the formulas with new
552
+ structure. NuFast-LBL is itself MIT-licensed (Copyright (c) 2024 Peter B.
553
+ Denton); this port is used under the terms of that license, with the original
554
+ authors' copyright credited here and in `mango/nufast.py`'s module docstring.
555
+ If you use the `nufast` backend, please also cite Denton & Parke (2024) as the
556
+ original authors request. The NuFast-LBL MIT licence is reproduced verbatim in
557
+ [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md), as its terms require.
558
+ - Validated against [OscProb](https://github.com/joaoabcoelho/OscProb) and
559
+ [NuFast](https://github.com/PeterDenton); reproduces
560
+ [nu-waves](https://github.com/nadrino/nu-waves) reference plots (see
561
+ [`examples/nuwaves/README.md`](examples/nuwaves/README.md) for per-figure
562
+ credit and the one physics-convention caveat on the solar plot).
563
+ - **Solar profile.** Bahcall, Serenelli & Basu, BS05(AGS,OP) standard solar
564
+ model (astro-ph/0412440); the table shipped at
565
+ [`examples/data/bs05_agsop.dat`](examples/data/bs05_agsop.dat) is that
566
+ published model's own data file, used as input to `mango.solar.load_bs05`
567
+ (`mango/solar.py`), which is otherwise an independent implementation of the
568
+ textbook averaged-adiabatic MSW formula.
569
+
570
+ See [`CITATION.cff`](CITATION.cff) for how to cite this software (and the
571
+ accompanying paper, once available), and [`CHANGELOG.md`](CHANGELOG.md) for
572
+ release history.
573
+
574
+ ## Releasing to PyPI
575
+
576
+ Publishing is automated via GitHub Actions
577
+ ([`.github/workflows/publish.yml`](.github/workflows/publish.yml)) using PyPI
578
+ **trusted publishing** (OIDC) — no API tokens or secrets.
579
+
580
+ **One-time setup** (on [pypi.org](https://pypi.org), needs your PyPI login). Account
581
+ → *Publishing* → *Add a pending publisher* with:
582
+
583
+ | field | value |
584
+ |-------|-------|
585
+ | PyPI Project Name | `mango` |
586
+ | Owner | `pgranger23` |
587
+ | Repository name | `mango-osc` |
588
+ | Workflow name | `publish.yml` |
589
+ | Environment name | `pypi` |
590
+
591
+ **To cut a release:**
592
+
593
+ 1. Bump the version in `pyproject.toml` **and** `mango/__init__.py`, commit, push.
594
+ 2. Tag and publish a GitHub Release: e.g. `git tag v0.1.0 && git push origin v0.1.0`,
595
+ then create a Release for that tag (or `gh release create v0.1.0 --generate-notes`).
596
+ 3. The workflow builds the sdist + wheel and publishes to PyPI → `pip install mango`.
597
+
598
+ (You can dry-run the build locally with `python -m build && twine check dist/*`.)
599
+
600
+ ## License
601
+
602
+ MIT — see [LICENSE](LICENSE).