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,289 @@
1
+ """Independent radius-domain TOV + tidal reference solver (NumPy/SciPy).
2
+
3
+ This is deliberately a *different* method from ``nmbackend.tov.solver`` so it can
4
+ serve as an in-process cross-check:
5
+
6
+ * integration variable: **radius r** (not pseudo-enthalpy h),
7
+ * stepper: **SciPy adaptive RK45** (not fixed-step RK4),
8
+ * tidal sector: the second-order **(H, beta)** system (Hinderer 2008), not the
9
+ first-order y-Riccati used by the production solver.
10
+
11
+ If the two agree to high precision on a smooth EOS, both formulations are
12
+ corroborated. Where they *disagree* (e.g. across a strong phase transition), the
13
+ adaptive RK45 here is the more trustworthy of the two and flags work for the
14
+ production stepper. This is **not** differentiable and is not in the hot path.
15
+
16
+ Geometric units: r, m in km; eps, p in km^-2 (consuming an ``EOSTable``).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ from typing import NamedTuple
22
+
23
+ import numpy as np
24
+ from scipy.integrate import solve_ivp
25
+
26
+ from ..eos.base import EOSTable
27
+ from ..constants import GMSUN_KM
28
+
29
+ _FOURPI = 4.0 * math.pi
30
+
31
+
32
+ class RefPoint(NamedTuple):
33
+ h_c: float
34
+ R_km: float
35
+ M_km: float
36
+ M_msun: float
37
+ C: float
38
+ y: float
39
+ k2: float
40
+ Lambda: float
41
+
42
+
43
+ class _EOSInterp:
44
+ """log-space NumPy interpolants eps(p), cs2(p) from an EOSTable (geometric).
45
+
46
+ ``consistent=False`` (default): the tidal term (eps + p)/cs2 takes the
47
+ table's node cs2, interpolated linearly in log p -- not the derivative of
48
+ the log-linear eps(p), so a steep cell leaves a phantom Delta eps in the
49
+ tidal sector (docs/devlog/2026-10-14-tidal-cs2.md). ``consistent=True``:
50
+ cs2 is the slope dp/deps of the log-linear eps(p) itself, segment by
51
+ segment, so the tidal source integrates to each segment's Delta eps.
52
+ Jump segments (|Delta ln p| <= 1e-12, or chord dp/deps <= 1e-6 at any
53
+ width: a density jump at (nearly) fixed p) get no tidal term; ``plateaus`` lists their (p, Delta eps) for the
54
+ junction condition (:func:`solve_reference`)."""
55
+
56
+ def __init__(self, table: EOSTable, consistent: bool = False):
57
+ self.h = np.asarray(table.h, dtype=float)
58
+ self.eps = np.asarray(table.eps, dtype=float)
59
+ self.p = np.asarray(table.p, dtype=float)
60
+ self.cs2 = np.clip(np.asarray(table.cs2, dtype=float), 1e-8, 1.0)
61
+ self._logp = np.log(self.p)
62
+ self._logeps = np.log(self.eps)
63
+ self.p_min = float(self.p[0])
64
+ self.p_max = float(self.p[-1])
65
+ self.consistent = consistent
66
+ self.plateaus = []
67
+ if consistent: # d ln eps / d ln p per segment
68
+ dlp = np.diff(self._logp)
69
+ de = np.diff(self.eps)
70
+ # a jump at (nearly) fixed p, by chord dp/deps at any width. The
71
+ # threshold is 1e-6, above the solver's 1e-8 (eos.base): RK45 steps
72
+ # over segments with a chord below ~4e-8 without resolving their
73
+ # tidal term (Lambda 1.2% low), so they take the exact junction
74
+ flat = (np.abs(dlp) <= 1e-12) | ((de > 0) & (np.diff(self.p) <= 1e-6 * de))
75
+ with np.errstate(divide="ignore", invalid="ignore"):
76
+ self._g = np.where(flat, 0.0, np.diff(self._logeps) / dlp)
77
+ self.plateaus = [(float(self.p[j]), float(self.eps[j + 1] - self.eps[j]))
78
+ for j in np.flatnonzero(flat)]
79
+
80
+ def eps_of_p(self, p):
81
+ lp = np.log(np.clip(p, self.p_min, self.p_max))
82
+ return np.exp(np.interp(lp, self._logp, self._logeps))
83
+
84
+ def cs2_of_p(self, p):
85
+ lp = np.log(np.clip(p, self.p_min, self.p_max))
86
+ return np.interp(lp, self._logp, self.cs2)
87
+
88
+ def tidal_term(self, p, eps):
89
+ """(eps + p)/cs2 at pressure ``p`` (``eps`` = eps_of_p(p))."""
90
+ if not self.consistent:
91
+ return (eps + p) / float(self.cs2_of_p(p))
92
+ lp = math.log(min(max(p, self.p_min), self.p_max))
93
+ j = min(max(int(np.searchsorted(self._logp, lp)), 1), self._g.size)
94
+ return (eps + p) * (eps / p) * float(self._g[j - 1]) # (eps+p) deps/dp
95
+
96
+ def central_from_hc(self, h_c):
97
+ eps_c = math.exp(np.interp(h_c, self.h, self._logeps))
98
+ p_c = math.exp(np.interp(h_c, self.h, self._logp))
99
+ return eps_c, p_c
100
+
101
+
102
+ def _k2_from_y_C(y, C):
103
+ onemtwoC = 1.0 - 2.0 * C
104
+ num = (8.0 / 5.0) * C**5 * onemtwoC**2 * (2.0 + 2.0 * C * (y - 1.0) - y)
105
+ den = (
106
+ 2.0 * C * (6.0 - 3.0 * y + 3.0 * C * (5.0 * y - 8.0))
107
+ + 4.0 * C**3 * (13.0 - 11.0 * y + C * (3.0 * y - 2.0)
108
+ + 2.0 * C**2 * (1.0 + y))
109
+ + 3.0 * onemtwoC**2 * (2.0 - y + 2.0 * C * (y - 1.0)) * math.log(onemtwoC)
110
+ )
111
+ return num / den
112
+
113
+
114
+ def _nan_point(h_c):
115
+ nan = float("nan")
116
+ return RefPoint(h_c=float(h_c), R_km=nan, M_km=nan, M_msun=nan, C=nan,
117
+ y=nan, k2=nan, Lambda=nan)
118
+
119
+
120
+ def _event_fired(sol):
121
+ """True iff the terminal event stopped ``sol`` (not r_max, not a failure)."""
122
+ return sol.status == 1 and sol.t_events[0].size > 0
123
+
124
+
125
+ def solve_reference(table: EOSTable, h_c: float, rtol=1e-8, atol=1e-10,
126
+ r0=1e-4, r_max=60.0, consistent_cs2=False):
127
+ """Reference (R, M, k2, Lambda) at central pseudo-enthalpy h_c.
128
+
129
+ ``consistent_cs2=True`` takes the tidal term from the slope of the log-linear
130
+ eps(p) this solver integrates (see :class:`_EOSInterp`), instead of the
131
+ table's node cs2. The default keeps the node cs2 (unchanged behaviour).
132
+
133
+ If the surface is not reached by ``r_max`` (or the integrator fails), every
134
+ field except ``h_c`` is NaN. Low-h_c stars on crust tables can have
135
+ R >> 60 km; pass a larger ``r_max`` for those.
136
+ """
137
+ eos = _EOSInterp(table, consistent=consistent_cs2)
138
+ eps_c, p_c = eos.central_from_hc(h_c)
139
+
140
+ # central series: m ~ 4/3 pi eps r^3 ; H ~ a0 r^2 ; beta = dH/dr ~ 2 a0 r.
141
+ m0 = (4.0 / 3.0) * math.pi * eps_c * r0**3
142
+ H0 = r0**2
143
+ beta0 = 2.0 * r0
144
+ p_surface = eos.p_min
145
+
146
+ def rhs(r, s):
147
+ m, p, H, beta = s
148
+ p = max(p, p_surface)
149
+ eps = float(eos.eps_of_p(p))
150
+ tid = eos.tidal_term(p, eps) # (eps + p)/cs2
151
+ one_minus = 1.0 - 2.0 * m / r
152
+ dm = _FOURPI * r**2 * eps
153
+ dp = -(eps + p) * (m + _FOURPI * r**3 * p) / (r**2 * one_minus)
154
+ dH = beta
155
+ # Hinderer 2008 (H, beta) second-order tidal system
156
+ term_a = (2.0 / one_minus) * (
157
+ -2.0 * math.pi * (5.0 * eps + 9.0 * p + tid)
158
+ + 3.0 / r**2
159
+ + 2.0 / one_minus * ((m + _FOURPI * r**3 * p) / r**2) ** 2
160
+ )
161
+ term_b = (2.0 * beta / r) / one_minus * (
162
+ -1.0 + m / r + 2.0 * math.pi * r**2 * (eps - p)
163
+ )
164
+ dbeta = term_a * H + term_b
165
+ return [dm, dp, dH, dbeta]
166
+
167
+ def hit_surface(r, s):
168
+ return s[1] - p_surface
169
+ hit_surface.terminal = True
170
+ hit_surface.direction = -1
171
+
172
+ # consistent_cs2: density jumps at fixed p (zero-width segments) get the
173
+ # junction y_out = y_in - 4 pi r^3 (eps_in - eps_out) / (m + 4 pi r^3 p), the
174
+ # zero-width limit of the tidal term (y falls across an outward density drop;
175
+ # cf. the self-bound-star surface term y(R) - 4 pi R^3 eps_s / M), integrating
176
+ # segment by segment between them
177
+ kicks = sorted(((pk, de) for pk, de in eos.plateaus
178
+ if p_surface < pk < p_c * (1.0 - 1e-12)), reverse=True)
179
+ state, r_start = [m0, p_c, H0, beta0], r0
180
+ for pk, de in kicks:
181
+ def hit_jump(r, s, pk=pk):
182
+ return s[1] - pk
183
+ hit_jump.terminal = True
184
+ hit_jump.direction = -1
185
+ seg = solve_ivp(rhs, (r_start, r_max), state, method="RK45", rtol=rtol,
186
+ atol=atol, events=[hit_surface, hit_jump], max_step=r_max)
187
+ if not (seg.status == 1 and seg.t_events[1].size > 0):
188
+ return _nan_point(h_c)
189
+ r_start = float(seg.t[-1])
190
+ m, _, H, beta = seg.y[:, -1]
191
+ y = r_start * beta / H - _FOURPI * r_start**3 * de / (
192
+ m + _FOURPI * r_start**3 * pk)
193
+ state = [m, pk, H, y * H / r_start]
194
+
195
+ sol = solve_ivp(rhs, (r_start, r_max), state,
196
+ method="RK45", rtol=rtol, atol=atol, events=hit_surface,
197
+ dense_output=False, max_step=r_max)
198
+ if not _event_fired(sol):
199
+ return _nan_point(h_c)
200
+ R = float(sol.t[-1])
201
+ m, _, H, beta = sol.y[:, -1]
202
+ M = float(m)
203
+ C = M / R
204
+ y = R * beta / H
205
+ k2 = _k2_from_y_C(y, C)
206
+ Lam = (2.0 / 3.0) * k2 / C**5
207
+ return RefPoint(h_c=float(h_c), R_km=R, M_km=M, M_msun=M / GMSUN_KM,
208
+ C=C, y=float(y), k2=float(k2), Lambda=float(Lam))
209
+
210
+
211
+ def reference_sequence(table: EOSTable, h_c_array, **kw):
212
+ """``solve_reference`` over ``h_c_array``; ``kw`` (e.g. ``r_max``) is forwarded."""
213
+ return [solve_reference(table, float(hc), **kw) for hc in np.asarray(h_c_array)]
214
+
215
+
216
+ def _hbeta_rhs(r, s, eos):
217
+ """(m, p, H, beta) radius-domain TOV + tidal rhs for a given EOS interp."""
218
+ m, p, H, beta = s
219
+ p = max(p, eos.p_min)
220
+ eps = float(eos.eps_of_p(p))
221
+ tid = eos.tidal_term(p, eps) # (eps + p)/cs2
222
+ one_minus = 1.0 - 2.0 * m / r
223
+ dm = _FOURPI * r**2 * eps
224
+ dp = -(eps + p) * (m + _FOURPI * r**3 * p) / (r**2 * one_minus)
225
+ term_a = (2.0 / one_minus) * (
226
+ -2.0 * math.pi * (5.0 * eps + 9.0 * p + tid)
227
+ + 3.0 / r**2
228
+ + 2.0 / one_minus * ((m + _FOURPI * r**3 * p) / r**2) ** 2
229
+ )
230
+ term_b = (2.0 * beta / r) / one_minus * (
231
+ -1.0 + m / r + 2.0 * math.pi * r**2 * (eps - p)
232
+ )
233
+ dbeta = term_a * H + term_b
234
+ return [dm, dp, beta, dbeta]
235
+
236
+
237
+ def solve_reference_hybrid(hybrid, h_c, rtol=1e-8, atol=1e-10, r0=1e-4,
238
+ r_max=60.0):
239
+ """Independent radius-domain reference for a HybridEOS, with the tidal
240
+ junction applied at the density discontinuity (different formulation from the
241
+ production enthalpy solver -> a genuine cross-check of the junction code)."""
242
+ # raw nodes: _EOSInterp is linear in (log p, log eps) between nodes, so the
243
+ # Hermite nodes added by refine_table would change its EOS
244
+ inner, outer = getattr(hybrid, "raw_segments", hybrid.segments)
245
+ tr = hybrid.transition
246
+ if h_c <= tr.h_t: # purely hadronic
247
+ return solve_reference(outer, h_c, rtol=rtol, atol=atol, r0=r0,
248
+ r_max=r_max)
249
+
250
+ ei_in, ei_out = _EOSInterp(inner), _EOSInterp(outer)
251
+ eps_c, p_c = ei_in.central_from_hc(h_c)
252
+ m0 = (4.0 / 3.0) * math.pi * eps_c * r0**3
253
+ s0 = [m0, p_c, r0**2, 2.0 * r0]
254
+
255
+ def hit_pt(r, s, eos):
256
+ return s[1] - tr.p_t
257
+ hit_pt.terminal = True
258
+ hit_pt.direction = -1
259
+ s1 = solve_ivp(_hbeta_rhs, (r0, r_max), s0, args=(ei_in,), method="RK45",
260
+ rtol=rtol, atol=atol, events=hit_pt, max_step=r_max)
261
+ if not _event_fired(s1):
262
+ return _nan_point(h_c)
263
+ r_d = float(s1.t[-1])
264
+ m_d, p_d, H_d, beta_d = s1.y[:, -1]
265
+
266
+ # junction: y = r beta / H ; Delta y = -4 pi r^3 (eps_in - eps_out)/(m+4pi r^3 p)
267
+ # (y falls outward; sign reversed before 2026-10-14, see tov.phase_transition)
268
+ dy = -_FOURPI * r_d**3 * (tr.eps_in - tr.eps_out) / (
269
+ m_d + _FOURPI * r_d**3 * tr.p_t)
270
+ beta_d = beta_d + (H_d / r_d) * dy
271
+
272
+ def hit_surface(r, s, eos):
273
+ return s[1] - ei_out.p_min
274
+ hit_surface.terminal = True
275
+ hit_surface.direction = -1
276
+ s2 = solve_ivp(_hbeta_rhs, (r_d, r_max), [m_d, p_d, H_d, beta_d],
277
+ args=(ei_out,), method="RK45", rtol=rtol, atol=atol,
278
+ events=hit_surface, max_step=r_max)
279
+ if not _event_fired(s2):
280
+ return _nan_point(h_c)
281
+ R = float(s2.t[-1])
282
+ m, _, H, beta = s2.y[:, -1]
283
+ M = float(m)
284
+ C = M / R
285
+ y = R * beta / H
286
+ k2 = _k2_from_y_C(y, C)
287
+ Lam = (2.0 / 3.0) * k2 / C**5
288
+ return RefPoint(h_c=float(h_c), R_km=R, M_km=M, M_msun=M / GMSUN_KM,
289
+ C=C, y=float(y), k2=float(k2), Lambda=float(Lam))
@@ -0,0 +1,26 @@
1
+ """RIFT integration: EOS-sequence I/O (robust NSSequence + legacy EOSSequenceLandry).
2
+
3
+ NOTE (logged for later improvement): by default the accessors use a SINGLE
4
+ stable branch, the primary one (the first stable run); ``branch="all"`` or an
5
+ int opts in to the other branches. Because the low-level sequence
6
+ parameter is the central pseudo-enthalpy h_c (monotone), the better long-term framing
7
+ is to parameterize the inference *directly* along h_c (a path integral in enthalpy),
8
+ which handles multiple / disconnected stable branches (twin stars) natively instead
9
+ of reducing to a single Lambda(m_ref) ordering. The NSSequence format already stores
10
+ everything vs h_c, so it is the substrate for that. See docs/backlog.md.
11
+ """
12
+ from .sequence import (write_nss, NSSequence, write_landry_legacy,
13
+ open_sequence, SequenceRepresentation,
14
+ NSS_FIELDS, NSS_UNITS)
15
+ from .compressed import (write_pca, write_pca_from_nss, PCASequence,
16
+ fit_sequence_pca, compression_ratio, PCA_FIELDS)
17
+
18
+ from .evidence import (CIPTabularEvidence, posterior_mass_lnZ,
19
+ read_eos_indices_xml)
20
+
21
+ __all__ = ["write_nss", "NSSequence", "write_landry_legacy",
22
+ "open_sequence", "SequenceRepresentation",
23
+ "NSS_FIELDS", "NSS_UNITS",
24
+ "write_pca", "write_pca_from_nss", "PCASequence",
25
+ "fit_sequence_pca", "compression_ratio", "PCA_FIELDS",
26
+ "CIPTabularEvidence", "posterior_mass_lnZ", "read_eos_indices_xml"]
@@ -0,0 +1,194 @@
1
+ """Compressed / functional EOS-sequence representations (PCA over M-R-Lambda curves).
2
+
3
+ This is the first *non-tabular* :class:`SequenceRepresentation` -- it delivers the
4
+ design mandate to "model functional spaces rather than pure draws". Instead of
5
+ storing every EOS sequence as raw samples, we treat each EOS's stellar sequence as a
6
+ set of functions of a normalized central coordinate u in [0,1]:
7
+
8
+ M(u), R(u), log Lambda(u)
9
+
10
+ stack them across the n_eos draws, and take a per-channel principal-component (SVD)
11
+ decomposition::
12
+
13
+ M(u) ~ mean_M(u) + sum_k a^M_k * phi^M_k(u)
14
+ R(u) ~ mean_R(u) + sum_k a^R_k * phi^R_k(u)
15
+ log Lambda ~ mean_L(u) + sum_k a^L_k * phi^L_k(u)
16
+
17
+ On disk we keep only ``mean`` (3, n_pts), the basis ``components`` (3, n_comp, n_pts),
18
+ and the per-EOS coefficients ``coeffs`` (n_eos, 3, n_comp) -- a large compression once
19
+ n_eos >> n_comp. Crucially this is a *function-space* model: ANY coefficient vector
20
+ reconstructs a smooth, valid-looking M-R-Lambda sequence, so the same machinery later
21
+ supports interpolating/sampling new EOS between the training draws (empirical
22
+ interpolants, GP priors over the coefficients, ...), not just replaying the draws.
23
+
24
+ The consumer API (``lambda_of_m``, ``radius_of_m``, ``m_max``, ``ordering_values``)
25
+ is identical to the tabular :class:`NSSequence`; ``open_sequence`` dispatches on the
26
+ ``representation="pca_hc/1"`` tag, so RIFT (and any other consumer) is unchanged.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import json
31
+ import datetime
32
+ import numpy as np
33
+
34
+ try:
35
+ import h5py
36
+ _HAVE_H5PY = True
37
+ except Exception: # pragma: no cover
38
+ _HAVE_H5PY = False
39
+
40
+ from .sequence import (SequenceRepresentation, _one_eos, _stable_branches,
41
+ NSS_FIELDS, _MEVFM3_TO_GCM3, _NB_TO_GCM3)
42
+ from .. import __version__ as _NMB_VERSION
43
+
44
+ PCA_FIELDS = ["M", "R", "logLambda"] # channels decomposed (u-indexed)
45
+
46
+
47
+ def _curves_from_tables(tables, n_points):
48
+ """Per-EOS (M, R, logLambda) curves on the common u-index grid -> (n_eos,3,n_pts)."""
49
+ iM, iR, iL = NSS_FIELDS.index("M"), NSS_FIELDS.index("R"), NSS_FIELDS.index("Lambda")
50
+ rows = []
51
+ for t in tables:
52
+ s = _one_eos(t, n_points)
53
+ M = s[:, iM]
54
+ R = s[:, iR]
55
+ Lam = np.maximum(s[:, iL], 1e-30)
56
+ rows.append(np.stack([M, R, np.log(Lam)], axis=0)) # (3, n_pts)
57
+ return np.stack(rows, axis=0) # (n_eos, 3, n_pts)
58
+
59
+
60
+ def _curves_from_sequence(seq):
61
+ """Per-EOS (M, R, logLambda) curves from a stored NSS ``sequence`` array.
62
+
63
+ ``seq`` is the ``(n_eos, n_pts, n_fields)`` dataset; no TOV re-run.
64
+ """
65
+ iM, iR, iL = NSS_FIELDS.index("M"), NSS_FIELDS.index("R"), NSS_FIELDS.index("Lambda")
66
+ M = seq[:, :, iM]
67
+ R = seq[:, :, iR]
68
+ logL = np.log(np.maximum(seq[:, :, iL], 1e-30))
69
+ return np.stack([M, R, logL], axis=1) # (n_eos, 3, n_pts)
70
+
71
+
72
+ def _fit_pca_curves(curves, n_components):
73
+ """Per-channel SVD of (n_eos, 3, n_pts) curves -> mean/components/coeffs dict."""
74
+ n_eos, n_ch, n_pts = curves.shape
75
+ k = int(min(n_components, n_eos, n_pts))
76
+ mean = curves.mean(axis=0) # (3, n_pts)
77
+ comps = np.zeros((n_ch, k, n_pts))
78
+ coeffs = np.zeros((n_eos, n_ch, k))
79
+ for c in range(n_ch):
80
+ X = curves[:, c, :] - mean[c] # (n_eos, n_pts)
81
+ # economy SVD: X = U S Vt; principal directions are rows of Vt
82
+ U, S, Vt = np.linalg.svd(X, full_matrices=False)
83
+ comps[c] = Vt[:k] # (k, n_pts)
84
+ coeffs[:, c, :] = (U[:, :k] * S[:k]) # (n_eos, k)
85
+ return dict(mean=mean, components=comps, coeffs=coeffs, n_points=n_pts)
86
+
87
+
88
+ def fit_sequence_pca(tables, n_points=80, n_components=6):
89
+ """Fit a per-channel PCA basis to a list of EOSTables (runs TOV via _one_eos).
90
+
91
+ Returns dict with ``mean`` (3,n_pts), ``components`` (3,n_comp,n_pts),
92
+ ``coeffs`` (n_eos,3,n_comp). ``n_components`` is clipped to min(n_eos, n_pts).
93
+ Prefer :func:`write_pca_from_nss` to compress an *existing* sequence file without
94
+ recomputing the stellar models.
95
+ """
96
+ return _fit_pca_curves(_curves_from_tables(tables, n_points), n_components)
97
+
98
+
99
+ def _write_pca_file(fname, fit, params, n_points):
100
+ with h5py.File(fname, "w") as f:
101
+ f.attrs["schema_version"] = "nmbackend.pca/1"
102
+ f.attrs["representation"] = "pca_hc/1"
103
+ f.attrs["generator"] = f"nmbackend {_NMB_VERSION}"
104
+ f.attrs["created"] = datetime.datetime.utcnow().isoformat()
105
+ f.attrs["channels"] = json.dumps(PCA_FIELDS)
106
+ f.attrs["n_points"] = int(n_points)
107
+ f.attrs["n_components"] = int(fit["components"].shape[1])
108
+ if params is not None:
109
+ f.attrs["eos_params"] = json.dumps(params)
110
+ f.create_dataset("mean", data=fit["mean"], compression="gzip")
111
+ f.create_dataset("components", data=fit["components"], compression="gzip")
112
+ f.create_dataset("coeffs", data=fit["coeffs"], compression="gzip")
113
+ return fname
114
+
115
+
116
+ def write_pca_from_nss(nss_fname, pca_fname, n_components=6):
117
+ """Compress an existing tabular ``NSSequence`` file into a ``pca_hc/1`` file.
118
+
119
+ Reads the stored sequence arrays (no TOV re-run), fits the PCA basis, and writes
120
+ the compact representation. This is the natural compression workflow.
121
+ """
122
+ if not _HAVE_H5PY:
123
+ raise ImportError("write_pca_from_nss requires h5py")
124
+ with h5py.File(nss_fname, "r") as f:
125
+ seq = f["sequence"][:]
126
+ params = (json.loads(f.attrs["eos_params"])
127
+ if "eos_params" in f.attrs else None)
128
+ fit = _fit_pca_curves(_curves_from_sequence(seq), n_components)
129
+ return _write_pca_file(pca_fname, fit, params, seq.shape[1])
130
+
131
+
132
+ def write_pca(fname, tables, params=None, n_points=80, n_components=6):
133
+ """Write a compressed ``pca_hc/1`` file from a list of EOSTables (runs TOV)."""
134
+ if not _HAVE_H5PY:
135
+ raise ImportError("write_pca requires h5py")
136
+ fit = fit_sequence_pca(tables, n_points=n_points, n_components=n_components)
137
+ return _write_pca_file(fname, fit, params, n_points)
138
+
139
+
140
+ def compression_ratio(n_eos, n_points, n_components, n_channels=3):
141
+ """Float-count compression vs storing the raw (n_eos, n_pts, n_channels) curves."""
142
+ raw = n_eos * n_points * n_channels
143
+ comp = (n_channels * n_points # mean
144
+ + n_channels * n_components * n_points # basis
145
+ + n_eos * n_channels * n_components) # coeffs
146
+ return raw / comp
147
+
148
+
149
+ class PCASequence(SequenceRepresentation):
150
+ """Reader for the compressed ``pca_hc/1`` representation; reconstructs on demand."""
151
+
152
+ def __init__(self, fname):
153
+ if not _HAVE_H5PY:
154
+ raise ImportError("PCASequence requires h5py")
155
+ with h5py.File(fname, "r") as f:
156
+ self.channels = json.loads(f.attrs["channels"])
157
+ self.params = (json.loads(f.attrs["eos_params"])
158
+ if "eos_params" in f.attrs else None)
159
+ self.mean = f["mean"][:] # (3, n_pts)
160
+ self.components = f["components"][:] # (3, n_comp, n_pts)
161
+ self.coeffs = f["coeffs"][:] # (n_eos, 3, n_comp)
162
+ self.n_eos = self.coeffs.shape[0]
163
+ self._iM, self._iR, self._iL = (self.channels.index("M"),
164
+ self.channels.index("R"),
165
+ self.channels.index("logLambda"))
166
+ self.stable_branch_counts = np.array([
167
+ len(self._branches(e)) for e in range(self.n_eos)
168
+ ], dtype=int)
169
+
170
+ def reconstruct(self, e):
171
+ """Reconstruct (M, R, Lambda) curves on the u grid for EOS index ``e``."""
172
+ # curve[c] = mean[c] + coeffs[e,c,:] @ components[c]
173
+ rec = self.mean + np.einsum("ck,ckp->cp", self.coeffs[e], self.components)
174
+ M, R, logL = rec[self._iM], rec[self._iR], rec[self._iL]
175
+ return M, R, np.exp(logL)
176
+
177
+ def _branch(self, e):
178
+ branches = self._branches(e)
179
+ if branches:
180
+ return branches[0]
181
+ empty = np.array([], dtype=float)
182
+ return empty, empty.copy(), empty.copy()
183
+
184
+ _lam_floor = 1e-30
185
+
186
+ def branches(self, e):
187
+ return self._branches(e)
188
+
189
+ def _branches(self, e):
190
+ M, R, Lam = self.reconstruct(e)
191
+ # rising branch: stable where dM/du > 0 (u monotone in central enthalpy)
192
+ stable = np.concatenate([[True], np.diff(M) > 0]).astype(float)
193
+ return _stable_branches(M, R, Lam, stable)
194
+