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.
Files changed (81) hide show
  1. nmbackend/__init__.py +22 -0
  2. nmbackend/adapters/__init__.py +4 -0
  3. nmbackend/adapters/rift.py +95 -0
  4. nmbackend/constants.py +55 -0
  5. nmbackend/cooling/README.md +159 -0
  6. nmbackend/cooling/__init__.py +13 -0
  7. nmbackend/cooling/build_nscool.sh +51 -0
  8. nmbackend/cooling/isothermal.py +76 -0
  9. nmbackend/cooling/nscool_nmbackend.patch +310 -0
  10. nmbackend/cooling/physics/__init__.py +18 -0
  11. nmbackend/cooling/physics/_spline.py +71 -0
  12. nmbackend/cooling/physics/blanket.py +66 -0
  13. nmbackend/cooling/physics/conduct.py +196 -0
  14. nmbackend/cooling/physics/core_conduct.py +68 -0
  15. nmbackend/cooling/physics/core_nu.py +268 -0
  16. nmbackend/cooling/physics/crust.py +113 -0
  17. nmbackend/cooling/physics/crust_nu.py +93 -0
  18. nmbackend/cooling/physics/curve.py +42 -0
  19. nmbackend/cooling/physics/envelope.py +37 -0
  20. nmbackend/cooling/physics/gaps.py +164 -0
  21. nmbackend/cooling/physics/geometry.py +131 -0
  22. nmbackend/cooling/physics/heat.py +125 -0
  23. nmbackend/cooling/physics/native.py +138 -0
  24. nmbackend/cooling/physics/reference.py +53 -0
  25. nmbackend/cooling/physics/star.py +225 -0
  26. nmbackend/cooling/physics/superfluid.py +41 -0
  27. nmbackend/cooling/physics/whole.py +136 -0
  28. nmbackend/cooling/runner.py +583 -0
  29. nmbackend/cooling/validate.py +120 -0
  30. nmbackend/data/crust_sly_dh2001.dat +81 -0
  31. nmbackend/data/frib_scenario_ladder.yaml +100 -0
  32. nmbackend/durca.py +111 -0
  33. nmbackend/ejecta.py +614 -0
  34. nmbackend/eos/__init__.py +19 -0
  35. nmbackend/eos/base.py +523 -0
  36. nmbackend/eos/compose.py +251 -0
  37. nmbackend/eos/coolcomp.py +67 -0
  38. nmbackend/eos/crust.py +318 -0
  39. nmbackend/eos/ddrmf.py +388 -0
  40. nmbackend/eos/hybrid.py +173 -0
  41. nmbackend/eos/leptons.py +74 -0
  42. nmbackend/eos/metamodel.py +303 -0
  43. nmbackend/eos/polytrope.py +33 -0
  44. nmbackend/eos/rmft.py +450 -0
  45. nmbackend/eos/skyrme.py +352 -0
  46. nmbackend/inference/__init__.py +13 -0
  47. nmbackend/inference/fisher.py +174 -0
  48. nmbackend/inference/synthetic.py +83 -0
  49. nmbackend/ipad.py +102 -0
  50. nmbackend/lab_likelihood.py +587 -0
  51. nmbackend/nscool_io.py +112 -0
  52. nmbackend/postmerger.py +264 -0
  53. nmbackend/priors/__init__.py +16 -0
  54. nmbackend/priors/bridge.py +437 -0
  55. nmbackend/priors/bridge_jax.py +435 -0
  56. nmbackend/priors/gp_pca.py +325 -0
  57. nmbackend/reference/__init__.py +11 -0
  58. nmbackend/reference/reprimand.py +108 -0
  59. nmbackend/reference/scipy_tov.py +289 -0
  60. nmbackend/rift/__init__.py +26 -0
  61. nmbackend/rift/compressed.py +194 -0
  62. nmbackend/rift/evidence.py +276 -0
  63. nmbackend/rift/sequence.py +428 -0
  64. nmbackend/rotating/__init__.py +7 -0
  65. nmbackend/rotating/rns.py +197 -0
  66. nmbackend/rotating/tabulated.py +249 -0
  67. nmbackend/thermal/__init__.py +1 -0
  68. nmbackend/thermal/diffusion.py +86 -0
  69. nmbackend/tov/__init__.py +15 -0
  70. nmbackend/tov/central.py +72 -0
  71. nmbackend/tov/family.py +155 -0
  72. nmbackend/tov/phase_transition.py +93 -0
  73. nmbackend/tov/solver.py +475 -0
  74. nmbackend/validation/__init__.py +5 -0
  75. nmbackend/validation/model_diagnostic.py +67 -0
  76. nmbackend/validation/reference_matrix.py +216 -0
  77. nmbackend-0.4.0.dist-info/METADATA +168 -0
  78. nmbackend-0.4.0.dist-info/RECORD +81 -0
  79. nmbackend-0.4.0.dist-info/WHEEL +5 -0
  80. nmbackend-0.4.0.dist-info/licenses/LICENSE +21 -0
  81. nmbackend-0.4.0.dist-info/top_level.txt +1 -0
nmbackend/eos/base.py ADDED
@@ -0,0 +1,523 @@
1
+ """EOS base classes and the geometric-unit EOS table consumed by the TOV solver.
2
+
3
+ An ``EOSTable`` holds JAX arrays describing a cold, barotropic EOS on a baryon
4
+ density grid, already converted to geometric units (km^-2). Everything is
5
+ ``jax.numpy`` so gradients propagate from EOS *parameters* all the way through
6
+ the TOV solve (e.g. dLambda/dL_sym).
7
+
8
+ Pseudo-enthalpy convention (Lindblom 1992): h(p) = integral_0^p dp'/(eps+p').
9
+
10
+ Motivated by ``jester`` (MIT) and RIFT ``EOSManager``; see ATTRIBUTION.md.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import math
16
+ import warnings
17
+ from typing import NamedTuple
18
+ import jax
19
+ import jax.numpy as jnp
20
+ import numpy as np
21
+
22
+ from ..constants import MEVFM3_TO_GEOM
23
+
24
+
25
+ class EOSTable(NamedTuple):
26
+ """Barotropic EOS sampled on a baryon-density grid, in geometric units.
27
+
28
+ Attributes
29
+ ----------
30
+ n : baryon number density, fm^-3 (increasing)
31
+ eps : total energy density, geometric km^-2
32
+ p : pressure, geometric km^-2
33
+ h : pseudo-enthalpy (dimensionless), increasing with n
34
+ cs2 : sound speed squared dp/deps at the nodes, by finite differences
35
+ (dimensionless, units of c^2; clipped to [1e-8, 1]). A
36
+ diagnostic/export field: the TOV tidal term uses the analytic
37
+ deps/dh of the Hermite cell instead (:meth:`at_h_tidal`).
38
+ eps_mevfm3 : energy density in MeV/fm^3 (handy for I/O / RIFT adapter)
39
+ p_mevfm3 : pressure in MeV/fm^3
40
+ """
41
+ n: jnp.ndarray
42
+ eps: jnp.ndarray
43
+ p: jnp.ndarray
44
+ h: jnp.ndarray
45
+ cs2: jnp.ndarray
46
+ eps_mevfm3: jnp.ndarray
47
+ p_mevfm3: jnp.ndarray
48
+
49
+ @property
50
+ def h_max(self) -> jnp.ndarray:
51
+ return self.h[-1]
52
+
53
+ @property
54
+ def cs2_chord(self) -> jnp.ndarray:
55
+ """Unclipped chord sound speed dp/deps of each cell (length N - 1).
56
+ ``cs2`` is clipped to [1e-8, 1], so it cannot show acausality (e.g. a
57
+ penalty on max(cs2) - 1 is identically zero); test causality on this.
58
+ Limits: it is the node chord, not the c_s^2 of the Hermite eps(h) the
59
+ solver integrates, which can overshoot it between nodes (SLy 250
60
+ nodes: 1.176 vs 1.140), so it under-reports interpolant acausality. A
61
+ cell with Delta eps <= 0 gives +inf (0 if Delta p = 0 too); NaN input
62
+ (a rejected table) gives NaN. Mask Delta eps <= 0 cells before any
63
+ penalty: with them, max-form penalties give an inf loss and NaN
64
+ reverse-mode gradient, and forward mode gives NaN even for sum forms.
65
+ A safe form is mean(relu(minimum(cs2_chord, cap) - 1)^2) over cells
66
+ with Delta eps > 0."""
67
+ dp, de = jnp.diff(self.p), jnp.diff(self.eps)
68
+ ok = de > 0
69
+ c = dp / jnp.where(ok, de, 1.0)
70
+ c = jnp.where(ok, c, jnp.where(dp == 0, 0.0, jnp.inf))
71
+ return jnp.where(jnp.isnan(dp) | jnp.isnan(de), jnp.nan, c)
72
+
73
+ @property
74
+ def mu(self) -> jnp.ndarray:
75
+ """Baryon chemical potential mu = (eps+p)/n (geometric km^-1 * ... ); the
76
+ pseudo-enthalpy is h = ln(mu/mu_surface), so mu = mu[0] * exp(h). Either
77
+ h or mu can be used as the (equivalent) thermodynamic parameter."""
78
+ return (self.eps + self.p) / self.n
79
+
80
+ # --- thermodynamically consistent interpolation in pseudo-enthalpy ---
81
+ def at_h(self, h_query):
82
+ """Return (eps, p, cs2) at pseudo-enthalpy ``h_query``, thermodynamically
83
+ consistent in the *structure* sector: p and eps come from a Hermite of p(h)
84
+ with node slopes dp/dh = eps + p, so eps = dp/dh - p and dp/dh = eps + p
85
+ hold by construction. cs2 is interpolated linearly in h from the node
86
+ values (free to be NON-MONOTONE -- never monotonized); it is a diagnostic,
87
+ not the derivative of this eps(h). See :func:`hermite_eos_at_h`."""
88
+ return hermite_eos_at_h(self.h, self.p, self.eps, self.cs2, h_query)
89
+
90
+ def at_h_tidal(self, h_query):
91
+ """Return (eps, p, deps/dh) at ``h_query``: eps and p as :meth:`at_h`,
92
+ and the analytic deps/dh of the same Hermite cell, which equals the tidal
93
+ term (eps + p)/cs^2. Used by the TOV solver. See
94
+ :func:`hermite_eos_tidal_at_h`."""
95
+ return hermite_eos_tidal_at_h(self.h, self.p, self.eps, h_query)
96
+
97
+ def at_h_loglinear(self, h_query):
98
+ """Legacy independent log-linear interpolation (NOT thermodynamically
99
+ consistent: dp/dh != eps+p between nodes; cs2 interpolated+clipped). Kept
100
+ for regression comparison only."""
101
+ h = self.h
102
+ logeps = jnp.interp(h_query, h, jnp.log(self.eps))
103
+ logp = jnp.interp(h_query, h, jnp.log(self.p))
104
+ cs2 = jnp.clip(jnp.interp(h_query, h, self.cs2), 1e-8, 1.0)
105
+ return jnp.exp(logeps), jnp.exp(logp), cs2
106
+
107
+
108
+ class Composition(NamedTuple):
109
+ """beta-equilibrium particle fractions per baryon on a density grid.
110
+
111
+ Charge neutrality: x_p = x_e + x_mu. ``n`` is the baryon density (fm^-3)
112
+ of the EOS model's own grid (before any surface continuation).
113
+ """
114
+ n: jnp.ndarray
115
+ x_p: jnp.ndarray
116
+ x_e: jnp.ndarray
117
+ x_mu: jnp.ndarray
118
+
119
+
120
+ def _hermite_cell(h_nodes, p_nodes, eps_nodes, h_query, xp, deps=False):
121
+ """Cubic Hermite of p(h) with node slopes eps + p: (eps, p[, deps/dh]) at
122
+ ``h_query``, eps = dp/dh - p unfloored. With ``deps``, also the cell's own
123
+ deps/dh = d^2p/dh^2 - dp/dh (see :func:`hermite_eos_tidal_at_h`)."""
124
+ h_nodes = xp.asarray(h_nodes)
125
+ N = h_nodes.shape[0]
126
+ i = xp.clip(xp.searchsorted(h_nodes, h_query), 1, N - 1)
127
+ h0, h1 = h_nodes[i - 1], h_nodes[i]
128
+ dh = h1 - h0
129
+ t = (h_query - h0) / dh
130
+ return _hermite_cell_t(i, t, dh, p_nodes, eps_nodes, deps)
131
+
132
+
133
+ def _hermite_cell_t(i, t, dh, p_nodes, eps_nodes, deps=False):
134
+ """:func:`_hermite_cell` in cell ``i`` (nodes i-1, i) of h-width ``dh`` at the
135
+ cell-local coordinate ``t`` in [0, 1]. The TOV solver calls it with t taken
136
+ on a gradient-stopped node grid (``tov.solver._eos_at_u``)."""
137
+ p0, p1 = p_nodes[i - 1], p_nodes[i]
138
+ e0, e1 = eps_nodes[i - 1], eps_nodes[i]
139
+ s0, s1 = e0 + p0, e1 + p1 # exact slopes dp/dh = eps + p
140
+ t2, t3 = t * t, t * t * t
141
+
142
+ H00, H10 = 2*t3 - 3*t2 + 1, t3 - 2*t2 + t
143
+ H01, H11 = -2*t3 + 3*t2, t3 - t2
144
+ p = H00*p0 + H10*dh*s0 + H01*p1 + H11*dh*s1
145
+
146
+ dH00, dH10 = 6*t2 - 6*t, 3*t2 - 4*t + 1
147
+ dH11 = 3*t2 - 2*t
148
+ # Combine the opposite pressure terms before division to reduce cancellation.
149
+ dpdh = dH00*(p0-p1) / dh + dH10*s0 + dH11*s1
150
+ eps = dpdh - p # derived: dp/dh = eps + p
151
+ if not deps:
152
+ return eps, p
153
+ # d^2p/dh^2 through the end-slope excesses over the secant S, so the
154
+ # O(s/dh) parts cancel analytically: dh p'' = (6t-4)(s0-S) + (6t-2)(s1-S).
155
+ S = (p1 - p0) / dh
156
+ d2pdh2 = ((6*t - 4)*(s0 - S) + (6*t - 2)*(s1 - S)) / dh
157
+ return eps, p, d2pdh2 - dpdh
158
+
159
+
160
+ def _floor_eps_p(eps, p, xp):
161
+ # Floor with where, not maximum/clip: under jaxlib <= 0.9 the batched JVP of
162
+ # these two maxima inside the TOV loop is miscompiled, so jax.jacfwd (not
163
+ # jax.jvp) of M, R, Lambda came out wrong by 1-20%. Pinned by
164
+ # tests/test_ad_gradients.py::test_jacfwd_matches_jvp_with_tidal.
165
+ return (xp.where(eps > 1e-300, eps, 1e-300),
166
+ xp.where(p > 1e-300, p, 1e-300))
167
+
168
+
169
+ def hermite_eos_at_h(h_nodes, p_nodes, eps_nodes, cs2_nodes, h_query, xp=jnp):
170
+ """Thermodynamically consistent EOS evaluation at pseudo-enthalpy ``h_query``.
171
+
172
+ The *structure* sector uses a cubic-Hermite interpolation of p(h) whose node
173
+ slopes are set to the EXACT thermodynamic value dp/dh = eps + p. Hence, by
174
+ construction:
175
+
176
+ * dp/dh = eps + p exactly at the nodes and smoothly (C^1) between them, so the
177
+ enthalpy-formulation TOV equations are evaluated consistently;
178
+ * eps(h) = dp/dh - p is *derived*, not independently interpolated.
179
+
180
+ The returned cs^2 is interpolated linearly in h from the node values
181
+ ``cs2_nodes`` (clipped to [1e-10, 1]); it is left free to be NON-MONOTONE and
182
+ is never monotonized. It is NOT the derivative of the eps(h) above, and since
183
+ 2026-10-14 the TOV tidal term no longer uses it: across a steep cell its
184
+ integral misses part of the cell's Delta eps. The tidal term takes deps/dh
185
+ from the same Hermite cell instead (:func:`hermite_eos_tidal_at_h`); this
186
+ cs^2 remains for diagnostics (e.g. the central cs^2 of ``tov.central``).
187
+
188
+ This uses h (equivalently the baryon chemical potential mu = mu0 e^h) as the
189
+ parameter, which is the natural variable for realistic tabulated EOS. Fully
190
+ JAX-differentiable; the integer interval index is piecewise-constant (standard
191
+ for interpolation) while gradients flow through the gathered node values.
192
+ ``xp=numpy`` evaluates in NumPy (no JAX compile for new array shapes).
193
+ """
194
+ eps, p = _hermite_cell(h_nodes, p_nodes, eps_nodes, h_query, xp)
195
+ cs2 = xp.clip(xp.interp(h_query, xp.asarray(h_nodes), cs2_nodes), 1e-10, 1.0)
196
+ eps, p = _floor_eps_p(eps, p, xp)
197
+ return eps, p, cs2
198
+
199
+
200
+ def hermite_eos_tidal_at_h(h_nodes, p_nodes, eps_nodes, h_query, xp=jnp):
201
+ """(eps, p, tidal term) at ``h_query``; eps and p are those of
202
+ :func:`hermite_eos_at_h`, bit for bit.
203
+
204
+ The tidal term is (eps + p)/cs^2 = (eps + p) deps/dp, which equals deps/dh
205
+ exactly because dp/dh = eps + p holds in the interpolant. It is taken as the
206
+ analytic deps/dh = d^2p/dh^2 - dp/dh of the cell's own eps(h) = dp/dh - p,
207
+ so across every cell the tidal source integrates to the Delta eps that the
208
+ structure equations see, however steep the cell
209
+ (docs/devlog/2026-10-14-tidal-cs2.md). The node cs^2 interpolated linearly
210
+ in h does not: across a stiff joint it leaves a "phantom" energy jump in y
211
+ and biases Lambda low. deps/dh is quadratic in h within a cell and jumps
212
+ at the nodes (the Hermite is C^1); the adaptive TOV solve stops at the nodes
213
+ (``jump_ts``).
214
+
215
+ Two guards (:func:`_tidal_term`):
216
+
217
+ * Jump cells -- a density jump at (nearly) fixed pressure: width <= 1e3 ulp
218
+ in h, or chord dp/deps <= 1e-8 at any width (exact or nudged plateaus)
219
+ -- carry no tidal term inside; their cubic's deps/dh is noise there or beyond the
220
+ clip. Their Delta eps = eps_in - eps_out > 0 is moved instead, as a
221
+ bubble (q+1) t^q Delta eps / dh (q = 32), into the regular cell just
222
+ below (outward). That is the junction condition
223
+ y_out = y_in - 4 pi r^3 Delta eps / (m + 4 pi r^3 p) (y falls outward),
224
+ smeared over the top ~3% of that cell.
225
+ * Elsewhere deps/dh is capped at 1e10 (eps + p), i.e. 1/cs^2 <= 1e10; the
226
+ chord test keeps every cell that could reach the cap a jump cell. It is
227
+ NOT floored at 0 (since 2026-10-14, PR #44 review 3, R2): a regular cell
228
+ whose cubic eps(h) dips (negative deps/dh near the outer end of a soft
229
+ cell spanning a large eps ratio) then still integrates to exactly its
230
+ Delta eps; a zero floor over-counted it (x(1 + 7.6e-2) at Delta eps = 3000
231
+ MeV/fm^3). With ``h_rule="trapezoid"`` the packaged SLy crust has such
232
+ dips (deps/dh down to -1.4e5 (eps + p)); that rule is not valid with the
233
+ tidal term."""
234
+ h_nodes = xp.asarray(h_nodes)
235
+ N = h_nodes.shape[0]
236
+ i = xp.clip(xp.searchsorted(h_nodes, h_query), 1, N - 1)
237
+ h0 = h_nodes[i - 1]
238
+ dh = h_nodes[i] - h0
239
+ t = (h_query - h0) / dh
240
+ eps, p, deps_dh = _hermite_cell_t(i, t, dh, p_nodes, eps_nodes, deps=True)
241
+ eps, p = _floor_eps_p(eps, p, xp)
242
+ deg, extra = _degenerate_cells(h_nodes, eps_nodes, p_nodes, xp)
243
+ return eps, p, _tidal_term(i, t, dh, deps_dh, eps, p, deg, extra, xp)
244
+
245
+
246
+ def _clip_tidal(deps_dh, eps, p, xp):
247
+ """deps/dh capped at 1e10 (eps + p) (with where; see _floor_eps_p). No
248
+ floor: a regular cell then integrates to exactly its Delta eps."""
249
+ hi = 1e10 * (eps + p)
250
+ return xp.where(deps_dh < hi, deps_dh, hi)
251
+
252
+
253
+ #: a cell no wider than this many ulp of h is a jump cell
254
+ _DEGENERATE_ULP = 1e3
255
+ #: ... and so is any cell whose chord dp/deps is below this (a density jump at
256
+ #: (nearly) fixed p, whatever its width; well inside the 1e10 (eps+p) clip)
257
+ _JUMP_CS2 = 1e-8
258
+ #: the junction bubble in the cell below a jump is (q+1) t^q Delta eps / dh
259
+ _BUBBLE_Q = 32
260
+
261
+
262
+ def _degenerate_cells(h, eps, p, xp):
263
+ """Per cell i (nodes i-1, i; index 0 unused): ``deg`` -- a jump cell: a
264
+ density jump at fixed pressure, by width (<= 1e3 ulp of h) or by chord
265
+ (dp <= 1e-8 deps, independent of width, so that no cell can sit between this
266
+ test and the 1e10 (eps+p) clip); ``extra`` -- for a regular cell, the
267
+ Delta eps (= eps_in - eps_out > 0) of the run of jump cells directly above
268
+ it, which its tidal term carries (:func:`_tidal_term`). Gradient-free mask,
269
+ differentiable ``extra``."""
270
+ h, eps, p = xp.asarray(h), xp.asarray(eps), xp.asarray(p)
271
+ n = h.shape[0]
272
+ dh = h[1:] - h[:-1]
273
+ de = eps[1:] - eps[:-1]
274
+ scale = xp.maximum(xp.abs(h[1:]), xp.abs(h[:-1]))
275
+ deg = ((dh <= _DEGENERATE_ULP * np.finfo(np.float64).eps * scale)
276
+ | ((de > 0) & (p[1:] - p[:-1] <= _JUMP_CS2 * de)))
277
+ a = xp.where(deg, de, 0.0)
278
+ idx = xp.arange(n - 1)
279
+ nr = xp.where(deg, n - 1, idx) # regular cells: own index
280
+ # index of the first regular cell above cell k (n - 1 if none): reverse
281
+ # running minimum of nr over the cells strictly above
282
+ if xp is np:
283
+ above = np.minimum.accumulate(nr[::-1])[::-1]
284
+ else:
285
+ above = jax.lax.cummin(nr, reverse=True)
286
+ above = xp.concatenate([above[1:], xp.full((1,), n - 1)])
287
+ c = xp.concatenate([xp.zeros((1,)), xp.cumsum(a)]) # c[k] = sum a[:k]
288
+ extra = xp.where(deg, 0.0, c[above] - c[idx + 1])
289
+ pad = lambda v, z: xp.concatenate([z, v])
290
+ return (pad(deg, xp.zeros((1,), dtype=bool)), pad(extra, xp.zeros((1,))))
291
+
292
+
293
+ def _tidal_term(i, t, dh, deps_dh, eps, p, deg, extra, xp):
294
+ """The tidal term in cell ``i`` at local ``t``: 0 in a jump cell, else the
295
+ clipped deps/dh plus the junction bubble (q+1) t^q Delta eps / dh carrying
296
+ the Delta eps of the jump run above (:func:`_degenerate_cells`). The
297
+ bubble sits within ~dh/(q+2) of the jump, so the smearing error of the
298
+ junction is that fraction of the cell below (it was dh/2 with 6t(1-t))."""
299
+ d = _clip_tidal(deps_dh, eps, p, xp)
300
+ dh_safe = xp.where(deg[i], 1.0, dh)
301
+ d = d + extra[i] * (_BUBBLE_Q + 1.0) * t ** _BUBBLE_Q / dh_safe
302
+ return xp.where(deg[i], 0.0, d)
303
+
304
+
305
+ def _h_steps_loglinear(eps, p, xp, n_gl=12):
306
+ """Per-cell pseudo-enthalpy steps: int dp/(eps + p) along the log-linear
307
+ (piecewise-polytrope) eps(p) between the two nodes, by Gauss-Legendre.
308
+ Cells with a non-positive eps or p fall back to the trapezoid."""
309
+ x, w = np.polynomial.legendre.leggauss(n_gl)
310
+ s, w = 0.5 * (x + 1.0), 0.5 * w
311
+ ok = (p[1:] > 0) & (p[:-1] > 0) & (eps[1:] > 0) & (eps[:-1] > 0)
312
+ one = xp.ones_like(p[1:])
313
+ lp = xp.log(xp.where(ok, p[1:], one) / xp.where(ok, p[:-1], one))
314
+ le = xp.log(xp.where(ok, eps[1:], one) / xp.where(ok, eps[:-1], one))
315
+ p0 = xp.where(ok, p[:-1], one)[:, None]
316
+ e0 = xp.where(ok, eps[:-1], one)[:, None]
317
+ ps = p0 * xp.exp(s[None, :] * lp[:, None])
318
+ es = e0 * xp.exp(s[None, :] * le[:, None])
319
+ gl = (w[None, :] * ps / (es + ps)).sum(axis=1) * lp # dp = p lp ds
320
+ integrand = 1.0 / (eps + p)
321
+ trap = 0.5 * (integrand[1:] + integrand[:-1]) * xp.diff(p)
322
+ return xp.where(ok, gl, trap)
323
+
324
+
325
+ def build_h_and_cs2(n, eps_mevfm3, p_mevfm3, h_base=None, xp=jnp, *,
326
+ h_rule="loglinear"):
327
+ """Given (n, eps, p) build the geometric ``EOSTable`` with h and cs2.
328
+
329
+ Parameters in MeV/fm^3 (eps, p) and fm^-3 (n). Pseudo-enthalpy steps are
330
+ dh = int dp/(eps+p) per cell in geometric units: with ``h_rule="loglinear"``
331
+ (default since 2026-10-14) along the log-linear eps(p) between the nodes
332
+ (12-point Gauss-Legendre); with ``"trapezoid"`` by the trapezoid rule (the
333
+ rule before 2026-10-14; it reproduces the old node h only, not the old
334
+ Lambda, and is not valid with the tidal term -- see docs/physics.rst). The
335
+ Hermite p(h) of :func:`hermite_eos_at_h` takes
336
+ its node slopes from dp/dh = eps + p and its cell widths from these steps;
337
+ the trapezoid width is inconsistent with those slopes by O((Delta ln eps)^2)
338
+ per cell, which made the Hermite eps(h) overshoot between coarse crust nodes
339
+ (R1.4 off by +4 m on the MetaModel and GM1 tables, +41 m on a 250-node SLy
340
+ table, at any core resolution; docs/devlog/2026-10-14-tidal-cs2.md). cs2 by
341
+ finite difference dp/deps on the grid. All JAX-differentiable.
342
+
343
+ ``h_base`` : if given, the pseudo-enthalpy at the lowest grid point is set to
344
+ this value instead of the small self-consistent offset. Used to continue the
345
+ enthalpy of an inner (e.g. quark) segment above a phase-transition enthalpy.
346
+
347
+ ``xp=numpy`` returns NumPy arrays, for inputs whose length varies from call
348
+ to call (every new length would compile each JAX op); see
349
+ :func:`refine_table`.
350
+ """
351
+ # force jnp so every EOSTable is uniform (numpy inputs -- hybrid combined table,
352
+ # ingested CompOSE/CMF tables -- otherwise break the jit-traced Hermite at_h)
353
+ n = xp.asarray(n)
354
+ eps_mevfm3 = xp.asarray(eps_mevfm3)
355
+ p_mevfm3 = xp.asarray(p_mevfm3)
356
+ eps = eps_mevfm3 * MEVFM3_TO_GEOM # km^-2
357
+ p = p_mevfm3 * MEVFM3_TO_GEOM # km^-2
358
+
359
+ # sound speed squared dp/deps via central-ish differences (log grid safe)
360
+ cs2 = xp.gradient(p) / xp.gradient(eps)
361
+ cs2 = xp.clip(cs2, 1e-8, 1.0)
362
+
363
+ # pseudo-enthalpy: dh = dp/(eps+p). Integrate from the lowest grid point.
364
+ if h_rule == "loglinear":
365
+ seg = _h_steps_loglinear(eps, p, xp)
366
+ elif h_rule == "trapezoid":
367
+ integrand = 1.0 / (eps + p)
368
+ seg = 0.5 * (integrand[1:] + integrand[:-1]) * xp.diff(p)
369
+ else:
370
+ raise ValueError(f"unknown h_rule {h_rule!r}")
371
+ h_rel = xp.concatenate([xp.zeros((1,)), xp.cumsum(seg)])
372
+ h0 = (p[0] / (eps[0] + p[0])) if h_base is None else h_base
373
+ h = h_rel + h0
374
+
375
+ return EOSTable(
376
+ n=n, eps=eps, p=p, h=h, cs2=cs2,
377
+ eps_mevfm3=eps_mevfm3, p_mevfm3=p_mevfm3,
378
+ )
379
+
380
+
381
+ def refine_table(table, n_out):
382
+ """``table`` with nodes added up to ``n_out`` in total, so that tables whose
383
+ node count varies from draw to draw have one length (and the TOV family
384
+ compiles once, not once per length). All original nodes are kept; each
385
+ added node splits the interval of largest remaining h-width and takes
386
+ (eps, p) from the table's own Hermite p(h) and cs2 from its linear
387
+ interpolant, so :meth:`EOSTable.at_h` is unchanged up to roundoff. n is
388
+ log-linear in h. Works in NumPy (pass a table from
389
+ ``build_h_and_cs2(..., xp=numpy)`` to avoid JAX ops on the variable
390
+ length) and returns JAX arrays; a table with ``n_out`` or more nodes only
391
+ changes array type (with a RuntimeWarning if more)."""
392
+ t = EOSTable(*(np.asarray(a) for a in table))
393
+ m = n_out - t.h.size
394
+ if m < 0:
395
+ warnings.warn(f"refine_table: {t.h.size} nodes > n_out={n_out}; the "
396
+ "table keeps its own length (one compile per length)",
397
+ RuntimeWarning, stacklevel=2)
398
+ if m > 0:
399
+ dh = np.diff(t.h)
400
+ c = np.zeros(dh.size, int) # added nodes per interval
401
+ for _ in range(m):
402
+ c[np.argmax(dh / (c + 1))] += 1
403
+ h_new = np.concatenate([t.h[i] + dh[i] * np.arange(1, c[i] + 1) / (c[i] + 1)
404
+ for i in np.flatnonzero(c)])
405
+ order = np.argsort(np.concatenate([t.h, h_new]), kind="stable")
406
+ eps_a, p_a, cs2_a = hermite_eos_at_h(t.h, t.p, t.eps, t.cs2, h_new, xp=np)
407
+ n_a = np.exp(np.interp(h_new, t.h, np.log(t.n)))
408
+ cat = lambda a, b: np.concatenate([a, b])[order]
409
+ eps, p = cat(t.eps, eps_a), cat(t.p, p_a)
410
+ t = EOSTable(n=cat(t.n, n_a), eps=eps, p=p, h=cat(t.h, h_new),
411
+ cs2=cat(t.cs2, cs2_a), eps_mevfm3=eps / MEVFM3_TO_GEOM,
412
+ p_mevfm3=p / MEVFM3_TO_GEOM)
413
+ return EOSTable(*(jnp.asarray(a) for a in t))
414
+
415
+
416
+ def extend_to_surface(n, eps_mevfm3, p_mevfm3, n_surface=1e-7, gamma_crust=1.3,
417
+ n_pts=120):
418
+ """Prepend a thermodynamically consistent low-density tail down to ``n_surface``.
419
+
420
+ The TOV radius depends on integrating the star out to (near) zero pressure. A
421
+ table that stops at, e.g., n_min ~ 3e-4 fm^-3 (just below neutron drip)
422
+ truncates the outer crust/atmosphere and **underestimates R by ~100 m** -- a
423
+ surface *convention* mismatch with reference solvers (RePrimAnd) that integrate
424
+ closer to p -> 0. Here we continue the EOS below its base point as a single
425
+ polytrope p = p0 (n/n0)^gamma_crust, with the energy density fixed by the cold
426
+ first law deps/dn = (eps+p)/n, whose closed-form solution::
427
+
428
+ eps(n) = A n + p/(gamma_crust - 1), A = (eps0 - p0/(gamma_crust-1))/n0
429
+
430
+ is continuous at the base point n0.
431
+
432
+ This is a *surface continuation*, NOT a physical crust (no composition / pasta);
433
+ ``gamma_crust`` and ``n_surface`` are the documented systematic knobs. All
434
+ JAX-differentiable (the tail tracks the base point, which depends on EOS params).
435
+ """
436
+ n = jnp.asarray(n)
437
+ eps = jnp.asarray(eps_mevfm3)
438
+ p = jnp.asarray(p_mevfm3)
439
+ n0, e0, p0 = n[0], eps[0], p[0]
440
+ A = (e0 - p0 / (gamma_crust - 1.0)) / n0
441
+ n_lo = jnp.exp(jnp.linspace(math.log(n_surface), jnp.log(n0), n_pts))[:-1]
442
+ p_lo = p0 * (n_lo / n0) ** gamma_crust
443
+ e_lo = A * n_lo + p_lo / (gamma_crust - 1.0)
444
+ return (jnp.concatenate([n_lo, n]),
445
+ jnp.concatenate([e_lo, eps]),
446
+ jnp.concatenate([p_lo, p]))
447
+
448
+
449
+ class EOSModel:
450
+ """Abstract base for parameterized EOS models.
451
+
452
+ Subclasses implement :meth:`eos_table` returning an :class:`EOSTable` for a
453
+ given parameter dictionary. Keeping the parameter -> table map pure and
454
+ JAX-traceable is what makes the whole pipeline differentiable.
455
+ """
456
+
457
+ #: human-readable model name
458
+ name: str = "EOSModel"
459
+
460
+ def eos_table(self, params: dict) -> EOSTable: # pragma: no cover - abstract
461
+ raise NotImplementedError
462
+
463
+ def __call__(self, params: dict) -> EOSTable:
464
+ return self.eos_table(params)
465
+
466
+ def _config(self):
467
+ """Hashable snapshot of the instance attributes (arrays as tuples); the
468
+ key of the table cached by :func:`compiled_table`."""
469
+ def key(v):
470
+ if hasattr(v, "shape"):
471
+ return tuple(np.asarray(v).ravel().tolist())
472
+ try:
473
+ hash(v)
474
+ return v
475
+ except TypeError:
476
+ return (type(v).__name__, repr(v))
477
+ return tuple(sorted((k, key(v)) for k, v in vars(self).items()))
478
+
479
+
480
+ class _ByConfig:
481
+ """Static jit argument standing for a model: equal for models of one type
482
+ and ``_config()``, so all such instances share one compiled table."""
483
+ __slots__ = ("model", "key")
484
+
485
+ def __init__(self, model):
486
+ self.model, self.key = model, (type(model), model._config())
487
+
488
+ def __hash__(self):
489
+ return hash(self.key)
490
+
491
+ def __eq__(self, other):
492
+ return isinstance(other, _ByConfig) and self.key == other.key
493
+
494
+
495
+ @functools.partial(jax.jit, static_argnums=(0, 1))
496
+ def _method_jit(handle, name, *args):
497
+ return getattr(handle.model, name)(*args)
498
+
499
+
500
+ def _floats(a):
501
+ """Numeric params as float arrays (one trace for int, float and array
502
+ inputs); str and None entries (labels) are dropped, as no model reads
503
+ them. Non-dict arguments pass through."""
504
+ if not isinstance(a, dict):
505
+ return a
506
+ return {k: jnp.asarray(v, float) for k, v in a.items()
507
+ if not (v is None or isinstance(v, (str, bytes)))}
508
+
509
+
510
+ def compiled_method(model, name, *args):
511
+ """``getattr(model, name)(*args)`` compiled once per model type,
512
+ ``_config()``, method and argument structure (dict arguments become float
513
+ arrays). Eager fori_loop bisections recompile on every call (the loop
514
+ body is a new closure each time), and each executable holds ~100 memory
515
+ maps."""
516
+ return _method_jit(_ByConfig(model), name, *(_floats(a) for a in args))
517
+
518
+
519
+ def compiled_table(model, p):
520
+ """``model._table_flags(p)`` through :func:`compiled_method`, then the eager
521
+ rejection of :func:`eos.crust.raise_rejected`."""
522
+ from .crust import raise_rejected
523
+ return raise_rejected(*compiled_method(model, "_table_flags", p))