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,435 @@
|
|
|
1
|
+
"""Differentiable version of the constrained Brownian-bridge prior (bridge.py).
|
|
2
|
+
|
|
3
|
+
:func:`bridge.draw_bridge_eos` draws its random numbers from a NumPy stream
|
|
4
|
+
while it builds the EOS. Here the random numbers are explicit arguments, so
|
|
5
|
+
one draw is a deterministic function of
|
|
6
|
+
|
|
7
|
+
theta = [nep..., corr_frac, ln_X, z (2^levels - 1, 3) flattened]
|
|
8
|
+
|
|
9
|
+
namely ``bridge_table(model, theta, nep_names, plan, cfg)``: the nuclear
|
|
10
|
+
empirical parameters ``nep`` (through the metamodel anchor at n_L), the
|
|
11
|
+
sound-speed correlation length, the pQCD scale, and the standard-normal
|
|
12
|
+
variates ``z``. Every step is written in JAX, so the map can be
|
|
13
|
+
differentiated with respect to all of these and composed with the TOV solver
|
|
14
|
+
(for example, a Fisher matrix with the variates as nuisance parameters whose
|
|
15
|
+
prior is a unit normal).
|
|
16
|
+
|
|
17
|
+
Differences from the NumPy sampler (same prior law, different realization):
|
|
18
|
+
|
|
19
|
+
* variates: each node of the refinement tree owns three normals
|
|
20
|
+
(heap index k = 1 .. 2^levels - 1), mapped to uniforms by the normal CDF.
|
|
21
|
+
``u_mu`` places mu by the inverse CDF of the KK marginal; ``u_n`` places n
|
|
22
|
+
by ONE inverse CDF over the whole tent-shaped marginal (the NumPy sampler
|
|
23
|
+
uses one uniform to pick the rising or falling side and another inside it);
|
|
24
|
+
``u_p`` places p uniformly in the slice. The tent map is continuous at the
|
|
25
|
+
apex, so the draw is smooth in its arguments away from the checks below.
|
|
26
|
+
* the tree is built level by level. Where the NumPy sampler skips a node (an
|
|
27
|
+
inconsistent interval, ln(mu_b/mu_a) < min_dlnmu, or a node outside its
|
|
28
|
+
parent interval), the node here collapses onto its left endpoint and its
|
|
29
|
+
descendants are skipped, which gives the same piecewise mu(n).
|
|
30
|
+
* the table is built with :func:`eos.base.build_h_and_cs2` from the raw nodes
|
|
31
|
+
(no :func:`eos.base.refine_table`), so its length is set by the bridge grid.
|
|
32
|
+
* the table length is static, so the number of bridge-grid rows is the count
|
|
33
|
+
at or below n_term for the LARGEST n_H over X in [1, 4]. A draw with a
|
|
34
|
+
smaller n_H has more grid rows below n_term in NumPy than here: at the
|
|
35
|
+
defaults up to 14 fewer rows, and the last row up to 6.8% below n_term
|
|
36
|
+
(at X = 1). With n_term_fac = inf the lengths agree.
|
|
37
|
+
* where :func:`bridge.draw_bridge_eos` raises ValueError (anchors
|
|
38
|
+
inconsistent, n_L outside the low-density table), :func:`make_plan`
|
|
39
|
+
raises, and :func:`bridge_arrays` raises when called outside a trace.
|
|
40
|
+
Under a trace it returns NaN arrays and ``info["valid"] = False``.
|
|
41
|
+
* ``Config.min_dlnmu`` exists only here; its default is the value
|
|
42
|
+
:func:`bridge.fractal_refine` uses (draw_bridge_eos does not expose it).
|
|
43
|
+
* n_L and n_term are in units of ``n_sat``, taken from ``nep_names`` when
|
|
44
|
+
``"n_sat"`` is one of them, else ``bridge.N_SAT``, as in
|
|
45
|
+
:func:`bridge.draw_bridge_eos`. The row count is fixed by the plan's
|
|
46
|
+
``n_sat_sel``: the evaluation point's n_sat, or ``n_sat_min`` passed to
|
|
47
|
+
:func:`make_plan`. A smaller n_sat puts the last row above n_term; that
|
|
48
|
+
draw is flagged (``info["rows_ok"]``) and returns NaN under a trace. When
|
|
49
|
+
sampling n_sat, make the plan with ``n_sat_min`` at the prior's lower edge;
|
|
50
|
+
larger n_sat then ends below n_term, as a smaller n_H does.
|
|
51
|
+
|
|
52
|
+
The checks above, the running maximum on mu, and the truncation at n_term
|
|
53
|
+
make the map piecewise smooth. Derivatives are exact inside a piece. Only
|
|
54
|
+
the row counts are fixed by :func:`make_plan`; which piece applies (skipped
|
|
55
|
+
nodes, interpolation cells) is chosen from the traced values with
|
|
56
|
+
``jnp.where`` and ``searchsorted``, so tracing never branches on a traced
|
|
57
|
+
value. A plan stays valid while the low-density table keeps the same number
|
|
58
|
+
of rows below n_L; :func:`bridge_arrays` checks this (``info["plan_ok"]``).
|
|
59
|
+
|
|
60
|
+
Units as bridge.py: mu in MeV, n in fm^-3, p and eps in MeV/fm^3.
|
|
61
|
+
"""
|
|
62
|
+
from __future__ import annotations
|
|
63
|
+
|
|
64
|
+
import functools
|
|
65
|
+
import math
|
|
66
|
+
from typing import NamedTuple
|
|
67
|
+
|
|
68
|
+
import jax
|
|
69
|
+
import jax.numpy as jnp
|
|
70
|
+
import numpy as np
|
|
71
|
+
from jax.scipy.special import ndtr
|
|
72
|
+
|
|
73
|
+
from .bridge import MU_H, N_SAT, PQCD_TABLE, _interval_consistent
|
|
74
|
+
|
|
75
|
+
_XS = np.array(sorted(PQCD_TABLE))
|
|
76
|
+
_C_N = np.polyfit(np.log(_XS), [PQCD_TABLE[x][0] for x in _XS], 2)
|
|
77
|
+
_C_P = np.polyfit(np.log(_XS), [PQCD_TABLE[x][1] for x in _XS], 2)
|
|
78
|
+
_U_EPS = 1e-12
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def pqcd_anchor(ln_X):
|
|
82
|
+
"""(mu_H, n_H, p_H) at mu = 2.6 GeV as bridge.pqcd_anchor, for ln X in [0, ln 4].
|
|
83
|
+
|
|
84
|
+
Outside [0, ln 4] ln X is clamped (zero derivative). At ln X = 0 and ln 4
|
|
85
|
+
exactly the derivative is the one-sided one from inside the interval
|
|
86
|
+
(jnp.clip would give half of it there)."""
|
|
87
|
+
ln_X = jnp.asarray(ln_X)
|
|
88
|
+
hi = math.log(4.0)
|
|
89
|
+
x = jnp.where(ln_X < 0.0, 0.0, jnp.where(ln_X > hi, hi, ln_X))
|
|
90
|
+
return (jnp.asarray(MU_H, x.dtype), jnp.polyval(jnp.asarray(_C_N), x),
|
|
91
|
+
jnp.polyval(jnp.asarray(_C_P), x))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------- KK volume ------
|
|
95
|
+
def _kk(bL, bH):
|
|
96
|
+
muL, nL, pL = bL
|
|
97
|
+
muH, nH, pH = bH
|
|
98
|
+
dp = pH - pL
|
|
99
|
+
den = muL * nH - muH * nL
|
|
100
|
+
num = muL * muH * (muH * nH - muL * nL - 2.0 * dp)
|
|
101
|
+
ok = (den > 0.0) & (num > 0.0)
|
|
102
|
+
ratio = jnp.where(ok, num / jnp.where(den > 0.0, den, 1.0), muL ** 2)
|
|
103
|
+
mu_c = jnp.where(ok, jnp.sqrt(jnp.clip(ratio, muL ** 2, muH ** 2)),
|
|
104
|
+
jnp.where(den <= 0.0, muH, muL))
|
|
105
|
+
|
|
106
|
+
def n_min(mu):
|
|
107
|
+
a = nL * mu / muL
|
|
108
|
+
d = (mu ** 2 - muL ** 2) * muH
|
|
109
|
+
b = (mu ** 3 * nH - mu * muH * (muH * nH - 2.0 * dp)) / jnp.where(d != 0.0, d, 1.0)
|
|
110
|
+
return jnp.where(mu <= mu_c, a, b)
|
|
111
|
+
|
|
112
|
+
def n_max(mu):
|
|
113
|
+
a = nH * mu / muH
|
|
114
|
+
d = (mu ** 2 - muH ** 2) * muL
|
|
115
|
+
b = (mu ** 3 * nL - muL * mu * (muL * nL + 2.0 * dp)) / jnp.where(d != 0.0, d, 1.0)
|
|
116
|
+
return jnp.where(mu >= mu_c, a, b)
|
|
117
|
+
|
|
118
|
+
def p_min(mu):
|
|
119
|
+
return pL + (mu ** 2 - muL ** 2) / (2.0 * mu) * n_min(mu)
|
|
120
|
+
|
|
121
|
+
n_c0 = n_max(muL) / muL
|
|
122
|
+
|
|
123
|
+
def p_max(mu, n):
|
|
124
|
+
return jnp.where(n <= n_c0 * mu,
|
|
125
|
+
pL + (mu ** 2 - muL ** 2) / (2.0 * mu) * n,
|
|
126
|
+
pH - (muH ** 2 - mu ** 2) / (2.0 * mu) * n)
|
|
127
|
+
|
|
128
|
+
return n_min, n_max, p_min, p_max, mu_c, n_c0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _consistent(a, b, rtol=1e-9):
|
|
132
|
+
muL, nL, pL = a
|
|
133
|
+
muH, nH, pH = b
|
|
134
|
+
dp = pH - pL
|
|
135
|
+
span = muH ** 2 - muL ** 2
|
|
136
|
+
lo = nL * span / (2.0 * muL)
|
|
137
|
+
hi = nH * span / (2.0 * muH)
|
|
138
|
+
tol = rtol * jnp.maximum(jnp.abs(hi), 1.0)
|
|
139
|
+
return (muH > muL) & (nH >= nL) & (lo - tol <= dp) & (dp <= hi + tol)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _sample(a, b, u, n_cdf=256):
|
|
143
|
+
"""One point in the KK volume between triplets a and b from uniforms u[3]."""
|
|
144
|
+
muL, muH = a[0], b[0]
|
|
145
|
+
n_min, n_max, p_min, p_max, mu_c, n_c0 = _kk(a, b)
|
|
146
|
+
m2 = jnp.linspace(muL ** 2, muH ** 2, n_cdf)
|
|
147
|
+
mc2, mL2, mH2 = mu_c ** 2, muL ** 2, muH ** 2
|
|
148
|
+
|
|
149
|
+
def sdiv(x, y):
|
|
150
|
+
good = y > 0.0
|
|
151
|
+
return jnp.where(good, x / jnp.where(good, y, 1.0), 0.0)
|
|
152
|
+
|
|
153
|
+
dens = jnp.where(m2 <= mc2,
|
|
154
|
+
sdiv((m2 - mL2) * (mH2 - mc2), (mc2 - mL2) * (mH2 - m2)),
|
|
155
|
+
sdiv((mH2 - m2) * (mc2 - mL2), (mH2 - mc2) * (m2 - mL2)))
|
|
156
|
+
dens = jnp.where(jnp.isfinite(dens), jnp.clip(dens, 0.0, None), 0.0)
|
|
157
|
+
cdf = jnp.concatenate([jnp.zeros(1), jnp.cumsum(0.5 * (dens[1:] + dens[:-1])
|
|
158
|
+
* jnp.diff(m2))])
|
|
159
|
+
tot = cdf[-1]
|
|
160
|
+
good = jnp.isfinite(tot) & (tot > 0.0)
|
|
161
|
+
mu2 = jnp.where(good, _interp(u[0] * jnp.where(good, tot, 1.0), cdf, m2),
|
|
162
|
+
0.5 * (mL2 + mH2))
|
|
163
|
+
mu = jnp.sqrt(mu2)
|
|
164
|
+
|
|
165
|
+
# n: one inverse CDF over the tent h(n) = p_max(mu, n) - p_min(mu)
|
|
166
|
+
n_lo, n_hi = n_min(mu), n_max(mu)
|
|
167
|
+
n_apex = jnp.minimum(jnp.maximum(n_c0 * mu, n_lo), n_hi)
|
|
168
|
+
pmin = p_min(mu)
|
|
169
|
+
h_apex = jnp.maximum(p_max(mu, n_apex) - pmin, 0.0)
|
|
170
|
+
h_lo = jnp.maximum(p_max(mu, n_lo) - pmin, 0.0)
|
|
171
|
+
h_hi = jnp.maximum(p_max(mu, n_hi) - pmin, 0.0)
|
|
172
|
+
A1 = 0.5 * (h_lo + h_apex) * jnp.maximum(n_apex - n_lo, 0.0)
|
|
173
|
+
A2 = 0.5 * (h_apex + h_hi) * jnp.maximum(n_hi - n_apex, 0.0)
|
|
174
|
+
At = A1 + A2
|
|
175
|
+
w = jnp.where(At > 0.0, A1 / jnp.where(At > 0.0, At, 1.0), 0.5)
|
|
176
|
+
|
|
177
|
+
def trap(x0, x1, h0, h1, s):
|
|
178
|
+
# inverse CDF of a linear density from h0 at x0 to h1 at x1, s in [0, 1]
|
|
179
|
+
dh = h1 - h0
|
|
180
|
+
flat = jnp.abs(dh) <= 1e-14 * jnp.maximum(jnp.abs(h1) + jnp.abs(h0), 1e-300)
|
|
181
|
+
root = jnp.sqrt(jnp.maximum(h0 ** 2 + s * (h1 ** 2 - h0 ** 2), 0.0))
|
|
182
|
+
frac = jnp.where(flat, s, (root - h0) / jnp.where(flat, 1.0, dh))
|
|
183
|
+
return x0 + (x1 - x0) * frac
|
|
184
|
+
|
|
185
|
+
s1 = jnp.clip(u[1] / jnp.where(w > 0.0, w, 1.0), 0.0, 1.0)
|
|
186
|
+
s2 = jnp.clip((u[1] - w) / jnp.where(w < 1.0, 1.0 - w, 1.0), 0.0, 1.0)
|
|
187
|
+
n = jnp.where(u[1] < w, trap(n_lo, n_apex, h_lo, h_apex, s1),
|
|
188
|
+
trap(n_apex, n_hi, h_apex, h_hi, s2))
|
|
189
|
+
n = jnp.where(At > 0.0, n, 0.5 * (n_lo + n_hi))
|
|
190
|
+
p = pmin + u[2] * jnp.maximum(p_max(mu, n) - pmin, 0.0)
|
|
191
|
+
return jnp.stack([mu, n, p])
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _interp(x, xp, fp):
|
|
195
|
+
"""Linear interpolation that stays finite (and has finite derivatives)
|
|
196
|
+
when xp has repeated values."""
|
|
197
|
+
i = jnp.clip(jnp.searchsorted(jax.lax.stop_gradient(xp), jax.lax.stop_gradient(x),
|
|
198
|
+
side="right"), 1, xp.shape[0] - 1)
|
|
199
|
+
x0, x1 = xp[i - 1], xp[i]
|
|
200
|
+
dx = x1 - x0
|
|
201
|
+
t = jnp.where(dx > 0.0, (x - x0) / jnp.where(dx > 0.0, dx, 1.0), 0.0)
|
|
202
|
+
return fp[i - 1] + jnp.clip(t, 0.0, 1.0) * (fp[i] - fp[i - 1])
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# ----------------------------------------------------------- refinement tree -----
|
|
206
|
+
def refine_tree(bL, bH, U, levels=9, min_dlnmu=1e-4):
|
|
207
|
+
"""Level-by-level fractal refinement with fixed uniforms ``U`` of shape
|
|
208
|
+
(2^levels, 3) (row 0 unused; row k is heap node k). Returns the points
|
|
209
|
+
(2^levels + 1, 3) in mu order, with skipped nodes collapsed onto their left
|
|
210
|
+
endpoint, and the per-node validity mask (heap order)."""
|
|
211
|
+
pts = jnp.stack([jnp.stack(bL), jnp.stack(bH)])
|
|
212
|
+
live = jnp.ones(1, bool)
|
|
213
|
+
valid = [jnp.zeros(1, bool)]
|
|
214
|
+
for lev in range(levels):
|
|
215
|
+
a, b = pts[:-1], pts[1:]
|
|
216
|
+
k0 = 2 ** lev
|
|
217
|
+
Uk = U[k0:2 * k0]
|
|
218
|
+
ok = live & (jnp.log(b[:, 0] / a[:, 0]) >= min_dlnmu)
|
|
219
|
+
ok = ok & jax.vmap(lambda x, y: _consistent(tuple(x), tuple(y)))(a, b)
|
|
220
|
+
# a skipped interval is sampled on the root interval instead, and the
|
|
221
|
+
# result discarded: sampling a degenerate interval gives NaN, which
|
|
222
|
+
# would reach the derivatives through jnp.where
|
|
223
|
+
sa = jnp.where(ok[:, None], a, pts[0])
|
|
224
|
+
sb = jnp.where(ok[:, None], b, pts[-1])
|
|
225
|
+
m = jax.vmap(lambda x, y, u: _sample(tuple(x), tuple(y), u))(sa, sb, Uk)
|
|
226
|
+
inside = ((a[:, 0] < m[:, 0]) & (m[:, 0] < b[:, 0]) & (a[:, 1] <= m[:, 1])
|
|
227
|
+
& (m[:, 1] <= b[:, 1]) & (a[:, 2] <= m[:, 2]) & (m[:, 2] <= b[:, 2]))
|
|
228
|
+
ok = ok & inside & jnp.all(jnp.isfinite(m), axis=1)
|
|
229
|
+
m = jnp.where(ok[:, None], m, a)
|
|
230
|
+
valid.append(ok)
|
|
231
|
+
new = jnp.empty((2 * a.shape[0] + 1, 3), pts.dtype)
|
|
232
|
+
new = new.at[0::2].set(pts).at[1::2].set(m)
|
|
233
|
+
pts = new
|
|
234
|
+
live = jnp.repeat(ok, 2)
|
|
235
|
+
return pts, jnp.concatenate(valid)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# ------------------------------------------------------------- diffusion ---------
|
|
239
|
+
def _thomas(a, b, c, d):
|
|
240
|
+
def fwd(carry, x):
|
|
241
|
+
cp, dp = carry
|
|
242
|
+
ai, bi, ci, di = x
|
|
243
|
+
m = bi - ai * cp
|
|
244
|
+
cn = ci / m
|
|
245
|
+
dn = (di - ai * dp) / m
|
|
246
|
+
return (cn, dn), (cn, dn)
|
|
247
|
+
|
|
248
|
+
(_, _), (cp, dp) = jax.lax.scan(fwd, (0.0 * d[0], 0.0 * d[0]), (a, b, c, d))
|
|
249
|
+
|
|
250
|
+
def bwd(xn, x):
|
|
251
|
+
cpi, dpi = x
|
|
252
|
+
xi = dpi - cpi * xn
|
|
253
|
+
return xi, xi
|
|
254
|
+
|
|
255
|
+
_, xs = jax.lax.scan(bwd, dp[-1], (cp[:-1], dp[:-1]), reverse=True)
|
|
256
|
+
return jnp.concatenate([xs, dp[-1:]])
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def diffuse_mu_of_n(x, mu, corr_frac, n_steps=40):
|
|
260
|
+
"""Backward-Euler diffusion of ln mu in x = ln n, Dirichlet ends (bridge.py)."""
|
|
261
|
+
dx = x[1] - x[0]
|
|
262
|
+
u = jnp.log(mu)
|
|
263
|
+
N = x.shape[0]
|
|
264
|
+
D = 0.25 * corr_frac ** 2
|
|
265
|
+
r = (1.0 / n_steps) * D / dx ** 2
|
|
266
|
+
a = jnp.full(N, -r).at[0].set(0.0).at[-1].set(0.0)
|
|
267
|
+
c = jnp.full(N, -r).at[0].set(0.0).at[-1].set(0.0)
|
|
268
|
+
b = jnp.full(N, 1.0 + 2.0 * r).at[0].set(1.0).at[-1].set(1.0)
|
|
269
|
+
|
|
270
|
+
def step(uu, _):
|
|
271
|
+
return _thomas(a, b, c, uu), None
|
|
272
|
+
|
|
273
|
+
u, _ = jax.lax.scan(step, u, None, length=n_steps)
|
|
274
|
+
return jnp.exp(u)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ------------------------------------------------------------- one draw ----------
|
|
278
|
+
class Plan(NamedTuple):
|
|
279
|
+
"""Static row counts, fixed by the concrete values at the evaluation point."""
|
|
280
|
+
n_keep: int # low-table rows strictly below n_L
|
|
281
|
+
n_sel: int # bridge-grid rows at or below n_term for the largest n_H
|
|
282
|
+
n_sat_sel: float = N_SAT # n_sat at which n_sel was counted
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class Config(NamedTuple):
|
|
286
|
+
"""Settings as in :func:`bridge.draw_bridge_eos`. ``min_dlnmu`` is not an
|
|
287
|
+
argument there; its default is the one :func:`bridge.fractal_refine` uses."""
|
|
288
|
+
levels: int = 9
|
|
289
|
+
n_L_fac: float = 2.0
|
|
290
|
+
n_term_fac: float = 12.0
|
|
291
|
+
n_grid_pts: int = 600
|
|
292
|
+
n_steps: int = 40
|
|
293
|
+
min_dlnmu: float = 1e-4
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def unpack(theta, nep_names, levels):
|
|
297
|
+
"""theta = [nep..., corr_frac, ln_X, z (2^levels - 1, 3) flattened]."""
|
|
298
|
+
k = len(nep_names)
|
|
299
|
+
nep = {nm: theta[i] for i, nm in enumerate(nep_names)}
|
|
300
|
+
z = theta[k + 2:].reshape(2 ** levels - 1, 3)
|
|
301
|
+
return nep, theta[k], theta[k + 1], z
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _is_concrete(x):
|
|
305
|
+
return not isinstance(x, jax.core.Tracer)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def bridge_arrays(model, theta, nep_names, plan: Plan, cfg: Config = Config()):
|
|
309
|
+
"""(n, eps, p, info) of one draw, MeV/fm^3, as JAX arrays of static length.
|
|
310
|
+
|
|
311
|
+
``info["valid"]`` is False where :func:`bridge.draw_bridge_eos` would raise
|
|
312
|
+
(``anchors_ok``: anchors inconsistent; ``in_table``: n_L outside the
|
|
313
|
+
low-density table) or where ``plan`` no longer fits the low-density table
|
|
314
|
+
(``plan_ok``); n, eps and p are then NaN. Outside a trace this raises
|
|
315
|
+
ValueError instead. ``info["node_ok"]`` is the per-node mask of the
|
|
316
|
+
refinement tree (heap order; skipped nodes are normal)."""
|
|
317
|
+
if plan.n_sel != _n_sel(cfg.n_L_fac, cfg.n_term_fac, cfg.n_grid_pts,
|
|
318
|
+
plan.n_sat_sel):
|
|
319
|
+
raise ValueError(f"plan {plan} was made for other settings than {cfg}")
|
|
320
|
+
nep, corr_frac, ln_X, z = unpack(theta, nep_names, cfg.levels)
|
|
321
|
+
n_sat = nep.get("n_sat", N_SAT)
|
|
322
|
+
n_L = cfg.n_L_fac * n_sat
|
|
323
|
+
n_cut = n_L * (1.0 - 1e-12)
|
|
324
|
+
t = model.eos_table(nep)
|
|
325
|
+
n_lo, eps_lo, p_lo = t.n, t.eps_mevfm3, t.p_mevfm3
|
|
326
|
+
eps_L = jnp.interp(n_L, n_lo, eps_lo)
|
|
327
|
+
p_L = jnp.interp(n_L, n_lo, p_lo)
|
|
328
|
+
mu_L = (eps_L + p_L) / n_L
|
|
329
|
+
bL = (mu_L, jnp.asarray(n_L), p_L)
|
|
330
|
+
bH = pqcd_anchor(ln_X)
|
|
331
|
+
|
|
332
|
+
k, s = plan.n_keep, plan.n_sel
|
|
333
|
+
in_table = (n_lo[0] < n_cut) & (n_cut <= n_lo[-1])
|
|
334
|
+
plan_ok = jnp.asarray(0 < k < n_lo.shape[0])
|
|
335
|
+
if 0 < k < n_lo.shape[0]:
|
|
336
|
+
plan_ok = (n_lo[k - 1] < n_cut) & (n_lo[k] >= n_cut)
|
|
337
|
+
anchors_ok = _consistent(bL, bH)
|
|
338
|
+
# last kept bridge row at or below n_term (the grid ends at this draw's n_H)
|
|
339
|
+
n_term = cfg.n_term_fac * n_sat
|
|
340
|
+
if math.isinf(cfg.n_term_fac):
|
|
341
|
+
rows_ok = jnp.asarray(True)
|
|
342
|
+
else:
|
|
343
|
+
ln_last = (jnp.log(n_L) + (jnp.log(bH[1]) - jnp.log(n_L))
|
|
344
|
+
* (s - 1) / (cfg.n_grid_pts - 1))
|
|
345
|
+
rows_ok = ln_last <= jnp.log(n_term) + 1e-12
|
|
346
|
+
valid = in_table & plan_ok & anchors_ok & rows_ok
|
|
347
|
+
if _is_concrete(valid) and not bool(valid):
|
|
348
|
+
raise ValueError(f"no bridge: n_L in table {bool(in_table)}, plan fits "
|
|
349
|
+
f"{bool(plan_ok)}, anchors consistent {bool(anchors_ok)}, "
|
|
350
|
+
f"rows at or below n_term {bool(rows_ok)} "
|
|
351
|
+
f"(mu_L={float(mu_L):.1f} MeV)")
|
|
352
|
+
|
|
353
|
+
U = jnp.concatenate([jnp.full((1, 3), 0.5),
|
|
354
|
+
jnp.clip(ndtr(z), _U_EPS, 1.0 - _U_EPS)])
|
|
355
|
+
pts, node_ok = refine_tree(bL, bH, U, cfg.levels, cfg.min_dlnmu)
|
|
356
|
+
ln_n_L = math.log(n_L) if _is_concrete(n_L) else jnp.log(n_L)
|
|
357
|
+
x = jnp.linspace(ln_n_L, jnp.log(bH[1]), cfg.n_grid_pts)
|
|
358
|
+
mu_grid = jnp.exp(_interp(x, jnp.log(pts[:, 1]), jnp.log(pts[:, 0])))
|
|
359
|
+
mu_s = jax.lax.cummax(diffuse_mu_of_n(x, mu_grid, corr_frac, cfg.n_steps))
|
|
360
|
+
grid = jnp.exp(x)
|
|
361
|
+
eps_b = eps_L + jnp.concatenate(
|
|
362
|
+
[jnp.zeros(1), jnp.cumsum(0.5 * (mu_s[1:] + mu_s[:-1]) * jnp.diff(grid))])
|
|
363
|
+
p_b = mu_s * grid - eps_b
|
|
364
|
+
n = jnp.concatenate([n_lo[:k], grid[:s]])
|
|
365
|
+
eps = jnp.concatenate([eps_lo[:k], eps_b[:s]])
|
|
366
|
+
p = jnp.concatenate([p_lo[:k], p_b[:s]])
|
|
367
|
+
n, eps, p = (jnp.where(valid, a, jnp.nan) for a in (n, eps, p))
|
|
368
|
+
return n, eps, p, dict(mu_L=mu_L, p_L=p_L, p_end_mismatch=(p_b[-1] - bH[2]) / bH[2],
|
|
369
|
+
grid=grid, mu=mu_s, pts=pts, node_ok=node_ok,
|
|
370
|
+
valid=valid, in_table=in_table, plan_ok=plan_ok,
|
|
371
|
+
anchors_ok=anchors_ok, rows_ok=rows_ok)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
@functools.lru_cache(maxsize=1024)
|
|
375
|
+
def _n_sel(n_L_fac, n_term_fac, n_grid_pts, n_sat=N_SAT):
|
|
376
|
+
"""Bridge-grid rows at or below n_term for the largest n_H over X in
|
|
377
|
+
[1, 4] (the fewest rows), so one length serves every X."""
|
|
378
|
+
xs = np.linspace(0.0, math.log(4.0), 65)
|
|
379
|
+
n_H = max(float(np.polyval(_C_N, x)) for x in xs)
|
|
380
|
+
n_L = n_L_fac * n_sat
|
|
381
|
+
grid = np.exp(np.linspace(math.log(n_L), math.log(n_H), n_grid_pts))
|
|
382
|
+
return int(np.sum(grid <= n_term_fac * n_sat))
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def make_plan(model, theta, nep_names, cfg: Config = Config(), n_sat_min=None):
|
|
386
|
+
"""Concrete pass: the static row counts at this evaluation point.
|
|
387
|
+
|
|
388
|
+
``n_sat_min``: count bridge rows at min(n_sat, n_sat_min), so the plan
|
|
389
|
+
holds for every n_sat above it (see the module notes).
|
|
390
|
+
|
|
391
|
+
Raises ValueError where :func:`bridge.draw_bridge_eos` would (n_L outside
|
|
392
|
+
the low-density table, inconsistent anchors). The plan holds at other
|
|
393
|
+
points while the low-density table keeps the same number of rows below
|
|
394
|
+
n_L, which :func:`bridge_arrays` checks."""
|
|
395
|
+
nep, _, ln_X, _ = unpack(np.asarray(theta), nep_names, cfg.levels)
|
|
396
|
+
n_sat = float(nep.get("n_sat", N_SAT))
|
|
397
|
+
if not (math.isfinite(n_sat) and n_sat > 0.0):
|
|
398
|
+
raise ValueError(f"n_sat must be finite and positive, got {n_sat!r}")
|
|
399
|
+
n_L = cfg.n_L_fac * n_sat
|
|
400
|
+
n_cut = n_L * (1.0 - 1e-12)
|
|
401
|
+
t = model.eos_table({k: float(v) for k, v in nep.items()})
|
|
402
|
+
n_lo, eps_lo, p_lo = (np.asarray(a) for a in (t.n, t.eps_mevfm3, t.p_mevfm3))
|
|
403
|
+
if not n_lo[0] < n_cut <= n_lo[-1]:
|
|
404
|
+
raise ValueError(f"low-density table spans n={n_lo[0]:.4g} to "
|
|
405
|
+
f"{n_lo[-1]:.4g} fm^-3, which must contain "
|
|
406
|
+
f"n_L={n_L:.4g} fm^-3")
|
|
407
|
+
eps_L, p_L = np.interp(n_L, n_lo, eps_lo), np.interp(n_L, n_lo, p_lo)
|
|
408
|
+
bL = ((eps_L + p_L) / n_L, n_L, p_L)
|
|
409
|
+
bH = tuple(float(v) for v in pqcd_anchor(float(ln_X)))
|
|
410
|
+
if not _interval_consistent(bL, bH):
|
|
411
|
+
raise ValueError(f"anchors inconsistent (mu_L={bL[0]:.1f} MeV)")
|
|
412
|
+
n_keep = int(np.sum(n_lo < n_cut))
|
|
413
|
+
n_sat_sel = n_sat if n_sat_min is None else min(n_sat, float(n_sat_min))
|
|
414
|
+
return Plan(n_keep=n_keep,
|
|
415
|
+
n_sel=_n_sel(cfg.n_L_fac, cfg.n_term_fac, cfg.n_grid_pts,
|
|
416
|
+
n_sat_sel),
|
|
417
|
+
n_sat_sel=n_sat_sel)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def bridge_table(model, theta, nep_names, plan: Plan, cfg: Config = Config()):
|
|
421
|
+
"""EOSTable of one draw (geometric units), differentiable in ``theta``.
|
|
422
|
+
NaN where ``bridge_arrays`` flags the draw invalid."""
|
|
423
|
+
from ..eos.base import build_h_and_cs2
|
|
424
|
+
n, eps, p, _ = bridge_arrays(model, theta, nep_names, plan, cfg)
|
|
425
|
+
return build_h_and_cs2(n, eps, p)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def draw_theta(rng, nep, corr_range=(0.2, 0.4), levels=9, nep_names=None):
|
|
429
|
+
"""A prior draw of theta for given nep (dict): corr_frac ~ U(corr_range),
|
|
430
|
+
ln X ~ U(0, ln 4), z ~ N(0, 1)."""
|
|
431
|
+
nep_names = list(nep) if nep_names is None else nep_names
|
|
432
|
+
c = rng.uniform(*corr_range)
|
|
433
|
+
lnX = rng.uniform(0.0, math.log(4.0))
|
|
434
|
+
z = rng.standard_normal((2 ** levels - 1) * 3)
|
|
435
|
+
return np.concatenate([[nep[k] for k in nep_names], [c, lnX], z])
|