nmbackend 0.4.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.
- nmbackend/__init__.py +22 -0
- nmbackend/adapters/__init__.py +4 -0
- nmbackend/adapters/rift.py +95 -0
- nmbackend/constants.py +55 -0
- nmbackend/cooling/README.md +159 -0
- nmbackend/cooling/__init__.py +13 -0
- nmbackend/cooling/build_nscool.sh +51 -0
- nmbackend/cooling/isothermal.py +76 -0
- nmbackend/cooling/nscool_nmbackend.patch +310 -0
- nmbackend/cooling/physics/__init__.py +18 -0
- nmbackend/cooling/physics/_spline.py +71 -0
- nmbackend/cooling/physics/blanket.py +66 -0
- nmbackend/cooling/physics/conduct.py +196 -0
- nmbackend/cooling/physics/core_conduct.py +68 -0
- nmbackend/cooling/physics/core_nu.py +268 -0
- nmbackend/cooling/physics/crust.py +113 -0
- nmbackend/cooling/physics/crust_nu.py +93 -0
- nmbackend/cooling/physics/curve.py +42 -0
- nmbackend/cooling/physics/envelope.py +37 -0
- nmbackend/cooling/physics/gaps.py +164 -0
- nmbackend/cooling/physics/geometry.py +131 -0
- nmbackend/cooling/physics/heat.py +125 -0
- nmbackend/cooling/physics/native.py +138 -0
- nmbackend/cooling/physics/reference.py +53 -0
- nmbackend/cooling/physics/star.py +225 -0
- nmbackend/cooling/physics/superfluid.py +41 -0
- nmbackend/cooling/physics/whole.py +136 -0
- nmbackend/cooling/runner.py +583 -0
- nmbackend/cooling/validate.py +120 -0
- nmbackend/data/crust_sly_dh2001.dat +81 -0
- nmbackend/data/frib_scenario_ladder.yaml +100 -0
- nmbackend/durca.py +111 -0
- nmbackend/ejecta.py +614 -0
- nmbackend/eos/__init__.py +19 -0
- nmbackend/eos/base.py +523 -0
- nmbackend/eos/compose.py +251 -0
- nmbackend/eos/coolcomp.py +67 -0
- nmbackend/eos/crust.py +318 -0
- nmbackend/eos/ddrmf.py +388 -0
- nmbackend/eos/hybrid.py +173 -0
- nmbackend/eos/leptons.py +74 -0
- nmbackend/eos/metamodel.py +303 -0
- nmbackend/eos/polytrope.py +33 -0
- nmbackend/eos/rmft.py +450 -0
- nmbackend/eos/skyrme.py +352 -0
- nmbackend/inference/__init__.py +13 -0
- nmbackend/inference/fisher.py +174 -0
- nmbackend/inference/synthetic.py +83 -0
- nmbackend/ipad.py +102 -0
- nmbackend/lab_likelihood.py +587 -0
- nmbackend/nscool_io.py +112 -0
- nmbackend/postmerger.py +264 -0
- nmbackend/priors/__init__.py +16 -0
- nmbackend/priors/bridge.py +437 -0
- nmbackend/priors/bridge_jax.py +435 -0
- nmbackend/priors/gp_pca.py +325 -0
- nmbackend/reference/__init__.py +11 -0
- nmbackend/reference/reprimand.py +108 -0
- nmbackend/reference/scipy_tov.py +289 -0
- nmbackend/rift/__init__.py +26 -0
- nmbackend/rift/compressed.py +194 -0
- nmbackend/rift/evidence.py +276 -0
- nmbackend/rift/sequence.py +428 -0
- nmbackend/rotating/__init__.py +7 -0
- nmbackend/rotating/rns.py +197 -0
- nmbackend/rotating/tabulated.py +249 -0
- nmbackend/thermal/__init__.py +1 -0
- nmbackend/thermal/diffusion.py +86 -0
- nmbackend/tov/__init__.py +15 -0
- nmbackend/tov/central.py +72 -0
- nmbackend/tov/family.py +155 -0
- nmbackend/tov/phase_transition.py +93 -0
- nmbackend/tov/solver.py +475 -0
- nmbackend/validation/__init__.py +5 -0
- nmbackend/validation/model_diagnostic.py +67 -0
- nmbackend/validation/reference_matrix.py +216 -0
- nmbackend-0.4.0.dist-info/METADATA +168 -0
- nmbackend-0.4.0.dist-info/RECORD +81 -0
- nmbackend-0.4.0.dist-info/WHEEL +5 -0
- nmbackend-0.4.0.dist-info/licenses/LICENSE +21 -0
- nmbackend-0.4.0.dist-info/top_level.txt +1 -0
nmbackend/tov/solver.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
"""Differentiable TOV solver in pseudo-enthalpy, with in-loop tidal Love number.
|
|
2
|
+
|
|
3
|
+
We integrate the TOV equations using the pseudo-enthalpy ``h`` as the independent
|
|
4
|
+
variable (Lindblom 1992), which removes the surface coordinate singularity and
|
|
5
|
+
makes the central boundary condition a simple series start. Alongside (r, m) we
|
|
6
|
+
carry the tidal variable y (Postnikov, Prakash & Lattimer 2010) to obtain the
|
|
7
|
+
l=2 Love number k2 and dimensionless tidal deformability Lambda.
|
|
8
|
+
|
|
9
|
+
Two backends sit behind one seam, ``solve_structure``:
|
|
10
|
+
|
|
11
|
+
* ``backend="diffrax"`` (default): **adaptive** Dopri5 + PID controller. This is
|
|
12
|
+
the accurate, recommended path -- it automatically resolves the stiff regions
|
|
13
|
+
near the centre (1/r terms) *and* near the surface (which the tidal sector needs)
|
|
14
|
+
and is validated against an independent radius-domain solver to <0.1% in M, R,
|
|
15
|
+
and Lambda (see ``tests/test_validation_reference.py``). Forward-mode AD flows
|
|
16
|
+
through it via ``diffrax.ForwardMode`` -- this is the supported sensitivity path
|
|
17
|
+
and reproduces the perturbation ("delta-TOV") equations. Two mechanisms make
|
|
18
|
+
the tangents accurate (docs/devlog/2026-10-12-tov-jump-ts.md):
|
|
19
|
+
|
|
20
|
+
- steps stop at the EOS table nodes (diffrax ``jump_ts``), where the
|
|
21
|
+
right-hand side has slope kinks. This fixes the EOS-*parameter* tangents,
|
|
22
|
+
which now converge with rtol at the level of the values (~3e-5 at the
|
|
23
|
+
default rtol, ~1e-7 at 1e-9; up to 10% before).
|
|
24
|
+
- the start of the integration is frozen against differentiation. This fixes
|
|
25
|
+
the *h_c* tangent (3.6e-2 -> 1.2e-4 at the default rtol). It converges like
|
|
26
|
+
rtol but sits ~1e3x above the values (~1e-4 at the default rtol, ~5e-7 at
|
|
27
|
+
1e-9), from the near-centre resolution; ``centre_refine=True`` buys ~10x.
|
|
28
|
+
The residual is a near-common factor on M, R, Lambda, so it largely cancels
|
|
29
|
+
in fixed-mass derivatives.
|
|
30
|
+
|
|
31
|
+
FIRST derivatives only w.r.t. h_c: d^2/dh_c^2 is wrong by orders of
|
|
32
|
+
magnitude (mixed d^2/dh_c dtheta is fine).
|
|
33
|
+
|
|
34
|
+
The tidal term (eps + p)/cs2 is the analytic deps/dh of the same Hermite cell
|
|
35
|
+
that gives eps(h) (``EOSTable.at_h_tidal``), so per cell it integrates to
|
|
36
|
+
exactly the Delta eps the structure sees (docs/devlog/2026-10-14-tidal-cs2.md).
|
|
37
|
+
Before 2026-10-14 it took the node cs2 interpolated linearly in h, which left
|
|
38
|
+
a "phantom" Delta eps at steep joints (Lambda up to ~10% low). The new term
|
|
39
|
+
jumps at the nodes, so y is carried in a node-anchored picture
|
|
40
|
+
(:func:`_derivs_x`; equal to h in value) in which the nodes do not move with
|
|
41
|
+
the EOS parameters, and the frozen mesh keeps the jumps' boundary terms in
|
|
42
|
+
the parameter tangents. First parameter derivatives of Lambda only.
|
|
43
|
+
|
|
44
|
+
* ``backend="scan"``: a lightweight fixed-step RK4 ``jax.lax.scan``. Fully
|
|
45
|
+
jit/vmap/grad-able (incl. reverse-mode for structure-only, ``tidal=False``), but
|
|
46
|
+
a *fixed* grid is only accurate with enough, well-placed steps -- prefer the
|
|
47
|
+
diffrax backend unless you specifically need the dependency-free scan. Its
|
|
48
|
+
uniform grid ignores the table nodes and moves with h_c; its tangent is the
|
|
49
|
+
exact derivative of that discrete map, so it agrees with FD of the same scan
|
|
50
|
+
but carries the grid's (low-order, node-straddling) discretization error.
|
|
51
|
+
Since the tidal term jumps at the nodes, its Lambda error is first order in
|
|
52
|
+
the step where a step straddles a node.
|
|
53
|
+
|
|
54
|
+
WARNING (see docs/validation-plan.md): neither backend yet handles strong
|
|
55
|
+
first-order phase transitions (cs^2 -> 0 plateaus / density discontinuities) with
|
|
56
|
+
their tidal junction conditions. Validate any phase-transition EOS against
|
|
57
|
+
RePrimAnd before trusting it.
|
|
58
|
+
|
|
59
|
+
Geometric units throughout: r, m in km; eps, p in km^-2.
|
|
60
|
+
"""
|
|
61
|
+
from __future__ import annotations
|
|
62
|
+
|
|
63
|
+
import math
|
|
64
|
+
from typing import NamedTuple
|
|
65
|
+
|
|
66
|
+
import jax
|
|
67
|
+
import jax.numpy as jnp
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
import diffrax
|
|
71
|
+
import equinox as eqx
|
|
72
|
+
_HAVE_DIFFRAX = True
|
|
73
|
+
except Exception: # pragma: no cover
|
|
74
|
+
_HAVE_DIFFRAX = False
|
|
75
|
+
|
|
76
|
+
from ..constants import GMSUN_KM
|
|
77
|
+
from ..eos.base import EOSTable
|
|
78
|
+
|
|
79
|
+
jax.config.update("jax_enable_x64", True)
|
|
80
|
+
|
|
81
|
+
_FOURPI = 4.0 * math.pi
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class TOVPoint(NamedTuple):
|
|
85
|
+
"""One stellar model."""
|
|
86
|
+
h_c: jnp.ndarray # central pseudo-enthalpy
|
|
87
|
+
R_km: jnp.ndarray # circumferential radius, km
|
|
88
|
+
M_km: jnp.ndarray # gravitational mass, geometric km
|
|
89
|
+
M_msun: jnp.ndarray # gravitational mass, solar masses
|
|
90
|
+
C: jnp.ndarray # compactness M/R (geometric)
|
|
91
|
+
y: jnp.ndarray # surface tidal variable
|
|
92
|
+
k2: jnp.ndarray # l=2 tidal Love number
|
|
93
|
+
Lambda: jnp.ndarray # dimensionless tidal deformability
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class TOVProfile(NamedTuple):
|
|
97
|
+
"""Structure-only profile, centre-series start to surface; r and m in km.
|
|
98
|
+
|
|
99
|
+
Enthalpy decreases outward. The first point is at the small nonzero
|
|
100
|
+
central-series radius. Redshift
|
|
101
|
+
uses the same finite-pressure surface convention as solve_structure.
|
|
102
|
+
"""
|
|
103
|
+
h: jnp.ndarray
|
|
104
|
+
r_km: jnp.ndarray
|
|
105
|
+
m_km: jnp.ndarray
|
|
106
|
+
ephi: jnp.ndarray
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _rhs(eps, p, deps_dh, state, tidal):
|
|
111
|
+
"""d(r, m, y)/dh from the EOS at one point. ``deps_dh`` is the tidal term
|
|
112
|
+
(eps + p)/cs^2, taken as the analytic deps/dh of the Hermite cell that also
|
|
113
|
+
gives eps, so the tidal source integrates to exactly the structure's
|
|
114
|
+
Delta eps per cell (docs/devlog/2026-10-14-tidal-cs2.md)."""
|
|
115
|
+
r, m, y = state
|
|
116
|
+
denom = m + _FOURPI * r**3 * p
|
|
117
|
+
drdh = -r * (r - 2.0 * m) / denom
|
|
118
|
+
dmdh = _FOURPI * r**2 * eps * drdh
|
|
119
|
+
|
|
120
|
+
if tidal:
|
|
121
|
+
one_minus_2mr = 1.0 - 2.0 * m / r
|
|
122
|
+
F = (1.0 - _FOURPI * r**2 * (eps - p)) / one_minus_2mr
|
|
123
|
+
Q = (_FOURPI / one_minus_2mr) * (
|
|
124
|
+
5.0 * eps + 9.0 * p + deps_dh - 6.0 / (_FOURPI * r**2)
|
|
125
|
+
) - (2.0 * (m + _FOURPI * r**3 * p) / (r**2 * one_minus_2mr)) ** 2
|
|
126
|
+
dydr = -(y**2 + y * F + r**2 * Q) / r
|
|
127
|
+
dydh = dydr * drdh
|
|
128
|
+
else:
|
|
129
|
+
# structure-only: keep y constant so its singular near-centre terms are
|
|
130
|
+
# never formed -> reverse-mode AD of (R, M) is clean.
|
|
131
|
+
dydh = 0.0 * r
|
|
132
|
+
return jnp.stack([drdh, dmdh, dydh])
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _derivs(h, state, table: EOSTable, tidal: bool = True):
|
|
136
|
+
"""d(r, m, y)/dh at pseudo-enthalpy ``h`` (scan backend)."""
|
|
137
|
+
eps, p, deps_dh = table.at_h_tidal(h)
|
|
138
|
+
return _rhs(eps, p, deps_dh, state, tidal)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# ----- the tidal variable in a node-anchored picture (adaptive backend) -----
|
|
142
|
+
# The tidal term deps/dh jumps at every table node (the Hermite of p(h) is C^1).
|
|
143
|
+
# The adaptive solve stops at the nodes with a mesh frozen against
|
|
144
|
+
# differentiation, so a node whose h moves with the EOS parameters carries a
|
|
145
|
+
# boundary term (f_above - f_below) dh_node/dtheta that the frozen mesh never
|
|
146
|
+
# sees (measured: dLambda/dL_sym off by a factor 2.6, dLambda/dscale on the
|
|
147
|
+
# steep-joint table by 2.5). So y is carried in a node-anchored picture: at
|
|
148
|
+
# solve coordinate x, y holds y(h(x)), where h(x) is piecewise linear with knots
|
|
149
|
+
# at the nodes' gradient-stopped positions U = stop_gradient(table.h) <-> h =
|
|
150
|
+
# table.h. The nodes then sit at fixed x for y, and their motion enters through
|
|
151
|
+
# h(x) and dh/dx. r and m stay in h (x == h): their right-hand side is
|
|
152
|
+
# continuous at the nodes, so they need no boundary term, and moving them too
|
|
153
|
+
# costs accuracy (dM/dL_sym 1e-6 -> 6e-4 at the default rtol, from the large
|
|
154
|
+
# intermediate shift tangent). The y equation needs r, m at h(x); they are
|
|
155
|
+
# taken to first order, r + (dr/dh) (h(x) - x), exact for first tangents since
|
|
156
|
+
# h(x) - x is zero in value. The cell holding the (frozen) start ``ua`` is
|
|
157
|
+
# mapped onto [h_{i-1}, ua], so h(x) = x at the start; at the end of a solve
|
|
158
|
+
# y is moved back to h = x by y - (dy/dx)(h(x) - x). At the primal U == table.h,
|
|
159
|
+
# so every value is bit-identical to integrating y in h; only first tangents
|
|
160
|
+
# change, by exactly the boundary terms. Second derivatives in EOS parameters
|
|
161
|
+
# (d^2/dtheta^2) were never supported and also miss the O((h(x) - x)^2) terms.
|
|
162
|
+
def _u_cell(table: EOSTable, x, ua):
|
|
163
|
+
"""Cell index and the y-picture map of cell i: (lo_u, lo_h, dh/dx) at ``x``,
|
|
164
|
+
with the cell holding the start ``ua`` anchored there."""
|
|
165
|
+
H = table.h
|
|
166
|
+
U = jax.lax.stop_gradient(H)
|
|
167
|
+
i = jnp.clip(jnp.searchsorted(U, x), 1, H.shape[0] - 1)
|
|
168
|
+
top = U[i] >= ua # the cell holding the start
|
|
169
|
+
hi_u = jnp.where(top, ua, U[i])
|
|
170
|
+
hi_h = jnp.where(top, ua, H[i])
|
|
171
|
+
return i, U[i - 1], H[i - 1], (hi_h - H[i - 1]) / (hi_u - U[i - 1])
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _shift(x, lo_u, lo_h, dhdx):
|
|
175
|
+
"""h(x) - x of the y picture; written so that it is exactly 0 in value."""
|
|
176
|
+
return (lo_h - lo_u) + (x - lo_u) * (dhdx - 1.0)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _derivs_x(x, state, table: EOSTable, ua, aux, tidal: bool = True):
|
|
180
|
+
"""d(r, m, y)/dx (adaptive backend): r, m in h (x == h), y in the
|
|
181
|
+
node-anchored picture (see the note above). ``aux`` is
|
|
182
|
+
``eos.base._degenerate_cells(table.h, table.eps, table.p)``."""
|
|
183
|
+
from ..eos.base import _floor_eps_p, _hermite_cell_t, _tidal_term
|
|
184
|
+
i, lo_u, lo_h, dhdx = _u_cell(table, x, ua)
|
|
185
|
+
dh = table.h[i] - lo_h
|
|
186
|
+
eps, p = _hermite_cell_t(i, (x - lo_h) / dh, dh, table.p, table.eps)
|
|
187
|
+
eps, p = _floor_eps_p(eps, p, jnp)
|
|
188
|
+
f = _rhs(eps, p, 0.0, state, False) # (dr/dh, dm/dh, 0)
|
|
189
|
+
if not tidal:
|
|
190
|
+
return f
|
|
191
|
+
t_y = (x - lo_u) * dhdx / dh # == (h(x) - h_{i-1}) / dh
|
|
192
|
+
eps_y, p_y, deps_y = _hermite_cell_t(i, t_y, dh, table.p, table.eps, deps=True)
|
|
193
|
+
eps_y, p_y = _floor_eps_p(eps_y, p_y, jnp)
|
|
194
|
+
deps_y = _tidal_term(i, t_y, dh, deps_y, eps_y, p_y, *aux, jnp)
|
|
195
|
+
s_y = state + f * _shift(x, lo_u, lo_h, dhdx) # r, m at h(x); f[2] == 0
|
|
196
|
+
fy = _rhs(eps_y, p_y, deps_y, s_y, True)[2] * dhdx
|
|
197
|
+
return jnp.stack([f[0], f[1], fy])
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _y_to_h(table, x, state, ua, aux):
|
|
201
|
+
"""Tidal state at solve coordinate ``x`` with y moved from h(x) back to h = x
|
|
202
|
+
(a zero-valued correction; first tangents exact)."""
|
|
203
|
+
_, lo_u, lo_h, dhdx = _u_cell(table, x, ua)
|
|
204
|
+
fy = _derivs_x(x, state, table, ua, aux, True)[2]
|
|
205
|
+
return state.at[2].add(-fy * _shift(x, lo_u, lo_h, dhdx))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _k2_from_y_C(y, C):
|
|
209
|
+
"""l=2 tidal Love number from surface y and compactness C (Hinderer 2008)."""
|
|
210
|
+
onemtwoC = 1.0 - 2.0 * C
|
|
211
|
+
num = (8.0 / 5.0) * C**5 * onemtwoC**2 * (2.0 + 2.0 * C * (y - 1.0) - y)
|
|
212
|
+
den = (
|
|
213
|
+
2.0 * C * (6.0 - 3.0 * y + 3.0 * C * (5.0 * y - 8.0))
|
|
214
|
+
+ 4.0 * C**3 * (13.0 - 11.0 * y + C * (3.0 * y - 2.0)
|
|
215
|
+
+ 2.0 * C**2 * (1.0 + y))
|
|
216
|
+
+ 3.0 * onemtwoC**2 * (2.0 - y + 2.0 * C * (y - 1.0)) * jnp.log(onemtwoC)
|
|
217
|
+
)
|
|
218
|
+
return num / den
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _central_start(table, h_c, frac=1e-8):
|
|
222
|
+
h_min = table.h[0]
|
|
223
|
+
h_c = jnp.asarray(h_c)
|
|
224
|
+
dh0 = (h_c - h_min) * frac
|
|
225
|
+
eps_c, p_c, _ = table.at_h(h_c)
|
|
226
|
+
r0 = jnp.sqrt(3.0 * dh0 / (2.0 * math.pi * (eps_c + 3.0 * p_c)))
|
|
227
|
+
m0 = (4.0 / 3.0) * math.pi * eps_c * r0**3
|
|
228
|
+
return h_min, h_c, dh0, jnp.stack([r0, m0, jnp.asarray(2.0)])
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _finish(R, M, y, h_c, tidal):
|
|
232
|
+
C = M / R
|
|
233
|
+
if tidal:
|
|
234
|
+
k2 = _k2_from_y_C(y, C)
|
|
235
|
+
Lam = (2.0 / 3.0) * k2 / C**5
|
|
236
|
+
else:
|
|
237
|
+
k2 = jnp.nan * R
|
|
238
|
+
Lam = jnp.nan * R
|
|
239
|
+
return TOVPoint(h_c=h_c, R_km=R, M_km=M, M_msun=M / GMSUN_KM,
|
|
240
|
+
C=C, y=y, k2=k2, Lambda=Lam)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# ----- fixed-step RK4 scan backend -----
|
|
244
|
+
def _solve_scan(table, h_c, n_steps, tidal):
|
|
245
|
+
h_min, h_c, dh0, state0 = _central_start(table, h_c)
|
|
246
|
+
hs = jnp.linspace(h_c - dh0, h_min, n_steps + 1)
|
|
247
|
+
h_lefts, dhs = hs[:-1], jnp.diff(hs)
|
|
248
|
+
|
|
249
|
+
def step(state, hd):
|
|
250
|
+
h0, dh = hd
|
|
251
|
+
k1 = _derivs(h0, state, table, tidal)
|
|
252
|
+
k2 = _derivs(h0 + 0.5 * dh, state + 0.5 * dh * k1, table, tidal)
|
|
253
|
+
k3 = _derivs(h0 + 0.5 * dh, state + 0.5 * dh * k2, table, tidal)
|
|
254
|
+
k4 = _derivs(h0 + dh, state + dh * k3, table, tidal)
|
|
255
|
+
return state + (dh / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4), None
|
|
256
|
+
|
|
257
|
+
state, _ = jax.lax.scan(step, state0, (h_lefts, dhs))
|
|
258
|
+
return _finish(state[0], state[1], state[2], h_c, tidal)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
# ----- adaptive diffrax backend -----
|
|
262
|
+
# Module-level vector fields: diffeqsolve is jitted with the term as a static key, so a
|
|
263
|
+
# fresh closure per call would recompile every solve and leak the executables.
|
|
264
|
+
def _field_tidal(x, s, args):
|
|
265
|
+
return _derivs_x(x, s, *args, True) # args = (table, ua, aux)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _field_structure(x, s, args):
|
|
269
|
+
return _derivs_x(x, s, *args, False)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _node_jumps(table):
|
|
273
|
+
"""Interior EOS-table nodes as diffrax ``jump_ts`` (gradient-stopped).
|
|
274
|
+
|
|
275
|
+
The TOV right-hand side is not smooth at any table node: eps comes from a
|
|
276
|
+
C^1 Hermite of p(h) (so eps' jumps), and the tidal term deps/dh of the same
|
|
277
|
+
Hermite jumps. An adaptive step that straddles a node rejects repeatedly
|
|
278
|
+
there, and ForwardMode then differentiates the mesh's position relative to
|
|
279
|
+
the non-smooth point -- a tangent bias that shrinks only slowly and
|
|
280
|
+
erratically with rtol (docs/devlog/2026-10-12-tov-jump-ts.md). Stepping to
|
|
281
|
+
just before and restarting just after each node removes both.
|
|
282
|
+
``table.h[0]`` is the surface (the integration end point) and is left out;
|
|
283
|
+
nodes outside the integration interval are inert, so the array keeps the
|
|
284
|
+
table's static length under jit/vmap. The positions are gradient-stopped:
|
|
285
|
+
the mesh is fixed. For r and m (continuous right-hand side) the node motion
|
|
286
|
+
enters through the vector field on each side of the node; for y (which
|
|
287
|
+
jumps) through its node-anchored picture (:func:`_derivs_x`), which carries
|
|
288
|
+
the boundary term (devlog 2026-10-14-tidal-cs2)."""
|
|
289
|
+
return jax.lax.stop_gradient(table.h[1:])
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _adaptive_tov(table, t0, t1, state0, rtol, atol, tidal, dt0,
|
|
293
|
+
adjoint=None, max_steps=100000, saveat=None, jump_nodes=True):
|
|
294
|
+
"""Adaptive Dopri5 integration of the TOV(+tidal) system from ``t0`` down to
|
|
295
|
+
``t1`` in pseudo-enthalpy, with steps cut at the EOS table nodes.
|
|
296
|
+
|
|
297
|
+
Three mechanisms, each fixing part of the tangent (docs/devlog/
|
|
298
|
+
2026-10-12-tov-jump-ts.md, 2026-10-14-tidal-cs2.md):
|
|
299
|
+
|
|
300
|
+
* ``jump_ts`` at the table nodes fixes the *parameter* tangents: the mesh
|
|
301
|
+
no longer straddles kinks whose position moves with the EOS parameters.
|
|
302
|
+
* The tidal y is carried in a node-anchored picture (:func:`_derivs_x`), so
|
|
303
|
+
the jump of the tidal term deps/dh at a node that moves with the
|
|
304
|
+
parameters contributes its boundary term, which the frozen mesh would
|
|
305
|
+
drop. The returned y is moved back to h = t1 (:func:`_y_to_h`).
|
|
306
|
+
* The frozen start fixes the *h_c* tangent and is REQUIRED whenever
|
|
307
|
+
``jump_ts`` is on. With a live t0/dt0 the mesh moves with h_c while the
|
|
308
|
+
(gradient-stopped) node clips do not, and the h_c tangent error grows as
|
|
309
|
+
rtol tightens (0.49 / 4.8e3 / 1.7e7 at rtol 1e-7 / 1e-8 / 1e-9).
|
|
310
|
+
|
|
311
|
+
The start time and the initial step are frozen against differentiation, so
|
|
312
|
+
no mesh point before the last carries a tangent. The start's dependence on
|
|
313
|
+
the inputs moves into the starting state through the flow expansion
|
|
314
|
+
``y(t0s) = y(t0) + f d + f' d^2 / 2`` with ``d = t0s - t0 == 0`` and
|
|
315
|
+
``f' = df/dt`` along the flow: values are unchanged, first tangents are
|
|
316
|
+
exact (``dy0 - f dt0``), and the ``f' dt0^2`` term of the second tangent is
|
|
317
|
+
kept. ``t1`` stays live: the last step ends there and spans no node.
|
|
318
|
+
|
|
319
|
+
Derivatives w.r.t. the start (h_c) are reliable to FIRST order only. Second
|
|
320
|
+
derivatives in h_c are wrong by orders of magnitude (the frozen mesh
|
|
321
|
+
under-resolves the (h_c - h)^-3/2 second tangent near the centre);
|
|
322
|
+
mixed d^2/dh_c dtheta and first parameter derivatives are fine; second
|
|
323
|
+
parameter derivatives are not (see solve_structure).
|
|
324
|
+
``tests/test_tov_jump_ts.py::test_second_hc_derivative_is_not_supported``
|
|
325
|
+
pins this. With ``tidal=True`` only the default ``saveat`` (the end
|
|
326
|
+
point) is supported: saved y would be in the node-anchored picture."""
|
|
327
|
+
sg = jax.lax.stop_gradient
|
|
328
|
+
t0, t1 = jnp.asarray(t0), jnp.asarray(t1) # a Python float here is a jit key
|
|
329
|
+
if tidal and saveat is not None:
|
|
330
|
+
raise ValueError("tidal solves save the end point only")
|
|
331
|
+
ua = sg(t0) # y picture anchored at the frozen start
|
|
332
|
+
from ..eos.base import _degenerate_cells
|
|
333
|
+
aux = _degenerate_cells(table.h, table.eps, table.p, jnp) # jumps at fixed p
|
|
334
|
+
t0s = sg(t0) # REQUIRED with jump_ts; see above
|
|
335
|
+
f0 = _derivs_x(t0, state0, table, ua, aux, tidal)
|
|
336
|
+
_, fdot = jax.jvp(lambda t, y: _derivs_x(t, y, table, ua, aux, tidal),
|
|
337
|
+
(t0, state0), (jnp.ones_like(t0), f0))
|
|
338
|
+
d = t0s - t0
|
|
339
|
+
state0 = state0 + f0 * d + 0.5 * fdot * d * d
|
|
340
|
+
term = diffrax.ODETerm(_field_tidal if tidal else _field_structure)
|
|
341
|
+
ctrl = diffrax.PIDController(
|
|
342
|
+
rtol=rtol, atol=atol,
|
|
343
|
+
jump_ts=_node_jumps(table) if jump_nodes else None)
|
|
344
|
+
if adjoint is None:
|
|
345
|
+
adjoint = diffrax.ForwardMode() # supports values, vmap, forward-mode AD
|
|
346
|
+
sol = diffrax.diffeqsolve(
|
|
347
|
+
term, diffrax.Dopri5(), t0=t0s, t1=t1, dt0=sg(dt0),
|
|
348
|
+
y0=state0, args=(table, ua, aux), stepsize_controller=ctrl, max_steps=max_steps,
|
|
349
|
+
adjoint=adjoint,
|
|
350
|
+
saveat=diffrax.SaveAt(t1=True) if saveat is None else saveat,
|
|
351
|
+
)
|
|
352
|
+
if not tidal:
|
|
353
|
+
return sol
|
|
354
|
+
ys = _y_to_h(table, t1, sol.ys[0], ua, aux)[None]
|
|
355
|
+
return eqx.tree_at(lambda s: s.ys, sol, ys)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
#: ``centre_refine``: the inner fraction of (h_c - h_min) integrated at a
|
|
359
|
+
#: tolerance tighter by ``_CENTRE_TOL`` (floored at min(rtol, ``_CENTRE_RTOL_MIN``))
|
|
360
|
+
_CENTRE_FRAC = 0.05
|
|
361
|
+
_CENTRE_TOL = 1e-3
|
|
362
|
+
_CENTRE_RTOL_MIN = 1e-13
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _integrate_diffrax(table, h_c, rtol, atol, tidal, adjoint=None,
|
|
366
|
+
max_steps=100000, saveat=None, *, jump_nodes=True,
|
|
367
|
+
centre_refine=False):
|
|
368
|
+
if not _HAVE_DIFFRAX: # pragma: no cover
|
|
369
|
+
raise ImportError("backend='diffrax' requires the 'diffrax' package; "
|
|
370
|
+
"pip install diffrax (or use backend='scan').")
|
|
371
|
+
h_min, h_c, dh0, state0 = _central_start(table, h_c)
|
|
372
|
+
t0, dt0 = h_c - dh0, -(h_c - h_min) * 1e-4
|
|
373
|
+
if not centre_refine:
|
|
374
|
+
return _adaptive_tov(table, t0, h_min, state0, rtol, atol, tidal, dt0,
|
|
375
|
+
adjoint, max_steps, saveat, jump_nodes)
|
|
376
|
+
if saveat is not None:
|
|
377
|
+
raise ValueError("centre_refine supports SaveAt(t1=True) only")
|
|
378
|
+
# Inner shell to a frozen split point at a tighter tolerance, then the rest.
|
|
379
|
+
# The split is an arbitrary interior point, so freezing it needs no
|
|
380
|
+
# correction; the state carries the tangents across.
|
|
381
|
+
h_split = jax.lax.stop_gradient(t0 - _CENTRE_FRAC * (h_c - h_min))
|
|
382
|
+
# inner rtol = max(rtol * 1e-3, min(rtol, 1e-13)): never looser than rtol
|
|
383
|
+
scale = jnp.maximum(_CENTRE_TOL, jnp.minimum(1.0, _CENTRE_RTOL_MIN / rtol))
|
|
384
|
+
inner = _adaptive_tov(table, t0, h_split, state0, rtol * scale,
|
|
385
|
+
atol * scale, tidal, dt0, adjoint, max_steps, None,
|
|
386
|
+
jump_nodes)
|
|
387
|
+
return _adaptive_tov(table, h_split, h_min, inner.ys[0], rtol, atol, tidal,
|
|
388
|
+
10.0 * dt0, adjoint, max_steps, None, jump_nodes)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _solve_diffrax(table, h_c, rtol, atol, tidal, adjoint=None, max_steps=100000,
|
|
392
|
+
*, jump_nodes=True, centre_refine=False):
|
|
393
|
+
sol = _integrate_diffrax(table, h_c, rtol, atol, tidal, adjoint, max_steps,
|
|
394
|
+
jump_nodes=jump_nodes, centre_refine=centre_refine)
|
|
395
|
+
ys = sol.ys[0]
|
|
396
|
+
return _finish(ys[0], ys[1], ys[2], h_c, tidal)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def solve_profile(table: EOSTable, h_c, *, n_points: int = 256,
|
|
400
|
+
rtol: float = 1e-7, atol: float = 1e-9, adjoint=None):
|
|
401
|
+
"""Save an adaptive spherical TOV profile for thermal volume integrals.
|
|
402
|
+
|
|
403
|
+
Quadratic spacing in enthalpy drop resolves the central r ~ sqrt(h_c-h)
|
|
404
|
+
behavior. Saving points does not change the adaptive integration mesh.
|
|
405
|
+
Default ForwardMode supports JVP/jacfwd through central enthalpy
|
|
406
|
+
and smooth table inputs, with n_points fixed.
|
|
407
|
+
Smooth EOS only; phase-transition junctions are not included.
|
|
408
|
+
"""
|
|
409
|
+
if n_points < 2:
|
|
410
|
+
raise ValueError("n_points must be at least 2")
|
|
411
|
+
if not _HAVE_DIFFRAX: # pragma: no cover
|
|
412
|
+
raise ImportError("solve_profile requires diffrax")
|
|
413
|
+
h_min, h_c, dh0, _ = _central_start(table, h_c)
|
|
414
|
+
h_start = h_c - dh0
|
|
415
|
+
h = h_start + (h_min - h_start) * jnp.linspace(0., 1., n_points)**2
|
|
416
|
+
h = h.at[0].set(h_start).at[-1].set(h_min)
|
|
417
|
+
sol = _integrate_diffrax(table, h_c, rtol, atol, False, adjoint,
|
|
418
|
+
saveat=diffrax.SaveAt(ts=h))
|
|
419
|
+
r, m = sol.ys[:, 0], sol.ys[:, 1]
|
|
420
|
+
ephi_surface = jnp.sqrt(1. - 2. * m[-1] / r[-1])
|
|
421
|
+
ephi = ephi_surface * jnp.exp(h_min - h)
|
|
422
|
+
return TOVProfile(h, r, m, ephi)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def solve_structure(table: EOSTable, h_c, *, backend: str = "diffrax",
|
|
426
|
+
tidal: bool = True, rtol: float = 1e-7, atol: float = 1e-9,
|
|
427
|
+
n_steps: int = 2000, adjoint=None, jump_nodes: bool = True,
|
|
428
|
+
centre_refine: bool = False):
|
|
429
|
+
"""Integrate one star at central pseudo-enthalpy ``h_c``. Returns TOVPoint.
|
|
430
|
+
|
|
431
|
+
Backend seam: callers depend only on this signature and ``TOVPoint``.
|
|
432
|
+
|
|
433
|
+
Parameters
|
|
434
|
+
----------
|
|
435
|
+
backend : "diffrax" (adaptive, accurate, forward-mode AD; default) or
|
|
436
|
+
"scan" (fixed-step RK4; lightweight, reverse-mode-capable).
|
|
437
|
+
tidal : integrate the tidal sector (k2, Lambda). ``tidal=False`` drops y so
|
|
438
|
+
reverse-mode AD of (R, M) is clean (scan backend).
|
|
439
|
+
rtol, atol : diffrax tolerances. n_steps : scan-backend step count.
|
|
440
|
+
adjoint : optional diffrax adjoint override (default ForwardMode()).
|
|
441
|
+
jump_nodes : (diffrax) stop steps at every EOS table node (default). False
|
|
442
|
+
was an opt-out for bulk value-only scans of tables with thousands
|
|
443
|
+
of rows (also exposed by ``build_family``). Since 2026-10-14 the
|
|
444
|
+
tidal term jumps at the nodes, so with tidal=True it no longer
|
|
445
|
+
saves time (MetaModel family 81 vs 88 ms, GM1 78 vs 38 ms) and
|
|
446
|
+
Lambda is ~1e4x less accurate (7e-4 MetaModel, 6e-3 GM1 at the
|
|
447
|
+
default rtol, vs 2e-7); NOT recommended with tidal=True. With
|
|
448
|
+
tidal=False it is unaffected. The parameter tangents are biased
|
|
449
|
+
by up to ~10%, and batched vs unbatched solves agree only to ~1e-4
|
|
450
|
+
(measured 3e-5 in Lambda; 1e-12 with the default). It is
|
|
451
|
+
NOT the pre-2026-10-12 solver: the start stays frozen (so the h_c
|
|
452
|
+
tangent stays accurate, 1-19% off the old one); parameter
|
|
453
|
+
tangents equal the old solver's, and values equal it only up to
|
|
454
|
+
step-decision roundoff (up to ~1e-4 in Lambda).
|
|
455
|
+
centre_refine : (diffrax) integrate the inner 5% of (h_c - h_min) at
|
|
456
|
+
rtol * 1e-3, floored at min(rtol, 1e-13) (never looser than the
|
|
457
|
+
rest of the star). Off by default. Cuts the h_c-tangent error at the
|
|
458
|
+
default rtol from ~1.2e-4 to ~8e-6 for +40-90% cost; parameter
|
|
459
|
+
tangents and values are unchanged.
|
|
460
|
+
|
|
461
|
+
Derivatives: forward-mode first derivatives in h_c and in any EOS
|
|
462
|
+
parameter, and mixed d^2/dh_c dtheta, are supported. Second derivatives
|
|
463
|
+
in h_c (d^2 X/dh_c^2) are NOT: they are wrong by orders of magnitude.
|
|
464
|
+
Nor are second derivatives in EOS parameters (d^2/dtheta^2): on the
|
|
465
|
+
MetaModel star of tests/test_tov_jump_ts.py, d^2(M, R, Lambda)/dL_sym^2 are
|
|
466
|
+
off by O(1) (and were off by 5, 10 and 900x before 2026-10-14); the tidal
|
|
467
|
+
y is moreover carried only to first order in the node motion (devlog
|
|
468
|
+
2026-10-14-tidal-cs2).
|
|
469
|
+
"""
|
|
470
|
+
if backend == "diffrax":
|
|
471
|
+
return _solve_diffrax(table, h_c, rtol, atol, tidal, adjoint=adjoint,
|
|
472
|
+
jump_nodes=jump_nodes, centre_refine=centre_refine)
|
|
473
|
+
elif backend == "scan":
|
|
474
|
+
return _solve_scan(table, h_c, n_steps, tidal)
|
|
475
|
+
raise ValueError(f"unknown backend {backend!r} (use 'diffrax' or 'scan')")
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Validation tooling: multi-solver reference matrix + EOS-level model diagnostic."""
|
|
2
|
+
from .reference_matrix import run as run_reference_matrix, build_ladder
|
|
3
|
+
from .model_diagnostic import model_diagnostic
|
|
4
|
+
|
|
5
|
+
__all__ = ["run_reference_matrix", "build_ladder", "model_diagnostic"]
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""EOS-level (model) cross-code diagnostic -- compares the EOS *itself*, not just the
|
|
2
|
+
TOV observables.
|
|
3
|
+
|
|
4
|
+
Two EOS (parametric models or ingested tables, anything exposing an ``EOSTable``)
|
|
5
|
+
are evaluated on a common baryon-density grid and their thermodynamic quantities are
|
|
6
|
+
tabulated with relative differences:
|
|
7
|
+
|
|
8
|
+
eps(n) energy density [MeV/fm^3]
|
|
9
|
+
p(n) pressure [MeV/fm^3]
|
|
10
|
+
mu(n) baryon chem. potential = (eps+p)/n [MeV-ish, geometric]
|
|
11
|
+
cs2(n) sound speed squared dp/deps
|
|
12
|
+
|
|
13
|
+
This catches model/convention disagreements (couplings, units, composition) that an
|
|
14
|
+
M-R-Lambda comparison can hide, and is the natural way to cross-check against an
|
|
15
|
+
external code's EOS table (e.g. MUSES cmf_solver) before ever solving a star.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
|
|
21
|
+
from ..eos.base import EOSTable
|
|
22
|
+
from ..constants import MEVFM3_TO_GEOM
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _interp_loglog(n_q, n, y):
|
|
26
|
+
"""log-log interpolation of y(n) at n_q (n, y > 0, n increasing)."""
|
|
27
|
+
return np.exp(np.interp(np.log(n_q), np.log(n), np.log(np.maximum(y, 1e-300))))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _quantities(table: EOSTable, n_q):
|
|
31
|
+
n = np.asarray(table.n)
|
|
32
|
+
eps_g = np.asarray(table.eps) # geometric km^-2
|
|
33
|
+
p_g = np.asarray(table.p)
|
|
34
|
+
cs2 = np.asarray(table.cs2)
|
|
35
|
+
eps = _interp_loglog(n_q, n, eps_g) / MEVFM3_TO_GEOM # -> MeV/fm^3
|
|
36
|
+
p = _interp_loglog(n_q, n, p_g) / MEVFM3_TO_GEOM
|
|
37
|
+
mu = (eps + p) / n_q # MeV/fm^3 per fm^-3
|
|
38
|
+
cs2_q = np.interp(np.log(n_q), np.log(n), cs2)
|
|
39
|
+
return dict(eps=eps, p=p, mu=mu, cs2=cs2_q)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def model_diagnostic(table_a: EOSTable, table_b: EOSTable, n_lo=0.05, n_hi=1.0,
|
|
43
|
+
npts=12, label_a="A", label_b="B", verbose=True):
|
|
44
|
+
"""Compare two EOS tables on a common density grid. Returns a dict of arrays
|
|
45
|
+
and the max relative differences; prints a table if ``verbose``."""
|
|
46
|
+
n_q = np.geomspace(n_lo, n_hi, npts)
|
|
47
|
+
A, B = _quantities(table_a, n_q), _quantities(table_b, n_q)
|
|
48
|
+
out = {"n": n_q}
|
|
49
|
+
maxrel = {}
|
|
50
|
+
for q in ("eps", "p", "mu", "cs2"):
|
|
51
|
+
rel = (A[q] - B[q]) / np.where(np.abs(B[q]) > 1e-30, B[q], 1e-30)
|
|
52
|
+
out[q + "_a"], out[q + "_b"], out[q + "_rel"] = A[q], B[q], rel
|
|
53
|
+
maxrel[q] = float(np.max(np.abs(rel)))
|
|
54
|
+
out["maxrel"] = maxrel
|
|
55
|
+
|
|
56
|
+
if verbose:
|
|
57
|
+
print(f"EOS model diagnostic: {label_a} vs {label_b} "
|
|
58
|
+
f"(relative diff = ({label_a}-{label_b})/{label_b})")
|
|
59
|
+
print(f"{'n':>7} {'eps_'+label_a[:3]:>10} {'eps_'+label_b[:3]:>10} "
|
|
60
|
+
f"{'d_eps':>9} {'d_p':>9} {'d_mu':>9} {'d_cs2':>9}")
|
|
61
|
+
for i, n in enumerate(n_q):
|
|
62
|
+
print(f"{n:7.3f} {A['eps'][i]:10.2f} {B['eps'][i]:10.2f} "
|
|
63
|
+
f"{out['eps_rel'][i]:9.1e} {out['p_rel'][i]:9.1e} "
|
|
64
|
+
f"{out['mu_rel'][i]:9.1e} {out['cs2_rel'][i]:9.1e}")
|
|
65
|
+
print(f"max |rel diff|: eps {maxrel['eps']:.2e} p {maxrel['p']:.2e} "
|
|
66
|
+
f"mu {maxrel['mu']:.2e} cs2 {maxrel['cs2']:.2e}")
|
|
67
|
+
return out
|