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,437 @@
1
+ """Constrained Brownian-bridge EOS prior (Gorda-Komoltsev-Kurkela-Sunde 2025).
2
+
3
+ Implements the nonparametric prior of arXiv:2512.18044: EOS draws that are
4
+ **mechanically stable, causal, and thermodynamically consistent by construction**,
5
+ bridging a low-density nuclear anchor to the perturbative-QCD limit. No shooting,
6
+ no accept/reject against a QCD likelihood -- consistency is built into the sampler.
7
+
8
+ Method (faithful to the paper):
9
+
10
+ 1. **KK 3-volume** (Komoltsev & Kurkela 2022, arXiv:2111.05350; GKKS App. A): given
11
+ endpoint triplets beta_L=(mu_L,n_L,p_L), beta_H=(mu_H,n_H,p_H), any valid
12
+ intermediate point lies in an analytic volume V: n_min(mu) <= n <= n_max(mu) and
13
+ p_min(mu) <= p <= p_max(mu,n).
14
+
15
+ 2. **Self-similar (fractal) refinement** (GKKS Sec. 2.2 / App. B): recursively draw a
16
+ uniform point in V and subdivide, producing an EOS with structure on all scales
17
+ that fills the entire allowed function space.
18
+
19
+ 3. **Diffusion smoothing** (GKKS Sec. 2.3 / App. C): heat-kernel smooth mu(n) with a
20
+ density-dependent diffusion coefficient D(n) = c^2 n^2 / 4 (flow time tau=1),
21
+ giving a log-constant sound-speed correlation length sigma/n = c. D ~ n^2
22
+ saturates the causality-preservation condition D'' - D'/n <= 0, and D>0 preserves
23
+ stability; thermodynamics are rebuilt by integrating eps = eps_L + int mu dn,
24
+ p = mu n - eps.
25
+
26
+ Anchors: the low end comes from OUR nuclear model (metamodel band at n_L = 2 n_sat),
27
+ so the prior is anchored to this backend's physics; the high end is the partial-N3LO
28
+ pQCD point at mu_H = 2.6 GeV (Gorda et al. 2021 values as tabulated in KK 2022
29
+ Table I), with renormalization-scale parameter X in [1,4] sampled log-uniformly.
30
+
31
+ Units: mu in MeV, n in fm^-3, p and eps in MeV/fm^3.
32
+
33
+ This module is plain numpy; the resulting tables feed the standard
34
+ differentiable EOSTable/TOV machinery. :mod:`nmbackend.priors.bridge_jax` is
35
+ the same prior with its random numbers as explicit arguments, written in JAX,
36
+ so a draw can be differentiated with respect to its arguments.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import math
41
+ import warnings
42
+
43
+ import numpy as np
44
+
45
+ N_SAT = 0.16 # fm^-3
46
+ MU_H = 2600.0 # MeV; pQCD matching point (KK 2022)
47
+
48
+ #: partial-N3LO pQCD (n_H [fm^-3], p_H [MeV/fm^3]) at mu = 2.6 GeV vs X
49
+ #: (Gorda et al. 2021 as tabulated in Komoltsev & Kurkela 2022, Table I)
50
+ PQCD_TABLE = {1.0: (6.14, 2334.0), 2.0: (6.47, 3823.0), 4.0: (6.87, 4284.0)}
51
+
52
+
53
+ def pqcd_anchor(X):
54
+ """(mu_H, n_H, p_H) at mu=2.6 GeV, interpolated in ln X over X in [1,4]."""
55
+ Xs = np.array(sorted(PQCD_TABLE))
56
+ lnX = np.log(np.clip(X, Xs[0], Xs[-1]))
57
+ ns = np.array([PQCD_TABLE[x][0] for x in Xs])
58
+ ps = np.array([PQCD_TABLE[x][1] for x in Xs])
59
+ # quadratic in lnX through the three tabulated values
60
+ n_H = float(np.polyval(np.polyfit(np.log(Xs), ns, 2), lnX))
61
+ p_H = float(np.polyval(np.polyfit(np.log(Xs), ps, 2), lnX))
62
+ return MU_H, n_H, p_H
63
+
64
+
65
+ # ---------------------------------------------------------------- KK 3-volume ----
66
+ def kk_volume(bL, bH):
67
+ """Closures (n_min, n_max, p_min, p_max, mu_c) for the KK volume between two
68
+ triplets ``bL=(muL,nL,pL)``, ``bH=(muH,nH,pH)`` (GKKS App. A, eqs. A1-A7)."""
69
+ muL, nL, pL = bL
70
+ muH, nH, pH = bH
71
+ dp = pH - pL
72
+ den = muL * nH - muH * nL
73
+ num = muL * muH * (muH * nH - muL * nL - 2.0 * dp)
74
+ if den <= 0.0 or num <= 0.0:
75
+ mu_c = muH if den <= 0.0 else muL
76
+ else:
77
+ mu_c = math.sqrt(min(max(num / den, muL ** 2), muH ** 2))
78
+
79
+ def n_min(mu):
80
+ if mu <= mu_c:
81
+ return nL * mu / muL
82
+ return (mu ** 3 * nH - mu * muH * (muH * nH - 2.0 * dp)) / \
83
+ ((mu ** 2 - muL ** 2) * muH)
84
+
85
+ def n_max(mu):
86
+ if mu >= mu_c:
87
+ return nH * mu / muH
88
+ return (mu ** 3 * nL - muL * mu * (muL * nL + 2.0 * dp)) / \
89
+ ((mu ** 2 - muH ** 2) * muL)
90
+
91
+ def p_min(mu):
92
+ return pL + (mu ** 2 - muL ** 2) / (2.0 * mu) * n_min(mu)
93
+
94
+ n_c0 = n_max(muL) / muL # n_c(mu) = n_c0 * mu (eq. A7)
95
+
96
+ def p_max(mu, n):
97
+ if n <= n_c0 * mu:
98
+ return pL + (mu ** 2 - muL ** 2) / (2.0 * mu) * n
99
+ return pH - (muH ** 2 - mu ** 2) / (2.0 * mu) * n
100
+
101
+ return n_min, n_max, p_min, p_max, mu_c
102
+
103
+
104
+ def _interval_consistent(bL, bH, rtol=1e-9):
105
+ """KK existence condition: dp_min <= dp <= dp_max for the interval."""
106
+ muL, nL, pL = bL
107
+ muH, nH, pH = bH
108
+ if muH <= muL or nH < nL:
109
+ return False
110
+ dp = pH - pL
111
+ span = (muH ** 2 - muL ** 2)
112
+ dp_lo = nL * span / (2.0 * muL)
113
+ dp_hi = nH * span / (2.0 * muH)
114
+ tol = rtol * max(abs(dp_hi), 1.0)
115
+ return (dp_lo - tol) <= dp <= (dp_hi + tol)
116
+
117
+
118
+ # ------------------------------------------------ uniform sampling in the volume --
119
+ def sample_point_in_volume(rng, bL, bH, n_cdf=256):
120
+ """Draw beta=(mu,n,p) uniformly from the KK volume (GKKS App. B).
121
+
122
+ mu from the marginal P(mu^2) (eq. B11) via a numeric inverse-CDF (robust against
123
+ the printed closed form); n from the triangular slice's tent-shaped marginal;
124
+ p uniformly within [p_min, p_max(mu,n)].
125
+ """
126
+ muL = bL[0]; muH = bH[0]
127
+ n_min, n_max, p_min, p_max, mu_c = kk_volume(bL, bH)
128
+
129
+ # --- mu: P(mu^2) per eq. (B11), normalized so P(mu_c)=1
130
+ m2 = np.linspace(muL ** 2, muH ** 2, n_cdf)
131
+ mc2, mL2, mH2 = mu_c ** 2, muL ** 2, muH ** 2
132
+ dens = np.where(
133
+ m2 <= mc2,
134
+ np.divide((m2 - mL2) * (mH2 - mc2), (mc2 - mL2) * (mH2 - m2),
135
+ out=np.zeros_like(m2), where=(mH2 - m2) > 0),
136
+ np.divide((mH2 - m2) * (mc2 - mL2), (mH2 - mc2) * (m2 - mL2),
137
+ out=np.zeros_like(m2), where=(m2 - mL2) > 0),
138
+ )
139
+ dens = np.clip(dens, 0.0, None)
140
+ dens[~np.isfinite(dens)] = 0.0 # singular slice edge (den->0): no weight
141
+ cdf = np.concatenate([[0.0], np.cumsum(0.5 * (dens[1:] + dens[:-1])
142
+ * np.diff(m2))])
143
+ if not (np.isfinite(cdf[-1]) and cdf[-1] > 0.0): # degenerate/singular -> midpoint
144
+ mu = math.sqrt(0.5 * (mL2 + mH2))
145
+ else:
146
+ mu = math.sqrt(float(np.interp(rng.uniform(0.0, cdf[-1]), cdf, m2)))
147
+
148
+ # --- n: tent-shaped marginal h(n) = p_max(mu,n) - p_min(mu) on [n_lo, n_hi]
149
+ n_lo, n_hi = n_min(mu), n_max(mu)
150
+ n_apex = min(max((n_max(muL) / muL) * mu, n_lo), n_hi)
151
+ pmin = p_min(mu)
152
+ h_apex = max(p_max(mu, n_apex) - pmin, 0.0)
153
+ h_lo = max(p_max(mu, n_lo) - pmin, 0.0)
154
+ h_hi = max(p_max(mu, n_hi) - pmin, 0.0)
155
+ A1 = 0.5 * (h_lo + h_apex) * max(n_apex - n_lo, 0.0)
156
+ A2 = 0.5 * (h_apex + h_hi) * max(n_hi - n_apex, 0.0)
157
+ if A1 + A2 <= 0.0:
158
+ n = 0.5 * (n_lo + n_hi)
159
+ elif rng.uniform(0.0, A1 + A2) < A1:
160
+ # rising trapezoid on [n_lo, n_apex]
161
+ u = rng.uniform()
162
+ if h_apex > h_lo:
163
+ n = n_lo + (n_apex - n_lo) * (
164
+ (math.sqrt(h_lo ** 2 + u * (h_apex ** 2 - h_lo ** 2)) - h_lo)
165
+ / (h_apex - h_lo))
166
+ else:
167
+ n = n_lo + u * (n_apex - n_lo)
168
+ else:
169
+ # falling trapezoid on [n_apex, n_hi]
170
+ u = rng.uniform()
171
+ if h_apex > h_hi:
172
+ n = n_hi - (n_hi - n_apex) * (
173
+ (math.sqrt(h_hi ** 2 + u * (h_apex ** 2 - h_hi ** 2)) - h_hi)
174
+ / (h_apex - h_hi))
175
+ else:
176
+ n = n_apex + u * (n_hi - n_apex)
177
+
178
+ # --- p: uniform within the slice
179
+ p = rng.uniform(pmin, max(p_max(mu, n), pmin))
180
+ return (mu, float(n), float(p))
181
+
182
+
183
+ # ------------------------------------------------------- fractal refinement ------
184
+ def fractal_refine(rng, bL, bH, levels=9, min_dlnmu=1e-4):
185
+ """Self-similar refinement (GKKS Sec. 2.2): recursively bisect [bL, bH] with
186
+ uniform draws from each sub-volume. Returns the sorted list of triplets."""
187
+ pts = []
188
+
189
+ def recurse(a, b, depth):
190
+ if depth <= 0 or math.log(b[0] / a[0]) < min_dlnmu:
191
+ return
192
+ if not _interval_consistent(a, b):
193
+ return
194
+ try:
195
+ m = sample_point_in_volume(rng, a, b)
196
+ except (ValueError, ZeroDivisionError, FloatingPointError):
197
+ return
198
+ # enforce strict ordering (numerical safety)
199
+ if not (a[0] < m[0] < b[0] and a[1] <= m[1] <= b[1]
200
+ and a[2] <= m[2] <= b[2]):
201
+ return
202
+ pts.append(m)
203
+ recurse(a, m, depth - 1)
204
+ recurse(m, b, depth - 1)
205
+
206
+ recurse(tuple(bL), tuple(bH), levels)
207
+ return [tuple(bL)] + sorted(pts) + [tuple(bH)]
208
+
209
+
210
+ # ------------------------------------------------------------ diffusion ----------
211
+ def _thomas(a, b, c, d):
212
+ """Tridiagonal solve (a: sub, b: diag, c: super, d: rhs)."""
213
+ n = len(d)
214
+ cp = np.empty(n); dp = np.empty(n)
215
+ cp[0] = c[0] / b[0]; dp[0] = d[0] / b[0]
216
+ for i in range(1, n):
217
+ m = b[i] - a[i] * cp[i - 1]
218
+ cp[i] = c[i] / m
219
+ dp[i] = (d[i] - a[i] * dp[i - 1]) / m
220
+ x = np.empty(n)
221
+ x[-1] = dp[-1]
222
+ for i in range(n - 2, -1, -1):
223
+ x[i] = dp[i] - cp[i] * x[i + 1]
224
+ return x
225
+
226
+
227
+ def diffuse_mu_of_n(n_grid, mu, corr_frac, n_steps=40):
228
+ """Heat-kernel smooth the EOS: constant-D diffusion of ln(mu) vs x = ln(n).
229
+
230
+ Equivalent to the paper's D(n) = corr_frac^2 n^2 / 4 choice (GKKS Sec. 2.3.1:
231
+ sigma/n = corr_frac, log-constant correlation length), but formulated in
232
+ (ln mu, ln n) where it is *provably safe*: with constant D the sound speed
233
+ cs^2 = d(ln mu)/d(ln n) satisfies the SAME heat equation, so it obeys a maximum
234
+ principle -- it can never leave the initial range [0, 1]. Causality and
235
+ stability are preserved exactly (continuum), and to discretization accuracy on
236
+ the uniform x grid (backward Euler is an M-matrix scheme; the discrete derivative
237
+ satisfies the same update away from the two boundary cells).
238
+
239
+ Dirichlet ends pin ln(mu) at both anchors, so mu_L, mu_H are exact and
240
+ int cs^2 dx = ln(mu_H/mu_L) is conserved identically.
241
+ """
242
+ n = np.asarray(n_grid, float)
243
+ x = np.log(n)
244
+ if not np.allclose(np.diff(x), x[1] - x[0], rtol=1e-6):
245
+ raise ValueError("diffuse_mu_of_n requires a log-uniform density grid")
246
+ dx = x[1] - x[0]
247
+ u = np.log(np.array(mu, float))
248
+ N = x.size
249
+ D = 0.25 * corr_frac ** 2 # sigma_x = corr_frac
250
+ dt = 1.0 / n_steps
251
+ r = dt * D / dx ** 2
252
+ a = np.full(N, -r); b = np.full(N, 1.0 + 2.0 * r); c = np.full(N, -r)
253
+ a[0] = c[0] = a[-1] = c[-1] = 0.0
254
+ b[0] = b[-1] = 1.0 # Dirichlet ends
255
+ for _ in range(n_steps):
256
+ u = _thomas(a.copy(), b.copy(), c.copy(), u.copy())
257
+ return np.exp(u)
258
+
259
+
260
+ # ------------------------------------------------------------- full draw ---------
261
+ def draw_bridge_eos(rng, low_table=None, model=None, nep_params=None,
262
+ corr_frac=0.2, levels=9, X=None, n_L_fac=2.0,
263
+ n_term_fac=12.0, n_grid_pts=600, n_steps=40,
264
+ n_table_pts="auto"):
265
+ """One stable-causal-consistent EOS draw bridging nuclear matter to pQCD.
266
+
267
+ Parameters
268
+ ----------
269
+ rng : numpy Generator.
270
+ low_table / model / nep_params : low-density anchor. Either give ``low_table``
271
+ (arrays dict with n, eps, p in fm^-3 / MeV/fm^3) or a ``model`` (EOSModel,
272
+ default MetaModelEOS) with parameter dict ``nep_params`` drawn outside.
273
+ corr_frac : sound-speed correlation length as a fraction of density
274
+ (sigma/n; GKKS use a hierarchical U[0.2, 0.4]).
275
+ levels : fractal refinement depth (2^levels - 1 interior points max).
276
+ X : pQCD renormalization-scale parameter (log-uniform [1,4] if None).
277
+ n_L_fac : bridge start in units of n_sat (paper: 2).
278
+ n_term_fac : truncation density for the returned stellar-structure table,
279
+ in units of n_sat.
280
+ Both use ``nep_params["n_sat"]`` when the caller samples it, else
281
+ ``N_SAT``; the metamodel then saturates where the bridge anchor sits.
282
+ n_table_pts : node count of the returned table, which adds nodes to the
283
+ raw (n, eps, p) (their count varies per draw) with
284
+ :func:`nmbackend.eos.base.refine_table`. "auto" is a bound on the raw
285
+ count that depends only on the settings (:func:`_table_pts_bound`);
286
+ None keeps the raw nodes.
287
+
288
+ Returns dict with the combined (n, eps, p) arrays, the EOSTable, the anchor
289
+ metadata, and the endpoint pressure mismatch diagnostic.
290
+ """
291
+ n_sat = float((nep_params or {}).get("n_sat", N_SAT))
292
+ if not (math.isfinite(n_sat) and n_sat > 0.0):
293
+ raise ValueError(f"n_sat must be finite and positive, got {n_sat!r}")
294
+ n_L = n_L_fac * n_sat
295
+ # ---- low-density anchor from our nuclear model
296
+ if low_table is None:
297
+ if model is None:
298
+ from ..eos.metamodel import MetaModelEOS
299
+ model = MetaModelEOS()
300
+ t = model.eos_table(nep_params or {})
301
+ n_lo = np.asarray(t.n); eps_lo = np.asarray(t.eps_mevfm3)
302
+ p_lo = np.asarray(t.p_mevfm3)
303
+ else:
304
+ n_lo = np.asarray(low_table["n"]); eps_lo = np.asarray(low_table["eps"])
305
+ p_lo = np.asarray(low_table["p"])
306
+ n_lo_all = n_lo.size
307
+ # bridge grid node 0 is n_L: a table node within roundoff of it is the same
308
+ # density, and a zero-width cell there is a hazard for the TOV solve
309
+ n_below = n_L * (1.0 - 1e-12)
310
+ if not n_lo[0] < n_below <= n_lo[-1]:
311
+ raise ValueError(f"low-density table spans n={n_lo[0]:.4g} to "
312
+ f"{n_lo[-1]:.4g} fm^-3, which must contain "
313
+ f"n_L={n_L:.4g} fm^-3")
314
+ # anchor at exactly n_L, from the full table: the filter drops any node there
315
+ eps_L = float(np.interp(n_L, n_lo, eps_lo))
316
+ p_L = float(np.interp(n_L, n_lo, p_lo))
317
+ keep = n_lo < n_below
318
+ n_lo, eps_lo, p_lo = n_lo[keep], eps_lo[keep], p_lo[keep]
319
+ mu_L = (eps_L + p_L) / n_L
320
+ bL = (mu_L, n_L, p_L)
321
+
322
+ # ---- pQCD anchor
323
+ if X is None:
324
+ X = float(np.exp(rng.uniform(np.log(1.0), np.log(4.0))))
325
+ bH = pqcd_anchor(X)
326
+
327
+ if not _interval_consistent(bL, bH):
328
+ raise ValueError(f"anchors inconsistent (mu_L={mu_L:.1f} MeV); "
329
+ "check the low-density model")
330
+
331
+ # ---- fractal bridge + log-linear completion onto a regular ln-n grid
332
+ pts = fractal_refine(rng, bL, bH, levels=levels)
333
+ mu_pts = np.array([q[0] for q in pts])
334
+ n_pts = np.array([q[1] for q in pts])
335
+ grid = np.exp(np.linspace(math.log(n_L), math.log(bH[1]), n_grid_pts))
336
+ # piecewise log-linear mu(n): chords have cs^2 in [0,1] automatically
337
+ mu_grid = np.exp(np.interp(np.log(grid), np.log(n_pts), np.log(mu_pts)))
338
+
339
+ # ---- diffusion smoothing
340
+ mu_s = diffuse_mu_of_n(grid, mu_grid, corr_frac, n_steps=n_steps)
341
+ mu_s = np.maximum.accumulate(mu_s) # numerical monotone guard
342
+
343
+ # ---- rebuild thermodynamics: eps = eps_L + int mu dn ; p = mu n - eps
344
+ eps_b = eps_L + np.concatenate(
345
+ [[0.0], np.cumsum(0.5 * (mu_s[1:] + mu_s[:-1]) * np.diff(grid))])
346
+ p_b = mu_s * grid - eps_b
347
+ p_end_mismatch = (p_b[-1] - bH[2]) / bH[2]
348
+
349
+ # ---- combine with the low-density table and truncate for stellar structure
350
+ n_term = n_term_fac * n_sat
351
+ sel = grid <= n_term
352
+ n_all = np.concatenate([n_lo, grid[sel]])
353
+ eps_all = np.concatenate([eps_lo, eps_b[sel]])
354
+ p_all = np.concatenate([p_lo, p_b[sel]])
355
+ # lazy import: keeps this module importable without the (JAX) table machinery
356
+ from ..eos.base import refine_table
357
+ from ..eos.compose import eos_table_from_arrays
358
+ if n_table_pts == "auto":
359
+ n_table_pts = _table_pts_bound(n_lo_all, n_L, n_term, n_grid_pts)
360
+ if n_table_pts is None:
361
+ table = eos_table_from_arrays(n_all, eps_all, p_all, n_surface=None)
362
+ else: # NumPy until the length is fixed: no compile per raw length
363
+ table = refine_table(eos_table_from_arrays(
364
+ n_all, eps_all, p_all, n_surface=None, xp=np), n_table_pts)
365
+
366
+ cs2 = np.diff(np.log(mu_s)) / np.diff(np.log(grid))
367
+ return dict(table=table, n=n_all, eps=eps_all, p=p_all,
368
+ bridge=dict(n=grid, mu=mu_s, mu0=mu_grid, p=p_b, eps=eps_b,
369
+ cs2=cs2),
370
+ meta=dict(X=X, corr_frac=corr_frac, mu_L=mu_L, p_L=p_L,
371
+ n_L=n_L, n_sat=n_sat,
372
+ p_end_mismatch=float(p_end_mismatch)))
373
+
374
+
375
+ def _table_pts_bound(n_low_table, n_L, n_term, n_grid_pts):
376
+ """Upper bound on the raw node count of :func:`draw_bridge_eos`: every
377
+ low-table node plus the bridge-grid nodes up to n_term for the smallest
378
+ pQCD density n_H over X in [1, 4]. Fixed for fixed settings."""
379
+ n_H = min(pqcd_anchor(x)[1] for x in np.geomspace(1.0, 4.0, 65))
380
+ if n_term >= n_H:
381
+ return n_low_table + n_grid_pts
382
+ frac = math.log(n_term / n_L) / math.log(n_H / n_L)
383
+ return n_low_table + int((n_grid_pts - 1) * frac) + 2
384
+
385
+
386
+ def _pbar(total, desc):
387
+ """tqdm if available, else a quiet stderr ticker; .update(k)/.close()."""
388
+ try:
389
+ from tqdm import tqdm
390
+ return tqdm(total=total, desc=desc, unit="eos")
391
+ except Exception:
392
+ import sys
393
+
394
+ class _T:
395
+ def __init__(self):
396
+ self.k = 0
397
+
398
+ def update(self, j=1):
399
+ self.k += j
400
+ if self.k % max(1, total // 20) == 0 or self.k == total:
401
+ print(f" {desc}: {self.k}/{total}", file=sys.stderr,
402
+ flush=True)
403
+
404
+ def close(self):
405
+ pass
406
+ return _T()
407
+
408
+
409
+ def draw_prior_ensemble(n_draws, seed=0, corr_range=(0.2, 0.4),
410
+ nep_sampler=None, progress=False, **kw):
411
+ """Draw an ensemble; returns (tables, records). Hierarchical corr_frac per
412
+ GKKS Sec. 4 (uniform over ``corr_range``); NEPs via ``nep_sampler(rng)``.
413
+ ``progress=True`` shows a bar (tqdm if installed)."""
414
+ rng = np.random.default_rng(seed)
415
+ bar = _pbar(n_draws, "bridge draws") if progress else None
416
+ tables, records = [], []
417
+ attempts = 0
418
+ while len(tables) < n_draws and attempts < 20 * n_draws:
419
+ attempts += 1
420
+ c = float(rng.uniform(*corr_range))
421
+ nep = nep_sampler(rng) if nep_sampler else {}
422
+ try:
423
+ d = draw_bridge_eos(rng, nep_params=nep, corr_frac=c, **kw)
424
+ except (ValueError, FloatingPointError, OverflowError):
425
+ continue
426
+ tables.append(d["table"])
427
+ rec = dict(corr_frac=c, **{f"nep_{k}": v for k, v in nep.items()})
428
+ rec.update({k: d["meta"][k] for k in ("X", "p_end_mismatch")})
429
+ records.append(rec)
430
+ if bar:
431
+ bar.update(1)
432
+ if bar:
433
+ bar.close()
434
+ if len(tables) < n_draws:
435
+ warnings.warn(f"draw_prior_ensemble: {len(tables)} of {n_draws} draws "
436
+ f"after {attempts} attempts", RuntimeWarning, stacklevel=2)
437
+ return tables, records