nmbackend 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nmbackend/__init__.py +22 -0
- nmbackend/adapters/__init__.py +4 -0
- nmbackend/adapters/rift.py +95 -0
- nmbackend/constants.py +55 -0
- nmbackend/cooling/README.md +159 -0
- nmbackend/cooling/__init__.py +13 -0
- nmbackend/cooling/build_nscool.sh +51 -0
- nmbackend/cooling/isothermal.py +76 -0
- nmbackend/cooling/nscool_nmbackend.patch +310 -0
- nmbackend/cooling/physics/__init__.py +18 -0
- nmbackend/cooling/physics/_spline.py +71 -0
- nmbackend/cooling/physics/blanket.py +66 -0
- nmbackend/cooling/physics/conduct.py +196 -0
- nmbackend/cooling/physics/core_conduct.py +68 -0
- nmbackend/cooling/physics/core_nu.py +268 -0
- nmbackend/cooling/physics/crust.py +113 -0
- nmbackend/cooling/physics/crust_nu.py +93 -0
- nmbackend/cooling/physics/curve.py +42 -0
- nmbackend/cooling/physics/envelope.py +37 -0
- nmbackend/cooling/physics/gaps.py +164 -0
- nmbackend/cooling/physics/geometry.py +131 -0
- nmbackend/cooling/physics/heat.py +125 -0
- nmbackend/cooling/physics/native.py +138 -0
- nmbackend/cooling/physics/reference.py +53 -0
- nmbackend/cooling/physics/star.py +225 -0
- nmbackend/cooling/physics/superfluid.py +41 -0
- nmbackend/cooling/physics/whole.py +136 -0
- nmbackend/cooling/runner.py +583 -0
- nmbackend/cooling/validate.py +120 -0
- nmbackend/data/crust_sly_dh2001.dat +81 -0
- nmbackend/data/frib_scenario_ladder.yaml +100 -0
- nmbackend/durca.py +111 -0
- nmbackend/ejecta.py +614 -0
- nmbackend/eos/__init__.py +19 -0
- nmbackend/eos/base.py +523 -0
- nmbackend/eos/compose.py +251 -0
- nmbackend/eos/coolcomp.py +67 -0
- nmbackend/eos/crust.py +318 -0
- nmbackend/eos/ddrmf.py +388 -0
- nmbackend/eos/hybrid.py +173 -0
- nmbackend/eos/leptons.py +74 -0
- nmbackend/eos/metamodel.py +303 -0
- nmbackend/eos/polytrope.py +33 -0
- nmbackend/eos/rmft.py +450 -0
- nmbackend/eos/skyrme.py +352 -0
- nmbackend/inference/__init__.py +13 -0
- nmbackend/inference/fisher.py +174 -0
- nmbackend/inference/synthetic.py +83 -0
- nmbackend/ipad.py +102 -0
- nmbackend/lab_likelihood.py +587 -0
- nmbackend/nscool_io.py +112 -0
- nmbackend/postmerger.py +264 -0
- nmbackend/priors/__init__.py +16 -0
- nmbackend/priors/bridge.py +437 -0
- nmbackend/priors/bridge_jax.py +435 -0
- nmbackend/priors/gp_pca.py +325 -0
- nmbackend/reference/__init__.py +11 -0
- nmbackend/reference/reprimand.py +108 -0
- nmbackend/reference/scipy_tov.py +289 -0
- nmbackend/rift/__init__.py +26 -0
- nmbackend/rift/compressed.py +194 -0
- nmbackend/rift/evidence.py +276 -0
- nmbackend/rift/sequence.py +428 -0
- nmbackend/rotating/__init__.py +7 -0
- nmbackend/rotating/rns.py +197 -0
- nmbackend/rotating/tabulated.py +249 -0
- nmbackend/thermal/__init__.py +1 -0
- nmbackend/thermal/diffusion.py +86 -0
- nmbackend/tov/__init__.py +15 -0
- nmbackend/tov/central.py +72 -0
- nmbackend/tov/family.py +155 -0
- nmbackend/tov/phase_transition.py +93 -0
- nmbackend/tov/solver.py +475 -0
- nmbackend/validation/__init__.py +5 -0
- nmbackend/validation/model_diagnostic.py +67 -0
- nmbackend/validation/reference_matrix.py +216 -0
- nmbackend-0.4.0.dist-info/METADATA +168 -0
- nmbackend-0.4.0.dist-info/RECORD +81 -0
- nmbackend-0.4.0.dist-info/WHEEL +5 -0
- nmbackend-0.4.0.dist-info/licenses/LICENSE +21 -0
- nmbackend-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"""Neutron-star EOS *sequence* I/O for RIFT (and beyond).
|
|
2
|
+
|
|
3
|
+
Two layers:
|
|
4
|
+
|
|
5
|
+
* ``NSSequence`` + :func:`write_nss` -- a robust, self-describing, efficient format
|
|
6
|
+
that stores every quantity as a function of **central pseudo-enthalpy h_c** (which
|
|
7
|
+
is monotone along the sequence), so M(h_c), R(h_c), Lambda(h_c) are single-valued
|
|
8
|
+
and branch structure (twin stars / phase transitions) is explicit via a ``stable``
|
|
9
|
+
flag. Lookups M -> Lambda are **branch-aware**. Regular ``(n_eos, n_pts,
|
|
10
|
+
n_fields)`` array -> contiguous, lazy-sliceable, vectorizable. See
|
|
11
|
+
docs/rift-sequence-audit.md.
|
|
12
|
+
|
|
13
|
+
* :func:`write_landry_legacy` + ``LandryCompat`` -- emit / read the exact
|
|
14
|
+
``EOSSequenceLandry`` HDF5 used by today's RIFT, so the new backend drops into the
|
|
15
|
+
existing tabular hyperpipeline unchanged. We write only the **stable branch**, so
|
|
16
|
+
RIFT's single-valued M->Lambda interpolation is correct by construction (fixing the
|
|
17
|
+
twin-star bug without touching RIFT code).
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import abc
|
|
22
|
+
import json
|
|
23
|
+
import datetime
|
|
24
|
+
import numpy as np
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
import h5py
|
|
28
|
+
_HAVE_H5PY = True
|
|
29
|
+
except Exception: # pragma: no cover
|
|
30
|
+
_HAVE_H5PY = False
|
|
31
|
+
|
|
32
|
+
import jax.numpy as jnp
|
|
33
|
+
|
|
34
|
+
from ..tov.family import build_family, default_hc_grid, _probe_masses
|
|
35
|
+
from .. import __version__ as _NMB_VERSION
|
|
36
|
+
|
|
37
|
+
NSS_FIELDS = ["hc", "M", "R", "Lambda", "M_b", "I", "rho_c", "cs2_c", "stable"]
|
|
38
|
+
NSS_UNITS = {"hc": "dimensionless", "M": "Msun", "R": "km", "Lambda": "dimensionless",
|
|
39
|
+
"M_b": "Msun", "I": "g cm^2", "rho_c": "fm^-3", "cs2_c": "c^2",
|
|
40
|
+
"stable": "bool"}
|
|
41
|
+
|
|
42
|
+
# 1 MeV/fm^3 -> g/cm^3 (i.e. /c^2), and baryon rest-mass density factor (m_b=1.66e-24 g)
|
|
43
|
+
_MEVFM3_TO_GCM3 = 1.602176634e33 / (2.99792458e10) ** 2 # ~1.7827e12
|
|
44
|
+
_NB_TO_GCM3 = 1e39 * 1.66e-24 # n[fm^-3] -> g/cm^3
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# ---------------- build per-EOS sequence arrays ----------------
|
|
48
|
+
def _sequence_stable(hc, M, R, Lam):
|
|
49
|
+
"""Stable rows from the sequence itself.
|
|
50
|
+
|
|
51
|
+
A row is stable if it is finite with M > 0 and heavier than the previous
|
|
52
|
+
finite row (the first finite row: lighter than the next one), and it is not
|
|
53
|
+
before ``i_min``. The backward difference keeps the M_max row. A failed
|
|
54
|
+
solve (NaN row) is skipped: the row after it is compared with the last
|
|
55
|
+
finite row.
|
|
56
|
+
|
|
57
|
+
``i_min`` is the lightest finite row at or before the heaviest stable row.
|
|
58
|
+
On a grid that starts below the minimum-mass star it is that star, so
|
|
59
|
+
rising rows on extended low-density configurations before it are excluded.
|
|
60
|
+
Limitation: if a twin-star dip falls below every earlier row and the later
|
|
61
|
+
branch is the heavier one, ``i_min`` is the dip and the first branch is
|
|
62
|
+
excluded too. The grid of :func:`_one_eos` starts at the minimum-mass star,
|
|
63
|
+
so this needs a first branch lighter than about the minimum-mass star.
|
|
64
|
+
|
|
65
|
+
The AD derivative ``Family.dM_dhc`` is not used here: it is wrong at
|
|
66
|
+
isolated h_c values (e.g. -158 against +8.65 by finite differences), and
|
|
67
|
+
one such row ends the stable branch in :func:`_stable_branches`."""
|
|
68
|
+
M = np.asarray(M, float)
|
|
69
|
+
valid = np.isfinite(M) & np.isfinite(R) & np.isfinite(Lam) & (M > 0)
|
|
70
|
+
rising = np.zeros(M.size, bool)
|
|
71
|
+
iv = np.flatnonzero(valid)
|
|
72
|
+
if iv.size >= 2:
|
|
73
|
+
up = np.diff(M[iv]) > 0 # each finite row against the last one
|
|
74
|
+
rising[iv[1:]] = up
|
|
75
|
+
rising[iv[0]] = up[0]
|
|
76
|
+
if not rising.any():
|
|
77
|
+
return np.zeros(M.size, bool)
|
|
78
|
+
order = np.arange(M.size)
|
|
79
|
+
i_max = int(np.argmax(np.where(rising, M, -np.inf)))
|
|
80
|
+
i_min = int(np.argmin(np.where(valid & (order <= i_max), M, np.inf)))
|
|
81
|
+
return rising & (order >= i_min)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _hc_grid_past_last_max(table, n_points, frac_lo, frac_hi, n_scan=40):
|
|
85
|
+
"""Central-enthalpy grid from the start of :func:`default_hc_grid` (the
|
|
86
|
+
minimum-mass star, or ``frac_lo`` h_max if that is denser) to two scan steps
|
|
87
|
+
past the last maximum of M(h_c).
|
|
88
|
+
|
|
89
|
+
``n_scan`` structure-only solves on [h_start, ``frac_hi`` h_max] locate the
|
|
90
|
+
maxima. The last one is the heaviest star of the densest stable branch, so
|
|
91
|
+
every stable branch is inside the grid and few rows fall on the collapsed
|
|
92
|
+
branch beyond it. If M still rises at ``frac_hi`` h_max the grid ends there,
|
|
93
|
+
and the table ends before the TOV maximum."""
|
|
94
|
+
h0 = float(default_hc_grid(table, n_models=2, frac_lo=frac_lo,
|
|
95
|
+
frac_hi=frac_hi)[0])
|
|
96
|
+
h_top = frac_hi * float(table.h[-1])
|
|
97
|
+
scan = np.linspace(h0, h_top, n_scan)
|
|
98
|
+
Ms = np.asarray(_probe_masses(table, jnp.asarray(scan))[0])
|
|
99
|
+
# peaks among the finite scan masses: a failed solve next to the last
|
|
100
|
+
# maximum must not hide it
|
|
101
|
+
idx = np.flatnonzero(np.isfinite(Ms))
|
|
102
|
+
Mf = Ms[idx]
|
|
103
|
+
h_end = h_top
|
|
104
|
+
if Mf.size >= 3 and Mf[-1] <= Mf[-2]:
|
|
105
|
+
peaks = [idx[j] for j in range(1, Mf.size - 1)
|
|
106
|
+
if Mf[j] >= Mf[j - 1] and Mf[j] > Mf[j + 1]]
|
|
107
|
+
if peaks:
|
|
108
|
+
h_end = scan[min(peaks[-1] + 2, n_scan - 1)]
|
|
109
|
+
return jnp.linspace(h0, h_end, n_points)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _one_eos(table, n_points=80, frac_lo=0.04, frac_hi=0.95):
|
|
113
|
+
"""One EOS's sequence rows from the minimum-mass star (or ``frac_lo``
|
|
114
|
+
h_max, if denser) to just past the last maximum of M(h_c)
|
|
115
|
+
(:func:`_hc_grid_past_last_max`; ``frac_hi`` h_max bounds the end). A grid
|
|
116
|
+
from ``frac_lo`` h_max alone can start below the minimum-mass star, on
|
|
117
|
+
extended R ~ 10^3 km configurations."""
|
|
118
|
+
hc_grid = _hc_grid_past_last_max(table, n_points, frac_lo, frac_hi)
|
|
119
|
+
fam = build_family(table, hc_grid)
|
|
120
|
+
hc = np.asarray(fam.h_c)
|
|
121
|
+
M = np.asarray(fam.M_msun)
|
|
122
|
+
R = np.asarray(fam.R_km)
|
|
123
|
+
Lam = np.asarray(fam.Lambda)
|
|
124
|
+
stable = _sequence_stable(hc, M, R, Lam).astype(float)
|
|
125
|
+
hh, n, cs2 = np.asarray(table.h), np.asarray(table.n), np.asarray(table.cs2)
|
|
126
|
+
rho_c = np.interp(hc, hh, n)
|
|
127
|
+
cs2_c = np.interp(hc, hh, cs2)
|
|
128
|
+
nan = np.full_like(M, np.nan) # M_b, I: solver TODO
|
|
129
|
+
return np.stack([hc, M, R, Lam, nan, nan, rho_c, cs2_c, stable], axis=1)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _stable_branches(M, R, Lam, stable):
|
|
133
|
+
"""Return contiguous stable, mass-rising branches in central-coordinate order.
|
|
134
|
+
|
|
135
|
+
A disconnected (twin-star) family can become stable again after an unstable
|
|
136
|
+
interval. Selecting every row before the global stable maximum mixes that
|
|
137
|
+
interval and the later branch into the primary ``M -> (R, Lambda)`` map. A
|
|
138
|
+
branch therefore ends whenever a row is invalid/unstable or mass ceases to
|
|
139
|
+
rise. Runs shorter than two samples cannot support interpolation and are
|
|
140
|
+
omitted.
|
|
141
|
+
"""
|
|
142
|
+
M = np.asarray(M)
|
|
143
|
+
R = np.asarray(R)
|
|
144
|
+
Lam = np.asarray(Lam)
|
|
145
|
+
valid = (np.isfinite(M) & np.isfinite(R) & np.isfinite(Lam)
|
|
146
|
+
& (M > 0) & (np.asarray(stable) > 0.5))
|
|
147
|
+
branches = []
|
|
148
|
+
start = None
|
|
149
|
+
for k in range(len(M)):
|
|
150
|
+
continues = (valid[k] and start is not None and k > 0
|
|
151
|
+
and valid[k - 1] and M[k] > M[k - 1])
|
|
152
|
+
if valid[k] and start is None:
|
|
153
|
+
start = k
|
|
154
|
+
elif valid[k] and not continues:
|
|
155
|
+
if k - start >= 2:
|
|
156
|
+
branches.append((M[start:k], R[start:k], Lam[start:k]))
|
|
157
|
+
start = k
|
|
158
|
+
elif not valid[k] and start is not None:
|
|
159
|
+
if k - start >= 2:
|
|
160
|
+
branches.append((M[start:k], R[start:k], Lam[start:k]))
|
|
161
|
+
start = None
|
|
162
|
+
if start is not None and len(M) - start >= 2:
|
|
163
|
+
branches.append((M[start:], R[start:], Lam[start:]))
|
|
164
|
+
return branches
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _stable_rising(M, R, Lam, stable):
|
|
168
|
+
"""Return the primary stable branch used by the NMB v1 RIFT contract."""
|
|
169
|
+
branches = _stable_branches(M, R, Lam, stable)
|
|
170
|
+
if branches:
|
|
171
|
+
return branches[0]
|
|
172
|
+
empty = np.array([], dtype=float)
|
|
173
|
+
return empty, empty.copy(), empty.copy()
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# ---------------- representation-agnostic accessor protocol ----------------
|
|
177
|
+
class SequenceRepresentation(abc.ABC):
|
|
178
|
+
"""Accessor protocol any EOS-sequence representation must provide.
|
|
179
|
+
|
|
180
|
+
A 'sequence' is an indexed family of EOS. Consumers (RIFT inference) depend ONLY
|
|
181
|
+
on these methods -- NOT on how the family is stored. Today's representation is
|
|
182
|
+
**tabular draws** stored vs central enthalpy (:class:`NSSequence`,
|
|
183
|
+
``representation='tabular_hc/1'``). The interface is deliberately storage-agnostic
|
|
184
|
+
so the internal representation can later be a **compressed / functional** form --
|
|
185
|
+
a Gaussian process over the EOS function space, PCA / spectral / empirical
|
|
186
|
+
interpolants, etc. -- modelling functional spaces rather than pure draws, without
|
|
187
|
+
changing any consumer. ``open_sequence`` dispatches on the ``representation`` tag.
|
|
188
|
+
"""
|
|
189
|
+
n_eos: int = 0
|
|
190
|
+
params = None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def ordering_values(self, m_ref, kind="Lambda"):
|
|
194
|
+
"""Ordering statistic (Lambda or R at m_ref) for every EOS."""
|
|
195
|
+
fn = self.lambda_of_m if kind.lower() == "lambda" else self.radius_of_m
|
|
196
|
+
return np.array([fn(m_ref, e) for e in range(self.n_eos)])
|
|
197
|
+
|
|
198
|
+
def n_stable_branches(self, e):
|
|
199
|
+
"""Number of resolved stable branches for EOS ``e``.
|
|
200
|
+
|
|
201
|
+
Scalar v1 accessors intentionally continue to use the primary branch.
|
|
202
|
+
This topology query lets consumers detect when that reduction discards
|
|
203
|
+
additional stable branches.
|
|
204
|
+
"""
|
|
205
|
+
return int(self.stable_branch_counts[e])
|
|
206
|
+
|
|
207
|
+
# ---- opt-in multi-branch contract ------------------------------------
|
|
208
|
+
# ``branch="primary"`` (the default) is the v1 contract: the first stable
|
|
209
|
+
# run. An integer selects that run (0 = primary); ``"all"`` uses every run.
|
|
210
|
+
_lam_floor = None # PCASequence floors Lambda at 1e-30
|
|
211
|
+
|
|
212
|
+
@abc.abstractmethod
|
|
213
|
+
def branches(self, e):
|
|
214
|
+
"""Every stable, mass-rising run of EOS ``e`` as (M, R, Lambda) arrays,
|
|
215
|
+
in central-coordinate order (see :func:`_stable_branches`)."""
|
|
216
|
+
|
|
217
|
+
def _runs(self, e, branch):
|
|
218
|
+
"""Runs selected by ``branch``: "primary" (run 0), "all", or an int
|
|
219
|
+
index into :meth:`branches` (negative counts from the densest run). An
|
|
220
|
+
index past the last run selects nothing."""
|
|
221
|
+
runs = self.branches(e)
|
|
222
|
+
if isinstance(branch, str) and branch in ("primary", "all"):
|
|
223
|
+
return runs if branch == "all" else runs[:1]
|
|
224
|
+
if isinstance(branch, (int, np.integer)) and not isinstance(branch, (bool, np.bool_)):
|
|
225
|
+
k = int(branch)
|
|
226
|
+
return [runs[k]] if -len(runs) <= k < len(runs) else []
|
|
227
|
+
raise ValueError(f"branch must be 'primary', 'all' or an int, not {branch!r}")
|
|
228
|
+
|
|
229
|
+
def _interp(self, m, run, which):
|
|
230
|
+
M, R, Lam = run
|
|
231
|
+
if M.size < 2:
|
|
232
|
+
return np.nan
|
|
233
|
+
if which == "R":
|
|
234
|
+
return float(np.interp(m, M, R, left=np.nan, right=np.nan))
|
|
235
|
+
if self._lam_floor is not None:
|
|
236
|
+
Lam = np.maximum(Lam, self._lam_floor)
|
|
237
|
+
return float(np.exp(np.interp(m, M, np.log(Lam),
|
|
238
|
+
left=np.nan, right=np.nan)))
|
|
239
|
+
|
|
240
|
+
def _of_m(self, m, e, branch, which):
|
|
241
|
+
runs = self._runs(e, branch)
|
|
242
|
+
if isinstance(branch, str) and branch == "all":
|
|
243
|
+
return np.array([self._interp(m, r, which) for r in runs])
|
|
244
|
+
return self._interp(m, runs[0], which) if runs else np.nan
|
|
245
|
+
|
|
246
|
+
def lambda_of_m(self, m, e, branch="primary"):
|
|
247
|
+
"""Lambda at mass ``m`` on one branch (NaN off it). ``branch="all"``
|
|
248
|
+
returns one value per stable branch, NaN where ``m`` is outside it."""
|
|
249
|
+
return self._of_m(m, e, branch, "Lambda")
|
|
250
|
+
|
|
251
|
+
def radius_of_m(self, m, e, branch="primary"):
|
|
252
|
+
"""R [km] at mass ``m``; ``branch`` as in :meth:`lambda_of_m`."""
|
|
253
|
+
return self._of_m(m, e, branch, "R")
|
|
254
|
+
|
|
255
|
+
def m_max(self, e, branch="primary"):
|
|
256
|
+
"""Heaviest star on the selected branch; ``branch="all"`` gives the
|
|
257
|
+
maximum stable mass over every branch. -inf if there is none."""
|
|
258
|
+
tops = [float(np.max(r[0])) for r in self._runs(e, branch) if r[0].size]
|
|
259
|
+
return max(tops) if tops else -np.inf
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def open_sequence(fname):
|
|
263
|
+
"""Open an EOS sequence, dispatching on its stored ``representation`` tag.
|
|
264
|
+
|
|
265
|
+
Returns a :class:`SequenceRepresentation`. Future compressed representations
|
|
266
|
+
(GP / interpolant) register here; today only 'tabular_hc' is implemented.
|
|
267
|
+
"""
|
|
268
|
+
if not _HAVE_H5PY:
|
|
269
|
+
raise ImportError("open_sequence requires h5py")
|
|
270
|
+
with h5py.File(fname, "r") as f:
|
|
271
|
+
rep = str(f.attrs.get("representation", "tabular_hc/1"))
|
|
272
|
+
if rep.startswith("tabular"):
|
|
273
|
+
return NSSequence(fname)
|
|
274
|
+
if rep.startswith("pca"):
|
|
275
|
+
from .compressed import PCASequence
|
|
276
|
+
return PCASequence(fname)
|
|
277
|
+
raise NotImplementedError(
|
|
278
|
+
f"sequence representation {rep!r} not yet supported "
|
|
279
|
+
"(reserved for future GP / interpolant representations)")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ---------------- parallel sequence builds ----------------
|
|
283
|
+
def _one_eos_worker(args):
|
|
284
|
+
"""Subprocess worker: rebuild the EOSTable from numpy and run _one_eos."""
|
|
285
|
+
arrays, n_points = args
|
|
286
|
+
from ..eos.base import EOSTable
|
|
287
|
+
t = EOSTable(*[jnp.asarray(a) for a in arrays])
|
|
288
|
+
return _one_eos(t, n_points)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _build_rows(tables, n_points, n_jobs=None, progress=False, desc="TOV sequences"):
|
|
292
|
+
"""Per-EOS sequence rows, parallel across EOS (process pool, spawn context).
|
|
293
|
+
|
|
294
|
+
``n_jobs=None`` -> max(5, cpu_count-1) workers (sequential for tiny batches,
|
|
295
|
+
where spawn+jax-init overhead would dominate). Workers are separate
|
|
296
|
+
processes, so per-EOS numerics are identical to the sequential path
|
|
297
|
+
(verified bitwise). NOTE: the spawn context requires the CALLING script to
|
|
298
|
+
use the standard ``if __name__ == "__main__":`` guard (all our CLIs do).
|
|
299
|
+
"""
|
|
300
|
+
import os as _os
|
|
301
|
+
if n_jobs is None:
|
|
302
|
+
n_jobs = max(5, (_os.cpu_count() or 5) - 1)
|
|
303
|
+
bar = None
|
|
304
|
+
if progress:
|
|
305
|
+
from ..priors.bridge import _pbar
|
|
306
|
+
bar = _pbar(len(tables), desc)
|
|
307
|
+
rows = [None] * len(tables)
|
|
308
|
+
if n_jobs <= 1 or len(tables) < max(8, n_jobs):
|
|
309
|
+
for k, t in enumerate(tables):
|
|
310
|
+
rows[k] = _one_eos(t, n_points)
|
|
311
|
+
if bar:
|
|
312
|
+
bar.update(1)
|
|
313
|
+
else:
|
|
314
|
+
import multiprocessing as mp
|
|
315
|
+
ctx = mp.get_context("spawn") # jax-safe (no fork-after-init)
|
|
316
|
+
payload = [(tuple(np.asarray(x) for x in t), n_points) for t in tables]
|
|
317
|
+
# each table length compiles once per worker (~120 memory maps per
|
|
318
|
+
# executable); recycle workers before vm.max_map_count (65530)
|
|
319
|
+
with ctx.Pool(min(n_jobs, len(tables)), maxtasksperchild=200) as pool:
|
|
320
|
+
for k, row in enumerate(pool.imap(_one_eos_worker, payload)):
|
|
321
|
+
rows[k] = row
|
|
322
|
+
if bar:
|
|
323
|
+
bar.update(1)
|
|
324
|
+
if bar:
|
|
325
|
+
bar.close()
|
|
326
|
+
return rows
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ---------------- new self-describing format (tabular representation) ----------------
|
|
330
|
+
def write_nss(fname, tables, params=None, n_points=80, progress=False,
|
|
331
|
+
n_jobs=None):
|
|
332
|
+
"""Write the robust ``NSSequence`` HDF5 (tabular_hc representation) from EOSTables.
|
|
333
|
+
|
|
334
|
+
The per-EOS TOV family builds (the dominant cost) run across ``n_jobs``
|
|
335
|
+
worker processes (default: max(5, cpu_count-1); sequential for small
|
|
336
|
+
batches). ``progress=True`` shows a per-EOS bar.
|
|
337
|
+
"""
|
|
338
|
+
if not _HAVE_H5PY:
|
|
339
|
+
raise ImportError("write_nss requires h5py")
|
|
340
|
+
seq = np.stack(_build_rows(tables, n_points, n_jobs=n_jobs,
|
|
341
|
+
progress=progress), axis=0)
|
|
342
|
+
with h5py.File(fname, "w") as f:
|
|
343
|
+
f.attrs["schema_version"] = "nmbackend.nss/1"
|
|
344
|
+
f.attrs["representation"] = "tabular_hc/1" # dispatch tag (see open_sequence)
|
|
345
|
+
f.attrs["generator"] = f"nmbackend {_NMB_VERSION}"
|
|
346
|
+
f.attrs["created"] = datetime.datetime.utcnow().isoformat()
|
|
347
|
+
f.attrs["fields"] = json.dumps(NSS_FIELDS)
|
|
348
|
+
f.attrs["units"] = json.dumps(NSS_UNITS)
|
|
349
|
+
if params is not None:
|
|
350
|
+
f.attrs["eos_params"] = json.dumps(params)
|
|
351
|
+
f.create_dataset("sequence", data=seq, compression="gzip")
|
|
352
|
+
return fname
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class NSSequence(SequenceRepresentation):
|
|
356
|
+
"""Tabular EOS sequence stored vs central enthalpy; branch-aware accessors."""
|
|
357
|
+
|
|
358
|
+
def __init__(self, fname):
|
|
359
|
+
if not _HAVE_H5PY:
|
|
360
|
+
raise ImportError("NSSequence requires h5py")
|
|
361
|
+
with h5py.File(fname, "r") as f:
|
|
362
|
+
self.fields = json.loads(f.attrs["fields"])
|
|
363
|
+
self.units = json.loads(f.attrs["units"])
|
|
364
|
+
self.params = (json.loads(f.attrs["eos_params"])
|
|
365
|
+
if "eos_params" in f.attrs else None)
|
|
366
|
+
self.seq = f["sequence"][:] # (n_eos, n_pts, n_fields)
|
|
367
|
+
self._i = {k: j for j, k in enumerate(self.fields)}
|
|
368
|
+
self.n_eos = self.seq.shape[0]
|
|
369
|
+
self.stable_branch_counts = np.array([
|
|
370
|
+
len(_stable_branches(
|
|
371
|
+
s[:, self._i["M"]], s[:, self._i["R"]],
|
|
372
|
+
s[:, self._i["Lambda"]], s[:, self._i["stable"]]
|
|
373
|
+
))
|
|
374
|
+
for s in self.seq
|
|
375
|
+
], dtype=int)
|
|
376
|
+
|
|
377
|
+
def branches(self, e):
|
|
378
|
+
s = self.seq[e]
|
|
379
|
+
return _stable_branches(s[:, self._i["M"]], s[:, self._i["R"]],
|
|
380
|
+
s[:, self._i["Lambda"]], s[:, self._i["stable"]])
|
|
381
|
+
|
|
382
|
+
def _branch(self, e):
|
|
383
|
+
s = self.seq[e]
|
|
384
|
+
return _stable_rising(s[:, self._i["M"]], s[:, self._i["R"]],
|
|
385
|
+
s[:, self._i["Lambda"]], s[:, self._i["stable"]])
|
|
386
|
+
|
|
387
|
+
def ordering_values(self, m_ref, kind="Lambda"):
|
|
388
|
+
"""Ordering statistic (Lambda or R at m_ref) for every EOS -- vectorized."""
|
|
389
|
+
fn = self.lambda_of_m if kind.lower() == "lambda" else self.radius_of_m
|
|
390
|
+
return np.array([fn(m_ref, e) for e in range(self.n_eos)])
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
# ---------------- legacy EOSSequenceLandry format (drop-in for RIFT) ----------------
|
|
394
|
+
def write_landry_legacy(fname, tables, eos_tables=None, n_points=120,
|
|
395
|
+
n_jobs=None, progress=False):
|
|
396
|
+
"""Write the exact ``EOSSequenceLandry`` HDF5 (id, ns/<name>{M,R,Lambda},
|
|
397
|
+
eos/<name>{pressurec2,energy_densityc2,baryon_density} in g/cm^3).
|
|
398
|
+
|
|
399
|
+
Only the **primary stable branch** (the first stable run) is stored, so RIFT's single-valued
|
|
400
|
+
M->Lambda interpolation is correct for phase-transition EOS without code changes.
|
|
401
|
+
``eos_tables`` (list of the same EOSTables) populates the optional ``eos`` group.
|
|
402
|
+
"""
|
|
403
|
+
if not _HAVE_H5PY:
|
|
404
|
+
raise ImportError("write_landry_legacy requires h5py")
|
|
405
|
+
with h5py.File(fname, "w") as f:
|
|
406
|
+
f.create_dataset("id", data=np.arange(len(tables)))
|
|
407
|
+
gns = f.create_group("ns")
|
|
408
|
+
geos = f.create_group("eos") if eos_tables is not None else None
|
|
409
|
+
rows = _build_rows(tables, n_points, n_jobs=n_jobs, progress=progress,
|
|
410
|
+
desc="TOV sequences (legacy)")
|
|
411
|
+
for k, t in enumerate(tables):
|
|
412
|
+
seq = rows[k]
|
|
413
|
+
M, R, Lam = _stable_rising(seq[:, 1], seq[:, 2], seq[:, 3], seq[:, 8])
|
|
414
|
+
ns = np.zeros(M.size, dtype=[("M", "f8"), ("R", "f8"), ("Lambda", "f8")])
|
|
415
|
+
ns["M"], ns["R"], ns["Lambda"] = M, R, Lam
|
|
416
|
+
gns.create_dataset(f"eos_{k}", data=ns)
|
|
417
|
+
if geos is not None:
|
|
418
|
+
te = eos_tables[k]
|
|
419
|
+
n = np.asarray(te.n)
|
|
420
|
+
p = np.asarray(te.p_mevfm3) * _MEVFM3_TO_GCM3
|
|
421
|
+
e = np.asarray(te.eps_mevfm3) * _MEVFM3_TO_GCM3
|
|
422
|
+
nb = n * _NB_TO_GCM3
|
|
423
|
+
et = np.zeros(n.size, dtype=[("pressurec2", "f8"),
|
|
424
|
+
("energy_densityc2", "f8"),
|
|
425
|
+
("baryon_density", "f8")])
|
|
426
|
+
et["pressurec2"], et["energy_densityc2"], et["baryon_density"] = p, e, nb
|
|
427
|
+
geos.create_dataset(f"eos_{k}", data=et)
|
|
428
|
+
return fname
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""External RNS equilibria; independent JAX operators live in rotating.pino.
|
|
2
|
+
|
|
3
|
+
RNS calls are conventional reference calculations, not JAX-differentiable.
|
|
4
|
+
"""
|
|
5
|
+
from .rns import RNSBackground, build_rns, load_background, solve_polytrope
|
|
6
|
+
|
|
7
|
+
__all__ = ["RNSBackground", "build_rns", "load_background", "solve_polytrope"]
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Build and run a pinned external RNS export driver without vendoring RNS.
|
|
2
|
+
|
|
3
|
+
Based on the public cgca/rns v2 sample interface; see ATTRIBUTION.md.
|
|
4
|
+
The supported runner uses polytropic K=G=c=1 units, never Hz or km.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
RNS_COMMIT = "87ea68246ee990256f94aa91a0506f54d78dd8d0"
|
|
21
|
+
MAIN_SHA256 = "5bbe51d50f4f13b7eb3b77fd4564289b7c2b9e8c76523b821ea33c7a3ba78423"
|
|
22
|
+
FIELDS = ("rho", "gama", "alpha", "omega", "velocity_sq", "energy", "pressure", "enthalpy")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _sha(path):
|
|
26
|
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class RNSBackground:
|
|
31
|
+
"""Radial-major RNS export; rho is a metric potential, not mass density."""
|
|
32
|
+
|
|
33
|
+
r: np.ndarray
|
|
34
|
+
mu: np.ndarray
|
|
35
|
+
fields: dict
|
|
36
|
+
metadata: dict
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def s(self):
|
|
40
|
+
return self.r / (self.r + self.metadata["r_e"])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def load_background(path):
|
|
44
|
+
"""Reject malformed, nonfinite or convention-inconsistent RNS exports."""
|
|
45
|
+
path = Path(path)
|
|
46
|
+
with path.open() as stream:
|
|
47
|
+
header = stream.readline()
|
|
48
|
+
metadata = {key: float(value) for key, value in re.findall(
|
|
49
|
+
r"([A-Za-z_]+)=([-+0-9.eE]+)", header)}
|
|
50
|
+
if not {"r_ratio", "r_e", "Omega"} <= metadata.keys():
|
|
51
|
+
raise ValueError("Missing RNS coordinate/rotation metadata")
|
|
52
|
+
if (not all(math.isfinite(x) for x in metadata.values())
|
|
53
|
+
or metadata["r_e"] <= 0 or not 0 < metadata["r_ratio"] <= 1):
|
|
54
|
+
raise ValueError("Invalid RNS coordinate/rotation metadata")
|
|
55
|
+
data = np.genfromtxt(path, delimiter=",", names=True, skip_header=1)
|
|
56
|
+
required = {"r", "mu", *FIELDS}
|
|
57
|
+
if data.ndim != 1 or not required <= set(data.dtype.names or ()):
|
|
58
|
+
raise ValueError("Incomplete RNS export schema")
|
|
59
|
+
if not all(np.all(np.isfinite(data[name])) for name in required):
|
|
60
|
+
raise ValueError("Nonfinite RNS export")
|
|
61
|
+
r, mu = np.unique(data["r"]), np.unique(data["mu"])
|
|
62
|
+
if (len(r) < 3 or len(mu) < 3 or r[0] != 0 or mu[0] != 0 or mu[-1] != 1
|
|
63
|
+
or not np.array_equal(data["r"], np.repeat(r, len(mu)))
|
|
64
|
+
or not np.array_equal(data["mu"], np.tile(mu, len(r)))):
|
|
65
|
+
raise ValueError("Expected a complete radial-major equatorial-symmetry grid")
|
|
66
|
+
fields = {name: data[name].reshape(len(r), len(mu)) for name in FIELDS}
|
|
67
|
+
matter = fields["energy"] > 0
|
|
68
|
+
if (not np.any(matter) or np.any(fields["energy"] < 0)
|
|
69
|
+
or np.any(fields["pressure"] < 0)
|
|
70
|
+
or np.any(fields["velocity_sq"][matter] < 0)
|
|
71
|
+
or np.any(fields["velocity_sq"][matter] >= 1)):
|
|
72
|
+
raise ValueError("Invalid RNS matter/velocity support")
|
|
73
|
+
rr, mm = np.meshgrid(r, mu, indexing="ij")
|
|
74
|
+
velocity = ((metadata["Omega"] - fields["omega"]) * rr
|
|
75
|
+
* np.sqrt(1 - mm**2) * np.exp(-fields["rho"]))**2
|
|
76
|
+
error = np.max(np.abs(velocity[matter] - fields["velocity_sq"][matter]))
|
|
77
|
+
if error > 1e-4:
|
|
78
|
+
raise ValueError(f"RNS metric/velocity convention mismatch: {error}")
|
|
79
|
+
if metadata["r_ratio"] == 1 and abs(metadata["Omega"]) > 1e-12:
|
|
80
|
+
raise ValueError("Nonzero rotation in a spherical RNS export")
|
|
81
|
+
if "Omega_K" in metadata and metadata["Omega"] > metadata["Omega_K"]:
|
|
82
|
+
raise ValueError("Requested RNS configuration exceeds mass shedding")
|
|
83
|
+
metadata.update(units="polytropic K=G=c=1", velocity_max_error=float(error),
|
|
84
|
+
csv_sha256=_sha(path), source_path=str(path.resolve()))
|
|
85
|
+
return RNSBackground(r, mu, fields, metadata)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_EXPORT_TAIL = r'''
|
|
89
|
+
double target_q = 0.8;
|
|
90
|
+
const char *q_env = getenv("NMB_RNS_Q");
|
|
91
|
+
if(q_env) target_q = strtod(q_env, NULL);
|
|
92
|
+
if(!isfinite(target_q) || target_q < 0.6 || target_q > 1) return 3;
|
|
93
|
+
for(int model=0; model<2; model++) {
|
|
94
|
+
if(model==1) {
|
|
95
|
+
int nstep = (int)ceil((1-target_q)/0.025);
|
|
96
|
+
for(int step=1; step<=nstep; step++) {
|
|
97
|
+
r_ratio = 1-(1-target_q)*step/nstep;
|
|
98
|
+
spin(s_gp,mu,log_e_tab,log_p_tab,log_h_tab,log_n0_tab,
|
|
99
|
+
n_tab,eos_type,Gamma_P,h_center,enthalpy_min,rho,gama,alpha,
|
|
100
|
+
omega,energy,pressure,enthalpy,velocity_sq,a_check,accuracy,cf,
|
|
101
|
+
r_ratio,&r_e,&Omega);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
mass_radius(s_gp,mu,log_e_tab,log_p_tab,log_h_tab,log_n0_tab,
|
|
105
|
+
n_tab,eos_type,Gamma_P,rho,gama,alpha,omega,energy,pressure,
|
|
106
|
+
enthalpy,velocity_sq,r_ratio,e_surface,r_e,Omega,
|
|
107
|
+
&Mass,&Mass_0,&J,&R_e,v_plus,v_minus,&Omega_K);
|
|
108
|
+
FILE *out=fopen(model ? "rns_rotating.csv":"rns_spherical.csv","w");
|
|
109
|
+
if(!out) return 2;
|
|
110
|
+
fprintf(out,"# r_ratio=%.17g r_e=%.17g Omega=%.17g h_center=%.17g "
|
|
111
|
+
"e_center=%.17g Gamma=%.17g Mass=%.17g Mass_b=%.17g "
|
|
112
|
+
"J=%.17g R_e=%.17g Omega_K=%.17g\n",
|
|
113
|
+
r_ratio,r_e,Omega,h_center,e_center,Gamma_P,Mass,Mass_0,J,R_e,Omega_K);
|
|
114
|
+
fprintf(out,"r,mu,rho,gama,alpha,omega,velocity_sq,energy,pressure,enthalpy\n");
|
|
115
|
+
for(int si=1;si<SDIV;si++) for(int mi=1;mi<=MDIV;mi++)
|
|
116
|
+
fprintf(out,"%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g\n",
|
|
117
|
+
r_e*s_gp[si]/(1-s_gp[si]),mu[mi],rho[si][mi],gama[si][mi],
|
|
118
|
+
alpha[si][mi],omega[si][mi],velocity_sq[si][mi],energy[si][mi],
|
|
119
|
+
pressure[si][mi],enthalpy[si][mi]);
|
|
120
|
+
fclose(out);
|
|
121
|
+
}
|
|
122
|
+
return 0;
|
|
123
|
+
}
|
|
124
|
+
'''
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def export_driver(source, destination):
|
|
128
|
+
"""Generate a separate driver from the exact pinned RNS sample main.c."""
|
|
129
|
+
source, destination = Path(source), Path(destination)
|
|
130
|
+
if _sha(source / "main.c") != MAIN_SHA256:
|
|
131
|
+
raise ValueError(f"main.c does not match cgca/rns {RNS_COMMIT}")
|
|
132
|
+
original = (source / "main.c").read_text()
|
|
133
|
+
original = original.replace("n_tab;", "n_tab=0;").replace("a_check;", "a_check=0;")
|
|
134
|
+
# The original parser reads argv[i+1] for every option. Guard that access.
|
|
135
|
+
original = original.replace("switch(argv[i][1]){", "if(i+1>=argc) return 4;\n switch(argv[i][1]){")
|
|
136
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
137
|
+
destination.write_text(original[:original.index(" dr=0.05;")] + _EXPORT_TAIL)
|
|
138
|
+
return destination
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def build_rns(source, output, *, radial_points=129, angular_points=65, cc="cc"):
|
|
142
|
+
"""Compile external RNS on the execution host; record input/binary hashes."""
|
|
143
|
+
if (radial_points < 33 or angular_points < 17
|
|
144
|
+
or (radial_points - 1) % 2 or (angular_points - 1) % 2):
|
|
145
|
+
raise ValueError("RNS Simpson grids need odd sizes >=33 radial, >=17 angular")
|
|
146
|
+
source, output = Path(source).resolve(), Path(output).resolve()
|
|
147
|
+
output.mkdir(parents=True, exist_ok=False)
|
|
148
|
+
driver = export_driver(source, output / "thermal_export.c")
|
|
149
|
+
executable = output / "rns_export"
|
|
150
|
+
command = [cc, "-std=c99", "-O2", f"-DMDIV={angular_points}",
|
|
151
|
+
f"-DSDIV={radial_points}", "-I", str(source), "-o", str(executable),
|
|
152
|
+
str(driver), *(str(source / name) for name in
|
|
153
|
+
("equil.c", "equil_util.c", "nrutil.c")), "-lm"]
|
|
154
|
+
result = subprocess.run(command, text=True, capture_output=True, timeout=120)
|
|
155
|
+
(output / "build.log").write_text(result.stdout + result.stderr)
|
|
156
|
+
result.check_returncode()
|
|
157
|
+
inputs = {path.name: _sha(path) for path in source.iterdir()
|
|
158
|
+
if path.suffix in (".c", ".h") and path.name != "thermal_export.c"}
|
|
159
|
+
(output / "build.json").write_text(json.dumps({
|
|
160
|
+
"upstream_commit": RNS_COMMIT, "source_sha256": inputs,
|
|
161
|
+
"generated_driver_sha256": _sha(driver), "command": command,
|
|
162
|
+
"binary_sha256": _sha(executable), "radial_points": radial_points,
|
|
163
|
+
"angular_points": angular_points,
|
|
164
|
+
}, indent=2) + "\n")
|
|
165
|
+
return executable
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def solve_polytrope(executable, output, *, energy_center=0.2, index=1.0,
|
|
169
|
+
axis_ratio=0.8, timeout=120):
|
|
170
|
+
"""Run conventional RNS in a fresh directory; reject unphysical exports.
|
|
171
|
+
|
|
172
|
+
The central value is energy density, not rest-mass density. The external
|
|
173
|
+
process is not an AD primitive. Passing a float derived from JAX does not
|
|
174
|
+
differentiate the equilibrium solve.
|
|
175
|
+
"""
|
|
176
|
+
if (not all(math.isfinite(x) for x in (energy_center, index, axis_ratio))
|
|
177
|
+
or energy_center <= 0 or index <= 0 or not 0.6 <= axis_ratio <= 1):
|
|
178
|
+
raise ValueError("Require positive energy/index and 0.6 <= axis ratio <= 1")
|
|
179
|
+
output = Path(output).resolve()
|
|
180
|
+
output.mkdir(parents=True, exist_ok=False)
|
|
181
|
+
executable = Path(executable).resolve()
|
|
182
|
+
command = [str(executable), "-q", "poly", "-N", str(index), "-e", str(energy_center)]
|
|
183
|
+
started = time.monotonic()
|
|
184
|
+
result = subprocess.run(command, cwd=output, capture_output=True, text=True,
|
|
185
|
+
timeout=timeout, env={**os.environ, "NMB_RNS_Q": str(axis_ratio)})
|
|
186
|
+
(output / "run.log").write_text(result.stdout + result.stderr)
|
|
187
|
+
result.check_returncode()
|
|
188
|
+
spherical = load_background(output / "rns_spherical.csv")
|
|
189
|
+
rotating = load_background(output / "rns_rotating.csv")
|
|
190
|
+
if abs(rotating.metadata["r_ratio"] - axis_ratio) > 1e-12:
|
|
191
|
+
raise ValueError("RNS export did not honor requested axis ratio")
|
|
192
|
+
(output / "run.json").write_text(json.dumps({
|
|
193
|
+
"command": command, "axis_ratio": axis_ratio,
|
|
194
|
+
"binary_sha256": _sha(executable), "elapsed_seconds": time.monotonic() - started,
|
|
195
|
+
"spherical": spherical.metadata, "rotating": rotating.metadata,
|
|
196
|
+
}, indent=2) + "\n")
|
|
197
|
+
return spherical, rotating
|