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,583 @@
|
|
|
1
|
+
"""Run NSCool (D. Page) on one star and return its cooling curve.
|
|
2
|
+
|
|
3
|
+
NSCool is built outside the repository by ``build_nscool.sh``; see
|
|
4
|
+
README.md in this directory for the source, the patch and the input
|
|
5
|
+
formats. Each call writes NSCool's input files into a fresh directory,
|
|
6
|
+
runs the binary there and parses the T_eff file.
|
|
7
|
+
|
|
8
|
+
NSCool prints the redshifted (observed at infinity) effective
|
|
9
|
+
temperature and photon luminosity. ``CoolingCurve`` carries those and
|
|
10
|
+
the local surface values T_s = T_inf / e^phi_s, L_local = L_inf / e^(2 phi_s)
|
|
11
|
+
with e^(2 phi_s) = 1 - 2GM/(R c^2) at NSCool's outer grid radius.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import inspect
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import shutil
|
|
19
|
+
import subprocess
|
|
20
|
+
import tempfile
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import NamedTuple, Optional, Union
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
__all__ = ["GapModel", "CoolingCurve", "IsothermalStar", "NSCool", "NSCoolError",
|
|
28
|
+
"ZoneDump", "parse_zone_dump",
|
|
29
|
+
"default_home", "parse_teff_file", "parse_star_file",
|
|
30
|
+
"parse_isothermal"]
|
|
31
|
+
|
|
32
|
+
PathLike = Union[str, os.PathLike]
|
|
33
|
+
|
|
34
|
+
#: G Msun / c^2 in cm
|
|
35
|
+
_GM_SUN_C2_CM = 1.4766250e5
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NSCoolError(RuntimeError):
|
|
39
|
+
"""NSCool or its TOV solver failed or produced no curve."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def default_home() -> Path:
|
|
43
|
+
"""Built NSCool tree: $NSCOOL_HOME/NSCool, else the build-script default."""
|
|
44
|
+
root = os.environ.get("NSCOOL_HOME",
|
|
45
|
+
str(Path.home() / ".local/share/nmbackend/nscool"))
|
|
46
|
+
return Path(root) / "NSCool"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class GapModel:
|
|
51
|
+
"""Pairing gaps: NSCool model codes plus Zhou+2026 Eq. 10 scalings.
|
|
52
|
+
|
|
53
|
+
Delta_x(n) = s_y * Delta_x,0(n / s_x) for x = p1S0 and n3P2, with n the
|
|
54
|
+
baryon density. s_y maps to NSCool's FP1S0 / FN3P2 (Tc multipliers;
|
|
55
|
+
Tc is proportional to Delta). s_x is applied by the nmbackend patch in
|
|
56
|
+
the core zones: the gap is evaluated at the Fermi momentum the star has
|
|
57
|
+
at n / s_x. Where n / s_x lies outside the core (above the centre, or
|
|
58
|
+
below the crust-core boundary) k_F scales as n^(1/3) from the nearest
|
|
59
|
+
core zone. Crust zones are not rescaled.
|
|
60
|
+
|
|
61
|
+
Model codes are NSCool's SFP1S0 / SFN3P2 / SFN1S0 values (precool.f,
|
|
62
|
+
subroutine get_Tc); 0 switches a channel off. Defaults are the
|
|
63
|
+
bundled Model_1: n1S0 SFB, n3P2 minimal-cooling gap "a", p1S0 T73.
|
|
64
|
+
|
|
65
|
+
``ca_n3p2`` is the axial coefficient of n3P2 pair-breaking emission,
|
|
66
|
+
a_A = c_A g_A^2 (nmbackend patch). The default 0.5 follows Leinson's
|
|
67
|
+
correction, as in A. W. Steiner's NSCool fork; the 2010 release, and
|
|
68
|
+
its bundled Model_1 output, use 2.
|
|
69
|
+
"""
|
|
70
|
+
n1s0: float = 1.0
|
|
71
|
+
n3p2: float = 101.0
|
|
72
|
+
p1s0: float = 3.0
|
|
73
|
+
sx_p1s0: float = 1.0
|
|
74
|
+
sy_p1s0: float = 1.0
|
|
75
|
+
sx_n3p2: float = 1.0
|
|
76
|
+
sy_n3p2: float = 1.0
|
|
77
|
+
ca_n3p2: float = 0.5
|
|
78
|
+
|
|
79
|
+
def __post_init__(self):
|
|
80
|
+
for name in self.__dataclass_fields__: # numpy scalars -> float
|
|
81
|
+
object.__setattr__(self, name, float(getattr(self, name)))
|
|
82
|
+
if self.n3p2 == 150.0:
|
|
83
|
+
raise ValueError("SFN3P2=150 (user Gaussian gap) is not supported")
|
|
84
|
+
for name in ("sx_p1s0", "sy_p1s0", "sx_n3p2", "sy_n3p2", "ca_n3p2"):
|
|
85
|
+
if not 0 < getattr(self, name) < np.inf:
|
|
86
|
+
raise ValueError(f"{name} must be finite and > 0")
|
|
87
|
+
|
|
88
|
+
def pairing_file(self) -> str:
|
|
89
|
+
return (
|
|
90
|
+
"PAIRING CONTROL:---------------------------------------\n"
|
|
91
|
+
f"{self.n1s0:<10.10g} SFN1S0\n"
|
|
92
|
+
f"{self.n3p2:<10.10g} SFN3P2\n"
|
|
93
|
+
f"{self.p1s0:<10.10g} SFP1S0\n"
|
|
94
|
+
"0. SFL1S0\n"
|
|
95
|
+
"1. FN1S0\n"
|
|
96
|
+
f"{self.sy_n3p2:<10.10g} FN3P2\n"
|
|
97
|
+
f"{self.sy_p1s0:<10.10g} FP1S0\n"
|
|
98
|
+
"1. FL1S0\n"
|
|
99
|
+
"0. SFQUARK\n"
|
|
100
|
+
f"{self.sx_p1s0:<10.10g} SXP1S0\n"
|
|
101
|
+
f"{self.sx_n3p2:<10.10g} SXN3P2\n"
|
|
102
|
+
f"{self.ca_n3p2:<10.10g} CA3P2\n")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class CoolingCurve(NamedTuple):
|
|
106
|
+
"""One NSCool run. Times in yr, temperatures in K, luminosities in erg/s."""
|
|
107
|
+
t_yr: np.ndarray
|
|
108
|
+
Teff_inf: np.ndarray # redshifted effective temperature
|
|
109
|
+
L_gamma_inf: np.ndarray # redshifted photon luminosity
|
|
110
|
+
L_nu_inf: np.ndarray # redshifted neutrino luminosity
|
|
111
|
+
L_heat_inf: np.ndarray
|
|
112
|
+
mass: float # gravitational mass, Msun
|
|
113
|
+
radius_cm: float # NSCool grid edge at rhosurf, not the TOV surface
|
|
114
|
+
star: Optional[dict] = None # per-zone profile if run(star=True)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def exp_phi_s(self) -> float:
|
|
118
|
+
return float(np.sqrt(1.0 - 2.0 * _GM_SUN_C2_CM * self.mass / self.radius_cm))
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def Ts(self) -> np.ndarray:
|
|
122
|
+
"""Local (unredshifted) surface temperature."""
|
|
123
|
+
return self.Teff_inf / self.exp_phi_s
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def L_gamma(self) -> np.ndarray:
|
|
127
|
+
"""Local photon luminosity."""
|
|
128
|
+
return self.L_gamma_inf / self.exp_phi_s ** 2
|
|
129
|
+
|
|
130
|
+
def at(self, t_yr, quantity: str = "Teff_inf") -> np.ndarray:
|
|
131
|
+
"""log-log interpolation of a column at ages t_yr."""
|
|
132
|
+
y = getattr(self, quantity)
|
|
133
|
+
return np.exp(np.interp(np.log(np.asarray(t_yr, float)),
|
|
134
|
+
np.log(self.t_yr), np.log(y)))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
_HEADER_RE = re.compile(r"Mstar\s*=\s*([-+.\dEe]+)\s+Rstar\s*=\s*([-+.\dEe]+)")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def parse_teff_file(path: PathLike) -> CoolingCurve:
|
|
141
|
+
"""Parse the T_eff file NSCool writes with PTEFF=1."""
|
|
142
|
+
text = Path(path).read_text()
|
|
143
|
+
m = _HEADER_RE.search(text)
|
|
144
|
+
if m is None:
|
|
145
|
+
raise NSCoolError(f"{path}: no Mstar/Rstar header")
|
|
146
|
+
rows = []
|
|
147
|
+
for line in text.splitlines():
|
|
148
|
+
f = line.split()
|
|
149
|
+
if len(f) == 6 and f[0].isdigit():
|
|
150
|
+
rows.append([float(x) for x in f[1:]])
|
|
151
|
+
if not rows:
|
|
152
|
+
raise NSCoolError(f"{path}: no time steps")
|
|
153
|
+
a = np.array(rows)
|
|
154
|
+
return CoolingCurve(a[:, 0], a[:, 1], a[:, 2], a[:, 3], a[:, 4],
|
|
155
|
+
float(m.group(1)), float(m.group(2)))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
_STAR_COLS = ("i", "rad", "emas", "rho", "pres", "nb", "kfe", "kfmu", "kfp",
|
|
159
|
+
"kfn", "kfla", "kfsm", "kfs0", "kfsp", "Tcn", "Tcp", "Tcla")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def parse_star_file(path: PathLike) -> dict:
|
|
163
|
+
"""Core-zone arrays (i = 0..icore) from the Star file NSCool writes with PSTAR=1.
|
|
164
|
+
|
|
165
|
+
Radii in m, densities in g/cm^3 (rho) and fm^-3 (nb), Fermi momenta
|
|
166
|
+
in fm^-1, critical temperatures in K (1 K means unpaired).
|
|
167
|
+
"""
|
|
168
|
+
rows = []
|
|
169
|
+
for line in Path(path).read_text().splitlines():
|
|
170
|
+
f = line.split()
|
|
171
|
+
if len(f) >= len(_STAR_COLS) and f[0].isdigit():
|
|
172
|
+
try:
|
|
173
|
+
row = [float(x) for x in f[:len(_STAR_COLS)]]
|
|
174
|
+
except ValueError:
|
|
175
|
+
continue
|
|
176
|
+
if row[0] == 0 and rows:
|
|
177
|
+
break # first profile only
|
|
178
|
+
rows.append(row)
|
|
179
|
+
if not rows:
|
|
180
|
+
raise NSCoolError(f"{path}: no zones")
|
|
181
|
+
a = np.array(rows)
|
|
182
|
+
return {k: a[:, j] for j, k in enumerate(_STAR_COLS)}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class IsothermalStar(NamedTuple):
|
|
186
|
+
"""NSCool physics summed over an isothermal star (``NSCool.isothermal``).
|
|
187
|
+
|
|
188
|
+
``T`` is the redshifted interior temperature (K). C in erg/K; all
|
|
189
|
+
luminosities in erg/s at infinity; ``eta_nscool`` is the eta NSCool's
|
|
190
|
+
envelope formula receives (input ETA / 0.443). ``T_in`` answers a
|
|
191
|
+
different question from the other columns: with T_b = T at NSCool's
|
|
192
|
+
outer grid point, it is the redshifted temperature at density rho_b,
|
|
193
|
+
from NSCool's steady heat-flux equation at L = L_gamma(T).
|
|
194
|
+
"""
|
|
195
|
+
T: np.ndarray
|
|
196
|
+
C: np.ndarray
|
|
197
|
+
L_nu: np.ndarray
|
|
198
|
+
L_heat: np.ndarray
|
|
199
|
+
L_gamma: np.ndarray
|
|
200
|
+
Teff_inf: np.ndarray
|
|
201
|
+
L_durca: np.ndarray
|
|
202
|
+
L_murca_brem: np.ndarray
|
|
203
|
+
L_pbf: np.ndarray
|
|
204
|
+
L_nu_crust: np.ndarray
|
|
205
|
+
C_core: np.ndarray
|
|
206
|
+
T_in: np.ndarray # T at rho_b when T_b = T (flux march); = T if rho_b unset
|
|
207
|
+
mass: float
|
|
208
|
+
radius_cm: float
|
|
209
|
+
exp_phi_s: float
|
|
210
|
+
eta_nscool: float
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def parse_isothermal(text: str) -> IsothermalStar:
|
|
214
|
+
"""Parse the stdout of ``NSCool_iso.out``."""
|
|
215
|
+
m = re.search(r"star M R e\^phi_s =\s*(\S+)\s+(\S+)\s+(\S+)", text)
|
|
216
|
+
e = re.search(r"eta used by fteff =\s*(\S+)", text)
|
|
217
|
+
rows = [[float(x) for x in l.split()[1:]] for l in text.splitlines()
|
|
218
|
+
if l.startswith("ISO ")]
|
|
219
|
+
if m is None or e is None or not rows:
|
|
220
|
+
raise NSCoolError("no isothermal scan in NSCool_iso output")
|
|
221
|
+
a = np.array(rows).T
|
|
222
|
+
if len(a) == 11: # binary without the T_in column
|
|
223
|
+
a = np.vstack([a, a[0]])
|
|
224
|
+
return IsothermalStar(*a, float(m.group(1)), float(m.group(2)),
|
|
225
|
+
float(m.group(3)), float(e.group(1)))
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
_ZST_COLS = ("i", "idurca_np", "rad", "rho", "pres", "nb", "debar", "dvol",
|
|
229
|
+
"ephi", "a2ephin", "emas", "Ye", "Ymu", "Yn", "Yp", "kfe", "kfm",
|
|
230
|
+
"kfn", "kfp", "mstn", "mstp", "Tcn", "Tcp", "A_cell", "A_ion",
|
|
231
|
+
"Z_ion", "v_ion", "fhad")
|
|
232
|
+
_ZON_COLS = ("T", "qnu", "qeebrem", "qnpb", "qplasma", "qsynch", "qbubble",
|
|
233
|
+
"qpair", "qphoto", "qbrem_nn", "qmurca_nucl", "qbrem_nucl",
|
|
234
|
+
"qmurca_hyp", "qbrem_hyp", "qdurca_np", "qdurca_lap", "qdurca_smn",
|
|
235
|
+
"qdurca_smla", "qdurca_sms0", "qfast", "qdurca_q", "qmurca_q",
|
|
236
|
+
"qpbf_n1s0", "qpbf_n3p2", "qpbf_p1s0", "qpbf_q", "cv", "cv_n",
|
|
237
|
+
"cv_p", "cv_e", "cv_m", "cv_l", "cv_sm", "cv_s0", "cv_sp", "cv_q",
|
|
238
|
+
"cv_ion", "lam", "fp")
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class ZoneDump(NamedTuple):
|
|
242
|
+
"""Per-zone NSCool physics at a few uniform redshifted temperatures.
|
|
243
|
+
|
|
244
|
+
``star``: T-independent arrays on zones i = 0..imax+1 (NSCool units:
|
|
245
|
+
cm, g/cm^3, fm^-3 for nb, fm^-1 for k_F, K for Tc). An unpaired zone
|
|
246
|
+
has Tc = 1 K times the channel's s_y (FP1S0, FN3P2), so test T < Tc,
|
|
247
|
+
not Tc == 1. Zone imax+1 holds only dvol; rho is NSCool's initial
|
|
248
|
+
profile, which its time loop changes in the envelope. ``zones``: indices of the temperature (odd) zones.
|
|
249
|
+
``terms``: arrays of shape (n_T, n_zones) for each column of
|
|
250
|
+
``_ZON_COLS``, at the local temperature T / e^phi; q in erg/cm^3/s,
|
|
251
|
+
cv in erg/cm^3/K, lam in erg/cm/s/K. ``fp`` is the flux-equation
|
|
252
|
+
coefficient of the C1 crust march (lam bar / L_sun).
|
|
253
|
+
"""
|
|
254
|
+
T: np.ndarray # redshifted temperatures of the dump
|
|
255
|
+
zones: np.ndarray
|
|
256
|
+
star: dict
|
|
257
|
+
terms: dict
|
|
258
|
+
imax: int
|
|
259
|
+
icore: int
|
|
260
|
+
idrip: int
|
|
261
|
+
isf: int # last zone with n3P2 pairing (NSCool's convention)
|
|
262
|
+
rhocore: float
|
|
263
|
+
rhodrip: float
|
|
264
|
+
gs14: float
|
|
265
|
+
eta_nscool: float
|
|
266
|
+
qimp: float
|
|
267
|
+
radius_cm: float
|
|
268
|
+
iso: Optional[IsothermalStar] = None
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def parse_zone_dump(text: str) -> ZoneDump:
|
|
272
|
+
"""Parse the ZSC/ZST/ZON lines of ``NSCool_iso.out`` (``NSCool.zone_dump``)."""
|
|
273
|
+
lines = text.splitlines()
|
|
274
|
+
sc = [l.split()[1:] for l in lines if l.startswith("ZSC ")]
|
|
275
|
+
st = np.array([[float(x) for x in l.split()[1:]] for l in lines
|
|
276
|
+
if l.startswith("ZST ")])
|
|
277
|
+
zon = np.array([[float(x) for x in l.split()[1:]] for l in lines
|
|
278
|
+
if l.startswith("ZON ")])
|
|
279
|
+
if len(sc) != 1 or not len(st) or not len(zon):
|
|
280
|
+
raise NSCoolError("no zone dump in NSCool_iso output")
|
|
281
|
+
if st.shape[1] != len(_ZST_COLS) or zon.shape[1] != 2 + len(_ZON_COLS):
|
|
282
|
+
raise NSCoolError("zone dump columns do not match the reader")
|
|
283
|
+
imax, icore, idrip, isf = (int(x) for x in sc[0][:4])
|
|
284
|
+
rhocore, rhodrip, gs14, eta, qimp, radius = (float(x) for x in sc[0][4:])
|
|
285
|
+
nT = int(zon[:, 0].max())
|
|
286
|
+
zones = zon[zon[:, 0] == 1, 1].astype(int)
|
|
287
|
+
a = zon[:, 2:].reshape(nT, zones.size, len(_ZON_COLS))
|
|
288
|
+
terms = {k: a[:, :, j] for j, k in enumerate(_ZON_COLS)}
|
|
289
|
+
star = {k: st[:, j] for j, k in enumerate(_ZST_COLS)}
|
|
290
|
+
for k in ("i", "idurca_np"):
|
|
291
|
+
star[k] = star[k].astype(int)
|
|
292
|
+
iso = parse_isothermal(text) if any(l.startswith("ISO ") for l in lines) else None
|
|
293
|
+
return ZoneDump(terms["T"][:, 0], zones, star, terms, imax, icore, idrip,
|
|
294
|
+
isf, rhocore, rhodrip, gs14, eta, qimp, radius, iso)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
_I_DAT = """PRINT OUT CONTROL:----------------------------------------
|
|
298
|
+
0 PSCREEN
|
|
299
|
+
0. DEBUG
|
|
300
|
+
0 ISTEP DEBUG
|
|
301
|
+
1 PTEFF
|
|
302
|
+
0 PTEMP
|
|
303
|
+
{pstar} PSTAR
|
|
304
|
+
1 IDUMP1
|
|
305
|
+
111 IDUMP2
|
|
306
|
+
421 IDUMP3
|
|
307
|
+
{tempmin:.3e} TEMPMIN
|
|
308
|
+
{tempini:.3e} TEMPINI
|
|
309
|
+
ELECTRON SPECIFIC HEAT in OUTER CRUST CONTROL:------------
|
|
310
|
+
0 ICVEL_NODEG
|
|
311
|
+
EFFECTIVE MASS CONTROL:-----------------------------------
|
|
312
|
+
5 EMNCO
|
|
313
|
+
5 EMNCR
|
|
314
|
+
3 EMP
|
|
315
|
+
INITIAL ROTATIONAL PERIOD:--------------------------------
|
|
316
|
+
0.1 p0: initial spin period
|
|
317
|
+
TPRINT: times at which you select the profiles---------
|
|
318
|
+
1.0e-10
|
|
319
|
+
1.0e+7
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
_BOUND = """ENVELOPE MODEL & BOUNDARY CONDITION:----------------------
|
|
323
|
+
3 IFTEFF (0=use table, 10,11=magnetar with Fe and Acc)
|
|
324
|
+
{eta:.6e} ETA (for accreted env., i.e., IFTEFF=3)
|
|
325
|
+
3. MAG_COEFF (for magnetars, i.e., IFTEFF=10,11)
|
|
326
|
+
0.0 TB_ACC0
|
|
327
|
+
'none-at-all.nut'
|
|
328
|
+
"""
|
|
329
|
+
|
|
330
|
+
_STRUCT = ("{rhocore:.4e} {rhodrip:.4e} {rhoenv:.4e} {rhosurf:.4e}"
|
|
331
|
+
" : rhocore rhodrip rhoenv rhosurf\n{icore} {idec} : icore idec\n")
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class NSCool:
|
|
335
|
+
"""Driver for a built NSCool tree (see ``build_nscool.sh``).
|
|
336
|
+
|
|
337
|
+
Parameters
|
|
338
|
+
----------
|
|
339
|
+
home : built ``NSCool`` directory (default: ``default_home()``).
|
|
340
|
+
workroot : parent of the per-run directories (default: system temp).
|
|
341
|
+
"""
|
|
342
|
+
|
|
343
|
+
def __init__(self, home: Optional[PathLike] = None,
|
|
344
|
+
workroot: Optional[PathLike] = None):
|
|
345
|
+
self.home = Path(home) if home is not None else default_home()
|
|
346
|
+
self.workroot = workroot
|
|
347
|
+
for exe in (self.exe, self.tov_exe):
|
|
348
|
+
if not exe.is_file():
|
|
349
|
+
raise FileNotFoundError(
|
|
350
|
+
f"{exe} missing: run nmbackend/cooling/build_nscool.sh")
|
|
351
|
+
|
|
352
|
+
@property
|
|
353
|
+
def exe(self) -> Path:
|
|
354
|
+
return self.home / "Code" / "NSCool.out"
|
|
355
|
+
|
|
356
|
+
@property
|
|
357
|
+
def tov_exe(self) -> Path:
|
|
358
|
+
return self.home / "TOV" / "TOV"
|
|
359
|
+
|
|
360
|
+
@property
|
|
361
|
+
def default_eos(self) -> Path:
|
|
362
|
+
"""Bundled APR core+crust table (Akmal, Pandharipande & Ravenhall)."""
|
|
363
|
+
return self.home / "EOS" / "APR_EOS_Cat.dat"
|
|
364
|
+
|
|
365
|
+
@property
|
|
366
|
+
def default_crust(self) -> Path:
|
|
367
|
+
return self.home / "EOS" / "Crust" / "Crust_EOS_Cat_HZD-NV.dat"
|
|
368
|
+
|
|
369
|
+
# ------------------------------------------------------------------
|
|
370
|
+
def _tov(self, d: Path, cmds: str, timeout: float):
|
|
371
|
+
"""Run NSCool's TOV in ``d``; return (rhoc [fm^-3], M [Msun]) of each star."""
|
|
372
|
+
try:
|
|
373
|
+
r = subprocess.run([str(self.tov_exe)], cwd=d, input=cmds,
|
|
374
|
+
capture_output=True, text=True, timeout=timeout)
|
|
375
|
+
except subprocess.TimeoutExpired as e:
|
|
376
|
+
raise NSCoolError(f"TOV timed out after {timeout} s") from e
|
|
377
|
+
rhoc = [float(x) for x in re.findall(r"rhoc:\s*([-+.\dEe]+)", r.stdout)]
|
|
378
|
+
mass = [float(x) for x in re.findall(r"masses\(g,b,p\):\s*([-+.\dEe]+)", r.stdout)]
|
|
379
|
+
if r.returncode != 0 or not mass or len(rhoc) != len(mass):
|
|
380
|
+
raise NSCoolError(f"TOV failed (rc={r.returncode}):\n{r.stdout[-2000:]}")
|
|
381
|
+
return rhoc, mass
|
|
382
|
+
|
|
383
|
+
def make_profile(self, eos_table: PathLike, mass: float, out: PathLike,
|
|
384
|
+
rhoc_start: float = 0.3, timeout: float = 120.0) -> Path:
|
|
385
|
+
"""Build a stellar profile at gravitational mass ``mass`` with NSCool's TOV.
|
|
386
|
+
|
|
387
|
+
``rhoc_start`` (fm^-3) seeds the target-mass search. The star must be
|
|
388
|
+
on the stable branch: a second TOV solve at 1.002 rho_c must give a
|
|
389
|
+
larger mass, else ``NSCoolError``. Returns ``out``.
|
|
390
|
+
"""
|
|
391
|
+
out = Path(out)
|
|
392
|
+
with tempfile.TemporaryDirectory(dir=self.workroot) as d:
|
|
393
|
+
d = Path(d)
|
|
394
|
+
(d / "Profile").mkdir()
|
|
395
|
+
os.symlink(Path(eos_table).resolve(), d / "eos.dat")
|
|
396
|
+
head = "cgs\neos='eos.dat'\ngeteos\n"
|
|
397
|
+
rhoc, m = self._tov(d, head + f"rhoc={rhoc_start}\ngo\n"
|
|
398
|
+
f"targetmass={mass}\ngo\ndump\ngo\nEOF\n", timeout)
|
|
399
|
+
prof = d / "Profile" / "prof.dat"
|
|
400
|
+
if not prof.is_file():
|
|
401
|
+
raise NSCoolError("TOV wrote no profile")
|
|
402
|
+
if abs(m[-1] - mass) > 1e-4 * mass:
|
|
403
|
+
raise NSCoolError(f"TOV reached M={m[-1]}, target {mass}")
|
|
404
|
+
_, m2 = self._tov(d, head + f"rhoc={1.002 * rhoc[-1]:.6e}\ngo\nEOF\n",
|
|
405
|
+
timeout)
|
|
406
|
+
if not m2[-1] > m[-1]:
|
|
407
|
+
raise NSCoolError(f"TOV star at rho_c={rhoc[-1]} fm^-3 is on the "
|
|
408
|
+
f"unstable branch (dM/drho_c <= 0)")
|
|
409
|
+
shutil.copy(prof, out)
|
|
410
|
+
return out
|
|
411
|
+
|
|
412
|
+
# ------------------------------------------------------------------
|
|
413
|
+
def _setup(self, d: Path, *, mass, profile, eos_table, crust_table, gaps,
|
|
414
|
+
eta, rhocore, rhodrip, rhoenv, rhosurf, icore, idec, tempini,
|
|
415
|
+
tempmin, neutrino_file, conduct_file, star) -> None:
|
|
416
|
+
"""Write NSCool's input files for one star into run directory ``d``."""
|
|
417
|
+
if (mass is None) == (profile is None):
|
|
418
|
+
raise ValueError("give exactly one of mass, profile")
|
|
419
|
+
eos_table = Path(eos_table) if eos_table else self.default_eos
|
|
420
|
+
crust_table = Path(crust_table) if crust_table else self.default_crust
|
|
421
|
+
m1 = d / "Model_1" # NSCool prefixes the master file with Model_1/
|
|
422
|
+
m1.mkdir()
|
|
423
|
+
os.symlink(self.home / "Code", d / "Code") # Code/Data_Files/*
|
|
424
|
+
os.symlink(eos_table.resolve(), d / "eos.dat")
|
|
425
|
+
os.symlink(crust_table.resolve(), d / "crust.dat")
|
|
426
|
+
if profile is None:
|
|
427
|
+
self.make_profile(eos_table, mass, d / "prof.dat")
|
|
428
|
+
else:
|
|
429
|
+
os.symlink(Path(profile).resolve(), d / "prof.dat")
|
|
430
|
+
files = {
|
|
431
|
+
"I_Struct.dat": _STRUCT.format(rhocore=rhocore, rhodrip=rhodrip,
|
|
432
|
+
rhoenv=rhoenv, rhosurf=rhosurf,
|
|
433
|
+
icore=icore, idec=idec),
|
|
434
|
+
"I_Bound.dat": _BOUND.format(eta=eta),
|
|
435
|
+
"I_Pairing.dat": gaps.pairing_file(),
|
|
436
|
+
"I.dat": _I_DAT.format(tempmin=tempmin, tempini=tempini,
|
|
437
|
+
pstar=int(star)),
|
|
438
|
+
}
|
|
439
|
+
for name, text in files.items():
|
|
440
|
+
(m1 / name).write_text(text)
|
|
441
|
+
for name in (neutrino_file, conduct_file, "I_Heat_0.dat",
|
|
442
|
+
"I_Bfield_0.dat", "I_Accretion_0.dat"):
|
|
443
|
+
shutil.copy(self.home / "I_Files" / name, m1 / name)
|
|
444
|
+
master = ["'NEW'", "BASIC MODEL FILES:", "'crust.dat'", "'eos.dat'",
|
|
445
|
+
"'prof.dat'", "OTHER MODEL FILES:",
|
|
446
|
+
"'Model_1/I_Struct.dat'", "'Model_1/I_Bound.dat'",
|
|
447
|
+
"'Model_1/I_Pairing.dat'", f"'Model_1/{neutrino_file}'",
|
|
448
|
+
f"'Model_1/{conduct_file}'", "'Model_1/I_Heat_0.dat'",
|
|
449
|
+
"'Model_1/I_Bfield_0.dat'", "'Model_1/I_Accretion_0.dat'",
|
|
450
|
+
"OUTPUT FILES:", "'Model_1/I.dat'", "'Model_1/Teff.dat'",
|
|
451
|
+
"'Model_1/Temp.dat'", "'Model_1/Star.dat'", ""]
|
|
452
|
+
(m1 / "Cool.in").write_text("\n".join(master))
|
|
453
|
+
|
|
454
|
+
def _exec(self, exe: Path, d: Path, stdin: str, gaps: GapModel,
|
|
455
|
+
timeout: float, keep: Optional[PathLike]) -> str:
|
|
456
|
+
"""Run ``exe`` in ``d``; check the run and the s_x echo; return stdout."""
|
|
457
|
+
env = dict(os.environ, OMP_NUM_THREADS="1")
|
|
458
|
+
try:
|
|
459
|
+
r = subprocess.run([str(exe)], cwd=d, input=stdin,
|
|
460
|
+
capture_output=True, text=True,
|
|
461
|
+
timeout=timeout, env=env)
|
|
462
|
+
except subprocess.TimeoutExpired as e:
|
|
463
|
+
raise NSCoolError(f"{exe.name} timed out after {timeout} s") from e
|
|
464
|
+
log = r.stdout + r.stderr # gfortran writes PAUSE to stderr
|
|
465
|
+
(d / "stdout.txt").write_text(log)
|
|
466
|
+
if keep is not None:
|
|
467
|
+
shutil.copytree(d, keep, symlinks=True, dirs_exist_ok=True)
|
|
468
|
+
if r.returncode != 0 or "Done" not in r.stdout or "PAUSE" in log.upper():
|
|
469
|
+
raise NSCoolError(f"{exe.name} failed (rc={r.returncode}):\n{log[-2000:]}")
|
|
470
|
+
m = re.search(r"nmbackend sx_p1s0 sx_n3p2 =\s*(\S+)\s+(\S+)", r.stdout)
|
|
471
|
+
if m is None or not np.allclose([float(m.group(1)), float(m.group(2))],
|
|
472
|
+
[gaps.sx_p1s0, gaps.sx_n3p2], rtol=1e-5):
|
|
473
|
+
raise NSCoolError("NSCool did not read the s_x values written "
|
|
474
|
+
f"({m.group(0) if m else 'no echo: unpatched build?'})")
|
|
475
|
+
m = re.search(r"nmbackend ca_n3p2 =\s*(\S+)", r.stdout)
|
|
476
|
+
if m is None or not np.isclose(float(m.group(1)), gaps.ca_n3p2, rtol=1e-5):
|
|
477
|
+
raise NSCoolError("NSCool did not read CA3P2 "
|
|
478
|
+
f"({m.group(0) if m else 'no echo: build predates CA3P2?'})")
|
|
479
|
+
return r.stdout
|
|
480
|
+
|
|
481
|
+
def run(self, *, mass: Optional[float] = None,
|
|
482
|
+
profile: Optional[PathLike] = None,
|
|
483
|
+
eos_table: Optional[PathLike] = None,
|
|
484
|
+
crust_table: Optional[PathLike] = None,
|
|
485
|
+
gaps: GapModel = GapModel(),
|
|
486
|
+
eta: float = 0.0,
|
|
487
|
+
rhocore: float = 1.6e14, rhodrip: float = 4.0e11,
|
|
488
|
+
rhoenv: float = 1.0e8, rhosurf: float = 1.0e10,
|
|
489
|
+
icore: int = 111, idec: int = 60,
|
|
490
|
+
tempini: float = 1.0e10, tempmin: float = 1.0e4,
|
|
491
|
+
neutrino_file: str = "I_Neutrino_1.dat",
|
|
492
|
+
conduct_file: str = "I_Conduct_32.dat",
|
|
493
|
+
star: bool = False,
|
|
494
|
+
timeout: float = 600.0,
|
|
495
|
+
keep: Optional[PathLike] = None) -> CoolingCurve:
|
|
496
|
+
"""Cool one star.
|
|
497
|
+
|
|
498
|
+
Give either ``mass`` (built from ``eos_table`` with NSCool's TOV) or
|
|
499
|
+
a ready ``profile``. ``eos_table`` is an NSCool 'NEW'-format core+crust
|
|
500
|
+
table (README.md); default the bundled APR. ``eta`` is written to
|
|
501
|
+
NSCool's ``ETA``; NSCool divides it by 0.443 before the envelope
|
|
502
|
+
formula of Potekhin, Chabrier & Yakovlev (1997) (README.md).
|
|
503
|
+
Grid defaults follow the bundled Model_1
|
|
504
|
+
(I_Struct_1.6e14-4.0e11-1e10_normal.dat).
|
|
505
|
+
``star=True`` also returns NSCool's per-zone profile (``parse_star_file``).
|
|
506
|
+
``keep`` copies the run directory there for inspection.
|
|
507
|
+
"""
|
|
508
|
+
opts = dict(mass=mass, profile=profile, eos_table=eos_table,
|
|
509
|
+
crust_table=crust_table, gaps=gaps, eta=eta,
|
|
510
|
+
rhocore=rhocore, rhodrip=rhodrip, rhoenv=rhoenv,
|
|
511
|
+
rhosurf=rhosurf, icore=icore, idec=idec, tempini=tempini,
|
|
512
|
+
tempmin=tempmin, neutrino_file=neutrino_file,
|
|
513
|
+
conduct_file=conduct_file, star=star)
|
|
514
|
+
with tempfile.TemporaryDirectory(dir=self.workroot) as d:
|
|
515
|
+
d = Path(d)
|
|
516
|
+
self._setup(d, **opts)
|
|
517
|
+
self._exec(self.exe, d, "Cool.in\n", gaps, timeout, keep)
|
|
518
|
+
curve = parse_teff_file(d / "Model_1" / "Teff.dat")
|
|
519
|
+
if star:
|
|
520
|
+
curve = curve._replace(star=parse_star_file(d / "Model_1" / "Star.dat"))
|
|
521
|
+
return curve
|
|
522
|
+
|
|
523
|
+
def isothermal(self, *, T_grid=(1e4, 1e10, 601), rho_b: float = 0.0,
|
|
524
|
+
timeout: float = 600.0,
|
|
525
|
+
keep: Optional[PathLike] = None, **kw) -> "IsothermalStar":
|
|
526
|
+
"""C(T), L_nu(T), L_gamma(T) of the star with uniform redshifted T.
|
|
527
|
+
|
|
528
|
+
Takes the star and physics arguments of ``run`` and returns NSCool's
|
|
529
|
+
own heat capacity and luminosities summed over zones at each
|
|
530
|
+
redshifted temperature of the log grid ``T_grid = (T_min, T_max, n)``
|
|
531
|
+
(``NSCool_iso.out``, built from ``nscool_isothermal_tail.f``).
|
|
532
|
+
``rho_b`` (g/cm^3) > ``rhosurf`` also fills ``T_in``, the temperature
|
|
533
|
+
at rho_b below a blanket at T_b = T (``isothermal_curve``).
|
|
534
|
+
"""
|
|
535
|
+
if not self.iso_exe.is_file():
|
|
536
|
+
raise FileNotFoundError(f"{self.iso_exe} missing: rerun build_nscool.sh")
|
|
537
|
+
tmin, tmax, n = T_grid
|
|
538
|
+
opts = {k: v.default for k, v in inspect.signature(self.run).parameters.items()
|
|
539
|
+
if k not in ("timeout", "keep")}
|
|
540
|
+
unknown = set(kw) - set(opts)
|
|
541
|
+
if unknown:
|
|
542
|
+
raise TypeError(f"unknown arguments {sorted(unknown)}")
|
|
543
|
+
opts.update(kw)
|
|
544
|
+
with tempfile.TemporaryDirectory(dir=self.workroot) as d:
|
|
545
|
+
d = Path(d)
|
|
546
|
+
self._setup(d, **opts)
|
|
547
|
+
out = self._exec(self.iso_exe, d,
|
|
548
|
+
f"Cool.in\n{int(n)} {tmin:.8e} {tmax:.8e} {rho_b:.8e}\n",
|
|
549
|
+
opts["gaps"], timeout, keep)
|
|
550
|
+
return parse_isothermal(out)
|
|
551
|
+
|
|
552
|
+
def zone_dump(self, T, *, T_grid=(1e8, 1e9, 2), rho_b: float = 0.0,
|
|
553
|
+
timeout: float = 600.0, keep: Optional[PathLike] = None,
|
|
554
|
+
**kw) -> ZoneDump:
|
|
555
|
+
"""Every term NSCool sums, zone by zone, at uniform redshifted T.
|
|
556
|
+
|
|
557
|
+
``T`` is a sequence of redshifted temperatures (K). Takes the star
|
|
558
|
+
and physics arguments of ``run``. The isothermal scan on ``T_grid``
|
|
559
|
+
(with ``rho_b``) comes back as ``ZoneDump.iso``.
|
|
560
|
+
"""
|
|
561
|
+
if not self.iso_exe.is_file():
|
|
562
|
+
raise FileNotFoundError(f"{self.iso_exe} missing: rerun build_nscool.sh")
|
|
563
|
+
T = np.atleast_1d(np.asarray(T, float))
|
|
564
|
+
tmin, tmax, n = T_grid
|
|
565
|
+
opts = {k: v.default for k, v in inspect.signature(self.run).parameters.items()
|
|
566
|
+
if k not in ("timeout", "keep")}
|
|
567
|
+
unknown = set(kw) - set(opts)
|
|
568
|
+
if unknown:
|
|
569
|
+
raise TypeError(f"unknown arguments {sorted(unknown)}")
|
|
570
|
+
opts.update(kw)
|
|
571
|
+
stdin = (f"Cool.in\n{int(n)} {tmin:.8e} {tmax:.8e} {rho_b:.8e}\n{T.size}\n"
|
|
572
|
+
+ "".join(f"{t:.10e}\n" for t in T))
|
|
573
|
+
with tempfile.TemporaryDirectory(dir=self.workroot) as d:
|
|
574
|
+
d = Path(d)
|
|
575
|
+
self._setup(d, **opts)
|
|
576
|
+
out = self._exec(self.iso_exe, d, stdin, opts["gaps"], timeout, keep)
|
|
577
|
+
if "ZSC " not in out:
|
|
578
|
+
raise NSCoolError("NSCool_iso.out wrote no zone dump: rerun build_nscool.sh")
|
|
579
|
+
return parse_zone_dump(out)
|
|
580
|
+
|
|
581
|
+
@property
|
|
582
|
+
def iso_exe(self) -> Path:
|
|
583
|
+
return self.home / "Code" / "NSCool_iso.out"
|