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,325 @@
1
+ """Adaptive Gaussian prior over the compressed (PCA) EOS-sequence space.
2
+
3
+ This is the substrate for **adaptive nonparametric EOS priors** (RIFT-GP-style
4
+ iterative refinement): the compressed ``pca_hc/1`` representation expresses every
5
+ EOS sequence as coefficients c in R^{3k} on a fixed functional basis
6
+ (mean + components for the M(u), R(u), log Lambda(u) channels). A Gaussian
7
+ distribution over c IS a Gaussian process over the sequence function space,
8
+ restricted to (and with covariance expressed in) the PCA basis -- so fitting,
9
+ sampling, and *re-fitting* the coefficient distribution gives a fully functional
10
+ GP prior whose draws are new, smooth, never-seen sequences (not replays).
11
+
12
+ The adaptive loop (one round):
13
+
14
+ 1. ``sample`` : draw n coefficient vectors -> n new EOS sequences;
15
+ 2. evaluate : per-EOS (marginal) evidence lnZ_e for each draw -- in
16
+ production this is the RIFT tabular per-EOS evidence (CIP); in tests a
17
+ synthetic likelihood;
18
+ 3. ``refine`` : importance-reweight the draws (w ~ exp(beta lnZ)) and re-fit
19
+ the Gaussian (weighted mean + covariance), optionally tempered (beta<1)
20
+ and shrunk toward the previous round for stability.
21
+
22
+ Iterating concentrates the prior in the high-evidence region of sequence space --
23
+ the prior *adapts to the inference results*, which (per the 2026-06 competition
24
+ scoping) is unpublished in the NS-EOS literature. ``iterative_refinement`` drives
25
+ the loop against an abstract ``evidence_fn`` so the same code runs synthetic
26
+ demonstrations and the real RIFT pipeline.
27
+
28
+ Plain numpy; draws feed the standard sequence machinery (PCASequence files that
29
+ RIFT opens via EOSSequenceFromFile).
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import datetime
35
+ import numpy as np
36
+
37
+ try:
38
+ import h5py
39
+ _HAVE_H5PY = True
40
+ except Exception: # pragma: no cover
41
+ _HAVE_H5PY = False
42
+
43
+ from ..rift.compressed import PCASequence, PCA_FIELDS
44
+ from .. import __version__ as _NMB_VERSION
45
+
46
+
47
+ class CoefficientPrior:
48
+ """Gaussian prior over flattened PCA coefficients (3*k dims).
49
+
50
+ Equivalent to a GP over the sequence function space in the PCA basis. Carries
51
+ the basis (mean curves + components) so draws reconstruct directly.
52
+ """
53
+
54
+ def __init__(self, mean_coeff, cov_coeff, basis_mean, basis_components,
55
+ generation=0):
56
+ self.mean_coeff = np.asarray(mean_coeff, float) # (3k,)
57
+ self.cov_coeff = np.asarray(cov_coeff, float) # (3k, 3k)
58
+ self.basis_mean = np.asarray(basis_mean, float) # (3, n_pts)
59
+ self.basis_components = np.asarray(basis_components, float) # (3,k,n_pts)
60
+ self.generation = int(generation)
61
+ self._n_ch, self._k, self._n_pts = self.basis_components.shape
62
+
63
+ # ---------------------------------------------------------------- fitting --
64
+ @classmethod
65
+ def fit(cls, coeffs, basis_mean, basis_components, weights=None,
66
+ jitter=1e-10, generation=0):
67
+ """Fit (weighted) Gaussian to coefficients ``coeffs`` (n_eos, 3, k)."""
68
+ X = np.asarray(coeffs, float).reshape(len(coeffs), -1) # (n, 3k)
69
+ if weights is None:
70
+ w = np.ones(X.shape[0])
71
+ else:
72
+ w = np.asarray(weights, float)
73
+ w = np.clip(w, 0.0, None)
74
+ w = w / w.sum()
75
+ mu = w @ X
76
+ D = X - mu
77
+ cov = (D * w[:, None]).T @ D
78
+ # effective sample size guard: inflate toward isotropic if ESS tiny
79
+ cov = cov + jitter * np.eye(cov.shape[0]) * max(np.trace(cov), 1.0)
80
+ return cls(mu, cov, basis_mean, basis_components, generation=generation)
81
+
82
+ @classmethod
83
+ def from_pca_file(cls, fname, weights=None):
84
+ """Fit the prior from an existing ``pca_hc/1`` file's stored coefficients."""
85
+ seq = PCASequence(fname)
86
+ return cls.fit(seq.coeffs, seq.mean, seq.components, weights=weights)
87
+
88
+ # --------------------------------------------------------------- sampling --
89
+ def sample_coeffs(self, n, rng):
90
+ L = np.linalg.cholesky(
91
+ self.cov_coeff + 1e-12 * np.eye(self.cov_coeff.shape[0]))
92
+ z = rng.standard_normal((n, self.cov_coeff.shape[0]))
93
+ return (self.mean_coeff + z @ L.T).reshape(n, self._n_ch, self._k)
94
+
95
+ def reconstruct_raw(self, coeff):
96
+ """Raw channel curves (3, n_pts) = (M, R, logLambda) for one coeff (3, k)."""
97
+ return self.basis_mean + np.einsum("ck,ckp->cp",
98
+ np.asarray(coeff),
99
+ self.basis_components)
100
+
101
+ def reconstruct(self, coeff):
102
+ """(M, R, Lambda) curves for one coefficient vector (3, k)."""
103
+ rec = self.reconstruct_raw(coeff)
104
+ iM, iR, iL = (PCA_FIELDS.index("M"), PCA_FIELDS.index("R"),
105
+ PCA_FIELDS.index("logLambda"))
106
+ return rec[iM], rec[iR], np.exp(rec[iL])
107
+
108
+ def sample_sequences(self, n, rng, max_tries=10):
109
+ """Draw n *valid* new sequences; returns (coeffs (n,3,k), kept fraction).
110
+
111
+ Validity: finite curves, positive M and R, a non-trivial rising branch
112
+ (M_max above the low end), Lambda positive (guaranteed by the log channel).
113
+ """
114
+ out, tried, kept = [], 0, 0
115
+ while len(out) < n and tried < max_tries * n + 10:
116
+ need = n - len(out)
117
+ cand = self.sample_coeffs(max(need, 8), rng)
118
+ tried += cand.shape[0]
119
+ for c in cand:
120
+ M, R, Lam = self.reconstruct(c)
121
+ if (np.all(np.isfinite(M)) and np.all(np.isfinite(R))
122
+ and np.all(M > 0) and np.all(R > 0)
123
+ and np.max(M) > M[0] + 0.05):
124
+ out.append(c)
125
+ kept += 1
126
+ if len(out) >= n:
127
+ break
128
+ if len(out) < n:
129
+ raise RuntimeError("could not draw enough valid sequences "
130
+ f"({len(out)}/{n}); prior too wide?")
131
+ return np.array(out), kept / max(tried, 1)
132
+
133
+ # -------------------------------------------------------------- adaptation --
134
+ def refine(self, coeffs, lnZ, beta=1.0, shrink=0.0):
135
+ """One adaptive-refinement step: importance-reweight and re-fit.
136
+
137
+ ``coeffs`` (n,3,k) are draws from THIS prior; ``lnZ`` their per-EOS
138
+ (marginal) evidences. Weights w ~ exp(beta (lnZ - max)); ``beta`` < 1
139
+ tempers the update, ``shrink`` in [0,1) blends the new moments toward the
140
+ current ones (regularization for small effective sample sizes). Returns a
141
+ new :class:`CoefficientPrior` (generation+1).
142
+ """
143
+ lnZ = np.asarray(lnZ, float)
144
+ ok = np.isfinite(lnZ)
145
+ w = np.zeros_like(lnZ)
146
+ w[ok] = np.exp(beta * (lnZ[ok] - np.max(lnZ[ok])))
147
+ new = CoefficientPrior.fit(coeffs, self.basis_mean, self.basis_components,
148
+ weights=w, generation=self.generation + 1)
149
+ if shrink > 0.0:
150
+ new.mean_coeff = (1 - shrink) * new.mean_coeff + shrink * self.mean_coeff
151
+ new.cov_coeff = (1 - shrink) * new.cov_coeff + shrink * self.cov_coeff
152
+ return new
153
+
154
+ def ess(self, lnZ, beta=1.0):
155
+ """Effective sample size of the refinement weights (diagnostic)."""
156
+ lnZ = np.asarray(lnZ, float)
157
+ ok = np.isfinite(lnZ)
158
+ w = np.exp(beta * (lnZ[ok] - np.max(lnZ[ok])))
159
+ w = w / w.sum()
160
+ return 1.0 / np.sum(w ** 2)
161
+
162
+
163
+ def sequence_lambda_of_m(prior, coeff, m=1.4):
164
+ """Branch-aware Lambda(m) of one reconstructed draw (NaN if m off-branch)."""
165
+ from ..rift.sequence import _stable_rising
166
+ M, R, Lam = prior.reconstruct(coeff)
167
+ stable = np.concatenate([[True], np.diff(M) > 0]).astype(float)
168
+ Mb, Rb, Lb = _stable_rising(M, R, Lam, stable)
169
+ if Mb.size < 2 or not (Mb[0] <= m <= Mb[-1]):
170
+ return np.nan
171
+ return float(np.exp(np.interp(m, Mb, np.log(np.maximum(Lb, 1e-30)))))
172
+
173
+
174
+ def save_prior(fname, prior):
175
+ """Persist a CoefficientPrior to npz (for round-by-round driving)."""
176
+ np.savez(fname, mean_coeff=prior.mean_coeff, cov_coeff=prior.cov_coeff,
177
+ basis_mean=prior.basis_mean, basis_components=prior.basis_components,
178
+ generation=prior.generation)
179
+ return fname
180
+
181
+
182
+ def load_prior(fname):
183
+ d = np.load(fname)
184
+ return CoefficientPrior(d["mean_coeff"], d["cov_coeff"], d["basis_mean"],
185
+ d["basis_components"], generation=int(d["generation"]))
186
+
187
+
188
+ def adapt_basis(prior, coeffs, lnZ, n_components=None, beta=1.0):
189
+ """Re-fit the PCA **basis itself** from evidence-weighted draws.
190
+
191
+ This is the genuine kernel adaptation of the functional GP: the covariance
192
+ operator (mean curves + principal components + spectrum) is re-estimated from
193
+ the weighted ensemble of *curves*, not merely the coefficient moments on a
194
+ frozen basis. Where the posterior concentrates, the adapted basis re-allocates
195
+ its resolution.
196
+
197
+ Parameters: ``coeffs`` (n, 3, k) draws from ``prior``; ``lnZ`` their evidences
198
+ (weights ~ exp(beta lnZ)); ``n_components`` defaults to the current k.
199
+
200
+ Returns ``(new_prior, diag)`` -- the new :class:`CoefficientPrior` on the
201
+ adapted basis (coefficient Gaussian re-fit on it) and diagnostics:
202
+
203
+ * ``captured`` : per-channel weighted variance fraction captured by the
204
+ new basis on the input draws (re-expansion residual = 1 - captured);
205
+ * ``principal_angles`` : per-channel principal angles (rad) between old and
206
+ new component subspaces (0 = unrotated);
207
+ * ``mean_shift`` : per-channel rms shift of the mean curve.
208
+ """
209
+ coeffs = np.asarray(coeffs, float)
210
+ lnZ = np.asarray(lnZ, float)
211
+ ok = np.isfinite(lnZ)
212
+ w = np.zeros_like(lnZ)
213
+ w[ok] = np.exp(beta * (lnZ[ok] - np.max(lnZ[ok])))
214
+ if w.sum() <= 0:
215
+ raise ValueError("all refinement weights vanished")
216
+ w = w / w.sum()
217
+ k_new = int(n_components or prior.basis_components.shape[1])
218
+
219
+ # weighted ensemble of raw curves (n, 3, n_pts)
220
+ curves = np.stack([prior.reconstruct_raw(c) for c in coeffs], axis=0)
221
+ n_ch, n_pts = curves.shape[1], curves.shape[2]
222
+ k_new = min(k_new, curves.shape[0] - 1, n_pts)
223
+
224
+ new_mean = np.einsum("n,ncp->cp", w, curves)
225
+ comps = np.zeros((n_ch, k_new, n_pts))
226
+ new_coeffs = np.zeros((curves.shape[0], n_ch, k_new))
227
+ captured = np.zeros(n_ch)
228
+ angles = []
229
+ for c in range(n_ch):
230
+ D = curves[:, c, :] - new_mean[c]
231
+ Xw = D * np.sqrt(w)[:, None]
232
+ U, S, Vt = np.linalg.svd(Xw, full_matrices=False)
233
+ comps[c] = Vt[:k_new]
234
+ new_coeffs[:, c, :] = D @ comps[c].T
235
+ tot = float(np.sum(S ** 2))
236
+ captured[c] = float(np.sum(S[:k_new] ** 2) / tot) if tot > 0 else 1.0
237
+ # principal angles between old and new subspaces (orthonormal rows)
238
+ M = prior.basis_components[c] @ comps[c].T
239
+ sv = np.clip(np.linalg.svd(M, compute_uv=False), -1.0, 1.0)
240
+ angles.append(np.arccos(sv))
241
+ new_prior = CoefficientPrior.fit(new_coeffs, new_mean, comps, weights=w,
242
+ generation=prior.generation + 1)
243
+ diag = dict(captured=captured,
244
+ principal_angles=np.array(angles),
245
+ mean_shift=np.sqrt(np.mean((new_mean - prior.basis_mean) ** 2,
246
+ axis=1)))
247
+ return new_prior, diag
248
+
249
+
250
+ def write_pca_draws(fname, prior, coeffs, params=None):
251
+ """Write new coefficient draws as a standard ``pca_hc/1`` file.
252
+
253
+ The file carries the SAME basis as the parent representation, with the new
254
+ per-EOS coefficients -- it opens through ``open_sequence`` /
255
+ RIFT ``EOSSequenceFromFile`` like any other compressed sequence.
256
+ """
257
+ if not _HAVE_H5PY:
258
+ raise ImportError("write_pca_draws requires h5py")
259
+ coeffs = np.asarray(coeffs, float)
260
+ with h5py.File(fname, "w") as f:
261
+ f.attrs["schema_version"] = "nmbackend.pca/1"
262
+ f.attrs["representation"] = "pca_hc/1"
263
+ f.attrs["generator"] = (f"nmbackend {_NMB_VERSION} "
264
+ f"(adaptive draw, generation {prior.generation})")
265
+ f.attrs["created"] = datetime.datetime.utcnow().isoformat()
266
+ f.attrs["channels"] = json.dumps(PCA_FIELDS)
267
+ f.attrs["n_points"] = int(prior.basis_mean.shape[1])
268
+ f.attrs["n_components"] = int(prior.basis_components.shape[1])
269
+ f.attrs["adaptive_generation"] = int(prior.generation)
270
+ if params is not None:
271
+ f.attrs["eos_params"] = json.dumps(params)
272
+ f.create_dataset("mean", data=prior.basis_mean, compression="gzip")
273
+ f.create_dataset("components", data=prior.basis_components,
274
+ compression="gzip")
275
+ f.create_dataset("coeffs", data=coeffs, compression="gzip")
276
+ return fname
277
+
278
+
279
+ def iterative_refinement(prior, evidence_fn, rng, n_rounds=3, n_per_round=64,
280
+ beta=1.0, shrink=0.2, adapt_basis_every=None,
281
+ verbose=False):
282
+ """RIFT-GP-style adaptive loop over the sequence-space prior. Two stages:
283
+
284
+ * **Stage 1 (default): moment refit.** Each round importance-reweights the
285
+ draws by their evidence and re-fits the coefficient Gaussian
286
+ (:meth:`CoefficientPrior.refine`). Cheap, stable, and sufficient when the
287
+ posterior lives inside the initial basis span -- the easy win.
288
+ * **Stage 2 (opt-in stretch): basis adaptation.** With
289
+ ``adapt_basis_every=k``, every k-th round additionally re-fits the PCA basis
290
+ itself from the weighted curves (:func:`adapt_basis`) -- re-centering the
291
+ mean and re-orienting the components to the posterior-concentrated
292
+ directions. NOTE: draws are in the current basis span by construction, so
293
+ adaptation re-allocates resolution *within* the span (rotation, mean shift,
294
+ effective truncation); expanding the span requires injecting fresh external
295
+ training curves (e.g. new bridge draws near the posterior).
296
+
297
+ ``evidence_fn(prior, coeffs) -> lnZ array`` abstracts the per-EOS evidence:
298
+ in production it writes the draws via :func:`write_pca_draws`, runs the RIFT
299
+ tabular per-EOS evidence (CIP) on the file, and returns the per-EOS lnZ; in
300
+ tests it is a synthetic likelihood over (M, R, Lambda) curves.
301
+
302
+ Returns (final_prior, history); history records per round the draws,
303
+ evidences, weight-ESS, and (when stage 2 fires) the basis diagnostics.
304
+ """
305
+ history = []
306
+ for r in range(n_rounds):
307
+ coeffs, keep_frac = prior.sample_sequences(n_per_round, rng)
308
+ lnZ = np.asarray(evidence_fn(prior, coeffs), float)
309
+ ess = prior.ess(lnZ, beta=beta)
310
+ rec = dict(round=r, coeffs=coeffs, lnZ=lnZ, ess=float(ess),
311
+ keep_frac=float(keep_frac), generation=prior.generation)
312
+ if verbose:
313
+ print(f"round {r}: gen={prior.generation} ESS={ess:.1f}/"
314
+ f"{n_per_round} keep={keep_frac:.2f} "
315
+ f"lnZ max={np.nanmax(lnZ):.2f}")
316
+ if adapt_basis_every and (r + 1) % adapt_basis_every == 0:
317
+ prior, diag = adapt_basis(prior, coeffs, lnZ, beta=beta)
318
+ rec["basis_diag"] = diag
319
+ if verbose:
320
+ print(f" basis adapted: captured={diag['captured']} "
321
+ f"mean_shift={diag['mean_shift']}")
322
+ else:
323
+ prior = prior.refine(coeffs, lnZ, beta=beta, shrink=shrink)
324
+ history.append(rec)
325
+ return prior, history
@@ -0,0 +1,11 @@
1
+ """Independent reference solvers for cross-validation (not in the hot path).
2
+
3
+ * ``scipy_tov`` : in-process radius-domain SciPy RK45 + (H, beta) tidal solver.
4
+ * ``reprimand`` : adapter to the external RePrimAnd high-accuracy TOV solver
5
+ (optional; requires ``pyreprimand``).
6
+ """
7
+ from .scipy_tov import (solve_reference, reference_sequence, RefPoint,
8
+ solve_reference_hybrid)
9
+
10
+ __all__ = ["solve_reference", "reference_sequence", "RefPoint",
11
+ "solve_reference_hybrid"]
@@ -0,0 +1,108 @@
1
+ """RePrimAnd high-accuracy TOV reference (optional; requires ``pyreprimand``).
2
+
3
+ RePrimAnd (Kastaun et al.; Zenodo 10617510) is our primary *external* reference for
4
+ M, R, Lambda, and baryon mass. This module builds a RePrimAnd barotropic-spline
5
+ EOS from an :class:`~nmbackend.eos.base.EOSTable` and runs its TOV branch solver.
6
+
7
+ Targets the **modern** pyreprimand API (verified against the 1.7 docs:
8
+ https://wokast.github.io/RePrimAnd/), with transparent fallbacks to the older API
9
+ (the one RIFT's ``EOSManager`` historically used). The two things that changed:
10
+ ``tov_acc_simple`` -> ``star_acc_simple`` (now takes two leading bool flags) and
11
+ ``make_tov_branch_stable`` (num_samp/mgrav_min -> mg_cut_low_rel/mg_cut_low_abs/
12
+ gm1_step). ``make_eos_barotr_spline`` and the sequence accessors are unchanged.
13
+
14
+ Import-guarded: ``HAVE_REPRIMAND`` is False if ``pyreprimand`` is absent; nothing
15
+ here is imported by the package by default.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import numpy as np
20
+
21
+ from ..constants import MEVFM3_TO_PA, MSUN_SI, C_SI
22
+ from ..eos.base import EOSTable
23
+
24
+ try:
25
+ import pyreprimand as pyr
26
+ HAVE_REPRIMAND = True
27
+ except Exception: # pragma: no cover
28
+ pyr = None
29
+ HAVE_REPRIMAND = False
30
+
31
+ # RePrimAnd's internal baryon mass (kg); units.FORMAL_BARYON_MASS_SI in the docs.
32
+ _M_BARYON_REPR_KG = 1.66e-27
33
+
34
+
35
+ # --- version-compatibility shims (modern pyreprimand, legacy fallback) ---
36
+ def _pyr_interval(lo, hi):
37
+ for nm in ("range", "interval", "range_t"):
38
+ f = getattr(pyr, nm, None)
39
+ if f is not None:
40
+ return f(lo, hi)
41
+ raise AttributeError("pyreprimand: no interval/range constructor found")
42
+
43
+
44
+ def _pyr_star_acc(acc_tov, acc_deform, minsteps, need_deform=True, need_bulk=False):
45
+ if hasattr(pyr, "star_acc_simple"):
46
+ # modern star_acc_simple takes keyword-only args: (*, need_deform, ...)
47
+ return pyr.star_acc_simple(need_deform=need_deform, need_bulk=need_bulk,
48
+ acc_tov=acc_tov, acc_deform=acc_deform,
49
+ minsteps=minsteps)
50
+ return pyr.tov_acc_simple(acc_tov, acc_deform, minsteps) # legacy
51
+
52
+
53
+ def _pyr_tov_branch(eos, acc, mgrav_min=0.0):
54
+ try:
55
+ return pyr.make_tov_branch_stable(eos, acc, mg_cut_low_rel=0.0,
56
+ mg_cut_low_abs=mgrav_min)
57
+ except TypeError:
58
+ try:
59
+ return pyr.make_tov_branch_stable(eos, acc) # modern defaults
60
+ except TypeError: # legacy API
61
+ return pyr.make_tov_branch_stable(eos, acc, num_samp=2000,
62
+ mgrav_min=mgrav_min)
63
+
64
+
65
+ def build_reprimand_eos(table: EOSTable, n_poly: float = 1.0,
66
+ pts_per_mag: int = 200):
67
+ """Build a RePrimAnd barotropic-spline EOS object from an EOSTable."""
68
+ if not HAVE_REPRIMAND:
69
+ raise ImportError("pyreprimand not installed; see docs/environment.md")
70
+
71
+ n = np.asarray(table.n) # fm^-3
72
+ p_mev = np.asarray(table.p_mevfm3)
73
+ eps_mev = np.asarray(table.eps_mevfm3)
74
+ cs2 = np.clip(np.asarray(table.cs2), 1e-8, 1.0)
75
+
76
+ rho_si = n * 1e45 * _M_BARYON_REPR_KG # kg/m^3 (rest-mass density)
77
+ eps_si_J = eps_mev * MEVFM3_TO_PA # J/m^3
78
+ p_si = p_mev * MEVFM3_TO_PA # Pa
79
+ spec_int = np.clip(eps_si_J / (rho_si * C_SI**2) - 1.0, 0.0, None)
80
+ cs = np.sqrt(cs2)
81
+
82
+ unew = pyr.units.geom_solar(MSUN_SI) # geometric G=c=Msun=1 (positional)
83
+ rho_u = rho_si / unew.density
84
+ p_u = p_si / unew.pressure
85
+ rgrho = _pyr_interval(rho_u.min() * 1.0000001, rho_u.max() / 1.0000001)
86
+
87
+ # temp / efrac unavailable -> empty lists (per RePrimAnd docs); isentropic EOS
88
+ return pyr.make_eos_barotr_spline(
89
+ rho_u, spec_int, p_u, cs, [], [], True, rgrho, n_poly, unew, pts_per_mag)
90
+
91
+
92
+ def reprimand_sequence(table: EOSTable, n_bins: int = 400, acc: float = 1e-6,
93
+ mgrav_min: float = 0.3):
94
+ """Return (M_msun, R_km, Lambda, gm1_center) from RePrimAnd's TOV branch."""
95
+ if not HAVE_REPRIMAND:
96
+ raise ImportError("pyreprimand not installed; see docs/environment.md")
97
+ eos = build_reprimand_eos(table)
98
+
99
+ star_acc = _pyr_star_acc(acc * 1e-2, acc, 500)
100
+ seq = _pyr_tov_branch(eos, star_acc, mgrav_min=mgrav_min)
101
+
102
+ u = seq.units_to_SI
103
+ rg = seq.range_center_gm1
104
+ gm1 = np.linspace(rg.min, rg.max, n_bins)
105
+ M = seq.grav_mass_from_center_gm1(gm1) # Msun
106
+ R = seq.circ_radius_from_center_gm1(gm1) * u.length / 1e3 # km
107
+ Lam = seq.lambda_tidal_from_center_gm1(gm1)
108
+ return np.asarray(M), np.asarray(R), np.asarray(Lam), gm1