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
@@ -0,0 +1,352 @@
1
+ """Standard Skyrme energy density functional for uniform npe-mu matter.
2
+
3
+ Homogeneous nuclear matter depends on the Skyrme parameters only through
4
+ seven combinations. With tau_q = (3/5)(3 pi^2)^(2/3) n_q^(5/3) and
5
+ tau = tau_n + tau_p (Chabanat et al., NPA 627, 710 (1997))::
6
+
7
+ H = h2m tau + a0 n^2 + b0 (n_n^2 + n_p^2)
8
+ + [a3 n^2 + b3 (n_n^2 + n_p^2)] n^sigma
9
+ + c1 n tau + c2 (n_n tau_n + n_p tau_p)
10
+
11
+ a0 = t0 (1 + x0/2) / 2 b0 = -t0 (x0 + 1/2) / 2
12
+ a3 = t3 (1 + x3/2) / 12 b3 = -t3 (x3 + 1/2) / 12
13
+ c1 = [t1 (2 + x1) + t2 (2 + x2)] / 8
14
+ c2 = [t2 (2 x2 + 1) - t1 (2 x1 + 1)] / 8
15
+
16
+ H is in MeV/fm^3 without rest mass; h2m = hbar^2 / 2m. Chemical potentials
17
+ are mu_q = M_q + dH/dn_q (autodiff), p = sum_q mu_q n_q - eps.
18
+ beta equilibrium uses npe-mu leptons (:func:`nmbackend.eos.leptons.lepton_sector`).
19
+
20
+ ``skyrme_from_saturation`` inverts (n0, E0, K, m*_s, m*_v, J, L) to the seven
21
+ combinations in closed form. The effective masses are
22
+ h2m / m*_s = h2m + (c1 + c2/2) n (symmetric matter) and
23
+ h2m / m*_v = h2m + c1 n (a proton in neutron matter), in units of m.
24
+
25
+ Extended Skyrme (BSk form; Chamel, Goriely & Pearson, PRC 80, 065804 (2009);
26
+ BSkG3, Grams et al., arXiv:2307.14276, Eq. 8) adds t4 and t5 terms, which in
27
+ uniform matter act as density-dependent t1 and t2:
28
+ c1 -> c1 + c1b n^beta + c1g n^gamma, and likewise c2. The effective masses
29
+ then depend on density beyond the 1/n form, which frees S(n) above
30
+ saturation (K_sym is no longer fixed by J, L, m*). All four extended
31
+ coefficients default to zero (standard Skyrme).
32
+
33
+ The Skyrme form is non-relativistic. At high density it can become acausal
34
+ (cs2 > 1) and the neutron effective mass can turn negative; the table does
35
+ not correct either, and the caller decides what to do (see ``diagnostics``).
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import math
40
+
41
+ import jax
42
+ import jax.numpy as jnp
43
+ import numpy as np
44
+
45
+ from ..constants import HBARC, M_N, M_P
46
+ from .base import (EOSModel, Composition, compiled_method, compiled_table,
47
+ _floats)
48
+ from .leptons import lepton_sector
49
+ from .crust import (N_T_DEFAULT, check_crust, core_grid, finish_table_flags,
50
+ monotone_core)
51
+
52
+ jax.config.update("jax_enable_x64", True)
53
+
54
+ _PI2 = math.pi ** 2
55
+ _CTAU = 0.6 * (3.0 * _PI2) ** (2.0 / 3.0)
56
+
57
+
58
+ def skyrme_from_t(t0, t1, t2, t3, x0, x1, x2, x3, sigma, h2m=20.73553):
59
+ """Uniform-matter combinations from standard Skyrme parameters."""
60
+ return dict(h2m=h2m, sigma=sigma,
61
+ a0=0.5 * t0 * (1.0 + 0.5 * x0), b0=-0.5 * t0 * (x0 + 0.5),
62
+ a3=t3 * (1.0 + 0.5 * x3) / 12.0, b3=-t3 * (x3 + 0.5) / 12.0,
63
+ c1=(t1 * (2.0 + x1) + t2 * (2.0 + x2)) / 8.0,
64
+ c2=(t2 * (2.0 * x2 + 1.0) - t1 * (2.0 * x1 + 1.0)) / 8.0)
65
+
66
+
67
+ #: SLy4: Chabanat, Bonche, Haensel, Meyer & Schaeffer, NPA 635, 231 (1998).
68
+ SLY4 = skyrme_from_t(t0=-2488.91, t1=486.82, t2=-546.39, t3=13777.0,
69
+ x0=0.834, x1=-0.344, x2=-1.0, x3=1.354, sigma=1.0 / 6.0)
70
+
71
+ #: Extended-Skyrme coefficients (zero: standard Skyrme).
72
+ EXT_ZERO = dict(c1b=0.0, c2b=0.0, c1g=0.0, c2g=0.0, beta=1.0 / 12.0,
73
+ gamma=0.25)
74
+
75
+
76
+ def skyrme_from_t_ext(t0, t1, t2, t3, t4, t5, x0, x1, x2t2, x3, x4, x5,
77
+ sigma, beta, gamma, h2m=20.73553):
78
+ """Uniform-matter combinations of the extended (BSk) Skyrme form.
79
+
80
+ t4 enters like t1 times n^beta, t5 like t2 times n^gamma. As in the BSk
81
+ tables, x2 is given through the product x2 t2."""
82
+ p = skyrme_from_t(t0, t1, 0.0, t3, x0, x1, 0.0, x3, sigma, h2m)
83
+ p["c1"] += (2.0 * t2 + x2t2) / 8.0
84
+ p["c2"] += (t2 + 2.0 * x2t2) / 8.0
85
+ p.update(c1b=t4 * (2.0 + x4) / 8.0, c2b=-t4 * (2.0 * x4 + 1.0) / 8.0,
86
+ c1g=t5 * (2.0 + x5) / 8.0, c2g=t5 * (2.0 * x5 + 1.0) / 8.0,
87
+ beta=beta, gamma=gamma)
88
+ return p
89
+
90
+
91
+ #: BSkG3: Grams, Ryssens, Scamps, Goriely & Chamel, arXiv:2307.14276,
92
+ #: Table 1 (single h2m; the paper uses separate n and p masses).
93
+ BSKG3 = skyrme_from_t_ext(t0=-2325.35, t1=749.82, t2=0.01, t3=14083.45,
94
+ t4=-498.01, t5=266.52, x0=0.558834, x1=2.940880,
95
+ x2t2=-432.256954, x3=0.628699, x4=5.657990,
96
+ x5=0.396933, sigma=0.2, beta=1.0 / 12.0, gamma=0.25)
97
+
98
+ DEFAULT_PARAMS = dict(SLY4, **EXT_ZERO)
99
+
100
+
101
+ def _c12(n, p):
102
+ """Density-dependent (c1, c2) of the extended form."""
103
+ if "c1b" not in p: # standard-Skyrme dict
104
+ return p["c1"], p["c2"]
105
+ nb, ng = n ** p["beta"], n ** p["gamma"]
106
+ return (p["c1"] + p["c1b"] * nb + p["c1g"] * ng,
107
+ p["c2"] + p["c2b"] * nb + p["c2g"] * ng)
108
+
109
+
110
+ def _H(n_n, n_p, p):
111
+ """Nuclear energy density without rest mass (MeV/fm^3)."""
112
+ n = n_n + n_p
113
+ tn = _CTAU * jnp.maximum(n_n, 0.0) ** (5.0 / 3.0)
114
+ tp = _CTAU * jnp.maximum(n_p, 0.0) ** (5.0 / 3.0)
115
+ s2 = n_n**2 + n_p**2
116
+ c1, c2 = _c12(n, p)
117
+ return (p["h2m"] * (tn + tp) + p["a0"] * n**2 + p["b0"] * s2
118
+ + (p["a3"] * n**2 + p["b3"] * s2) * n ** p["sigma"]
119
+ + c1 * n * (tn + tp) + c2 * (n_n * tn + n_p * tp))
120
+
121
+
122
+ def _nucleon(n_n, n_p, p):
123
+ """eps (MeV/fm^3, with rest mass), mu_n, mu_p (MeV)."""
124
+ H = _H(n_n, n_p, p)
125
+ dHn = jax.grad(lambda a, b: jnp.sum(_H(a, b, p)), 0)(n_n, n_p)
126
+ dHp = jax.grad(lambda a, b: jnp.sum(_H(a, b, p)), 1)(n_n, n_p)
127
+ return H + n_n * M_N + n_p * M_P, dHn + M_N, dHp + M_P
128
+
129
+
130
+ def _solve_xp(n_B, p, n_iter=60):
131
+ """beta-equilibrium proton fraction (npe-mu): mu_n - mu_p = mu_e."""
132
+ def g(x_p):
133
+ _, mu_n, mu_p = _nucleon((1.0 - x_p) * n_B, x_p * n_B, p)
134
+ return (mu_n - mu_p) - HBARC * lepton_sector(x_p * n_B, muons=True)[0]
135
+
136
+ lo = jnp.full_like(n_B, 1e-6)
137
+ hi = jnp.full_like(n_B, 0.5)
138
+
139
+ def body(_, c):
140
+ lo, hi = c
141
+ mid = 0.5 * (lo + hi)
142
+ gm = g(mid)
143
+ return jnp.where(gm > 0.0, mid, lo), jnp.where(gm > 0.0, hi, mid)
144
+
145
+ lo, hi = jax.lax.fori_loop(0, n_iter, body, (lo, hi))
146
+ x0 = jax.lax.stop_gradient(0.5 * (lo + hi))
147
+ dg = jax.grad(lambda x: jnp.sum(g(x)))(x0)
148
+ return x0 - g(x0) / dg
149
+
150
+
151
+ _solve_xp_jit = jax.jit(_solve_xp, static_argnames="n_iter")
152
+
153
+
154
+ def _eps_p(n_B, x_p, p):
155
+ n_p, n_n = x_p * n_B, (1.0 - x_p) * n_B
156
+ eps, mu_n, mu_p = _nucleon(n_n, n_p, p)
157
+ mu_e, n_e, n_mu, eps_l = lepton_sector(n_p, muons=True)
158
+ pres = mu_n * n_n + mu_p * n_p - eps + HBARC * (mu_e * (n_e + n_mu) - eps_l)
159
+ return eps + HBARC * eps_l, pres
160
+
161
+
162
+ def symmetric_matter(n, params=None):
163
+ """E/A (MeV, no rest mass), p (MeV/fm^3), S(n) (MeV, curvature) for
164
+ symmetric matter on ``n`` (fm^-3)."""
165
+ p = dict(DEFAULT_PARAMS)
166
+ if params:
167
+ p.update(params)
168
+ n = jnp.asarray(n, float)
169
+ ea = lambda nn, d: _H(nn * (1 + d) / 2, nn * (1 - d) / 2, p) / nn
170
+ EA = ea(n, 0.0)
171
+ dEA = jax.vmap(jax.grad(ea, 0), (0, None))(n, 0.0)
172
+ S = 0.5 * jax.vmap(jax.grad(jax.grad(ea, 1), 1), (0, None))(n, 0.0)
173
+ return dict(EA=EA, p=n**2 * dEA, S=S)
174
+
175
+
176
+ def saturation_properties(params=None, n_lo=0.10, n_hi=0.22, npts=2401):
177
+ """n0, B/A, K, E_sym (= J), L, K_sym, m*_s/m, m*_v/m of a Skyrme set."""
178
+ p = dict(DEFAULT_PARAMS)
179
+ if params:
180
+ p.update(params)
181
+ ns = np.linspace(n_lo, n_hi, npts)
182
+ s = {k: np.asarray(v) for k, v in symmetric_matter(ns, p).items()}
183
+ i = int(np.argmin(s["EA"]))
184
+ dn = ns[1] - ns[0]
185
+ e0, e1, e2 = s["EA"][i - 1:i + 2]
186
+ n0 = ns[i] + 0.5 * dn * (e0 - e2) / (e0 - 2 * e1 + e2)
187
+ q = lambda a: float(np.interp(n0, ns, a))
188
+ d = lambda a: np.gradient(a, dn)
189
+ ms, mv = effective_masses(p, n0)
190
+ return dict(n0=float(n0), BA=q(s["EA"]), K=9.0 * q(d(s["p"])),
191
+ E_sym=q(s["S"]), L=3.0 * n0 * q(d(s["S"])),
192
+ K_sym=9.0 * n0**2 * q(d(d(s["S"]))),
193
+ ms_frac=float(ms), mv_frac=float(mv))
194
+
195
+
196
+ def effective_masses(params, n):
197
+ """(m*_s/m, m*_v/m) at density n (symmetric matter)."""
198
+ p = dict(DEFAULT_PARAMS)
199
+ p.update(params)
200
+ c1, c2 = _c12(np.asarray(n, float), p)
201
+ return (p["h2m"] / (p["h2m"] + (c1 + 0.5 * c2) * n),
202
+ p["h2m"] / (p["h2m"] + c1 * n))
203
+
204
+
205
+ def skyrme_from_saturation(n0=0.160, BA=-15.97, K=230.0, ms_frac=0.70,
206
+ mv_frac=0.80, J=32.0, L=46.0, h2m=20.73553,
207
+ ms_hi=None, mv_hi=None, n_hi=(2.0, 4.0),
208
+ beta=1.0 / 12.0, gamma=0.25):
209
+ """Uniform-matter Skyrme combinations reproducing a saturation point.
210
+
211
+ With T(n) = (3/5) h2m kF^2 (symmetric) and u(n) = c1 + c2/2,
212
+ E/A = T (1 + u n / h2m) + A n + B n^(sigma+1); E/A(n0) = BA and
213
+ p(n0) = 0 fix A, B for given sigma, and K fixes sigma. The isovector part
214
+ is linear in (b0, b3) given c1(n), c2(n). Raises ValueError if
215
+ sigma <= 0.
216
+
217
+ Standard Skyrme: c1, c2 constant, fixed by m*_s, m*_v at n0. Extended
218
+ Skyrme: pass ``ms_hi`` and ``mv_hi``, the effective masses (units of m) at
219
+ the two densities ``n_hi`` (units of n0); with the n0 values they fix the
220
+ constant, n^beta and n^gamma parts of u(n) and c1(n) (3x3 linear solves).
221
+ """
222
+ kf2 = lambda n: (1.5 * _PI2 * n) ** (2.0 / 3.0)
223
+ T = lambda n: 0.6 * h2m * kf2(n)
224
+ ext = dict(EXT_ZERO, beta=beta, gamma=gamma)
225
+ if ms_hi is None:
226
+ u0 = (h2m / ms_frac - h2m) / n0
227
+ v0 = (h2m / mv_frac - h2m) / n0
228
+ else:
229
+ ns = n0 * np.array([1.0, n_hi[0], n_hi[1]])
230
+ Mx = np.stack([np.ones(3), ns**beta, ns**gamma], axis=1)
231
+ ru = (h2m / np.array([ms_frac, ms_hi[0], ms_hi[1]]) - h2m) / ns
232
+ rv = (h2m / np.array([mv_frac, mv_hi[0], mv_hi[1]]) - h2m) / ns
233
+ u0, ub, ug = np.linalg.solve(Mx, ru)
234
+ v0, vb, vg = np.linalg.solve(Mx, rv)
235
+ ext.update(c1b=vb, c2b=2.0 * (ub - vb), c1g=vg, c2g=2.0 * (ug - vg))
236
+ c1, c2 = v0, 2.0 * (u0 - v0)
237
+ pc = dict(ext, c1=c1, c2=c2)
238
+
239
+ def kin(n): # kinetic E/A in symmetric matter
240
+ a, b = _c12(n, pc)
241
+ return T(n) * (1.0 + (a + 0.5 * b) * n / h2m)
242
+
243
+ def skin(n): # kinetic S(n)
244
+ a, b = _c12(n, pc)
245
+ return (5.0 / 9.0) * T(n) * (1.0 + (a + 2.0 * b) * n / h2m)
246
+
247
+ h = 1e-3 * n0
248
+ d1 = lambda f: (f(n0 + h) - f(n0 - h)) / (2.0 * h)
249
+ d2 = lambda f: (f(n0 + h) - 2.0 * f(n0) + f(n0 - h)) / h**2
250
+ Tk = kin(n0)
251
+ Q = n0 * d1(kin) + BA - Tk
252
+ KT = 9.0 * n0**2 * d2(kin)
253
+ sigma = (KT - K) / (9.0 * Q) - 1.0
254
+ if not sigma > 0.0:
255
+ raise ValueError(f"no Skyrme sigma > 0 for K={K} (sigma={sigma:.3f})")
256
+ B = -Q / (sigma * n0 ** (sigma + 1.0))
257
+ A = (BA - Tk - B * n0 ** (sigma + 1.0)) / n0
258
+ # isovector: S = S_kin(n) + b0 n/2 + b3 n^(s+1)/2
259
+ Sk, dSk = skin(n0), d1(skin)
260
+ y = n0 ** (sigma + 1.0) / 2.0
261
+ b3 = (L / 3.0 - n0 * dSk - J + Sk) / (sigma * y)
262
+ b0 = 2.0 * (J - Sk - b3 * y) / n0
263
+ out = dict(h2m=h2m, sigma=float(sigma), a0=A - 0.5 * b0, b0=b0,
264
+ a3=B - 0.5 * b3, b3=b3, c1=c1, c2=c2)
265
+ if ms_hi is not None:
266
+ out.update({k: float(v) for k, v in ext.items()})
267
+ return out
268
+
269
+
270
+ def landau_masses(params, n, x_p):
271
+ """(m*_n/m, m*_p/m) in matter of density n and proton fraction x_p.
272
+
273
+ The Skyrme single-particle energy is quadratic in k, so the Landau mass
274
+ at the Fermi surface is h2m / m*_q = h2m + c1(n) n + c2(n) n_q. In units
275
+ of the h2m mass (one mass for n and p)."""
276
+ p = dict(DEFAULT_PARAMS)
277
+ p.update(params or {})
278
+ n = jnp.asarray(n, float)
279
+ x_p = jnp.asarray(x_p, float)
280
+ c1, c2 = _c12(n, p)
281
+ em = lambda nq: p["h2m"] / (p["h2m"] + c1 * n + c2 * nq)
282
+ return em((1.0 - x_p) * n), em(x_p * n)
283
+
284
+
285
+ def diagnostics(params, n):
286
+ """Per-density checks on beta-equilibrium matter: minimum of
287
+ h2m/m*_q (MeV fm^2; must be > 0) over q = n, p."""
288
+ p = dict(DEFAULT_PARAMS)
289
+ p.update(params)
290
+ n = np.asarray(n, float)
291
+ x = np.asarray(_solve_xp_jit(jnp.asarray(n), _floats(p)))
292
+ c1, c2 = _c12(n, p)
293
+ em = lambda nq: p["h2m"] + c1 * n + c2 * nq
294
+ return np.minimum(em((1 - x) * n), em(x * n))
295
+
296
+
297
+ class SkyrmeEOS(EOSModel):
298
+ """Standard or extended (BSk) Skyrme EDF, npe-mu beta equilibrium."""
299
+
300
+ name = "SkyrmeEOS"
301
+
302
+ def __init__(self, n_min=1e-3, n_max=1.5, n_points=220,
303
+ n_surface=1e-7, gamma_crust=1.3,
304
+ crust="sly", n_t=N_T_DEFAULT,
305
+ allow_unstable_core=False):
306
+ self.n_grid = jnp.exp(jnp.linspace(math.log(n_min), math.log(n_max),
307
+ n_points))
308
+ self.n_surface = n_surface
309
+ self.gamma_crust = gamma_crust
310
+ self.crust = check_crust(crust, n_surface)
311
+ self.n_t = n_t
312
+ self.allow_unstable_core = allow_unstable_core
313
+
314
+ def _table_grid(self):
315
+ """Uniform-matter nodes of the EOS table (above n_t with the SLy crust)."""
316
+ if self.crust == "sly" and self.n_surface is not None:
317
+ return core_grid(self.n_grid, self.n_t)
318
+ return self.n_grid
319
+
320
+ @staticmethod
321
+ def _p(params):
322
+ p = dict(DEFAULT_PARAMS)
323
+ if params:
324
+ p.update(params)
325
+ return p
326
+
327
+ def composition(self, params: dict = None) -> Composition:
328
+ """beta-equilibrium (x_p, x_e, x_mu) on ``self.n_grid``."""
329
+ p = self._p(params)
330
+ return compiled_method(self, "_composition", p)
331
+
332
+ def _composition(self, p):
333
+ n = self.n_grid
334
+ x_p = _solve_xp(n, p)
335
+ _, n_e, n_mu, _ = lepton_sector(x_p * n, muons=True)
336
+ return Composition(n=n, x_p=x_p, x_e=n_e / n, x_mu=n_mu / n)
337
+
338
+ def landau_masses(self, params, comp):
339
+ """(m*_n/m, m*_p/m) on ``comp`` (see :func:`landau_masses`)."""
340
+ return landau_masses(self._p(params), comp.n, comp.x_p)
341
+
342
+ def eos_table(self, params: dict = None):
343
+ return compiled_table(self, self._p(params))
344
+
345
+ def _table_flags(self, p):
346
+ n = self._table_grid()
347
+ x_p = _solve_xp(n, p)
348
+ eps, pres = _eps_p(n, x_p, p)
349
+ pres, ln_nu = monotone_core(n, pres, self.n_t)
350
+ return finish_table_flags(n, eps, pres, self.crust, self.n_t,
351
+ self.n_surface, self.gamma_crust, ln_nu,
352
+ self.allow_unstable_core)
@@ -0,0 +1,13 @@
1
+ """Inference utilities built on the differentiable EOS/TOV core.
2
+
3
+ Currently: forward-mode sensitivity (Jacobian) and Fisher-matrix forecasting of NS
4
+ observables (Lambda(m), R(m), M_max) with respect to EOS parameters -- the first
5
+ consumer of the backend's differentiability.
6
+ """
7
+ from .fisher import (eos_observables, sensitivity_matrix, fisher_matrix,
8
+ fisher_covariance, GRADIENT_RTOL, GRADIENT_ATOL)
9
+ from .synthetic import lambda_tilde, draw_bns_events, SyntheticTidalEvents
10
+
11
+ __all__ = ["eos_observables", "sensitivity_matrix", "fisher_matrix",
12
+ "fisher_covariance", "GRADIENT_RTOL", "GRADIENT_ATOL",
13
+ "lambda_tilde", "draw_bns_events", "SyntheticTidalEvents"]
@@ -0,0 +1,174 @@
1
+ """Forward-mode sensitivities and Fisher-matrix forecasting of NS observables.
2
+
3
+ The whole point of the differentiable backend is that gradients of stellar
4
+ observables with respect to EOS parameters -- dLambda/dtheta, dR/dtheta,
5
+ dM_max/dtheta -- come out by automatic differentiation, reproducing the perturbation
6
+ ("delta-TOV") equations. This module packages those into:
7
+
8
+ * :func:`eos_observables` -- (Lambda(m_i), R(m_j), M_max) for a parameter dict;
9
+ * :func:`sensitivity_matrix`-- the Jacobian J[obs, param] by forward-mode AD;
10
+ * :func:`fisher_matrix` -- F = J^T C^-1 J for a (diagonal) data covariance;
11
+ * :func:`fisher_covariance` -- F^-1, the forecast parameter covariance.
12
+
13
+ Fixed-mass sensitivities via the implicit-function theorem
14
+ ----------------------------------------------------------
15
+ A naive ``d/dtheta`` of an interpolated ``Lambda(m_target)`` over a TOV family is
16
+ inaccurate -- the dominant term is the reparameterization of the central enthalpy as
17
+ the fixed-mass target shifts, and differentiating through the coarse family
18
+ interpolation gets it badly wrong (it can even flip the sign). Instead we use the
19
+ implicit-function theorem on the *single-star* tangents, which are accurate at
20
+ moderate tolerance (see tests/test_ad_gradients.py):
21
+
22
+ h_c*(theta) solves M(h_c*, theta) = m_target
23
+ dh_c*/dtheta = -(dM/dtheta|_hc) / (dM/dh_c)
24
+ dLambda/dtheta|_m = dLambda/dtheta|_hc + (dLambda/dh_c) * dh_c*/dtheta
25
+ dR/dtheta|_m = dR/dtheta|_hc + (dR/dh_c) * dh_c*/dtheta
26
+
27
+ and the *envelope theorem* for the maximum mass (dM/dh_c = 0 at the peak):
28
+
29
+ dM_max/dtheta = dM/dtheta|_{h_c,max}
30
+
31
+ All partials are clean forward-mode single-star derivatives. This resolves the
32
+ "gradient tightening" backlog item for Fisher/forecasting use without needing ever
33
+ tighter ODE tolerances.
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import numpy as np
38
+ import jax
39
+ import jax.numpy as jnp
40
+
41
+ from ..tov import build_family, m_max, lambda_of_mass, radius_of_mass
42
+ from ..tov.family import default_hc_grid
43
+ from ..tov.solver import solve_structure
44
+
45
+ #: default solver tolerances for *gradient* work (single-star tangents).
46
+ #: Deliberately tighter than solve_structure's 1e-7: parameter tangents are
47
+ #: accurate there (~3e-5) but the h_c tangent sits at ~1e-4 (frozen-start
48
+ #: near-centre resolution), ~5e-8 at 1e-10. Do not loosen to 1e-7; see
49
+ #: docs/devlog/2026-10-12-tov-jump-ts.md.
50
+ GRADIENT_RTOL = 1e-10
51
+ GRADIENT_ATOL = 1e-12
52
+
53
+
54
+ def eos_observables(model, params, *, masses_lambda=(1.4,), masses_radius=(1.4,),
55
+ include_mmax=True, hc_grid_n=160, rtol=GRADIENT_RTOL,
56
+ atol=GRADIENT_ATOL):
57
+ """Stack of NS observables for one parameter dict, plus their names.
58
+
59
+ Observables: ``Lambda(m)`` for each ``masses_lambda``, ``R(m)`` for each
60
+ ``masses_radius`` (km), then ``M_max`` (Msun) if ``include_mmax``. Built from a
61
+ single TOV family (so all share one solve), branch-aware on the stable rising
62
+ branch. Fully forward-mode differentiable in ``params``.
63
+ """
64
+ table = model.eos_table(params)
65
+ fam = build_family(table, default_hc_grid(table, n_models=hc_grid_n),
66
+ rtol=rtol, atol=atol)
67
+ vals, names = [], []
68
+ for m in masses_lambda:
69
+ vals.append(lambda_of_mass(fam, m)); names.append(f"Lambda({m})")
70
+ for m in masses_radius:
71
+ vals.append(radius_of_mass(fam, m)); names.append(f"R({m})")
72
+ if include_mmax:
73
+ vals.append(m_max(fam)); names.append("M_max")
74
+ return jnp.stack(vals), names
75
+
76
+
77
+ def _star_MRL(model, params, hc, rtol, atol):
78
+ pt = solve_structure(model.eos_table(params), hc, rtol=rtol, atol=atol)
79
+ return jnp.stack([pt.M_msun, pt.R_km, pt.Lambda])
80
+
81
+
82
+ def _partials_at(model, params, param_names, hc, rtol, atol):
83
+ """At fixed central enthalpy ``hc``: values [M,R,Lam], d[M,R,Lam]/dtheta (3,np),
84
+ and d[M,R,Lam]/dhc (3,) -- all clean single-star forward-mode tangents."""
85
+ theta0 = jnp.array([float(params[k]) for k in param_names])
86
+
87
+ def g_theta(theta):
88
+ p = dict(params)
89
+ for k, v in zip(param_names, theta):
90
+ p[k] = v
91
+ return _star_MRL(model, p, hc, rtol, atol)
92
+
93
+ val = g_theta(theta0)
94
+ d_theta = jax.jacfwd(g_theta)(theta0) # (3, n_param)
95
+ d_hc = jax.jacfwd(lambda h: _star_MRL(model, params, h, rtol, atol))(hc) # (3,)
96
+ return np.asarray(val), np.asarray(d_theta), np.asarray(d_hc)
97
+
98
+
99
+ def _locate(model, params, masses, hc_grid_n, rtol_locate=1e-8):
100
+ """Central enthalpies giving each target mass on the stable rising branch, and the
101
+ enthalpy at maximum mass. Values only (used as expansion points)."""
102
+ t = model.eos_table(params)
103
+ fam = build_family(t, default_hc_grid(t, n_models=hc_grid_n),
104
+ rtol=rtol_locate, atol=rtol_locate * 1e-2)
105
+ b = np.flatnonzero(np.asarray(fam.stable)) # minimum-mass star to M_max
106
+ M = np.asarray(fam.M_msun)[b]
107
+ H = np.asarray(fam.h_c)[b]
108
+ imax = int(np.argmax(M))
109
+ hc_for = {m: float(np.interp(m, M[:imax + 1], H[:imax + 1])) for m in masses}
110
+ return hc_for, float(H[imax])
111
+
112
+
113
+ def sensitivity_matrix(model, params, param_names, *, masses_lambda=(1.4,),
114
+ masses_radius=(1.4,), include_mmax=True, hc_grid_n=160,
115
+ rtol=GRADIENT_RTOL, atol=GRADIENT_ATOL):
116
+ """Jacobian J[i, j] = d(observable_i)/d(param_j) at fixed mass, via the IFT.
117
+
118
+ Observables (rows): ``Lambda(m)`` for each ``masses_lambda``, ``R(m)`` for each
119
+ ``masses_radius``, then ``M_max``. Fixed-mass rows use the implicit-function
120
+ theorem; ``M_max`` uses the envelope theorem -- both built from accurate
121
+ single-star tangents (NOT differentiation through the family interpolation).
122
+
123
+ ``params`` must give a numeric value for every name in ``param_names``. Returns
124
+ ``(J, obs_names, param_names)``, ``J`` shape ``(n_obs, n_param)``.
125
+ """
126
+ param_names = list(param_names)
127
+ masses = sorted(set(masses_lambda) | set(masses_radius))
128
+ hc_for, hc_max = _locate(model, params, masses, hc_grid_n)
129
+
130
+ # cache single-star partials at each needed expansion point
131
+ cache = {}
132
+ for m in masses:
133
+ cache[m] = _partials_at(model, params, param_names, hc_for[m], rtol, atol)
134
+
135
+ def fixed_mass_row(m, channel):
136
+ _, d_theta, d_hc = cache[m]
137
+ dM_dhc = d_hc[0]
138
+ dhc_dtheta = -d_theta[0] / dM_dhc # IFT
139
+ return d_theta[channel] + d_hc[channel] * dhc_dtheta
140
+
141
+ rows, names = [], []
142
+ for m in masses_lambda:
143
+ rows.append(fixed_mass_row(m, 2)); names.append(f"Lambda({m})")
144
+ for m in masses_radius:
145
+ rows.append(fixed_mass_row(m, 1)); names.append(f"R({m})")
146
+ if include_mmax:
147
+ _, d_theta_max, _ = _partials_at(model, params, param_names, hc_max, rtol, atol)
148
+ rows.append(d_theta_max[0]); names.append("M_max") # envelope theorem
149
+ return np.stack(rows, axis=0), names, param_names
150
+
151
+
152
+ def fisher_matrix(J, sigma):
153
+ """Fisher information ``F = J^T C^-1 J`` for a diagonal data covariance.
154
+
155
+ ``sigma`` is the per-observable 1-sigma measurement uncertainty (same order as the
156
+ rows of ``J``). ``F`` has shape ``(n_param, n_param)``.
157
+ """
158
+ J = jnp.asarray(J)
159
+ sigma = jnp.asarray(sigma)
160
+ Cinv = jnp.diag(1.0 / sigma ** 2)
161
+ return J.T @ Cinv @ J
162
+
163
+
164
+ def fisher_covariance(J, sigma, prior_precision=None):
165
+ """Forecast parameter covariance ``(F + Pi)^-1`` (Pi = optional prior precision).
166
+
167
+ The Cramer-Rao parameter covariance for a Gaussian likelihood; add a prior
168
+ precision matrix ``prior_precision`` (n_param x n_param) to regularize / include
169
+ priors. Returns the covariance matrix.
170
+ """
171
+ F = fisher_matrix(J, sigma)
172
+ if prior_precision is not None:
173
+ F = F + jnp.asarray(prior_precision)
174
+ return jnp.linalg.inv(F)
@@ -0,0 +1,83 @@
1
+ """Genie-style synthetic multi-event likelihoods for adaptive-prior development.
2
+
3
+ Recipe (after gwkokab's 'genie', per RO): for each synthetic BNS event, use a
4
+ Fisher-like width to set the measurement covariance, draw an offset from it to
5
+ displace the observed peak from the truth, and use the quadratic peak as the
6
+ log-likelihood. The per-EOS evidence of one event is then
7
+
8
+ lnZ_e^(i) = -(LambdaTilde_e(m1_i, m2_i) - x_obs_i)^2 / (2 sigma_i^2)
9
+
10
+ (up to constants), and **multiple events multiply**: lnZ_e = sum_i lnZ_e^(i).
11
+ This gives a zero-cost stand-in for the per-event CIP evidences -- the multi-event
12
+ scaling of the exact ("painful") mode is n_events x n_EOS full CIP runs per
13
+ generation, so synthetic likelihoods are how the adaptive loop is developed and
14
+ its convergence characterized before burning core-hours.
15
+
16
+ The observable is the leading tidal combination
17
+ LambdaTilde(m1, m2, Lambda1, Lambda2) (Favata/Wade convention).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import numpy as np
22
+
23
+ from ..priors.gp_pca import sequence_lambda_of_m
24
+
25
+
26
+ def lambda_tilde(m1, m2, lam1, lam2):
27
+ """Leading-order effective tidal deformability (dimensionless)."""
28
+ mt = m1 + m2
29
+ return (16.0 / 13.0) * ((m1 + 12.0 * m2) * m1 ** 4 * lam1
30
+ + (m2 + 12.0 * m1) * m2 ** 4 * lam2) / mt ** 5
31
+
32
+
33
+ def draw_bns_events(rng, n_events, truth_lambda_of_m, m_mean=1.35, m_sigma=0.06,
34
+ sigma_lamtilde=80.0, sigma_scatter=0.3):
35
+ """Draw a synthetic BNS event set with genie-style observed peaks.
36
+
37
+ Masses ~ N(m_mean, m_sigma) (sorted so m1 >= m2); each event's measurement
38
+ width sigma_i = sigma_lamtilde * exp(N(0, sigma_scatter)) (an SNR-like
39
+ spread); observed peak = truth + N(0, sigma_i) offset. Returns a list of
40
+ dicts (m1, m2, sigma, x_obs, x_true).
41
+ """
42
+ events = []
43
+ for _ in range(n_events):
44
+ m = np.sort(rng.normal(m_mean, m_sigma, size=2))[::-1]
45
+ lam1 = truth_lambda_of_m(m[0])
46
+ lam2 = truth_lambda_of_m(m[1])
47
+ if not (np.isfinite(lam1) and np.isfinite(lam2)):
48
+ continue
49
+ x_true = lambda_tilde(m[0], m[1], lam1, lam2)
50
+ sig = sigma_lamtilde * np.exp(rng.normal(0.0, sigma_scatter))
51
+ events.append(dict(m1=float(m[0]), m2=float(m[1]), sigma=float(sig),
52
+ x_true=float(x_true),
53
+ x_obs=float(x_true + rng.normal(0.0, sig))))
54
+ return events
55
+
56
+
57
+ class SyntheticTidalEvents:
58
+ """``evidence_fn(prior, coeffs) -> lnZ`` for a fixed synthetic event set.
59
+
60
+ Per EOS draw e: evaluate Lambda(m1_i), Lambda(m2_i) from the reconstructed
61
+ sequence, form LambdaTilde, and sum the quadratic-peak log-likelihoods over
62
+ events. Draws whose stable branch does not cover an event's masses get a
63
+ heavy penalty (they cannot produce the observed system).
64
+ """
65
+
66
+ def __init__(self, events, off_branch_penalty=-50.0):
67
+ self.events = list(events)
68
+ self.off_branch_penalty = float(off_branch_penalty)
69
+
70
+ def __call__(self, prior, coeffs):
71
+ out = np.zeros(len(coeffs))
72
+ for k, c in enumerate(coeffs):
73
+ tot = 0.0
74
+ for ev in self.events:
75
+ l1 = sequence_lambda_of_m(prior, c, ev["m1"])
76
+ l2 = sequence_lambda_of_m(prior, c, ev["m2"])
77
+ if not (np.isfinite(l1) and np.isfinite(l2)):
78
+ tot += self.off_branch_penalty
79
+ continue
80
+ x = lambda_tilde(ev["m1"], ev["m2"], l1, l2)
81
+ tot += -0.5 * ((x - ev["x_obs"]) / ev["sigma"]) ** 2
82
+ out[k] = tot
83
+ return out