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/ddrmf.py ADDED
@@ -0,0 +1,388 @@
1
+ """Density-dependent relativistic mean field (DD-RMF), Typel-Wolter form.
2
+
3
+ Nucleons couple to sigma, omega and rho mesons with couplings that depend on
4
+ the baryon density n (Typel & Wolter, NPA 656, 331 (1999)):
5
+
6
+ Gamma_i(n) = Gamma_i(n_ref) f_i(x), x = n / n_ref
7
+ f_i(x) = a_i (1 + b_i (x+d_i)^2) / (1 + c_i (x+d_i)^2) (i = sigma, omega)
8
+ f_rho(x) = exp(-a_rho (x - 1))
9
+
10
+ There are no meson self-interactions. With C_i(n) = (Gamma_i(n)/m_i)^2 (fm^2),
11
+ Phi = Gamma_sigma sigma, n_3 = n_p - n_n and isospin t_p = +1, t_n = -1
12
+ (the convention of DD2 and DDME2)::
13
+
14
+ m*_i = M_i - Phi, Phi = C_sigma(n) n_s (self-consistent)
15
+ eps = sum_i eps_kin(kF_i, m*_i) + Phi^2 / (2 C_sigma)
16
+ + C_omega n^2 / 2 + C_rho n_3^2 / 2 + eps_leptons
17
+ mu_i = E*_Fi + C_omega n + t_i C_rho n_3 + Sigma_R
18
+ Sigma_R = -C_sigma' n_s^2 / 2 + C_omega' n^2 / 2 + C_rho' n_3^2 / 2
19
+
20
+ Sigma_R is the rearrangement term (C' = dC/dn). Without it p = sum mu_i n_i
21
+ - eps is not the thermodynamic pressure n^2 d(eps/n)/dn.
22
+
23
+ beta equilibrium and charge neutrality use npe-mu leptons
24
+ (:func:`nmbackend.eos.leptons.lepton_sector`).
25
+
26
+ ``couplings_from_saturation_dd`` maps (n0, B/A, K, m*/M, J, L) to couplings,
27
+ with c_i = 1/(3 d_i^2) (f''(0) = 0). The shape parameters d_sigma, d_omega
28
+ default to their DD2 values and may be passed freely. DD2 is a member of
29
+ that family. The rho decay a_rho follows from L at fixed J; a_rho < 0 (rho
30
+ coupling growing with density, L above its a_rho = 0 value) is rejected
31
+ unless ``allow_negative_arho=True``.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import math
36
+
37
+ import jax
38
+ import jax.numpy as jnp
39
+ import numpy as np
40
+
41
+ from ..constants import HBARC
42
+ from .base import EOSModel, Composition, compiled_method, compiled_table
43
+ from .leptons import lepton_sector
44
+ from .crust import (N_T_DEFAULT, check_crust, core_grid, finish_table_flags,
45
+ monotone_core)
46
+
47
+ jax.config.update("jax_enable_x64", True)
48
+
49
+ _PI2 = math.pi ** 2
50
+
51
+
52
+ def _set(M_n, M_p, n_ref, m_s, m_w, m_r, G_s, G_w, G_r, s, w, a_r):
53
+ """Parameter dict from published (masses, couplings, TW coefficients)."""
54
+ C = lambda G, m: (G * HBARC / m) ** 2 # fm^2
55
+ return dict(M_n=M_n, M_p=M_p, n_ref=n_ref,
56
+ C_sigma=C(G_s, m_s), C_omega=C(G_w, m_w), C_rho=C(G_r, m_r),
57
+ a_s=s[0], b_s=s[1], c_s=s[2], d_s=s[3],
58
+ a_w=w[0], b_w=w[1], c_w=w[2], d_w=w[3], a_r=a_r)
59
+
60
+
61
+ #: DD2: Typel, Roepke, Klaehn, Blaschke & Wolter, PRC 81, 015803 (2010),
62
+ #: arXiv:0908.2344, Tables II-III.
63
+ DD2 = _set(939.56536, 938.27203, 0.149065, 546.212459, 783.0, 763.0,
64
+ 10.686681, 13.342362, 3.626940,
65
+ (1.357630, 0.634442, 1.005358, 0.575810),
66
+ (1.369718, 0.496475, 0.817753, 0.638452), 0.518903)
67
+
68
+ #: DDME2: Lalazissis, Niksic, Vretenar & Ring, PRC 71, 024312 (2005), Table I.
69
+ #: Single nucleon mass 939 MeV.
70
+ DDME2 = _set(939.0, 939.0, 0.152, 550.1238, 783.0, 763.0,
71
+ 10.5396, 13.0189, 3.6836,
72
+ (1.3881, 1.0943, 1.7057, 0.4421),
73
+ (1.3892, 0.9240, 1.4620, 0.4775), 0.5647)
74
+
75
+ DEFAULT_PARAMS = dict(DD2)
76
+
77
+
78
+ # --- coupling functions C_i(n) and dC_i/dn ---------------------------------
79
+ def _tw(x, a, b, c, d):
80
+ y = (x + d) ** 2
81
+ f = a * (1.0 + b * y) / (1.0 + c * y)
82
+ fp = 2.0 * a * (b - c) * (x + d) / (1.0 + c * y) ** 2
83
+ return f, fp
84
+
85
+
86
+ def _couplings(n, p):
87
+ """(C_sigma, C_omega, C_rho) and their n-derivatives at density n."""
88
+ x = n / p["n_ref"]
89
+ fs, fsp = _tw(x, p["a_s"], p["b_s"], p["c_s"], p["d_s"])
90
+ fw, fwp = _tw(x, p["a_w"], p["b_w"], p["c_w"], p["d_w"])
91
+ fr = jnp.exp(-p["a_r"] * (x - 1.0))
92
+ fr_p = -p["a_r"] * fr
93
+ C = (p["C_sigma"] * fs**2, p["C_omega"] * fw**2, p["C_rho"] * fr**2)
94
+ dC = (2.0 * p["C_sigma"] * fs * fsp / p["n_ref"],
95
+ 2.0 * p["C_omega"] * fw * fwp / p["n_ref"],
96
+ 2.0 * p["C_rho"] * fr * fr_p / p["n_ref"])
97
+ return C, dC
98
+
99
+
100
+ # --- Fermi-gas integrals (degeneracy 2, fm units) --------------------------
101
+ def _kf(n_i):
102
+ return (3.0 * _PI2 * jnp.maximum(n_i, 1e-30)) ** (1.0 / 3.0)
103
+
104
+
105
+ def _rho_s(kf, ms):
106
+ ef = jnp.sqrt(kf**2 + ms**2)
107
+ return (ms / (2.0 * _PI2)) * (kf * ef - ms**2 * jnp.log((kf + ef) / ms))
108
+
109
+
110
+ def _eps_kin(kf, ms):
111
+ ef = jnp.sqrt(kf**2 + ms**2)
112
+ return (1.0 / (8.0 * _PI2)) * (
113
+ kf * (2.0 * kf**2 + ms**2) * ef - ms**4 * jnp.log((kf + ef) / ms))
114
+
115
+
116
+ def _solve_phi(n_n, n_p, p, nbis=60):
117
+ """Phi = C_sigma(n) n_s(M - Phi): the residual is monotone in Phi, so
118
+ bisection on [0, M_min) finds the unique root; a final Newton step from a
119
+ stop-gradient start gives the implicit derivative."""
120
+ Mn, Mp = p["M_n"] / HBARC, p["M_p"] / HBARC
121
+ kfn, kfp = _kf(n_n), _kf(n_p)
122
+ Cs = _couplings(n_n + n_p, p)[0][0]
123
+
124
+ def resid(Phi):
125
+ return Phi - Cs * (_rho_s(kfn, Mn - Phi) + _rho_s(kfp, Mp - Phi))
126
+
127
+ lo = jnp.zeros_like(kfn)
128
+ hi = 0.999 * jnp.minimum(Mn, Mp) + 0.0 * kfn
129
+
130
+ def body(_i, c):
131
+ lo, hi = c
132
+ mid = 0.5 * (lo + hi)
133
+ r = resid(mid)
134
+ return jnp.where(r < 0.0, mid, lo), jnp.where(r < 0.0, hi, mid)
135
+
136
+ lo, hi = jax.lax.fori_loop(0, nbis, body, (lo, hi))
137
+ x0 = jax.lax.stop_gradient(0.5 * (lo + hi))
138
+ d = jax.grad(lambda x: jnp.sum(resid(x)))(x0)
139
+ return x0 - resid(x0) / d
140
+
141
+
142
+ def _nucleon_state(n_n, n_p, p):
143
+ """Nucleon eps (fm^-4) and mu_n, mu_p (fm^-1)."""
144
+ Mn, Mp = p["M_n"] / HBARC, p["M_p"] / HBARC
145
+ n = n_n + n_p
146
+ n3 = n_p - n_n
147
+ Phi = _solve_phi(n_n, n_p, p)
148
+ kfn, kfp = _kf(n_n), _kf(n_p)
149
+ msn, msp = Mn - Phi, Mp - Phi
150
+ ns = _rho_s(kfn, msn) + _rho_s(kfp, msp)
151
+ (Cs, Cw, Cr), (dCs, dCw, dCr) = _couplings(n, p)
152
+ eps = (_eps_kin(kfn, msn) + _eps_kin(kfp, msp) + 0.5 * Phi**2 / Cs
153
+ + 0.5 * Cw * n**2 + 0.5 * Cr * n3**2)
154
+ sig_r = -0.5 * dCs * ns**2 + 0.5 * dCw * n**2 + 0.5 * dCr * n3**2
155
+ base = Cw * n + sig_r
156
+ mu_n = jnp.sqrt(kfn**2 + msn**2) + base - Cr * n3
157
+ mu_p = jnp.sqrt(kfp**2 + msp**2) + base + Cr * n3
158
+ return eps, mu_n, mu_p, Phi
159
+
160
+
161
+ def landau_masses(params, n, x_p):
162
+ """(m*_n/M_n, m*_p/M_p): Landau masses at the Fermi surface.
163
+
164
+ The single-particle energy is sqrt(k^2 + m_D^2) + (vector and
165
+ rearrangement self-energies, independent of k), so the Landau mass
166
+ k_F / (d e/dk) is E*_F = sqrt(k_F^2 + m_D^2), with Dirac mass
167
+ m_D = M_i - Phi."""
168
+ p = dict(DEFAULT_PARAMS)
169
+ p.update({k: v for k, v in (params or {}).items() if k != "L0"})
170
+ n = jnp.asarray(n, float)
171
+ x_p = jnp.asarray(x_p, float)
172
+ n_n, n_p = (1.0 - x_p) * n, x_p * n
173
+ Phi = _solve_phi(n_n, n_p, p)
174
+ Mn, Mp = p["M_n"] / HBARC, p["M_p"] / HBARC
175
+ ef = lambda kf, m: jnp.sqrt(kf**2 + (m - Phi) ** 2) / m
176
+ return ef(_kf(n_n), Mn), ef(_kf(n_p), Mp)
177
+
178
+
179
+ def _solve_xp(n_B, p, n_iter=60):
180
+ """beta-equilibrium proton fraction (npe-mu): mu_n - mu_p = mu_e."""
181
+ def g(x_p):
182
+ _, mu_n, mu_p, _ = _nucleon_state((1.0 - x_p) * n_B, x_p * n_B, p)
183
+ return (mu_n - mu_p) - lepton_sector(x_p * n_B, muons=True)[0]
184
+
185
+ lo = jnp.full_like(n_B, 1e-5)
186
+ hi = jnp.full_like(n_B, 0.5)
187
+
188
+ def body(_, c):
189
+ lo, hi = c
190
+ mid = 0.5 * (lo + hi)
191
+ gm = g(mid) # decreasing in x_p
192
+ return jnp.where(gm > 0.0, mid, lo), jnp.where(gm > 0.0, hi, mid)
193
+
194
+ lo, hi = jax.lax.fori_loop(0, n_iter, body, (lo, hi))
195
+ x0 = jax.lax.stop_gradient(0.5 * (lo + hi))
196
+ dg = jax.grad(lambda x: jnp.sum(g(x)))(x0)
197
+ return x0 - g(x0) / dg
198
+
199
+
200
+ def _eps_p(n_B, x_p, p, leptons=True):
201
+ """eps, p (MeV/fm^3) at (n_B, x_p); p = sum_i mu_i n_i - eps."""
202
+ n_p, n_n = x_p * n_B, (1.0 - x_p) * n_B
203
+ eps, mu_n, mu_p, _ = _nucleon_state(n_n, n_p, p)
204
+ pres = mu_n * n_n + mu_p * n_p - eps
205
+ if leptons:
206
+ mu_e, n_e, n_mu, eps_l = lepton_sector(n_p, muons=True)
207
+ eps = eps + eps_l
208
+ pres = pres + mu_e * (n_e + n_mu) - eps_l
209
+ return eps * HBARC, pres * HBARC
210
+
211
+
212
+ def symmetric_matter(n, params=None):
213
+ """Symmetric nuclear matter (no leptons): dict of E/A - M_avg (MeV),
214
+ p (MeV/fm^3), m*/M_avg, S(n) (MeV) on density array ``n`` (fm^-3).
215
+ S uses the curvature form S = kF^2 / (6 E*_F) + C_rho n / 2."""
216
+ p = dict(DEFAULT_PARAMS)
217
+ if params:
218
+ p.update({k: v for k, v in params.items() if k != "L0"})
219
+ return _symmetric(jnp.asarray(n, float), p)
220
+
221
+
222
+ @jax.jit
223
+ def _symmetric(n, p):
224
+ eps, mu_n, mu_p, Phi = _nucleon_state(n / 2.0, n / 2.0, p)
225
+ M = 0.5 * (p["M_n"] + p["M_p"]) / HBARC
226
+ pres = 0.5 * (mu_n + mu_p) * n - eps
227
+ kf = _kf(n / 2.0)
228
+ ms = M - Phi
229
+ Cr = _couplings(n, p)[0][2]
230
+ S = kf**2 / (6.0 * jnp.sqrt(kf**2 + ms**2)) + 0.5 * Cr * n
231
+ return dict(EA=(eps / n - M) * HBARC, p=pres * HBARC, mstar=ms / M,
232
+ S=S * HBARC)
233
+
234
+
235
+ def saturation_properties(params=None, n_lo=0.10, n_hi=0.20, npts=2001):
236
+ """n0, B/A, K, m*/M, E_sym (= J), L of a DD-RMF parameter set."""
237
+ ns = np.linspace(n_lo, n_hi, npts)
238
+ s = {k: np.asarray(v) for k, v in symmetric_matter(ns, params).items()}
239
+ i = int(np.argmin(s["EA"]))
240
+ dn = ns[1] - ns[0]
241
+ # refine the minimum with a parabola through three nodes
242
+ e0, e1, e2 = s["EA"][i - 1:i + 2]
243
+ t = 0.5 * (e0 - e2) / (e0 - 2 * e1 + e2)
244
+ n0 = ns[i] + t * dn
245
+ q = lambda a: float(np.interp(n0, ns, a))
246
+ d = lambda a: np.gradient(a, dn)
247
+ K = 9.0 * q(d(s["p"]))
248
+ L = 3.0 * n0 * q(d(s["S"]))
249
+ return dict(n0=float(n0), BA=q(s["EA"]), K=K, mstar_frac=q(s["mstar"]),
250
+ E_sym=q(s["S"]), L=L)
251
+
252
+
253
+ def _tw_from_b(b, d):
254
+ """(a, b, c, d) with f(1) = 1 and f''(0) = 0 for given b, d."""
255
+ c = 1.0 / (3.0 * d * d)
256
+ a = (1.0 + c * (1.0 + d) ** 2) / (1.0 + b * (1.0 + d) ** 2)
257
+ return a, b, c, d
258
+
259
+
260
+ def couplings_from_saturation_dd(n0=0.149065, BA=-16.02, K=242.7,
261
+ mstar_frac=0.5628, J=31.7, L=55.0,
262
+ M_mev=938.9187, d_s=DD2["d_s"],
263
+ d_w=DD2["d_w"], b_start=(DD2["b_s"], DD2["b_w"]),
264
+ allow_negative_arho=False):
265
+ """DD-RMF couplings reproducing a saturation point.
266
+
267
+ n0 in fm^-3; BA, K, J, L in MeV. C_sigma(n0) from m*/M, C_omega(n0) from
268
+ B/A, (b_sigma, b_omega) from p(n0) = 0 and K (2-d root), C_rho(n0) from J
269
+ and a_rho from L. Single nucleon mass ``M_mev``.
270
+
271
+ Raises ValueError if no solution exists, if a coupling function turns
272
+ negative or singular on 0 <= x <= 12, or (unless ``allow_negative_arho``)
273
+ if a_rho < 0, a rho coupling that grows with density.
274
+ """
275
+ from scipy.optimize import fsolve
276
+
277
+ M = M_mev / HBARC
278
+ ms = mstar_frac * M
279
+ Phi0 = M - ms
280
+ kf = float(_kf(n0 / 2.0))
281
+ ef = math.sqrt(kf**2 + ms**2)
282
+ ns0 = float(2.0 * _rho_s(kf, ms))
283
+ Cs0 = Phi0 / ns0
284
+ ekin = float(2.0 * _eps_kin(kf, ms))
285
+ Cw0 = 2.0 * (n0 * (M_mev + BA) / HBARC - ekin - 0.5 * Phi0**2 / Cs0) / n0**2
286
+ if Cs0 <= 0.0 or Cw0 <= 0.0:
287
+ raise ValueError("saturation point needs a non-positive coupling")
288
+
289
+ def params(b):
290
+ s, w = _tw_from_b(b[0], d_s), _tw_from_b(b[1], d_w)
291
+ return dict(M_n=M_mev, M_p=M_mev, n_ref=n0, C_sigma=Cs0, C_omega=Cw0,
292
+ C_rho=1.0, a_s=s[0], b_s=s[1], c_s=s[2], d_s=s[3],
293
+ a_w=w[0], b_w=w[1], c_w=w[2], d_w=w[3], a_r=0.0)
294
+
295
+ h = 2e-4 * n0
296
+ grid = jnp.array([n0 - h, n0, n0 + h])
297
+
298
+ def resid(b):
299
+ pr = np.asarray(symmetric_matter(grid, params(b))["p"])
300
+ return [pr[1] / 1.0, (9.0 * (pr[2] - pr[0]) / (2 * h) - K) / K]
301
+
302
+ b, info, ier, _ = fsolve(resid, b_start, full_output=True, xtol=1e-11)
303
+ if ier != 1 or max(abs(v) for v in resid(b)) > 1e-6:
304
+ raise ValueError("no (b_sigma, b_omega) reproduces p(n0) = 0 and K")
305
+ p = params(b)
306
+ x = np.linspace(0.0, 12.0, 241)
307
+ for k in ("s", "w"):
308
+ f, _ = _tw(x, p["a_" + k], p["b_" + k], p["c_" + k], p["d_" + k])
309
+ den = 1.0 + p["c_" + k] * (x + p["d_" + k]) ** 2
310
+ if not (np.all(np.asarray(f) > 0.0) and np.all(den > 0.0)):
311
+ raise ValueError("coupling function not positive on 0 <= x <= 12")
312
+ # isovector: J -> C_rho(n0); L -> a_rho
313
+ T = kf**2 / (6.0 * ef)
314
+ Srho = J / HBARC - T
315
+ if Srho <= 0.0:
316
+ raise ValueError("J below its kinetic part")
317
+ p["C_rho"] = 2.0 * Srho / n0
318
+ S = np.asarray(symmetric_matter(grid, p)["S"]) # a_r = 0 here
319
+ L_a0 = 3.0 * n0 * (S[2] - S[0]) / (2 * h) # L at a_rho = 0
320
+ a_r = (L_a0 - L) / (6.0 * Srho * HBARC) # dL/da_rho = -6 S_rho
321
+ if a_r < 0.0 and not allow_negative_arho:
322
+ raise ValueError(f"L={L} above the a_rho = 0 value {L_a0:.1f}")
323
+ p["a_r"] = float(a_r)
324
+ p.update(L0=float(L_a0))
325
+ return p
326
+
327
+
328
+ class DDRMFEOS(EOSModel):
329
+ """Density-dependent RMF (Typel-Wolter), npe-mu beta equilibrium."""
330
+
331
+ name = "DDRMFEOS"
332
+
333
+ def __init__(self, n_min=1e-3, n_max=1.2, n_points=200,
334
+ n_surface=1e-7, gamma_crust=1.3,
335
+ crust="sly", n_t=N_T_DEFAULT,
336
+ allow_unstable_core=False):
337
+ self.n_grid = jnp.exp(jnp.linspace(math.log(n_min), math.log(n_max),
338
+ n_points))
339
+ self.n_surface = n_surface
340
+ self.gamma_crust = gamma_crust
341
+ self.crust = check_crust(crust, n_surface)
342
+ self.n_t = n_t
343
+ self.allow_unstable_core = allow_unstable_core
344
+
345
+ def _table_grid(self):
346
+ """Uniform-matter nodes of the EOS table (above n_t with the SLy crust)."""
347
+ if self.crust == "sly" and self.n_surface is not None:
348
+ return core_grid(self.n_grid, self.n_t)
349
+ return self.n_grid
350
+
351
+ @staticmethod
352
+ def _p(params):
353
+ p = dict(DEFAULT_PARAMS)
354
+ if params:
355
+ p.update({k: v for k, v in params.items() if k != "L0"})
356
+ return p
357
+
358
+ def composition(self, params: dict = None) -> Composition:
359
+ """beta-equilibrium (x_p, x_e, x_mu) on ``self.n_grid``."""
360
+ p = self._p(params)
361
+ return compiled_method(self, "_composition", p)
362
+
363
+ def _composition(self, p):
364
+ n = self.n_grid
365
+ x_p = _solve_xp(n, p)
366
+ _, n_e, n_mu, _ = lepton_sector(x_p * n, muons=True)
367
+ return Composition(n=n, x_p=x_p, x_e=n_e / n, x_mu=n_mu / n)
368
+
369
+ def landau_masses(self, params, comp):
370
+ """(m*_n/M_n, m*_p/M_p) on ``comp`` (see :func:`landau_masses`)."""
371
+ # _solve_phi bisects: compiled, or it recompiles on every call
372
+ return compiled_method(self, "_landau", self._p(params), comp.n, comp.x_p)
373
+
374
+ @staticmethod
375
+ def _landau(params, n, x_p):
376
+ return landau_masses(params, n, x_p)
377
+
378
+ def eos_table(self, params: dict = None):
379
+ return compiled_table(self, self._p(params))
380
+
381
+ def _table_flags(self, p):
382
+ n = self._table_grid()
383
+ x_p = _solve_xp(n, p)
384
+ eps, pres = _eps_p(n, x_p, p)
385
+ pres, ln_nu = monotone_core(n, pres, self.n_t)
386
+ return finish_table_flags(n, eps, pres, self.crust, self.n_t,
387
+ self.n_surface, self.gamma_crust, ln_nu,
388
+ self.allow_unstable_core)
@@ -0,0 +1,173 @@
1
+ """Hybrid hadron--quark EOS with a first-order (Maxwell) phase transition.
2
+
3
+ A hadronic branch (the metamodel) up to a transition pressure ``p_trans``; then a
4
+ **density discontinuity** at constant pressure (Maxwell construction) into a
5
+ constant-sound-speed (CSS) quark branch. This is the deliberate *stress test* for
6
+ the TOV solver: across the jump ``cs^2 -> 0`` and the energy density is
7
+ discontinuous, which the smooth solver mishandles and which requires the tidal
8
+ **junction condition** (see ``nmbackend.tov.phase_transition``).
9
+
10
+ Across a Maxwell transition the pressure and the chemical potential mu = (eps+p)/n
11
+ are continuous while n and eps jump; we use mu-continuity to set the baryon density
12
+ on the quark side: n_Q = n_H (eps_Q + p_t)/(eps_H + p_t).
13
+
14
+ Two builders:
15
+ * :meth:`segments` / :meth:`transition` -- smooth sub-tables + jump data for the
16
+ sharp (junction-corrected) solver.
17
+ * :meth:`eos_table` -- one combined table (jump represented by cs^2 -> 0 cell),
18
+ for the RIFT adapter / plotting.
19
+ * :meth:`eos_table_smeared` -- the jump replaced by a finite-width crossover, so
20
+ the *standard* adaptive solver resolves it; used to validate the junction in the
21
+ sharp limit (width -> 0).
22
+
23
+ Construction uses NumPy (static per parameter set); AD through the transition
24
+ parameters is future work.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ from typing import NamedTuple
30
+
31
+ import numpy as np
32
+
33
+ from ..constants import MEVFM3_TO_GEOM
34
+ from .base import build_h_and_cs2, refine_table, EOSTable
35
+ from .metamodel import MetaModelEOS
36
+
37
+
38
+ class TransitionInfo(NamedTuple):
39
+ h_t: float # pseudo-enthalpy at the transition (dimensionless)
40
+ p_t: float # transition pressure, geometric km^-2
41
+ eps_in: float # inner (higher-density, quark) side, geometric km^-2
42
+ eps_out: float # outer (lower-density, hadronic) side, geometric km^-2
43
+
44
+
45
+ class HybridEOS:
46
+ name = "HybridEOS"
47
+
48
+ def __init__(self, hadronic=None, had_params=None, p_trans_mev=80.0,
49
+ delta_eps_mev=200.0, cs2_quark=1.0, eps_max_fac=6.0,
50
+ n_quark=200, n_hadronic="auto"):
51
+ self.hadronic = hadronic or MetaModelEOS()
52
+ self.had_params = had_params
53
+ self.p_trans_mev = p_trans_mev
54
+ self.delta_eps_mev = delta_eps_mev
55
+ self.cs2_quark = cs2_quark
56
+ self.eps_max_fac = eps_max_fac
57
+ self.n_quark = n_quark
58
+ # node count of the hadronic segment (refine_table), which otherwise
59
+ # varies with p_trans; "auto" is the length of the full hadronic
60
+ # table, None keeps the raw nodes
61
+ self.n_hadronic = n_hadronic
62
+ self._build()
63
+
64
+ # ---- construction ----
65
+ def _hadronic_arrays(self):
66
+ t = self.hadronic.eos_table(self.had_params)
67
+ return (np.asarray(t.n), np.asarray(t.eps_mevfm3),
68
+ np.asarray(t.p_mevfm3))
69
+
70
+ def _build(self):
71
+ n_h, eps_h, p_h = self._hadronic_arrays()
72
+ pt = float(self.p_trans_mev)
73
+ if pt <= p_h[0] or pt >= p_h[-1]:
74
+ raise ValueError(f"p_trans={pt} outside hadronic pressure range "
75
+ f"[{p_h[0]:.3g}, {p_h[-1]:.3g}] MeV/fm^3")
76
+ eps_t = float(np.interp(pt, p_h, eps_h)) # hadronic eps at p_t
77
+ n_t = float(np.interp(pt, p_h, n_h))
78
+
79
+ # outer (hadronic) segment: p < p_t, capped with the transition point
80
+ m = p_h < pt
81
+ self._had_seg = (np.append(n_h[m], n_t),
82
+ np.append(eps_h[m], eps_t),
83
+ np.append(p_h[m], pt))
84
+
85
+ # quark (inner) CSS segment from (p_t, eps_Q)
86
+ cs2 = float(self.cs2_quark)
87
+ eps_Q = eps_t + float(self.delta_eps_mev)
88
+ n_Q = n_t * (eps_Q + pt) / (eps_t + pt) # mu-continuity
89
+ eps_q = np.geomspace(eps_Q, eps_Q * self.eps_max_fac, self.n_quark)
90
+ p_q = pt + cs2 * (eps_q - eps_Q)
91
+ c0 = pt - cs2 * eps_Q
92
+ n_q = n_Q * (((1 + cs2) * eps_q + c0) /
93
+ ((1 + cs2) * eps_Q + c0)) ** (1.0 / (1.0 + cs2))
94
+ self._quark_seg = (n_q, eps_q, p_q)
95
+
96
+ # build segment tables; quark enthalpy continues above hadronic h_t
97
+ self._n_outer = n_h.size if self.n_hadronic == "auto" else self.n_hadronic
98
+ if self._n_outer is None:
99
+ outer = build_h_and_cs2(*[np.asarray(a) for a in self._had_seg])
100
+ self._outer_raw = outer
101
+ else: # NumPy until the length is fixed: no compile per raw length
102
+ self._outer_raw = build_h_and_cs2(*self._had_seg, xp=np)
103
+ outer = refine_table(self._outer_raw, self._n_outer)
104
+ h_t = float(outer.h[-1])
105
+ inner = build_h_and_cs2(*[np.asarray(a) for a in self._quark_seg],
106
+ h_base=h_t)
107
+ self._outer, self._inner = outer, inner
108
+ self._transition = TransitionInfo(
109
+ h_t=h_t, p_t=pt * MEVFM3_TO_GEOM,
110
+ eps_in=eps_Q * MEVFM3_TO_GEOM, eps_out=eps_t * MEVFM3_TO_GEOM,
111
+ )
112
+ self._eps_t_mev, self._eps_Q_mev = eps_t, eps_Q
113
+
114
+ # ---- accessors ----
115
+ @property
116
+ def segments(self):
117
+ """(inner_quark_table, outer_hadronic_table)."""
118
+ return self._inner, self._outer
119
+
120
+ @property
121
+ def raw_segments(self):
122
+ """(inner, outer) with the outer segment on its raw nodes, before
123
+ :func:`refine_table`. For solvers that interpolate between nodes
124
+ linearly (``reference.scipy_tov``), where added nodes change p(eps)."""
125
+ return self._inner, self._outer_raw
126
+
127
+ @property
128
+ def transition(self) -> TransitionInfo:
129
+ return self._transition
130
+
131
+ def eos_table(self) -> EOSTable:
132
+ """Combined table (jump as a cs^2->0 cell); for adapter / plotting."""
133
+ no, eo, po = self._had_seg
134
+ nq, eq, pq = self._quark_seg
135
+ n = np.concatenate([no, nq])
136
+ eps = np.concatenate([eo, eq])
137
+ p = np.concatenate([po, pq])
138
+ if self._n_outer is None:
139
+ return build_h_and_cs2(n, eps, p)
140
+ return refine_table(build_h_and_cs2(n, eps, p, xp=np),
141
+ self._n_outer + self.n_quark)
142
+
143
+ def eos_table_smeared(self, width_frac=0.02, n_ramp=60) -> EOSTable:
144
+ """Replace the sharp jump with a finite-width crossover in pressure.
145
+
146
+ The transition is spread over dp = width_frac * p_t, with eps rising
147
+ eps_out -> eps_in across it (cs^2 = dp/deps small but finite). As
148
+ width_frac -> 0 this approaches the sharp transition; the standard adaptive
149
+ solver resolves it, giving an independent value to compare the junction
150
+ solver against. At width_frac <= ~1e-8 every ramp cell has chord
151
+ dp/deps <= 1e-8 and is treated as a jump cell (eos.base), so the table
152
+ then tests the junction bubble, not a smear. p is strictly increasing
153
+ by construction (ramp, then the quark branch without its first node).
154
+ """
155
+ no, eo, po = self._had_seg
156
+ nq, eq, pq = self._quark_seg
157
+ pt = float(self.p_trans_mev)
158
+ dp = width_frac * pt
159
+ # ramp at constant-ish small cs^2 between the two eps values
160
+ eps_ramp = np.linspace(self._eps_t_mev, self._eps_Q_mev, n_ramp)
161
+ p_ramp = pt + dp * (eps_ramp - self._eps_t_mev) / (
162
+ self._eps_Q_mev - self._eps_t_mev)
163
+ n_ramp_arr = np.linspace(no[-1], nq[0], n_ramp)
164
+ # quark branch shifted to start at p_t + dp
165
+ pq2 = pq + dp
166
+ # the ramp ends on the first quark node: drop that duplicate. (Until
167
+ # 2026-10-14 an absolute 1e-12 * k MeV/fm^3 was added to every p to make
168
+ # it strictly increasing, which moved outer-crust pressures by up to 41%
169
+ # and left a width-independent +2e-4 floor in Lambda.)
170
+ n = np.concatenate([no[:-1], n_ramp_arr, nq[1:]])
171
+ eps = np.concatenate([eo[:-1], eps_ramp, eq[1:]])
172
+ p = np.concatenate([po[:-1], p_ramp, pq2[1:]])
173
+ return build_h_and_cs2(n, eps, p)
@@ -0,0 +1,74 @@
1
+ """Cold lepton sector (electrons, optionally muons) at fixed charge density.
2
+
3
+ Shared by the RMFT and metamodel EOSs. Units: fm (hbar c = 1), i.e. momenta and
4
+ chemical potentials in fm^-1, densities in fm^-3, energy densities in fm^-4.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ import jax
10
+ import jax.numpy as jnp
11
+
12
+ from ..constants import HBARC, M_E, M_MU
13
+
14
+ _PI2 = math.pi ** 2
15
+
16
+
17
+ def eps_kin_one(kf, m):
18
+ """Kinetic + rest energy density of one degeneracy-2 Fermi gas (fm^-4)."""
19
+ ef = jnp.sqrt(kf**2 + m**2)
20
+ return (1.0 / (8.0 * _PI2)) * (
21
+ kf * (2.0 * kf**2 + m**2) * ef - m**4 * jnp.log((kf + ef) / m))
22
+
23
+
24
+ def _kf_of_mu(mu, m):
25
+ """sqrt(mu^2 - m^2) for mu > m, else 0; NaN-free derivative at threshold."""
26
+ x = mu**2 - m**2
27
+ return jnp.where(x > 0.0, jnp.sqrt(jnp.where(x > 0.0, x, 1.0)), 0.0)
28
+
29
+
30
+ def lepton_sector(n_charge, muons=True, n_bis=50):
31
+ """Leptons in chemical equilibrium (mu_e = mu_mu) with n_e + n_mu = n_charge.
32
+
33
+ Muons switch on once mu_e > m_mu (~106 MeV); ``muons=False`` gives the
34
+ electron-only (npe) limit. Bisection plus a Newton polish gives the primal;
35
+ ``custom_root`` supplies implicit derivatives, including the energy Hessian
36
+ needed when differentiating pressure. Threshold contacts are excluded.
37
+
38
+ Returns (mu_e [fm^-1], n_e, n_mu [fm^-3], eps_lep [fm^-4]).
39
+ """
40
+ m_e, m_mu = M_E / HBARC, M_MU / HBARC
41
+ n_charge = jnp.maximum(n_charge, 1e-30)
42
+ mu_on = 1.0 if muons else 0.0
43
+
44
+ def nlep(mu):
45
+ ke, kmu = _kf_of_mu(mu, m_e), _kf_of_mu(mu, m_mu)
46
+ return (ke**3 + mu_on * kmu**3) / (3.0 * _PI2)
47
+
48
+ mu_lo = jnp.full_like(n_charge, m_e)
49
+ mu_hi = jnp.sqrt((3.0 * _PI2 * n_charge) ** (2.0 / 3.0) + m_e**2) * 1.0001
50
+
51
+ def body(_i, c):
52
+ lo, hi = c
53
+ mid = 0.5 * (lo + hi)
54
+ f = nlep(mid) - n_charge # increasing in mu
55
+ return jnp.where(f < 0.0, mid, lo), jnp.where(f < 0.0, hi, mid)
56
+
57
+ def solve(fun, initial):
58
+ lo, hi = jax.lax.fori_loop(0, n_bis, body, (mu_lo, mu_hi))
59
+ mu0 = 0.5 * (lo + hi)
60
+ dn = jax.grad(lambda m: jnp.sum(nlep(m)))(mu0)
61
+ return mu0 - fun(mu0) / dn
62
+
63
+ # Each charge-density entry has an independent scalar root: the linearized
64
+ # Jacobian is diagonal. A stop-gradient start plus one Newton polish recovers
65
+ # only the first derivative; pressure sensitivities need the true second one.
66
+ mu_e = jax.lax.custom_root(lambda mu: nlep(mu)-n_charge,
67
+ 0.5*(mu_lo+mu_hi), solve,
68
+ lambda g, y: y/g(jnp.ones_like(y)))
69
+ ke = _kf_of_mu(mu_e, m_e)
70
+ kmu = mu_on * _kf_of_mu(mu_e, m_mu)
71
+ n_e = ke**3 / (3.0 * _PI2)
72
+ n_mu = kmu**3 / (3.0 * _PI2)
73
+ eps_lep = eps_kin_one(ke, m_e) + eps_kin_one(kmu, m_mu) # =0 if kf=0
74
+ return mu_e, n_e, n_mu, eps_lep