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,587 @@
1
+ """Density-tagged laboratory (FRIB/HIC) likelihoods for the metamodel EOS (MB-N2).
2
+
3
+ Two encodings of laboratory symmetry-energy constraints, per the FRIB scoping
4
+ decision (nmb-papers ``scoping/FRIB-SCOPING.md`` §2, §3.2 proposal MB-N2):
5
+
6
+ 1. **Density-tagged pressure likelihood** (recommended primary encoding, after
7
+ Huth et al. arXiv:2107.06229 and Tsang et al. arXiv:2310.11588): each
8
+ constraint k carries a *sensitive density* n_k and a Gaussian measurement of
9
+ the symmetry pressure there,
10
+
11
+ lnL(EOS) = sum_k ln N( P_sym(n_k); mu_k, sigma_k^2 + sigma_model^2 )
12
+
13
+ where sigma_model is the **transport-model systematic floor** — the
14
+ across-code spread of HIC extractions (e.g. SpiRIT's seven-code spread).
15
+ sigma_model may be a fixed value *or a prior*, in which case it is
16
+ **marginalized numerically** (`SigmaModelPrior`). The hierarchical
17
+ treatment of the lab systematic is this module's novel feature and the
18
+ honest response to the PREX/CREX episode: never encode an observable as a
19
+ fixed-width likelihood when the extraction map itself is uncertain.
20
+
21
+ Information content: P_sym = n^2 dS/dn carries **no E_sym information**
22
+ (E_sym is the constant term of S(n) and dies under d/dn) — dlnL/dE_sym is
23
+ identically zero. Replacing the (E_sym, L_sym) Gaussian below with this
24
+ encoding therefore *discards* any sigma(E_sym) constraint a scenario
25
+ carries; combine both forms if both pieces of information are wanted.
26
+
27
+ 2. **Correlated (E_sym, L_sym) Gaussian** (`CorrelatedSymGaussian`): the cheap
28
+ parameter-space alternative, with a full 2x2 covariance (off-diagonal
29
+ E_sym–L_sym correlation), matching the metamodel NEP coordinates directly.
30
+ Pitfall to remember: this form imports whatever model map was used to
31
+ extract (S0, L) from data.
32
+
33
+ P_sym(n) is evaluated from the metamodel symmetry-energy expansion
34
+ (``eos/metamodel.py``: S(n) = E_sym + L_sym x + K_sym x^2/2 + Q_sym x^3/6,
35
+ x = (n - n_sat)/(3 n_sat)) via the thermodynamic derivative
36
+
37
+ P_sym(n) = n^2 dS/dn [MeV/fm^3],
38
+
39
+ computed with ``jax.grad`` of the *same* ``_esat_S`` the EOS table uses, so the
40
+ likelihood and the EOS can never use different expansions. At saturation this
41
+ reduces to the textbook P_sym(n_sat) = n_sat L_sym / 3. Everything here is
42
+ differentiable w.r.t. the NEPs (fixed *and* marginalized forms), so these
43
+ likelihoods drop into the Fisher / AD-Jacobian machinery unchanged. Unknown
44
+ parameter keys are rejected (a typo'd key would otherwise silently return the
45
+ fiducial likelihood with zero gradient).
46
+
47
+ **Beta-equilibrium caveat (MB-N5) — read before tagging densities at or above
48
+ ~2 n_sat.** In the full bridge EOS (``priors/bridge.py``), everything from
49
+ the bridge matching density upward (``n_L_fac * n_sat``, default 2 n_sat) is a
50
+ nonparametric *beta-equilibrated* sector: it carries no isospin decomposition,
51
+ so a symmetric/asymmetric-matter quantity like P_sym is simply not defined
52
+ there for a bridge draw. A density-tagged likelihood with n_k at or above the
53
+ matching density therefore applies to the **metamodel sector only** (the
54
+ analytic expansion extrapolated past its match point), *not* to the bridge —
55
+ it constrains bridge draws only indirectly, through the sub-2 n_sat anchor and
56
+ continuity. Quantifying how much of a P_sym(2 n0) likelihood survives that
57
+ beta-eq projection is exactly the open "isospin map" question (MB-N5); this
58
+ module warns when you cross the line but does not resolve it. The default
59
+ warning threshold is the metamodel's own ``n_match_fac * n_sat``; if you draw
60
+ bridges with a non-default ``n_L_fac``, pass the true boundary explicitly as
61
+ ``n_beta_eq`` — the two knobs are independent and only coincide at defaults.
62
+
63
+ Scenario input: `load_scenario_ladder()` reads the packaged **copy** of the
64
+ FRIB scenario ladder (``data/frib_scenario_ladder.yaml``). The source of
65
+ truth lives in nmb-papers ``scoping/frib_scenario_ladder.yaml``; the copy
66
+ carries a provenance header, and every number in it is an *assumption* — no
67
+ published paper commits to "sigma_L = +/-X by year Y" for FRIB.
68
+
69
+ Downstream consumers: the p5-crossover Tier-B forecast (claim C3 encoding
70
+ comparison) and the paper-1 EM-likelihood robustness variant in nmb-papers.
71
+
72
+ Motivated by: Huth et al. Nature 606 (2022) 276 (arXiv:2107.06229) and
73
+ Tsang et al. (arXiv:2310.11588) — pressure-at-density likelihood encodings
74
+ re-implemented from the papers, no code reused; (S0, L) Gaussian priors after
75
+ Biswas et al. / the Margueron metamodel line. See ATTRIBUTION.md.
76
+ """
77
+ from __future__ import annotations
78
+
79
+ import math
80
+ import warnings
81
+ from dataclasses import dataclass, field
82
+ from importlib import resources
83
+ from typing import Optional, Sequence, Union
84
+
85
+ import numpy as np
86
+ import jax
87
+ import jax.numpy as jnp
88
+ from jax.scipy.special import logsumexp
89
+
90
+ from .eos.metamodel import DEFAULT_PARAMS, _esat_S
91
+
92
+ jax.config.update("jax_enable_x64", True)
93
+
94
+ _LOG_2PI = float(np.log(2.0 * np.pi))
95
+
96
+ __all__ = [
97
+ "psym",
98
+ "DensityTaggedConstraint",
99
+ "SigmaModelPrior",
100
+ "DensityTaggedPressureLikelihood",
101
+ "CorrelatedSymGaussian",
102
+ "load_scenario_ladder",
103
+ "scenario_by_name",
104
+ "gaussian_from_scenario",
105
+ "density_tagged_from_scenario",
106
+ ]
107
+
108
+
109
+ # ----------------------------------------------------------------------------
110
+ # P_sym(n) from the metamodel expansion
111
+ # ----------------------------------------------------------------------------
112
+
113
+ def _merged(params: Optional[dict], base: Optional[dict] = None) -> dict:
114
+ """Merge ``params`` over ``base`` (default: metamodel DEFAULT_PARAMS).
115
+
116
+ Unknown keys raise: a typo'd NEP key ("Lsym") would otherwise be silently
117
+ ignored, returning the fiducial likelihood with an exactly-zero gradient —
118
+ the easiest way to produce a wrong-but-plausible robustness number.
119
+ """
120
+ p = dict(DEFAULT_PARAMS if base is None else base)
121
+ if params:
122
+ unknown = sorted(set(params) - set(DEFAULT_PARAMS))
123
+ if unknown:
124
+ raise ValueError(
125
+ f"unknown EOS parameter key(s) {unknown}; known keys: "
126
+ f"{sorted(DEFAULT_PARAMS)}")
127
+ p.update(params)
128
+ return p
129
+
130
+
131
+ def _psym_of(n_arr, p: dict):
132
+ """P_sym on a 1D array for a fully merged parameter dict."""
133
+ dS_dn = jax.vmap(jax.grad(lambda nn: _esat_S(nn, p)[1]))(n_arr)
134
+ return n_arr**2 * dS_dn
135
+
136
+
137
+ def psym(n, params: Optional[dict] = None):
138
+ """Symmetry pressure P_sym(n) = n^2 dS/dn [MeV/fm^3] of the metamodel.
139
+
140
+ ``n`` is baryon density in fm^-3 (scalar or array of any rank; the output
141
+ has the input's shape); ``params`` overrides
142
+ ``eos.metamodel.DEFAULT_PARAMS`` (E_sym, L_sym, K_sym, Q_sym, n_sat, ...) —
143
+ unknown keys raise. Differentiable w.r.t. the NEPs. dS/dn is taken with
144
+ ``jax.grad`` of the same symmetry-energy expansion the EOS table is built
145
+ from, so this cannot drift from the EOS. At n = n_sat it equals
146
+ n_sat * L_sym / 3.
147
+ """
148
+ p = _merged(params)
149
+ n_arr = jnp.asarray(n, dtype=jnp.float64)
150
+ return _psym_of(n_arr.ravel(), p).reshape(n_arr.shape)
151
+
152
+
153
+ # ----------------------------------------------------------------------------
154
+ # density-tagged pressure likelihood
155
+ # ----------------------------------------------------------------------------
156
+
157
+ @dataclass(frozen=True)
158
+ class DensityTaggedConstraint:
159
+ """One laboratory constraint: P_sym at its sensitive density.
160
+
161
+ Density-sensitivity assignment after Tsang et al. arXiv:2310.11588: each
162
+ experiment constrains the symmetry pressure at one tagged density n_k.
163
+
164
+ Attributes
165
+ ----------
166
+ n : float sensitive density [fm^-3]
167
+ mu : float measured P_sym(n) central value [MeV/fm^3]
168
+ sigma : float measurement (statistical+experimental) width [MeV/fm^3];
169
+ the transport-model floor sigma_model is NOT included
170
+ here — it is a shared hyperparameter of the likelihood.
171
+ name : str label (e.g. "SpiRIT pions", "FRIB400 P_sym(2n0)")
172
+ source : str provenance note (arXiv id / scenario ladder entry)
173
+ """
174
+ n: float
175
+ mu: float
176
+ sigma: float
177
+ name: str = ""
178
+ source: str = ""
179
+
180
+ def __post_init__(self):
181
+ for attr in ("n", "mu", "sigma"):
182
+ if not math.isfinite(getattr(self, attr)):
183
+ raise ValueError(f"constraint {self.name!r}: {attr} must be finite")
184
+ if not (self.n > 0.0):
185
+ raise ValueError(f"constraint {self.name!r}: density must be > 0")
186
+ # sigma**2 must survive squaring in float64 (sigma ~ 1e-200 would give
187
+ # var = 0 and a NaN likelihood downstream)
188
+ if not (self.sigma > 0.0 and self.sigma**2 > 0.0):
189
+ raise ValueError(f"constraint {self.name!r}: sigma must be > 0 "
190
+ "(and sigma**2 must not underflow)")
191
+
192
+
193
+ @dataclass(frozen=True)
194
+ class SigmaModelPrior:
195
+ """Numerical prior over the transport-model systematic floor sigma_model.
196
+
197
+ Represented as quadrature nodes ``grid`` (sigma values, MeV/fm^3) with
198
+ ``log_weights`` (prior pdf x quadrature weight). Weights are validated and
199
+ normalized (so logsumexp(log_weights) = 0) on construction — including
200
+ direct ``SigmaModelPrior(grid, log_weights)`` construction, so a
201
+ hand-built prior cannot silently offset the evidence. Marginalization is
202
+ then a logsumexp — exact for a delta prior, trapezoid-accurate otherwise
203
+ (default n=129 is accurate to ~3e-6 in lnL in the worst realistic case),
204
+ and differentiable w.r.t. the EOS parameters.
205
+ """
206
+ grid: tuple = field(repr=False)
207
+ log_weights: tuple = field(repr=False)
208
+ label: str = ""
209
+
210
+ def __post_init__(self):
211
+ grid = np.asarray(self.grid, dtype=float)
212
+ logw = np.asarray(self.log_weights, dtype=float)
213
+ if grid.ndim != 1 or grid.shape != logw.shape or grid.size < 1:
214
+ raise ValueError("grid and log_weights must be equal-length 1D")
215
+ if not np.all(np.isfinite(grid)) or np.any(grid < 0.0):
216
+ raise ValueError("sigma_model support must be finite and >= 0")
217
+ if np.any(np.isnan(logw)):
218
+ raise ValueError("log_weights must not contain NaN")
219
+ m = np.max(logw)
220
+ if not np.isfinite(m):
221
+ raise ValueError("log_weights must contain at least one finite entry")
222
+ logw = logw - (m + np.log(np.sum(np.exp(logw - m))))
223
+ object.__setattr__(self, "grid", tuple(grid))
224
+ object.__setattr__(self, "log_weights", tuple(logw))
225
+
226
+ @classmethod
227
+ def _trapezoid(cls, grid, logpdf_vals, label) -> "SigmaModelPrior":
228
+ """Trapezoid rule on a uniform grid; the single quadrature site."""
229
+ w = np.full(len(grid), 1.0)
230
+ w[0] *= 0.5
231
+ w[-1] *= 0.5
232
+ return cls(tuple(grid), tuple(np.asarray(logpdf_vals) + np.log(w)), label)
233
+
234
+ @classmethod
235
+ def fixed(cls, value: float) -> "SigmaModelPrior":
236
+ """Delta prior — marginalization reduces exactly to the fixed form."""
237
+ return cls((value,), (0.0,), f"fixed({value})")
238
+
239
+ @classmethod
240
+ def uniform(cls, lo: float, hi: float, n: int = 129) -> "SigmaModelPrior":
241
+ if not (0.0 <= lo < hi):
242
+ raise ValueError("need 0 <= lo < hi")
243
+ if n < 2:
244
+ raise ValueError("need n >= 2 quadrature nodes (n=1 would silently "
245
+ "collapse to a delta at lo; use .fixed() for a delta)")
246
+ g = np.linspace(lo, hi, n)
247
+ return cls._trapezoid(g, np.zeros(n), f"uniform[{lo},{hi}]")
248
+
249
+ @classmethod
250
+ def half_normal(cls, scale: float, n: int = 129,
251
+ n_scales: float = 5.0) -> "SigmaModelPrior":
252
+ """Half-normal on sigma_model >= 0 (truncated at n_scales*scale)."""
253
+ if not scale > 0.0:
254
+ raise ValueError("scale must be > 0")
255
+ if n < 2:
256
+ raise ValueError("need n >= 2 quadrature nodes (use .fixed() for a delta)")
257
+ g = np.linspace(0.0, n_scales * scale, n)
258
+ return cls._trapezoid(g, -0.5 * (g / scale) ** 2, f"half_normal({scale})")
259
+
260
+ @classmethod
261
+ def from_logpdf(cls, logpdf, lo: float, hi: float,
262
+ n: int = 129, label: str = "custom") -> "SigmaModelPrior":
263
+ """Arbitrary (unnormalized) logpdf callable on [lo, hi]."""
264
+ if not lo < hi:
265
+ raise ValueError("need lo < hi")
266
+ if n < 2:
267
+ raise ValueError("need n >= 2 quadrature nodes (use .fixed() for a delta)")
268
+ g = np.linspace(lo, hi, n)
269
+ lp = np.array([float(logpdf(s)) for s in g])
270
+ return cls._trapezoid(g, lp, label)
271
+
272
+
273
+ def _ln_normal(x, mu, var):
274
+ return -0.5 * (_LOG_2PI + jnp.log(var) + (x - mu) ** 2 / var)
275
+
276
+
277
+ class DensityTaggedPressureLikelihood:
278
+ """lnL(EOS) = sum_k ln N(P_sym(n_k); mu_k, sigma_k^2 + sigma_model^2).
279
+
280
+ ``sigma_model`` (the transport-model systematic floor, shared across
281
+ constraints) is either a fixed float or a `SigmaModelPrior`; with a prior
282
+ it is marginalized numerically:
283
+
284
+ lnL_marg = ln integral dsigma p(sigma) prod_k N(...; sigma_k^2 + sigma^2)
285
+
286
+ Both forms include the Gaussian normalization (mandatory for the
287
+ marginalization to be meaningful) and are differentiable w.r.t. the NEP
288
+ dict passed to ``__call__`` / ``ln_likelihood`` (unknown keys raise).
289
+
290
+ ``eos_params`` is the **fiducial** parameter set: it becomes the base the
291
+ per-call ``params`` are merged over, so a likelihood built at a non-default
292
+ fiducial evaluates at that fiducial by default.
293
+
294
+ Beta-equilibrium caveat (MB-N5): constraints tagged at or above the bridge
295
+ matching density apply to the **metamodel sector only**, not to the
296
+ beta-equilibrated nonparametric bridge — see the module docstring.
297
+ Construction warns when a tag reaches that boundary (silence with
298
+ ``warn_above_match=False`` once acknowledged). The default threshold is
299
+ the metamodel's ``n_match_fac * n_sat``; when drawing bridges with a
300
+ non-default ``n_L_fac``, pass the true boundary as ``n_beta_eq`` — the two
301
+ knobs are independent and only coincide at defaults.
302
+ """
303
+
304
+ def __init__(self,
305
+ constraints: Sequence[DensityTaggedConstraint],
306
+ sigma_model: Union[float, SigmaModelPrior] = 0.0,
307
+ warn_above_match: bool = True,
308
+ eos_params: Optional[dict] = None,
309
+ n_beta_eq: Optional[float] = None):
310
+ constraints = tuple(constraints)
311
+ if len(constraints) == 0:
312
+ raise ValueError("need at least one constraint")
313
+ self.constraints = constraints
314
+ if isinstance(sigma_model, SigmaModelPrior):
315
+ self.sigma_model = sigma_model
316
+ self._prior_grid = jnp.asarray(sigma_model.grid, dtype=jnp.float64)
317
+ self._prior_logw = jnp.asarray(sigma_model.log_weights,
318
+ dtype=jnp.float64)
319
+ else:
320
+ sm = float(sigma_model) # rejects SigmaModelPrior-like misuse,
321
+ if not (math.isfinite(sm) and sm >= 0.0): # catches np/jnp scalars
322
+ raise ValueError("sigma_model must be finite and >= 0")
323
+ self.sigma_model = sm
324
+ self._prior_grid = self._prior_logw = None
325
+ self._n = jnp.asarray([c.n for c in constraints], dtype=jnp.float64)
326
+ self._mu = jnp.asarray([c.mu for c in constraints], dtype=jnp.float64)
327
+ self._sig = jnp.asarray([c.sigma for c in constraints], dtype=jnp.float64)
328
+
329
+ self.eos_params = _merged(eos_params)
330
+ if n_beta_eq is None:
331
+ n_beta_eq = self.eos_params["n_match_fac"] * self.eos_params["n_sat"]
332
+ self.n_beta_eq = float(n_beta_eq)
333
+ at_or_above = [c for c in constraints if c.n >= self.n_beta_eq]
334
+ if at_or_above and warn_above_match:
335
+ names = ", ".join(c.name or f"n={c.n:g}" for c in at_or_above)
336
+ warnings.warn(
337
+ f"density tag(s) at or above the matching density n_beta_eq = "
338
+ f"{self.n_beta_eq:g} fm^-3 ({names}): from there up the bridge "
339
+ "EOS is beta-equilibrated-only, so this likelihood applies to "
340
+ "the metamodel sector, not the bridge (MB-N5; see the "
341
+ "nmbackend.lab_likelihood module docstring). If your bridge "
342
+ "uses a non-default n_L_fac, pass the true boundary as "
343
+ "n_beta_eq=. Silence with warn_above_match=False.",
344
+ UserWarning, stacklevel=2)
345
+
346
+ def psym_tagged(self, params: Optional[dict] = None):
347
+ """P_sym at the tagged densities [MeV/fm^3], shape (n_constraints,).
348
+
349
+ ``params`` are merged over the construction-time fiducial
350
+ ``eos_params`` (unknown keys raise).
351
+ """
352
+ return _psym_of(self._n, _merged(params, base=self.eos_params))
353
+
354
+ def ln_likelihood(self, params: Optional[dict] = None,
355
+ sigma_model: Optional[float] = None):
356
+ """Fixed-sigma_model log-likelihood (normalized Gaussian sum)."""
357
+ if isinstance(sigma_model, SigmaModelPrior):
358
+ raise TypeError("got a SigmaModelPrior; use "
359
+ "ln_likelihood_marginalized(prior=...) to marginalize")
360
+ if sigma_model is None:
361
+ if isinstance(self.sigma_model, SigmaModelPrior):
362
+ raise TypeError("sigma_model is a prior; use "
363
+ "ln_likelihood_marginalized (or __call__)")
364
+ sigma_model = self.sigma_model
365
+ ps = self.psym_tagged(params)
366
+ var = self._sig**2 + jnp.asarray(sigma_model, dtype=jnp.float64) ** 2
367
+ return jnp.sum(_ln_normal(ps, self._mu, var))
368
+
369
+ def ln_likelihood_marginalized(self, params: Optional[dict] = None,
370
+ prior: Optional[SigmaModelPrior] = None):
371
+ """sigma_model numerically marginalized under ``prior``.
372
+
373
+ Defaults to the prior given at construction. Implemented as
374
+ logsumexp(log_weights + lnL(sigma_i)) over the prior's quadrature
375
+ grid — differentiable w.r.t. ``params``.
376
+ """
377
+ if prior is None:
378
+ if not isinstance(self.sigma_model, SigmaModelPrior):
379
+ raise TypeError("no SigmaModelPrior given at construction; "
380
+ "pass prior= explicitly")
381
+ grid, logw = self._prior_grid, self._prior_logw
382
+ elif isinstance(prior, SigmaModelPrior):
383
+ grid = jnp.asarray(prior.grid, dtype=jnp.float64)
384
+ logw = jnp.asarray(prior.log_weights, dtype=jnp.float64)
385
+ else:
386
+ raise TypeError(f"prior must be a SigmaModelPrior, got "
387
+ f"{type(prior).__name__}; for a fixed sigma_model "
388
+ "use ln_likelihood(sigma_model=...)")
389
+ ps = self.psym_tagged(params)
390
+ var = self._sig[None, :] ** 2 + grid[:, None] ** 2 # (n_sigma, n_k)
391
+ lnL = jnp.sum(_ln_normal(ps[None, :], self._mu[None, :], var), axis=1)
392
+ return logsumexp(logw + lnL)
393
+
394
+ def __call__(self, params: Optional[dict] = None):
395
+ """Dispatch on the sigma_model given at construction."""
396
+ if isinstance(self.sigma_model, SigmaModelPrior):
397
+ return self.ln_likelihood_marginalized(params)
398
+ return self.ln_likelihood(params)
399
+
400
+
401
+ # ----------------------------------------------------------------------------
402
+ # correlated (E_sym, L_sym) Gaussian — the cheap alternative encoding
403
+ # ----------------------------------------------------------------------------
404
+
405
+ class CorrelatedSymGaussian:
406
+ """Full-covariance 2x2 Gaussian likelihood on (E_sym, L_sym) [MeV].
407
+
408
+ The cheap parameter-space encoding (Biswas / Margueron-line style). Keep
409
+ in mind that it imports the model map used to extract (S0, L) from data —
410
+ the PREX-vs-CREX discrepancy is the same skin under different maps; the
411
+ density-tagged form above is the more honest encoding.
412
+ """
413
+
414
+ def __init__(self, mean, cov):
415
+ mean = np.asarray(mean, dtype=float)
416
+ cov = np.asarray(cov, dtype=float)
417
+ if mean.shape != (2,) or cov.shape != (2, 2):
418
+ raise ValueError("mean must be (2,), cov (2,2): [E_sym, L_sym]")
419
+ if not (np.all(np.isfinite(mean)) and np.all(np.isfinite(cov))):
420
+ raise ValueError("mean and cov must be finite")
421
+ if not np.allclose(cov, cov.T):
422
+ raise ValueError("cov must be symmetric")
423
+ sign, logdet = np.linalg.slogdet(cov)
424
+ if not (sign > 0 and np.all(np.diag(cov) > 0)):
425
+ raise ValueError("cov must be positive definite")
426
+ self.mean = jnp.asarray(mean)
427
+ self.cov = jnp.asarray(cov)
428
+ self._inv = jnp.asarray(np.linalg.inv(cov))
429
+ self._logdet = float(logdet)
430
+
431
+ @classmethod
432
+ def from_sigmas(cls, mean_E: float, mean_L: float,
433
+ sigma_E: float, sigma_L: float,
434
+ rho: float = 0.0) -> "CorrelatedSymGaussian":
435
+ """Build from marginal widths and correlation coefficient rho."""
436
+ if not (sigma_E > 0.0 and sigma_L > 0.0):
437
+ # a negative sigma would survive squaring and silently flip the
438
+ # sign of the built correlation
439
+ raise ValueError("sigma_E and sigma_L must be > 0")
440
+ if not (-1.0 < rho < 1.0):
441
+ raise ValueError("need -1 < rho < 1")
442
+ off = rho * sigma_E * sigma_L
443
+ return cls([mean_E, mean_L],
444
+ [[sigma_E**2, off], [off, sigma_L**2]])
445
+
446
+ def ln_likelihood(self, params: Optional[dict] = None):
447
+ p = _merged(params)
448
+ x = jnp.asarray([p["E_sym"], p["L_sym"]], dtype=jnp.float64)
449
+ r = x - self.mean
450
+ return -0.5 * (2.0 * _LOG_2PI + self._logdet + r @ self._inv @ r)
451
+
452
+ __call__ = ln_likelihood
453
+
454
+
455
+ # ----------------------------------------------------------------------------
456
+ # scenario-ladder input (packaged copy; provenance in the file header)
457
+ # ----------------------------------------------------------------------------
458
+
459
+ def load_scenario_ladder(path: Optional[str] = None) -> dict:
460
+ """Load the FRIB scenario ladder (packaged copy by default).
461
+
462
+ The packaged file ``nmbackend/data/frib_scenario_ladder.yaml`` is a COPY of
463
+ the source of truth in nmb-papers ``scoping/frib_scenario_ladder.yaml``,
464
+ carried with a provenance header per the FRIB-SCOPING §8 decision (no live
465
+ cross-repo dependency). Every number in it is an assumption.
466
+ """
467
+ try:
468
+ import yaml
469
+ except ImportError as exc: # pragma: no cover
470
+ raise ImportError("load_scenario_ladder requires pyyaml "
471
+ "(pip install pyyaml)") from exc
472
+ if path is not None:
473
+ with open(path, encoding="utf-8") as f:
474
+ return yaml.safe_load(f)
475
+ ref = resources.files("nmbackend") / "data" / "frib_scenario_ladder.yaml"
476
+ return yaml.safe_load(ref.read_text(encoding="utf-8"))
477
+
478
+
479
+ def scenario_by_name(ladder: dict, name: str) -> dict:
480
+ """Pick one scenario entry by its ``name`` (or ``tag``)."""
481
+ for sc in ladder["scenarios"]:
482
+ if sc["name"] == name or sc.get("tag") == name:
483
+ return sc
484
+ known = [f"{sc['name']} (tag {sc.get('tag')})" for sc in ladder["scenarios"]]
485
+ raise KeyError(f"scenario {name!r} not in ladder; known: {known}")
486
+
487
+
488
+ def gaussian_from_scenario(scenario: dict, rho: float = 0.0,
489
+ mean_E: Optional[float] = None,
490
+ mean_L: Optional[float] = None,
491
+ eos_params: Optional[dict] = None,
492
+ ) -> Optional[CorrelatedSymGaussian]:
493
+ """Correlated (E_sym, L_sym) Gaussian from a ladder scenario.
494
+
495
+ Widths come from the scenario's ``lab_sigma`` (E_sym and L_sym keys). Any
496
+ other lab_sigma key (e.g. K_sym in +FRIB400+Ksym) **cannot be encoded in
497
+ the 2x2 form and is dropped with a UserWarning** — in this encoding the
498
+ +FRIB400 and +FRIB400+Ksym rungs are identical, so an encoding-comparison
499
+ sweep must not read that as "K_sym information buys nothing"; use
500
+ `density_tagged_from_scenario` for the curvature information.
501
+
502
+ Means default to the fiducial model (``eos_params`` merged over the
503
+ metamodel defaults — pass the same fiducial you give the density-tagged
504
+ builder so the claim-C3 encoding comparison is centered consistently);
505
+ ``mean_E``/``mean_L`` override individually. The ladder carries no
506
+ correlation, so rho defaults to 0; pass rho to explore correlated
507
+ variants. Returns None for a scenario with no lab constraint (GW-only).
508
+ """
509
+ sig = scenario.get("lab_sigma") or {}
510
+ if not sig:
511
+ return None
512
+ if "E_sym" not in sig or "L_sym" not in sig:
513
+ raise ValueError(f"scenario {scenario.get('name')!r} lab_sigma must "
514
+ "carry both E_sym and L_sym for the Gaussian form")
515
+ dropped = sorted(set(sig) - {"E_sym", "L_sym"})
516
+ if dropped:
517
+ warnings.warn(
518
+ f"scenario {scenario.get('name')!r}: lab_sigma key(s) {dropped} "
519
+ "cannot be encoded in the 2x2 (E_sym, L_sym) Gaussian and are "
520
+ "DROPPED — this encoding is then blind to that information "
521
+ "(use density_tagged_from_scenario for the curvature content).",
522
+ UserWarning, stacklevel=2)
523
+ p = _merged(eos_params)
524
+ return CorrelatedSymGaussian.from_sigmas(
525
+ mean_E if mean_E is not None else p["E_sym"],
526
+ mean_L if mean_L is not None else p["L_sym"],
527
+ sig["E_sym"], sig["L_sym"], rho=rho)
528
+
529
+
530
+ def density_tagged_from_scenario(scenario: dict,
531
+ eos_params: Optional[dict] = None,
532
+ sigma_model: Union[float, SigmaModelPrior] = 0.0,
533
+ warn_above_match: bool = True,
534
+ n_beta_eq: Optional[float] = None,
535
+ ) -> Optional[DensityTaggedPressureLikelihood]:
536
+ """Density-tagged P_sym(2 n0) likelihood from a ladder scenario.
537
+
538
+ Uses the scenario's ``psym2n0_frac`` (fractional width, e.g. 0.30 for
539
+ FRIB400's "P(2n0) to ~30%"): the constraint is centered on the fiducial
540
+ model's P_sym(2 n_sat) with sigma = frac * mu — a forecast injection, not
541
+ a measurement. Returns None if the scenario carries no ``psym2n0_frac``.
542
+
543
+ Interpretation note: the ladder's "P(2n0)" is applied here to the
544
+ **symmetry pressure** P_sym = n^2 dS/dn, not to the neutron-matter
545
+ pressure P_PNM = n^2 (de_sat/dn + dS/dn); the two differ at 2 n_sat by
546
+ the isoscalar term (they coincide only at n_sat). This is an encoding
547
+ choice carried with the ladder copy's provenance header.
548
+
549
+ Usage: **construct once at the fiducial, then evaluate with per-draw
550
+ parameters** (``like({"L_sym": ...})``). The fiducial ``eos_params`` is
551
+ stored, so evaluation defaults to it and the fiducial sits at the peak.
552
+ Do NOT rebuild with each draw's NEPs as ``eos_params`` — that re-centers
553
+ the forecast on every draw, producing a pseudo-likelihood that
554
+ systematically rewards small-|P_sym| draws.
555
+
556
+ Raises if the fiducial P_sym(2 n_sat) is not positive: a fractional-width
557
+ forecast is ill-defined there (with default K_sym = -100 this happens for
558
+ L_sym below about 33 MeV — near the zero-crossing the width collapses
559
+ toward a delta, which would silently over-tighten the posterior).
560
+
561
+ MB-N5: the 2 n_sat tag sits exactly at the default beta-equilibrium
562
+ boundary, so a UserWarning fires — the caveat genuinely applies to this
563
+ constraint. Silence with ``warn_above_match=False`` once acknowledged.
564
+ """
565
+ frac = scenario.get("psym2n0_frac")
566
+ if frac is None:
567
+ return None
568
+ frac = float(frac)
569
+ if not (0.0 < frac):
570
+ raise ValueError(f"psym2n0_frac must be > 0, got {frac}")
571
+ p = _merged(eos_params)
572
+ n_tag = 2.0 * p["n_sat"]
573
+ mu = float(psym(n_tag, p))
574
+ if not mu > 0.0:
575
+ raise ValueError(
576
+ f"fiducial P_sym(2 n_sat) = {mu:g} MeV/fm^3 is not positive for "
577
+ "these eos_params, so a fractional-width forecast (sigma = "
578
+ f"frac * mu) is ill-defined; choose a fiducial with positive "
579
+ "P_sym(2 n_sat) or build the DensityTaggedConstraint directly "
580
+ "with an absolute sigma.")
581
+ c = DensityTaggedConstraint(
582
+ n=n_tag, mu=mu, sigma=frac * mu,
583
+ name=f"{scenario.get('name', '?')} P_sym(2n0)",
584
+ source="frib_scenario_ladder.yaml (ASSUMED forecast value)")
585
+ return DensityTaggedPressureLikelihood(
586
+ [c], sigma_model=sigma_model, warn_above_match=warn_above_match,
587
+ eos_params=eos_params, n_beta_eq=n_beta_eq)