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,251 @@
1
+ """Ingestion of tabulated EOS, incl. the CompOSE format (compose.obspm.fr).
2
+
3
+ Reads a cold, beta-equilibrium 1D EOS table into the standard :class:`EOSTable`, so
4
+ any community / MUSES-generated table flows through the same thermodynamically
5
+ consistent h(mu)-interpolation + TOV pipeline as the parametric models.
6
+
7
+ Two entry points:
8
+
9
+ * :func:`load_compose` -- the CompOSE ``eos.nb`` + ``eos.thermo`` pair (the standard
10
+ distribution format). Column convention (Typel et al. CompOSE manual): the
11
+ ``eos.thermo`` first line is ``m_n m_p I_flag``; each data row is
12
+ ``i_t i_nb i_yq Q1 Q2 Q3 Q4 Q5 Q6 Q7 N_add [extra...]`` with
13
+ ``Q1 = p/n_B`` [MeV] and ``Q7 = e/(n_B m_n) - 1`` (internal energy per baryon,
14
+ rest mass included). Hence p = Q1 n_B and eps = (Q7+1) n_B m_n.
15
+ ``eos.nb`` starts with two lines, the indices of its first and last point, then
16
+ one n_B per line; row ``i_nb`` of ``eos.thermo`` is point ``i_nb`` of that range.
17
+ Tested on the real CompOSE eos/116 and eos/188 files (tests/data/compose_*).
18
+
19
+ * :func:`load_simple` -- an unambiguous 3-column ``n_B[fm^-3] eps[MeV/fm^3]
20
+ p[MeV/fm^3]`` text table, for derived tables where the CompOSE columns are not at
21
+ hand.
22
+
23
+ ``write_compose`` emits the eos.nb/eos.thermo pair (for round-trip validation and
24
+ for exporting our parametric EOS to CompOSE consumers).
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import os
29
+ import numpy as np
30
+
31
+ from ..constants import M_N
32
+ from .base import build_h_and_cs2, extend_to_surface, EOSModel, EOSTable
33
+
34
+
35
+ # ---------------- low-level readers (return n[fm^-3], eps, p [MeV/fm^3]) -----------
36
+ def _numbers(line_or_text):
37
+ """Floats of a whitespace-separated text; Fortran ``D`` exponents allowed."""
38
+ return [float(t.replace("D", "E").replace("d", "e")) for t in line_or_text.split()]
39
+
40
+
41
+ def read_compose_nb(path):
42
+ """(index of the first point, n_B array) from a CompOSE ``eos.nb``.
43
+
44
+ The standard file (CompOSE manual v3) has two header lines, the first and the
45
+ last point index, then ``last - first + 1`` values. The one-line form (point
46
+ count, then the values) is what :func:`write_compose` wrote before 2026-10-25
47
+ and is still read. Anything else raises ``ValueError``."""
48
+ with open(path) as fh:
49
+ v = _numbers(fh.read())
50
+ if len(v) >= 3 and v[0].is_integer() and v[1].is_integer() \
51
+ and len(v) - 2 == int(v[1]) - int(v[0]) + 1:
52
+ return int(v[0]), np.asarray(v[2:], float)
53
+ if len(v) >= 2 and v[0].is_integer() and int(v[0]) == len(v) - 1:
54
+ return 1, np.asarray(v[1:], float)
55
+ head = v[:2]
56
+ raise ValueError(f"{path}: header {head} matches neither 'first, last' nor 'count' "
57
+ f"for {len(v)} numbers")
58
+
59
+
60
+ def read_compose(path_dir, thermo="eos.thermo", nb="eos.nb"):
61
+ """Read CompOSE eos.nb + eos.thermo (cold, 1D beta-eq) -> (n, eps, p, m_n).
62
+
63
+ Raises ``ValueError`` if the table has more than one temperature or Y_q index,
64
+ or if an n_B index is out of the ``eos.nb`` range or repeated."""
65
+ nb_path = os.path.join(path_dir, nb) if os.path.isdir(path_dir) else nb
66
+ th_path = os.path.join(path_dir, thermo) if os.path.isdir(path_dir) else thermo
67
+
68
+ i_first, n_arr = read_compose_nb(nb_path)
69
+ with open(th_path) as fh:
70
+ header = fh.readline().split()
71
+ m_n = _numbers(header[0])[0] if header else M_N
72
+ rows = [_numbers(ln) for ln in fh if ln.strip()]
73
+ rows = np.array([r[:11] for r in rows if len(r) >= 11])
74
+ if rows.size == 0:
75
+ raise ValueError(f"{th_path}: no data rows with >= 11 columns")
76
+ if np.unique(rows[:, 0]).size != 1 or np.unique(rows[:, 2]).size != 1:
77
+ raise ValueError(f"{th_path}: not a 1D table (several T or Y_q indices)")
78
+ k = rows[:, 1].astype(int) - i_first # i_nb counts from eos.nb's first index
79
+ if np.any(k < 0) or np.any(k >= n_arr.size) or np.unique(k).size != k.size:
80
+ raise ValueError(f"{th_path}: n_B indices out of the eos.nb range "
81
+ f"[{i_first}, {i_first + n_arr.size - 1}] or repeated")
82
+ Q1 = rows[:, 3] # p / n_B [MeV] (col index 3)
83
+ Q7 = rows[:, 9] # e/(n_B m_n) - 1 (col index 9)
84
+ n = n_arr[k]
85
+ p = Q1 * n # MeV/fm^3
86
+ eps = (Q7 + 1.0) * n * m_n # MeV/fm^3 (incl. rest mass)
87
+ order = np.argsort(n)
88
+ return n[order], eps[order], p[order], m_n
89
+
90
+
91
+ def _count_header_lines(path, sep=","):
92
+ """Number of leading lines of ``path`` that are not data rows.
93
+
94
+ MUSES CMF++ writes its CSV tables **headerless** (``pandas.to_csv(header=False)``
95
+ in ``clean_output.py``), so for a real CMF file this returns 0. A table with a
96
+ text header row (e.g. a hand-made or CompOSE-style export) returns the number of
97
+ lines to skip so that :func:`numpy.genfromtxt` starts on the first data row.
98
+ A UTF-8 BOM (Excel / Windows round-trip) is ignored, and the all-integer
99
+ ``0,1,2,...`` header that ``pandas.to_csv`` emits for an unnamed DataFrame is
100
+ treated as a header, not as a data row. Stops at the first data row.
101
+ """
102
+ with open(path, encoding="utf-8-sig") as fh:
103
+ for i, line in enumerate(fh):
104
+ toks = line.strip().split(sep)
105
+ try:
106
+ vals = [float(tok) for tok in toks]
107
+ except ValueError:
108
+ continue
109
+ if len(vals) > 1 and vals == list(range(len(vals))):
110
+ continue # pandas default header
111
+ return i
112
+ return 0
113
+
114
+
115
+ def read_cmf_csv(path, col_nb=5, col_eps=8, col_p=9, sep=",", skip_header=None):
116
+ """Read a MUSES CMF (or CompOSE-style) CSV EOS table -> (n, eps, p).
117
+
118
+ MUSES CMF++ (v1.1.0) output CSVs are **intentionally headerless**; the
119
+ ``CMF_output_{stable,metastable,unstable}.csv`` layout (1-based columns,
120
+ ``api/OpenAPI_Specifications_CMF.yaml`` schema ``CMF_output_all_EoS_variables``) is
121
+
122
+ 1 T [MeV] 2 mu_B 3 mu_S 4 mu_Q [MeV]
123
+ 5 n_B 6 n_S 7 n_Q [1/fm^3] 8 eps 9 p [MeV/fm^3] 10 s [1/fm^3]
124
+ 11 sigma 12 zeta 13 delta 14 omega 15 phi 16 rho [MeV] 17 Phi_order
125
+ 18 n_B_without_Phi_order 19 n_quark 20 n_octet 21 n_decuplet [1/fm^3]
126
+
127
+ The ``CMF_output_for_Lepton_*.csv`` files carry only columns 1-10 plus 18 (11
128
+ columns), so the (5, 8, 9) default mapping is the same for both families. Column 5
129
+ is the full baryon density (including the Polyakov-loop ``Phi_order`` term in
130
+ mu_B; it is what pairs thermodynamically with eps and p), column 18 excludes it
131
+ (Cruz-Camacho et al. 2409.06837; docs/muses-integration.md).
132
+
133
+ ``skip_header=None`` (default) auto-detects: leading non-numeric lines are skipped,
134
+ so a real headerless CMF file loses no rows (the first row of the default C4 run is
135
+ the mu_B = 922 MeV nuclear-matter onset) while a file with a text header still
136
+ reads correctly. Pass an int to force a fixed number of skipped lines.
137
+ The CMF grid runs over (mu_B, mu_S, mu_Q), so n_B can repeat / be non-monotone and
138
+ the Lepton files include metastable points with p < 0; we keep the physical
139
+ (n, eps, p > 0, finite), sorted, strictly-increasing-density points (for the cold
140
+ beta-eq NS EOS, point CMF at its Lepton/Synthesis output along the NS line).
141
+ """
142
+ if skip_header is None:
143
+ skip_header = _count_header_lines(path, sep)
144
+ d = np.genfromtxt(path, delimiter=sep, skip_header=skip_header, encoding="utf-8-sig")
145
+ d = np.atleast_2d(d)
146
+ need = max(col_nb, col_eps, col_p)
147
+ if d.size == 0 or d.shape[1] < need:
148
+ raise ValueError(f"{path}: expected >= {need} numeric columns after skipping "
149
+ f"{skip_header} header line(s); got shape {d.shape}")
150
+ n, eps, p = d[:, col_nb - 1], d[:, col_eps - 1], d[:, col_p - 1]
151
+ ok = (n > 0) & (eps > 0) & (p > 0) & np.isfinite(n) & np.isfinite(eps) & np.isfinite(p)
152
+ if not np.any(ok):
153
+ raise ValueError(f"{path}: no rows with finite n_B, eps, p > 0 in columns "
154
+ f"({col_nb}, {col_eps}, {col_p}); is this a CMF EOS table?")
155
+ n, eps, p = n[ok], eps[ok], p[ok]
156
+ o = np.argsort(n)
157
+ n, eps, p = n[o], eps[o], p[o]
158
+ keep = np.concatenate([[True], np.diff(n) > 1e-12]) # dedupe repeated n_B
159
+ return n[keep], eps[keep], p[keep]
160
+
161
+
162
+ def read_simple(path):
163
+ """Read a 3-column n_B[fm^-3] eps[MeV/fm^3] p[MeV/fm^3] table -> (n, eps, p)."""
164
+ d = np.loadtxt(path, comments="#", ndmin=2)
165
+ n, eps, p = d[:, 0], d[:, 1], d[:, 2]
166
+ o = np.argsort(n)
167
+ return n[o], eps[o], p[o]
168
+
169
+
170
+ # ---------------- writer (for round-trip / export) ----------------
171
+ def write_compose(path_dir, n, eps, p, m_n=M_N, m_p=M_N):
172
+ """Write eos.nb + eos.thermo for a cold 1D EOS (n[fm^-3], eps, p [MeV/fm^3])."""
173
+ os.makedirs(path_dir, exist_ok=True)
174
+ n, eps, p = map(np.asarray, (n, eps, p))
175
+ with open(os.path.join(path_dir, "eos.nb"), "w") as fh:
176
+ fh.write(f"1\n{n.size}\n") # first and last point index
177
+ for v in n:
178
+ fh.write(f"{v:.10e}\n")
179
+ Q1 = p / n
180
+ Q7 = eps / (n * m_n) - 1.0
181
+ z = np.zeros_like(n)
182
+ with open(os.path.join(path_dir, "eos.thermo"), "w") as fh:
183
+ fh.write(f"{m_n:.6f} {m_p:.6f} 1\n")
184
+ for j in range(n.size):
185
+ fh.write(f"1 {j + 1} 1 {Q1[j]:.10e} {z[j]:.1e} {z[j]:.1e} {z[j]:.1e} "
186
+ f"{z[j]:.1e} {z[j]:.1e} {Q7[j]:.10e} 0\n")
187
+
188
+
189
+ # ---------------- table / model construction ----------------
190
+ def eos_table_from_arrays(n, eps, p, n_surface=1e-7, gamma_crust=1.3,
191
+ xp=None) -> EOSTable:
192
+ """Build an EOSTable from (n[fm^-3], eps, p [MeV/fm^3]); optional surface tail.
193
+ ``xp`` is passed to :func:`build_h_and_cs2`.
194
+
195
+ eps and p are made non-decreasing by a running maximum. The table starts at
196
+ the first row with p > 0; rows below it are dropped. A run of equal pressures
197
+ at the bottom (from the running maximum) is a layer of zero thickness: only its
198
+ first row is kept, so the first cell has a positive h-width. The first row is
199
+ the only one of the run whose p is its own; the others carry p[0] from the
200
+ running maximum with their own, larger eps.
201
+ Positive pressures are not floored. Until 2026-10-25 p was floored at 1e-12
202
+ MeV/fm^3: a table with two or more rows below that started with cells of zero
203
+ h-width, and the TOV solve ended (at h[0]) inside one of them, where the
204
+ tidal variable's dh/dx is 0/0, so Lambda was NaN while M and R stayed finite
205
+ (docs/devlog/2026-10-25-compose-header-floor.md)."""
206
+ n = np.asarray(n, float)
207
+ eps = np.asarray(eps, float)
208
+ p = np.asarray(p, float)
209
+ pos = np.flatnonzero(p > 0)
210
+ if pos.size == 0:
211
+ raise ValueError("eos_table_from_arrays: no row with p > 0")
212
+ n, eps, p = n[pos[0]:], eps[pos[0]:], p[pos[0]:]
213
+ eps = np.maximum.accumulate(eps)
214
+ p = np.maximum.accumulate(p)
215
+ j = int(np.searchsorted(p, p[0], side="right")) # first row above the bottom run
216
+ n, eps, p = (np.concatenate([a[:1], a[j:]]) for a in (n, eps, p))
217
+ if p.size < 2:
218
+ raise ValueError("eos_table_from_arrays: fewer than two rows with distinct p > 0")
219
+ if n_surface is not None and n[0] > n_surface:
220
+ n, eps, p = extend_to_surface(n, eps, p, n_surface=n_surface,
221
+ gamma_crust=gamma_crust)
222
+ if xp is None:
223
+ return build_h_and_cs2(n, eps, p)
224
+ return build_h_and_cs2(n, eps, p, xp=xp)
225
+
226
+
227
+ def load_compose(path_dir, **kw) -> EOSTable:
228
+ n, eps, p, _ = read_compose(path_dir)
229
+ return eos_table_from_arrays(n, eps, p, **kw)
230
+
231
+
232
+ def load_simple(path, **kw) -> EOSTable:
233
+ return eos_table_from_arrays(*read_simple(path), **kw)
234
+
235
+
236
+ def load_cmf(path, **kw) -> EOSTable:
237
+ """Load a MUSES CMF CSV EOS table into an EOSTable (see :func:`read_cmf_csv`)."""
238
+ return eos_table_from_arrays(*read_cmf_csv(path), **kw)
239
+
240
+
241
+ class TabularEOS(EOSModel):
242
+ """Wrap a loaded EOSTable as an EOSModel (for the RIFT adapter, families, etc.)."""
243
+ name = "TabularEOS"
244
+
245
+ def __init__(self, table: EOSTable, name=None):
246
+ self._table = table
247
+ if name:
248
+ self.name = name
249
+
250
+ def eos_table(self, params: dict = None):
251
+ return self._table
@@ -0,0 +1,67 @@
1
+ """beta-equilibrium composition and Landau effective masses for cooling.
2
+
3
+ ``cooling_composition(model, params)`` returns, on the model's composition
4
+ grid, the particle fractions per baryon and the Landau effective masses at
5
+ the Fermi surface (units of the bare nucleon mass). Prescriptions:
6
+
7
+ * Skyrme (sk, skx): exact for the functional, h2m/m*_q = h2m + c1 n + c2 n_q.
8
+ * RMF (rmf, rmfwr) and DD-RMF (dd, ddf): m*_q = E*_Fq = sqrt(kF_q^2 + m_D^2).
9
+ * metamodel (mm): Margueron+2018 form with m*_sat/m = 0.75,
10
+ Delta m*_sat/m = 0.10 (see :mod:`nmbackend.eos.metamodel`).
11
+
12
+ ``pack_d0`` / ``unpack_d0`` store (x_p, x_mu, m*_n, m*_p) of one draw on the
13
+ fixed grid ``D0_GRID`` (the paper-6 x_p grid), float32, NaN above the model's
14
+ grid. x_n = 1 - x_p and x_e = x_p - x_mu are not stored.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from typing import NamedTuple
19
+
20
+ import numpy as np
21
+ import jax.numpy as jnp
22
+
23
+ __all__ = ["CoolingComposition", "cooling_composition", "D0_GRID",
24
+ "D0_FIELDS", "pack_d0", "unpack_d0"]
25
+
26
+ #: fm^-3; paper 6 c1_pilot2 N_GRID
27
+ D0_GRID = np.linspace(0.08, 1.2, 57)
28
+ D0_FIELDS = ("x_p", "x_mu", "mst_n", "mst_p")
29
+
30
+
31
+ class CoolingComposition(NamedTuple):
32
+ """Fractions per baryon and Landau masses m*/m on a density grid (fm^-3).
33
+
34
+ Has the fields of :class:`nmbackend.eos.Composition`, so
35
+ :func:`nmbackend.durca.durca_onset` accepts it."""
36
+ n: jnp.ndarray
37
+ x_n: jnp.ndarray
38
+ x_p: jnp.ndarray
39
+ x_e: jnp.ndarray
40
+ x_mu: jnp.ndarray
41
+ mst_n: jnp.ndarray
42
+ mst_p: jnp.ndarray
43
+
44
+
45
+ def cooling_composition(model, params=None) -> CoolingComposition:
46
+ """Composition and Landau masses of ``model`` (a MetaModelEOS, RMFTEOS,
47
+ DDRMFEOS or SkyrmeEOS) at ``params``. JAX-traceable."""
48
+ c = model.composition(params)
49
+ mn, mp = model.landau_masses(params, c)
50
+ return CoolingComposition(n=c.n, x_n=1.0 - c.x_p, x_p=c.x_p, x_e=c.x_e,
51
+ x_mu=c.x_mu, mst_n=mn, mst_p=mp)
52
+
53
+
54
+ def pack_d0(cc, n_grid=D0_GRID, dtype=np.float32):
55
+ """(4, len(n_grid)) array of D0_FIELDS, linear in n, NaN outside ``cc.n``."""
56
+ n = np.asarray(cc.n, float)
57
+ return np.stack([np.interp(n_grid, n, np.asarray(getattr(cc, f), float),
58
+ left=np.nan, right=np.nan)
59
+ for f in D0_FIELDS]).astype(dtype)
60
+
61
+
62
+ def unpack_d0(arr, n_grid=D0_GRID) -> CoolingComposition:
63
+ """Inverse of :func:`pack_d0` (float64 NumPy arrays)."""
64
+ x_p, x_mu, mn, mp = np.asarray(arr, float)
65
+ return CoolingComposition(n=np.asarray(n_grid, float), x_n=1.0 - x_p,
66
+ x_p=x_p, x_e=x_p - x_mu, x_mu=x_mu,
67
+ mst_n=mn, mst_p=mp)
nmbackend/eos/crust.py ADDED
@@ -0,0 +1,318 @@
1
+ """Tabulated SLy crust joined to a uniform-matter core.
2
+
3
+ Crust: the SLy unified EOS (BPS + Haensel-Pichon outer crust, Douchin &
4
+ Haensel 2001 inner crust, astro-ph/0111092), ``data/crust_sly_dh2001.dat``.
5
+ Below ``n_t`` the table is used as is. This is the fixed crust of the paper-1
6
+ crust+cEFT ensemble (n_t = 0.055 fm^-3 = 0.34 n_sat).
7
+
8
+ Join (the P(rho) matching of Fortin et al. 2016, arXiv:1604.01944, Sec. II.B):
9
+
10
+ * The core table starts at the static density n_j = ``bridge`` * n_t (the
11
+ models put a grid node exactly there).
12
+ * Join density n*: n_j if the core pressure there is at least
13
+ p_t (eps_j/eps_t)^GAMMA_MIN, else the first density above n_j where the core
14
+ reaches that curve (found by interpolation, so n* is continuous in the core
15
+ parameters). Core nodes in [n_j, 2 n_j) move affinely in ln n onto
16
+ [n*, 2 n_j) and take the core values there; with n* = n_j nothing moves.
17
+ Node count and order never change, so the table is continuous in the
18
+ parameters.
19
+ * Between the crust point (eps_t, p_t) and the core at n*, p is a power law
20
+ in eps (index >= GAMMA_MIN) on fixed segment nodes; p is continuous and
21
+ strictly increasing.
22
+ * n follows the first law, d ln n = d eps/(eps + p), along the crust and the
23
+ segment. It then misses the core n* by a constant factor f (|f - 1| is
24
+ 1e-3 to 1e-2). We rescale the crust and segment n by f (Fortin et al.
25
+ Eq. 11, applied on the crust side).
26
+
27
+ * Rejection: a core that does not reach p_t (eps/eps_t)^GAMMA_MIN below
28
+ 2 n_j e^-0.1, or whose pressure is at the model floor (1e-9 MeV fm^-3) or not
29
+ increasing anywhere between the join n* and 2 n_j, is outside the model's
30
+ validity above the crust. The table is then NaN (under jit) or InvalidCoreError is raised
31
+ (eager); samplers treat both as failed draws. Cores just inside this
32
+ boundary (low L) join with slope kinks of up to ~6% in Lambda(L).
33
+
34
+ Unstable core (:func:`monotone_core`, :func:`finish_table`): the models floor
35
+ and cummax the core pressure, so where the raw pressure falls with density the
36
+ table has a plateau (cs2 = 1e-8, first-law residual up to ~4e-2). A core whose
37
+ raw pressure falls by more than roundoff, or sits at the floor, above 2 n_j is
38
+ rejected in the same way when a star centred at the onset of that interval
39
+ lies below the maximum-mass star (UnstableCoreError when eager). Accepted cores then carry no plateau
40
+ below the maximum-mass star, and Lambda approaches the rejection boundary
41
+ smoothly. ``allow_unstable_core=True`` on the model keeps the plateau tables.
42
+
43
+ The TOV equations see only p(eps), which is the core's own above n_j; the
44
+ core baryon density, and hence the composition and dUrca onset density, are
45
+ untouched. Vary ``n_t`` to estimate the crust-matching systematic; above
46
+ n_t = 0.076 fm^-3 (the SLy crust-core edge) the "crust" includes SLy4 core
47
+ rows of the table.
48
+ """
49
+ from __future__ import annotations
50
+
51
+ import math
52
+ import os
53
+ import warnings
54
+
55
+ import numpy as np
56
+ import jax
57
+ import jax.numpy as jnp
58
+
59
+ N_T_DEFAULT = 0.055 # fm^-3, 0.34 n_sat (paper 1, GKKS arXiv:2512.18044)
60
+ N_FLOOR = 3e-10 # fm^-3, lowest crust node: p = 4e-12 MeV fm^-3, chosen
61
+ # above the 1e-12 floor compose.eos_table_from_arrays
62
+ # had until 2026-10-25
63
+ BRIDGE = 1.25 # the core table starts at n_j = BRIDGE * n_t
64
+ GAMMA_MIN = 0.5 # the segment p ~ eps^Gamma has Gamma >= GAMMA_MIN
65
+ REMAP = 2.0 # core nodes in [n_j, REMAP n_j) may move (see join)
66
+ P_FLOOR = 1e-9 # MeV fm^-3, the pressure floor of the core models
67
+ JOIN_CAP = 0.1 # n* <= REMAP n_j e^-JOIN_CAP
68
+ P_DROP_RTOL = 1e-10 # pressure drops below this relative size are roundoff
69
+ M_LOW = 0.5 # Msun; below it M falls with h_c only below the M_min star
70
+ H_TOP = 0.92 # tov.default_hc_grid stops at H_TOP h_max
71
+ N_CRUST_PTS = 150
72
+ N_SEG_PTS = 16 # interior nodes of the power-law segment
73
+
74
+ _G_CM3_TO_MEVFM3 = 5.60958860e-13 # (1 g/cm^3) c^2 in MeV/fm^3
75
+ _DYN_CM2_TO_MEVFM3 = 6.241509074e-34
76
+ _TABLE = None
77
+
78
+
79
+ def sly_crust():
80
+ """SLy crust table (n [fm^-3], eps, p [MeV/fm^3]) as NumPy arrays."""
81
+ global _TABLE
82
+ if _TABLE is None:
83
+ path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data",
84
+ "crust_sly_dh2001.dat")
85
+ n, rho, P = np.loadtxt(path, comments="#", unpack=True)
86
+ _TABLE = (n, rho * _G_CM3_TO_MEVFM3, P * _DYN_CM2_TO_MEVFM3)
87
+ return _TABLE
88
+
89
+
90
+ def crust_nodes(n_t=N_T_DEFAULT, n_floor=N_FLOOR, n_pts=N_CRUST_PTS):
91
+ """Crust (n, eps, p) on a log grid from ``n_floor`` to ``n_t`` inclusive."""
92
+ n0, e0, p0 = sly_crust()
93
+ if not n0[0] <= n_floor < n_t <= n0[-1]:
94
+ raise ValueError(f"n_t={n_t} outside the crust table")
95
+ n = np.geomspace(n_floor, n_t, n_pts)
96
+ ln = np.log(n)
97
+ e = np.exp(np.interp(ln, np.log(n0), np.log(e0)))
98
+ p = np.exp(np.interp(ln, np.log(n0), np.log(p0)))
99
+ return n, e, p
100
+
101
+
102
+ def attach_crust(n, eps, p, n_t=N_T_DEFAULT, n_floor=N_FLOOR,
103
+ n_crust_pts=N_CRUST_PTS, n_seg=N_SEG_PTS, n_quad=257,
104
+ gamma_min=GAMMA_MIN):
105
+ """Join the SLy crust below ``n_t`` to a core (n, eps, p) whose first node
106
+ is n_j = BRIDGE * n_t (fm^-3, MeV/fm^3). JAX-traceable in the core arrays;
107
+ the node count is static. Returns the combined (n, eps, p)."""
108
+ n, eps, p = jnp.asarray(n), jnp.asarray(eps), jnp.asarray(p)
109
+ nc, ec, pc = crust_nodes(n_t, n_floor, n_crust_pts)
110
+ et, pt = ec[-1], pc[-1]
111
+ ln, le, lp = jnp.log(n), jnp.log(eps), jnp.log(p)
112
+ lnj = math.log(join_density(n_t))
113
+ lnw = lnj + math.log(REMAP)
114
+ bad = join_invalid(n, eps, p, n_t, gamma_min)
115
+ # join density n*: n_j if the core there lies on or above
116
+ # p_t (eps/eps_t)^gamma_min, else the first crossing of that curve
117
+ # (linear in ln n between core nodes, so continuous in the parameters)
118
+ lnx = jnp.minimum(_join_lnn(ln, le, lp, et, pt, gamma_min), lnw - JOIN_CAP)
119
+ # core nodes in [n_j, REMAP n_j) move affinely (in ln n) onto [n*, REMAP n_j)
120
+ # and take the core values there (log-log interpolation); the identity when
121
+ # n* = n_j, and continuous in n* otherwise
122
+ inw = ln < lnw
123
+ lm = jnp.where(inw, lnx + (ln - ln[0]) * (lnw - lnx) / (lnw - ln[0]), ln)
124
+ n = jnp.where(inw, jnp.exp(lm), n)
125
+ eps = jnp.where(inw, jnp.exp(jnp.interp(lm, ln, le)), eps)
126
+ p = jnp.where(inw, jnp.exp(jnp.interp(lm, ln, lp)), p)
127
+ # power law p(eps) from the crust point to the (moved) first core node
128
+ lr = jnp.log(eps[0] / et)
129
+ gam = jnp.log(p[0] / pt) / lr
130
+ # ln n - ln n_t = int deps/(eps + p) along the segment, on a fine s grid
131
+ sq = jnp.linspace(0.0, 1.0, n_quad)
132
+ eq = et * jnp.exp(sq * lr)
133
+ integrand = eq / (eq + pt * (eq / et) ** gam) * lr # d/ds
134
+ cum = jnp.concatenate([jnp.zeros(1), jnp.cumsum(
135
+ 0.5 * (integrand[1:] + integrand[:-1]) * jnp.diff(sq))])
136
+ f = n[0] / (n_t * jnp.exp(cum[-1])) # rescales crust + segment n
137
+ s = jnp.linspace(0.0, 1.0, n_seg + 2)[1:-1]
138
+ es = et * jnp.exp(s * lr)
139
+ ns = f * n_t * jnp.exp(jnp.interp(s, sq, cum))
140
+ ps = pt * (es / et) ** gam
141
+ nan = jnp.where(bad, jnp.nan, 0.0) # invalid core: NaN table
142
+ return (jnp.concatenate([f * jnp.asarray(nc), ns, n]) + nan,
143
+ jnp.concatenate([jnp.asarray(ec), es, eps]) + nan,
144
+ jnp.concatenate([jnp.asarray(pc), ps, p]) + nan)
145
+
146
+
147
+ class InvalidCoreError(ValueError):
148
+ """The uniform-matter core cannot be joined to the crust (see
149
+ :func:`join_invalid`); the draw is outside the model's validity."""
150
+
151
+
152
+ class UnstableCoreError(InvalidCoreError):
153
+ """The core's raw pressure falls with density below the maximum-mass star
154
+ (see :func:`monotone_core`). Under jit such a table is NaN like any other
155
+ rejected core; an eager rebuild tells the two apart."""
156
+
157
+
158
+ def _join_lnn(ln, le, lp, et, pt, gamma_min):
159
+ """ln n*: ln n_j if the core there lies on or above p_t (eps/eps_t)^gamma_min,
160
+ else the first crossing of that curve (linear in ln n between nodes, so
161
+ continuous in the parameters); +inf if there is none."""
162
+ g = lp - math.log(pt) - gamma_min * (le - math.log(et))
163
+ up = (ln > ln[0]) & (g >= 0.0)
164
+ k = jnp.maximum(jnp.argmax(up), 1)
165
+ t = jnp.clip(-g[k - 1] / jnp.where(g[k] > g[k - 1], g[k] - g[k - 1], 1.0), 0.0, 1.0)
166
+ lnx = jnp.where(g[0] >= 0.0, ln[0], ln[k - 1] + t * (ln[k] - ln[k - 1]))
167
+ return jnp.where((g[0] >= 0.0) | jnp.any(up), lnx, jnp.inf)
168
+
169
+
170
+ def join_invalid(n, eps, p, n_t=N_T_DEFAULT, gamma_min=GAMMA_MIN):
171
+ """True if :func:`attach_crust` must reject this core (see
172
+ :class:`InvalidCoreError`). JAX-traceable; ``n`` starts at n_j.
173
+
174
+ Rejected: the join density n* (where the core first reaches
175
+ p_t (eps/eps_t)^gamma_min) lies beyond the cap 2 n_j e^-0.1, or the core
176
+ pressure is at the floor or not increasing anywhere between n* and 2 n_j.
177
+ Below n* the extended crust replaces the core, so a floor there is allowed:
178
+ low-L cores are mechanically unstable just above n_t, where the real crust
179
+ extends further."""
180
+ n, eps, p = jnp.asarray(n), jnp.asarray(eps), jnp.asarray(p)
181
+ _, ec, pc = crust_nodes(n_t)
182
+ et, pt = ec[-1], pc[-1]
183
+ ln = jnp.log(n)
184
+ lnw = math.log(join_density(n_t) * REMAP)
185
+ lnx = _join_lnn(ln, jnp.log(eps), jnp.log(p), et, pt, gamma_min)
186
+ above = (ln < lnw) & (ln >= lnx - 1e-12)
187
+ flat = jnp.any(above[1:] & above[:-1] & (jnp.diff(p) <= 0.0))
188
+ floor = jnp.any(above & (p <= P_FLOOR * 1.001))
189
+ return flat | floor | (lnx > lnw - JOIN_CAP)
190
+
191
+
192
+ def join_density(n_t=N_T_DEFAULT):
193
+ """n_j, where the core table starts (fm^-3)."""
194
+ return BRIDGE * n_t
195
+
196
+
197
+ def core_grid(n_grid, n_t=N_T_DEFAULT):
198
+ """Static core grid for the crust join: n_j, then the nodes of ``n_grid``
199
+ above it (a node closer than 1% to n_j is dropped)."""
200
+ nj = join_density(n_t)
201
+ g = np.asarray(n_grid)
202
+ return jnp.asarray(np.concatenate([[nj], g[g > nj * 1.01]]))
203
+
204
+
205
+ CRUSTS = ("sly", "polytrope")
206
+
207
+
208
+ def check_crust(crust, n_surface=None):
209
+ """Validate ``crust``; warn that a non-default ``n_surface`` only acts with
210
+ the polytrope (``n_surface=None`` still disables the low-density part)."""
211
+ if crust not in CRUSTS:
212
+ raise ValueError(f"crust={crust!r}; use one of {CRUSTS}")
213
+ if crust == "sly" and n_surface is not None and n_surface != 1e-7:
214
+ warnings.warn("n_surface is ignored with crust='sly' (the SLy table "
215
+ f"starts at {N_FLOOR} fm^-3)", stacklevel=3)
216
+ return crust
217
+
218
+
219
+ def monotone_core(n, p, n_t=N_T_DEFAULT):
220
+ """Floor and cummax the raw core pressure ``p`` (MeV fm^-3) on ``n``
221
+ (fm^-3). Returns (p_monotone, ln n_u): n_u is where the first unstable
222
+ interval above REMAP n_j begins, +inf if there is none. An interval is a
223
+ run of nodes where the raw p is at the floor or more than P_DROP_RTOL below
224
+ the running maximum; it begins at the node that set the maximum.
225
+ JAX-traceable."""
226
+ n, p = jnp.asarray(n), jnp.asarray(p)
227
+ pf = jnp.maximum(p, P_FLOOR)
228
+ pm = jax.lax.cummax(pf)
229
+ ln = jnp.log(n)
230
+ drop = (pf < pm * (1.0 - P_DROP_RTOL)) | (pf <= P_FLOOR * 1.001)
231
+ idx = jnp.arange(n.shape[0])
232
+ anchor = jax.lax.cummax(jnp.where(drop, 0, idx)) # last node not in a drop
233
+ above = drop & (ln >= math.log(REMAP * join_density(n_t)))
234
+ return pm, jnp.min(jnp.where(above, ln[anchor], jnp.inf))
235
+
236
+
237
+ def unstable_below_mmax(table, ln_nu):
238
+ """True if a star centred at n_u lies below the maximum-mass star: M rises
239
+ with h_c there, or M < M_LOW (the falling branch below the minimum-mass
240
+ star). Onsets above H_TOP h_max, beyond the stellar sequences of
241
+ :func:`nmbackend.tov.default_hc_grid`, are kept. Solves one star, only
242
+ where needed (under vmap it solves a harmless star at h_max/2 instead).
243
+ JAX-traceable."""
244
+ from ..tov.solver import solve_structure
245
+
246
+ def check(t, hu):
247
+ m, dm = jax.jvp(lambda h: solve_structure(t, h).M_msun, (hu,),
248
+ (jnp.ones_like(hu),))
249
+ return (dm > 0.0) | (m < M_LOW)
250
+
251
+ hmax = table.h[-1]
252
+ hu = jnp.interp(jnp.minimum(ln_nu, jnp.log(table.n[-1])),
253
+ jnp.log(table.n), table.h)
254
+ ok = (jnp.isfinite(ln_nu) & (hu < H_TOP * hmax)
255
+ & jnp.all(jnp.isfinite(table.p)))
256
+ hu = jnp.where(ok, hu, 0.5 * hmax)
257
+ try: # eager: skip the solve if stable
258
+ if not bool(ok):
259
+ return jnp.asarray(False)
260
+ return check(table, hu)
261
+ except jax.errors.ConcretizationTypeError:
262
+ return jax.lax.cond(ok, check, lambda t, h: jnp.asarray(False),
263
+ table, hu)
264
+
265
+
266
+ def _raise_if(bad, err, msg):
267
+ try: # eager call: raise; jit: NaN table
268
+ if bool(bad):
269
+ raise err(msg)
270
+ except jax.errors.ConcretizationTypeError:
271
+ pass
272
+
273
+
274
+ def finish_table(n, eps, p, crust, n_t, n_surface, gamma_crust,
275
+ ln_nu=math.inf, allow_unstable=False):
276
+ """Low-density completion shared by the uniform-matter models, then the
277
+ EOSTable. ``crust="sly"``: :func:`attach_crust` (the core must start at
278
+ :func:`join_density`). ``crust="polytrope"``: the legacy surface continuation
279
+ :func:`nmbackend.eos.base.extend_to_surface`. ``n_surface=None`` skips
280
+ both (table truncated at the core grid start).
281
+
282
+ ``ln_nu`` is the unstable-interval onset from :func:`monotone_core`. Unless
283
+ ``allow_unstable``, the table is rejected (InvalidCoreError when eager, NaN
284
+ under jit) if :func:`unstable_below_mmax`."""
285
+ return raise_rejected(*finish_table_flags(
286
+ n, eps, p, crust, n_t, n_surface, gamma_crust, ln_nu, allow_unstable))
287
+
288
+
289
+ def finish_table_flags(n, eps, p, crust, n_t, n_surface, gamma_crust,
290
+ ln_nu=math.inf, allow_unstable=False):
291
+ """:func:`finish_table` without the raise, for use inside jit: returns
292
+ (table, bad_join, bad_unstable), with a NaN table if either flag is set.
293
+ :func:`raise_rejected` then raises when the flags are concrete."""
294
+ from .base import EOSTable, build_h_and_cs2, extend_to_surface
295
+ bad_join = jnp.asarray(False)
296
+ if n_surface is not None:
297
+ if crust == "sly":
298
+ n, eps, p = attach_crust(n, eps, p, n_t=n_t)
299
+ bad_join = ~jnp.all(jnp.isfinite(p))
300
+ else:
301
+ n, eps, p = extend_to_surface(n, eps, p, n_surface=n_surface,
302
+ gamma_crust=gamma_crust)
303
+ table = build_h_and_cs2(n, eps, p)
304
+ if allow_unstable:
305
+ return table, bad_join, jnp.asarray(False)
306
+ bad = unstable_below_mmax(table, ln_nu)
307
+ return EOSTable(*(jnp.where(bad, jnp.nan, a) for a in table)), bad_join, bad
308
+
309
+
310
+ def raise_rejected(table, bad_join, bad_unstable):
311
+ """Raise InvalidCoreError / UnstableCoreError for concrete flags from
312
+ :func:`finish_table_flags`; under a trace, return the (NaN) table."""
313
+ _raise_if(bad_join, InvalidCoreError, "core invalid above the crust (p at "
314
+ "the floor or not increasing near n_j)")
315
+ _raise_if(bad_unstable, UnstableCoreError, "core mechanically unstable "
316
+ "(dp/dn <= 0) below the "
317
+ "maximum-mass central density")
318
+ return table