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,276 @@
1
+ """Production evidence_fn: per-EOS evidence from a RIFT CIP run (tabular method).
2
+
3
+ Glue between the adaptive sequence-space prior (:mod:`nmbackend.priors.gp_pca`)
4
+ and RIFT's tabular per-EOS evidence. One CIP run per refinement round:
5
+
6
+ 1. write the round's draws as a ``pca_hc/1`` file (:func:`write_pca_draws`) --
7
+ CIP opens it through ``EOSManager.EOSSequenceFromFile``;
8
+ 2. run CIP with ``--tabular-eos-file <draws> --input-eos-index`` against the
9
+ trained likelihood interpolant (``all.net``), requesting posterior samples;
10
+ 3. read the posterior samples (ligolw XML; the EOS index is serialized in the
11
+ sim_inspiral ``alpha`` column via ``lalsimutils``) and convert the per-EOS
12
+ **posterior mass** into per-EOS log-evidence: under the uniform-in-sequence
13
+ prior CIP samples, ``p(e|d) \\propto Z_e``, so ``lnZ_e = ln(mass_e) + const``
14
+ -- exactly the weights :meth:`CoefficientPrior.refine` consumes (the constant
15
+ cancels).
16
+
17
+ Cardinality note (IMPORTANT): an ``all.net`` built by a previous ILE/CIP cycle
18
+ carries per-point EOS indices bound to the sequence it was produced with. For a
19
+ *new* draw file the index column must reference valid indices; ``remap_index_mod``
20
+ rewrites it as ``index % n_draws`` per round. That is the correct *plumbing/demo*
21
+ configuration (same caveat as the live smoke test); a production paper-1 run
22
+ regenerates ``all.net`` with conventions matched to the draw cardinality.
23
+
24
+ This module shells out to CIP (subprocess) and lazily imports ``RIFT.lalsimutils``
25
+ only to read the samples -- it requires a working RIFT+LAL environment at call
26
+ time, not at import time.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ import subprocess
32
+ import sys
33
+
34
+ import numpy as np
35
+
36
+ def _write_pca_draws(*a, **kw):
37
+ # deferred to avoid a circular import (priors.gp_pca imports rift.compressed,
38
+ # whose package init pulls in this module before gp_pca finishes loading)
39
+ from ..priors.gp_pca import write_pca_draws
40
+ return write_pca_draws(*a, **kw)
41
+
42
+ #: CIP argument template for the GW170817-style tabular run; {net} and {seq} are
43
+ #: filled per round. Override via ``extra_args`` / constructor knobs as needed.
44
+ DEFAULT_CIP_ARGS = (
45
+ "--fname {net} --parameter mc --parameter delta_mc --parameter-implied xi "
46
+ "--parameter-implied chiMinus --parameter-nofit s1z --parameter-nofit s2z "
47
+ "--input-tides --input-eos-index --tabular-eos-file {seq} "
48
+ "--lambda-max 20000 --fit-method rf --no-plots "
49
+ "--mc-range [1.197,1.1985] --eta-range [0.2,0.249999] "
50
+ "--downselect-parameter m1 --downselect-parameter-range [1,3] "
51
+ "--downselect-parameter m2 --downselect-parameter-range [1,3] "
52
+ "--sampler-method default --aligned-prior alignedspin_zprior --chi-max 0.05"
53
+ )
54
+
55
+
56
+ def posterior_mass_lnZ(eos_indices, n_eos, floor_counts=0.1):
57
+ """Per-EOS log-evidence (up to a constant) from posterior-sample EOS indices.
58
+
59
+ ``mass_e \\propto Z_e`` under a uniform sequence prior; Laplace-style
60
+ ``floor_counts`` keeps unsampled EOS at small-but-finite weight.
61
+ """
62
+ idx = np.asarray(eos_indices)
63
+ idx = idx[np.isfinite(idx)].astype(int)
64
+ idx = idx[(idx >= 0) & (idx < n_eos)]
65
+ counts = np.bincount(idx, minlength=n_eos).astype(float) + floor_counts
66
+ return np.log(counts / counts.sum())
67
+
68
+
69
+ def read_eos_indices_xml(samples_xml):
70
+ """EOS indices from a CIP posterior-samples ligolw XML (sim_inspiral.alpha)."""
71
+ from RIFT import lalsimutils # lazy: needs lal env
72
+ plist = lalsimutils.xml_to_ChooseWaveformParams_array(str(samples_xml))
73
+ out = []
74
+ for P in plist:
75
+ v = getattr(P, "eos_table_index", None)
76
+ out.append(np.nan if v is None else float(v))
77
+ return np.array(out)
78
+
79
+
80
+ def remap_net_index_column(net_in, net_out, n_eos, index_col=11):
81
+ """Rewrite the composite's EOS-index column as ``index % n_eos`` (demo mode)."""
82
+ dat = np.loadtxt(net_in)
83
+ dat[:, index_col] = np.mod(dat[:, index_col].astype(int), n_eos)
84
+ np.savetxt(net_out, dat)
85
+ return net_out
86
+
87
+
88
+ #: MARG-style argument template for the exact per-EOS ("painful") mode: one full
89
+ #: CIP evidence per fixed EOS realization, EOS supplied via --using-eos nmbseq:…
90
+ PAINFUL_CIP_ARGS = (
91
+ "--fname {net} --parameter mc --parameter delta_mc --parameter-implied xi "
92
+ "--parameter-implied chiMinus --parameter-nofit s1z --parameter-nofit s2z "
93
+ "--parameter-implied LambdaTilde --input-tides "
94
+ "--using-eos nmbseq:{seq}:{index} "
95
+ "--lambda-max 20000 --fit-method rf --no-plots "
96
+ "--mc-range [1.197,1.1985] --eta-range [0.2,0.249999] "
97
+ "--downselect-parameter m1 --downselect-parameter-range [1,3] "
98
+ "--downselect-parameter m2 --downselect-parameter-range [1,3] "
99
+ "--sampler-method default --aligned-prior alignedspin_zprior --chi-max 0.05"
100
+ )
101
+
102
+
103
+ def strip_index_column(net_in, net_out, index_col=11):
104
+ """Remove the EOS-index column from a tabular composite (for fixed-EOS runs:
105
+ without ``--input-eos-index`` CIP expects no index column after lambda2)."""
106
+ dat = np.loadtxt(net_in)
107
+ np.savetxt(net_out, np.delete(dat, index_col, axis=1))
108
+ return net_out
109
+
110
+
111
+ class CIPPerEOSEvidence:
112
+ """EXACT per-EOS evidence: one full CIP run per EOS realization (MARG-style).
113
+
114
+ This is the reference ("painful") computation: for each draw, CIP is run with
115
+ the EOS held FIXED (``--using-eos nmbseq:<draws.h5>:<e>``, requiring the
116
+ patched RIFT with ``EOSSequenceSingleIndex``), and the per-EOS lnZ is read
117
+ from ``integral_result.dat``. No ordering-statistic approximation -- use it
118
+ to VALIDATE :class:`CIPTabularEvidence` (the Vilkha grid method, which treats
119
+ the posterior over the sequence index as robust) and for referee-grade runs.
120
+
121
+ Cost: n_draws CIP jobs per round (× n_events for multi-event); ~30 s each at
122
+ demo settings -- i.e. 10^4 draws ≈ 80+ core-hours per generation per event.
123
+ ``n_parallel`` runs that many subprocesses concurrently on one host; for real
124
+ campaigns drive via condor.
125
+ """
126
+
127
+ def __init__(self, cip_exe, net_file, workdir, rift_code=None,
128
+ python_exe=None, args_template=PAINFUL_CIP_ARGS, extra_args="",
129
+ n_max=150000, n_eff=10, strip_net_index=True, index_col=11,
130
+ n_parallel=2, timeout=3600, verbose=False):
131
+ self.cip_exe = str(cip_exe)
132
+ self.net_file = str(net_file)
133
+ self.workdir = str(workdir)
134
+ self.rift_code = rift_code
135
+ self.python_exe = python_exe or sys.executable
136
+ self.args_template = args_template
137
+ self.extra_args = extra_args
138
+ self.n_max = int(n_max)
139
+ self.n_eff = int(n_eff)
140
+ self.strip_net_index = strip_net_index
141
+ self.index_col = index_col
142
+ self.n_parallel = max(1, int(n_parallel))
143
+ self.timeout = timeout
144
+ self.verbose = verbose
145
+ self._net_stripped = None
146
+
147
+ def _net(self):
148
+ if not self.strip_net_index:
149
+ return self.net_file
150
+ if self._net_stripped is None:
151
+ os.makedirs(self.workdir, exist_ok=True)
152
+ self._net_stripped = strip_index_column(
153
+ self.net_file, os.path.join(self.workdir, "net_noindex.dat"),
154
+ index_col=self.index_col)
155
+ return self._net_stripped
156
+
157
+ def _one(self, seq, e, rdir):
158
+ os.makedirs(rdir, exist_ok=True)
159
+ cmd = ([self.python_exe, self.cip_exe]
160
+ + self.args_template.format(net=self._net(), seq=seq,
161
+ index=e).split()
162
+ + ["--n-max", str(self.n_max), "--n-eff", str(self.n_eff)]
163
+ + (self.extra_args.split() if self.extra_args else []))
164
+ env = dict(os.environ)
165
+ if self.rift_code:
166
+ env["PYTHONPATH"] = (str(self.rift_code) + ":"
167
+ + env.get("PYTHONPATH", ""))
168
+ return subprocess.Popen(cmd, cwd=rdir, env=env,
169
+ stdout=subprocess.DEVNULL,
170
+ stderr=subprocess.DEVNULL)
171
+
172
+ def __call__(self, prior, coeffs):
173
+ n_eos = len(coeffs)
174
+ gen = prior.generation
175
+ base = os.path.join(self.workdir, f"gen_{gen}_painful")
176
+ os.makedirs(base, exist_ok=True)
177
+ seq = os.path.join(base, "draws.pca.h5")
178
+ _write_pca_draws(seq, prior, coeffs)
179
+
180
+ lnZ = np.full(n_eos, np.nan)
181
+ pending = list(range(n_eos))
182
+ running = {}
183
+ while pending or running:
184
+ while pending and len(running) < self.n_parallel:
185
+ e = pending.pop(0)
186
+ running[e] = self._one(seq, e, os.path.join(base, f"eos_{e}"))
187
+ done = [e for e, p in running.items() if p.poll() is not None]
188
+ for e in done:
189
+ running.pop(e)
190
+ f = os.path.join(base, f"eos_{e}", "integral_result.dat")
191
+ if os.path.exists(f):
192
+ lnZ[e] = float(np.loadtxt(f))
193
+ if self.verbose:
194
+ print(f"[gen {gen}] painful eos_{e}: lnZ={lnZ[e]}")
195
+ if running:
196
+ import time
197
+ time.sleep(2.0)
198
+ return lnZ
199
+
200
+
201
+ class CIPTabularEvidence:
202
+ """``evidence_fn(prior, coeffs) -> lnZ`` running one CIP job per round.
203
+
204
+ Parameters
205
+ ----------
206
+ cip_exe : path to ``util_ConstructIntrinsicPosterior_GenericCoordinates.py``
207
+ (the patched RIFT with ``EOSSequenceFromFile``).
208
+ net_file : the trained likelihood composite (``all.net``-style).
209
+ workdir : scratch directory (one subdir per generation).
210
+ rift_code : RIFT ``Code`` dir to prepend to PYTHONPATH for the subprocess.
211
+ n_max, n_eff, n_output_samples, timeout, extra_args : CIP run knobs.
212
+ remap_index_mod : rewrite the net's EOS-index column per round (demo mode --
213
+ see module docstring).
214
+ """
215
+
216
+ def __init__(self, cip_exe, net_file, workdir, rift_code=None,
217
+ python_exe=None, args_template=DEFAULT_CIP_ARGS, extra_args="",
218
+ n_max=150000, n_eff=10, n_output_samples=4000,
219
+ remap_index_mod=True, floor_counts=0.1, timeout=1800,
220
+ verbose=False):
221
+ self.cip_exe = str(cip_exe)
222
+ self.net_file = str(net_file)
223
+ self.workdir = str(workdir)
224
+ self.rift_code = rift_code
225
+ self.python_exe = python_exe or sys.executable
226
+ self.args_template = args_template
227
+ self.extra_args = extra_args
228
+ self.n_max = int(n_max)
229
+ self.n_eff = int(n_eff)
230
+ self.n_output_samples = int(n_output_samples)
231
+ self.remap_index_mod = remap_index_mod
232
+ self.floor_counts = floor_counts
233
+ self.timeout = timeout
234
+ self.verbose = verbose
235
+ self.last_run = None # diagnostics
236
+
237
+ def __call__(self, prior, coeffs):
238
+ n_eos = len(coeffs)
239
+ gen = prior.generation
240
+ rdir = os.path.join(self.workdir, f"gen_{gen}")
241
+ os.makedirs(rdir, exist_ok=True)
242
+ seq = os.path.join(rdir, "draws.pca.h5")
243
+ _write_pca_draws(seq, prior, coeffs)
244
+
245
+ net = self.net_file
246
+ if self.remap_index_mod:
247
+ net = remap_net_index_column(
248
+ self.net_file, os.path.join(rdir, "net_remapped.dat"), n_eos)
249
+
250
+ samples_base = os.path.join(rdir, "posterior_samples")
251
+ cmd = ([self.python_exe, self.cip_exe]
252
+ + self.args_template.format(net=net, seq=seq).split()
253
+ + ["--n-max", str(self.n_max), "--n-eff", str(self.n_eff),
254
+ "--fname-output-samples", samples_base,
255
+ "--n-output-samples", str(self.n_output_samples)]
256
+ + (self.extra_args.split() if self.extra_args else []))
257
+ env = dict(os.environ)
258
+ if self.rift_code:
259
+ env["PYTHONPATH"] = (str(self.rift_code) + ":"
260
+ + env.get("PYTHONPATH", ""))
261
+ res = subprocess.run(cmd, cwd=rdir, env=env, capture_output=True,
262
+ text=True, timeout=self.timeout)
263
+ self.last_run = dict(returncode=res.returncode, dir=rdir,
264
+ tail=res.stdout[-2000:] + res.stderr[-2000:])
265
+ if res.returncode != 0:
266
+ raise RuntimeError(f"CIP failed (gen {gen}); see last_run tail:\n"
267
+ + self.last_run["tail"][-800:])
268
+ idx = read_eos_indices_xml(samples_base + ".xml.gz")
269
+ lnZ = posterior_mass_lnZ(idx, n_eos, floor_counts=self.floor_counts)
270
+ if self.verbose:
271
+ occ = int(np.sum(np.exp(lnZ) > 1.5 * self.floor_counts
272
+ / (len(idx) + n_eos * self.floor_counts)))
273
+ print(f"[gen {gen}] CIP ok: {len(idx)} samples over {n_eos} EOS "
274
+ f"({occ} occupied); lnZ spread "
275
+ f"{np.max(lnZ)-np.min(lnZ):.2f}")
276
+ return lnZ