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,249 @@
1
+ """Physical tabulated-EOS exchange with pinned external RNS (not differentiable).
2
+
3
+ RNS uses legacy CGS constants and scaled geometry internally. Keep these units
4
+ explicit: its global Omega is rad/s, whereas exported frame dragging is scaled.
5
+ The finite low-density EOSTable boundary is matched, without extrapolation.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ import os
12
+ from pathlib import Path
13
+ import re
14
+ import subprocess
15
+ import tempfile
16
+ import time
17
+
18
+ import numpy as np
19
+
20
+ from ..constants import MSUN_SI
21
+ from .rns import RNS_COMMIT, RNSBackground, _sha, export_driver, load_background
22
+
23
+ C_CGS = 2.9979e10
24
+ G_CGS = 6.6732e-8
25
+ MB_G = 1.66e-24
26
+ LENGTH_CM = math.sqrt(1.e-15 * C_CGS**2 / G_CGS)
27
+ MEVFM3_TO_ERGCM3 = 1.602176634e33
28
+ MAX_ROWS = 8192
29
+
30
+
31
+ # All compiled translation units and local headers, upstream source/rns.v2.0.
32
+ RNS_SOURCE_SHA256 = {
33
+ 'main.c': '5bbe51d50f4f13b7eb3b77fd4564289b7c2b9e8c76523b821ea33c7a3ba78423',
34
+ 'equil.c': 'c4bcad5e3e3caa89a108cb54f484853e0f059743fe6b43959f5a505e89adbc4a',
35
+ 'equil_util.c': 'd6d5270f086bef92bf58c02472f77d4fa5bdf3746394ae66068df8e717e73937',
36
+ 'nrutil.c': 'b1af981ac2a0f21c7911e4d92c3925a36aea2eb2436210c0247f6a23f9815ee0',
37
+ 'consts.h': 'a557c0d417b15e5ce4ac982c9794785fef185aa512d04849029037c509c4911f',
38
+ 'equil.h': '42ed6a75a54b049059898a72be30d37e92e96bbad58263eed6321df7b3a1a348',
39
+ 'equil_util.h': '1cc8d2f64be79930709a6afa926254d3874539bd9aff9a5d195464c6b9c6e61a',
40
+ 'nrutil.h': 'e1138958c6011df88e208ae7840363dbba6de11b1f95fc133842b44fe42418fa',
41
+ }
42
+ SPIN_MAX_ITERATIONS = 1000
43
+
44
+
45
+ def _validate_source(source):
46
+ for name, expected in RNS_SOURCE_SHA256.items():
47
+ path = source / name
48
+ if not path.is_file() or _sha(path) != expected:
49
+ raise ValueError(f'Pinned RNS source mismatch: {name}')
50
+
51
+
52
+ def _guard_equilibrium(text, *, max_iterations=SPIN_MAX_ITERATIONS):
53
+ # a_check is passed by value upstream: a divergence used to return normally.
54
+ replacements = {
55
+ '#include <stdio.h>': '#include <stdio.h>\n#include <stdlib.h>',
56
+ 'a_check=200;': 'fprintf(stderr, "NMB_RNS_SPIN_DIVERGED\\n"); exit(9);',
57
+ 'while(dif> accuracy || n_of_it<2) {':
58
+ 'while(dif> accuracy || n_of_it<2) {\n'
59
+ f' if(n_of_it >= {max_iterations}) {{ fprintf(stderr, '
60
+ '"NMB_RNS_SPIN_ITERATION_LIMIT\\n"); exit(10); }',
61
+ 'dif=fabs(r_e_old-r_e)/r_e;':
62
+ 'dif=fabs(r_e_old-r_e)/r_e;\n'
63
+ ' if(!isfinite(dif)) { fprintf(stderr, '
64
+ '"NMB_RNS_SPIN_NONFINITE_RESIDUAL\\n"); exit(11); }',
65
+ '/* COMPUTE OMEGA */':
66
+ 'if(!isfinite(dif) || dif>accuracy || n_of_it<2 || '
67
+ '!isfinite(r_e) || r_e<=0) { fprintf(stderr, '
68
+ '"NMB_RNS_SPIN_NOT_CONVERGED\\n"); exit(12); }\n'
69
+ '/* COMPUTE OMEGA */',
70
+ '/* UPDATE r_e_new */':
71
+ 'if(!isfinite(*Omega)) { fprintf(stderr, '
72
+ '"NMB_RNS_SPIN_NONFINITE_OMEGA\\n"); exit(13); }\n'
73
+ '/* UPDATE r_e_new */',
74
+ }
75
+ counts = {'#include <stdio.h>': 1, 'a_check=200;': 2,
76
+ 'while(dif> accuracy || n_of_it<2) {': 1,
77
+ 'dif=fabs(r_e_old-r_e)/r_e;': 1,
78
+ '/* COMPUTE OMEGA */': 1, '/* UPDATE r_e_new */': 1}
79
+ for old, new in replacements.items():
80
+ if text.count(old) != counts[old]:
81
+ raise ValueError('Pinned RNS convergence contract changed')
82
+ text = text.replace(old, new)
83
+ return text
84
+
85
+
86
+ def export_eos(table, path):
87
+ """Write native rho,p,c²h,n table, with units and boundary provenance."""
88
+ path = Path(path)
89
+ n, eps, p, h = (np.asarray(getattr(table, key), dtype=float)
90
+ for key in ('n', 'eps_mevfm3', 'p_mevfm3', 'h'))
91
+ if (n.ndim != 1 or not 4 <= len(n) <= MAX_ROWS or any(a.shape != n.shape for a in (eps,p,h))
92
+ or any(not np.all(np.isfinite(a)) or np.any(a <= 0)
93
+ or np.any(np.diff(a) <= 0) for a in (n,eps,p,h))):
94
+ raise ValueError('RNS requires 4..8192 finite positive strictly increasing EOS rows')
95
+ rows = np.column_stack((eps*MEVFM3_TO_ERGCM3/C_CGS**2,
96
+ p*MEVFM3_TO_ERGCM3, h*C_CGS**2, n*1.e39))
97
+ if not np.all(np.isfinite(rows)) or np.any(rows <= 0):
98
+ raise ValueError('Native EOS unit conversion overflow or underflow')
99
+ path.parent.mkdir(parents=True, exist_ok=True)
100
+ np.savetxt(path, rows, header=str(len(n)), comments='', fmt='%.17e')
101
+ manifest = dict(format='RNS rho,p,c2h,n0', columns=['g/cm^3','dyne/cm^2','erg/g','cm^-3'],
102
+ rows=len(n), sha256=_sha(path), surface='finite EOSTable minimum',
103
+ c_cgs=C_CGS, g_cgs=G_CGS, baryon_mass_g=MB_G,
104
+ enthalpy_min=float(h[0]), energy_surface_g_cm3=float(rows[0,0]),
105
+ pressure_surface_dyn_cm2=float(rows[0,1]))
106
+ path.with_suffix(path.suffix+'.json').write_text(json.dumps(manifest, indent=2)+'\n')
107
+ return manifest
108
+
109
+
110
+ def build_tabulated_rns(source, output, *, radial_points=129, angular_points=65,
111
+ accuracy=1.e-5, cc='cc'):
112
+ """Build a derived driver with full table capacity and matching surface."""
113
+ if radial_points < 33 or angular_points < 17 or radial_points%2 != 1 or angular_points%2 != 1:
114
+ raise ValueError('Require odd RNS Simpson grids >=33 radial, >=17 angular')
115
+ if not math.isfinite(accuracy) or not 0 < accuracy <= 1.e-5:
116
+ raise ValueError('Native accuracy must be finite and 0 < accuracy <= 1e-5')
117
+ source, output = Path(source).resolve(), Path(output).resolve()
118
+ _validate_source(source)
119
+ output.mkdir(parents=True, exist_ok=False)
120
+ driver = export_driver(source, output/'tabulated_export.c')
121
+ text = driver.read_text().replace('[201]', f'[{MAX_ROWS+1}]')
122
+ if text.count('accuracy=1e-5;') != 1:
123
+ raise ValueError('Pinned driver accuracy contract changed')
124
+ text = text.replace('accuracy=1e-5;', f'accuracy={accuracy:.17g};')
125
+ for old, new in (
126
+ ('e_surface=7.8*C*C*KSCALE;', 'e_surface=strtod(getenv("NMB_TAB_ES"),NULL)*C*C*KSCALE;'),
127
+ ('p_surface=1.01e8*KSCALE;', 'p_surface=strtod(getenv("NMB_TAB_PS"),NULL)*KSCALE;'),
128
+ ('enthalpy_min=1.0/(C*C);', 'enthalpy_min=strtod(getenv("NMB_TAB_HS"),NULL);')):
129
+ if old not in text:
130
+ raise ValueError('Pinned driver surface contract changed')
131
+ text = text.replace(old,new)
132
+ # Fail cleanly if somebody invokes the derived driver outside this runner.
133
+ text = text.replace('e_surface=strtod',
134
+ 'if(!getenv("NMB_TAB_ES") || !getenv("NMB_TAB_PS") || !getenv("NMB_TAB_HS")) return 8;\n e_surface=strtod')
135
+ driver.write_text(text)
136
+ equilibrium = output/'tabulated_equil.c'
137
+ equilibrium.write_text(_guard_equilibrium((source/'equil.c').read_text()))
138
+ executable = output/'rns_tabulated'
139
+ command = [cc,'-std=c99','-O2',f'-DMDIV={angular_points}',f'-DSDIV={radial_points}',
140
+ '-I',str(source),'-o',str(executable),str(driver),str(equilibrium),
141
+ *(str(source/name) for name in ('equil_util.c','nrutil.c')),'-lm']
142
+ result = subprocess.run(command,capture_output=True,text=True,timeout=120)
143
+ (output/'build.log').write_text(result.stdout+result.stderr)
144
+ result.check_returncode()
145
+ (output/'build.json').write_text(json.dumps(dict(upstream_commit=RNS_COMMIT,
146
+ source_sha256={name:_sha(source/name) for name in RNS_SOURCE_SHA256},
147
+ generated_equilibrium_sha256=_sha(equilibrium),spin_max_iterations=SPIN_MAX_ITERATIONS,
148
+ generated_driver_sha256=_sha(driver), binary_sha256=_sha(executable),command=command,
149
+ radial_points=radial_points,angular_points=angular_points,max_eos_rows=MAX_ROWS,
150
+ accuracy=float(accuracy),
151
+ c_cgs=C_CGS,g_cgs=G_CGS,baryon_mass_g=MB_G),indent=2)+'\n')
152
+ return executable
153
+
154
+
155
+ def _native_log_interp(x, xp, yp):
156
+ """Mirrors RNS interp's local four-point polynomial, on logarithms."""
157
+ x = np.asarray(x)
158
+ start = np.clip(np.searchsorted(xp,x,side='right')-2,0,len(xp)-4)
159
+ xx = xp[start[...,None]+np.arange(4)]
160
+ yy = yp[start[...,None]+np.arange(4)]
161
+ result = np.zeros_like(x,dtype=float)
162
+ for j in range(4):
163
+ term = yy[...,j].copy()
164
+ for k in range(4):
165
+ if k != j:
166
+ term *= (x-xx[...,k])/(xx[...,j]-xx[...,k])
167
+ result += term
168
+ return result
169
+
170
+
171
+ def load_tabulated_background(path, eos_path):
172
+ """Validate scaled geometry; attach physical units and native n(e) bridge.
173
+
174
+ Geometry arrays retain the RNS length scale LENGTH_CM. metadata Omega is
175
+ converted to its matching internal unit; Omega_rad_s retains physical spin.
176
+ Mass/Radius physical convenience values have explicit unit suffixes.
177
+ """
178
+ path, eos_path = Path(path), Path(eos_path)
179
+ original = path.read_text()
180
+ raw = {k:float(v) for k,v in re.findall(r'([A-Za-z_]+)=([-+0-9.eE]+)',original.splitlines()[0])}
181
+ internal_omega = raw['Omega']*LENGTH_CM/C_CGS
182
+ header = original.splitlines()[0]
183
+ header = re.sub(r'(?<![A-Za-z_])Omega=[-+0-9.eE]+',f'Omega={internal_omega:.17g}',header)
184
+ if 'Omega_K' in raw:
185
+ header = re.sub(r'Omega_K=[-+0-9.eE]+',f'Omega_K={raw["Omega_K"]*LENGTH_CM/C_CGS:.17g}',header)
186
+ with tempfile.TemporaryDirectory() as temporary:
187
+ normalized = Path(temporary)/'normalized.csv'
188
+ normalized.write_text(header+'\n'+'\n'.join(original.splitlines()[1:])+'\n')
189
+ star = load_background(normalized)
190
+ rows = np.loadtxt(eos_path,skiprows=1)
191
+ manifest = json.loads(eos_path.with_suffix(eos_path.suffix+'.json').read_text())
192
+ if _sha(eos_path) != manifest['sha256']:
193
+ raise ValueError('EOS provenance checksum mismatch')
194
+ fields = dict(star.fields)
195
+ matter = fields['energy'] > 0
196
+ n = np.zeros_like(fields['energy'])
197
+ loge = np.log10(rows[:,0]/1.e15)
198
+ sampled = np.log10(fields['energy'][matter])
199
+ if sampled.size and (sampled.min() < loge[0]-1.e-5 or sampled.max() > loge[-1]+1.e-5):
200
+ raise ValueError('RNS matter outside exported EOS range')
201
+ n[matter] = 10**_native_log_interp(sampled,loge,np.log10(rows[:,3]))/1.e39
202
+ fields['n_fm3'] = n
203
+ metadata = dict(star.metadata)
204
+ metadata.pop('Gamma',None) # native default Gamma is irrelevant for tabulated EOS
205
+ metadata.update(units='RNS scaled tabulated geometry; explicit CGS conversion metadata',
206
+ eos_kind='tabulated',Omega_rad_s=raw['Omega'],frequency_hz=raw['Omega']/(2*np.pi),
207
+ length_scale_cm=LENGTH_CM,c_cgs=C_CGS,g_cgs=G_CGS,baryon_mass_g=MB_G,
208
+ source_path=str(path.resolve()),csv_sha256=_sha(path),eos_sha256=_sha(eos_path),
209
+ native_header=raw,surface=manifest['surface'])
210
+ for key in ('Mass','Mass_b'):
211
+ if key in raw:
212
+ metadata[key+'_msun'] = raw[key]/(MSUN_SI*1000)
213
+ if 'R_e' in raw:
214
+ metadata['R_e_km'] = raw['R_e']/1.e5
215
+ if 'J' in raw:
216
+ metadata['J_g_cm2_s'] = raw['J']
217
+ if 'Mass_b' in raw:
218
+ metadata['baryon_number'] = raw['Mass_b']/MB_G
219
+ return RNSBackground(star.r,star.mu,fields,metadata)
220
+
221
+
222
+ def solve_tabulated(executable, output, table, *, energy_center_g_cm3, axis_ratio=.8, timeout=120):
223
+ """Solve one central total energy/c² and axis ratio, plus spherical control."""
224
+ if not math.isfinite(energy_center_g_cm3) or energy_center_g_cm3 <= 0 or not .6 <= axis_ratio <= 1:
225
+ raise ValueError('Require positive total energy/c² and .6<=axis_ratio<=1')
226
+ executable,output = Path(executable).resolve(),Path(output).resolve()
227
+ output.mkdir(parents=True,exist_ok=False)
228
+ eos_path = output/'eos.dat'
229
+ manifest = export_eos(table,eos_path)
230
+ rows = np.loadtxt(eos_path,skiprows=1)
231
+ if not rows[0,0] < energy_center_g_cm3 < rows[-1,0]:
232
+ raise ValueError('Central energy must lie strictly inside EOS table')
233
+ command = [str(executable),'-q','tab','-f','eos.dat','-e',str(energy_center_g_cm3)]
234
+ environment = {**os.environ,'NMB_RNS_Q':str(axis_ratio),
235
+ 'NMB_TAB_ES':str(manifest['energy_surface_g_cm3']),
236
+ 'NMB_TAB_PS':str(manifest['pressure_surface_dyn_cm2']),
237
+ 'NMB_TAB_HS':str(manifest['enthalpy_min'])}
238
+ started = time.monotonic()
239
+ result = subprocess.run(command,cwd=output,capture_output=True,text=True,env=environment,timeout=timeout)
240
+ (output/'run.log').write_text(result.stdout+result.stderr)
241
+ result.check_returncode()
242
+ spherical = load_tabulated_background(output/'rns_spherical.csv',eos_path)
243
+ rotating = load_tabulated_background(output/'rns_rotating.csv',eos_path)
244
+ if abs(rotating.metadata['r_ratio']-axis_ratio)>1.e-12:
245
+ raise ValueError('RNS did not honor requested axis ratio')
246
+ (output/'run.json').write_text(json.dumps(dict(command=command,binary_sha256=_sha(executable),
247
+ elapsed_seconds=time.monotonic()-started,eos=manifest,spherical=spherical.metadata,
248
+ rotating=rotating.metadata),indent=2)+'\n')
249
+ return spherical,rotating
@@ -0,0 +1 @@
1
+ """Conditional heat transport on a supplied stationary rotating background."""
@@ -0,0 +1,86 @@
1
+ """Conservative scalar transport on a frozen axisymmetric metric.
2
+
3
+ Discretizes Beznogov et al. (2023), Eq. 10, in (r, mu=cos(theta)).
4
+ Closed rectangular meridional domains only: no envelope or oblate surface.
5
+ All inputs use a single consistent unit system; no physical constants implied.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import NamedTuple
10
+
11
+ import jax.numpy as jnp
12
+ from jax.scipy.sparse.linalg import cg
13
+
14
+
15
+ class ThermalOperator(NamedTuple):
16
+ """Cell capacity and internal face conductances, with insulated boundaries."""
17
+
18
+ capacity: jnp.ndarray
19
+ radial: jnp.ndarray
20
+ angular: jnp.ndarray
21
+ source_weight: jnp.ndarray
22
+
23
+
24
+ def metric_factors(rho, gama, alpha, velocity_sq):
25
+ """RNS potentials -> lapse N, meridional A, azimuthal B, Lorentz Gamma.
26
+
27
+ velocity_sq must be the physical ZAMO velocity squared divided by c^2,
28
+ restricted to stellar matter with 0 <= velocity_sq < 1.
29
+ """
30
+ return (jnp.exp((gama + rho) / 2), jnp.exp(alpha),
31
+ jnp.exp((gama - rho) / 2), 1 / jnp.sqrt(1 - velocity_sq))
32
+
33
+
34
+ def build_operator(r_faces, mu_faces, lapse, meridional, azimuthal,
35
+ lorentz, heat_capacity, conductivity):
36
+ """Midpoint finite volumes for positive, temperature-independent Cv and K.
37
+
38
+ Fields broadcast to (nr, nmu). All fields must be positive; dt >= 0.
39
+ r_faces >= 0 and mu_faces in [-1,1]
40
+ must increase. Faces use distance-weighted series resistance. Geometry is fixed
41
+ during differentiation; this does not differentiate an RNS solution.
42
+ """
43
+ r_faces, mu_faces = jnp.asarray(r_faces), jnp.asarray(mu_faces)
44
+ r = (r_faces[:-1] + r_faces[1:]) / 2
45
+ mu = (mu_faces[:-1] + mu_faces[1:]) / 2
46
+ dr, dm = jnp.diff(r_faces), jnp.diff(mu_faces)
47
+ shape = (r.size, mu.size)
48
+ N, A, B, G, cv, k = [jnp.broadcast_to(jnp.asarray(x), shape) for x in
49
+ (lapse, meridional, azimuthal, lorentz,
50
+ heat_capacity, conductivity)]
51
+ volume = (jnp.diff(r_faces**3) / 3)[:, None] * dm[None, :]
52
+ capacity = volume * A**2 * B * G * cv
53
+ knb = k * N * B
54
+ radial = (r_faces[1:-1, None]**2 * dm[None, :] /
55
+ (dr[:-1, None]/(2*knb[:-1]) + dr[1:, None]/(2*knb[1:])))
56
+ angular = (dr[:, None] * (1-mu_faces[None, 1:-1]**2) /
57
+ (dm[None, :-1]/(2*knb[:, :-1]) + dm[None, 1:]/(2*knb[:, 1:])))
58
+ return ThermalOperator(capacity, radial, angular,
59
+ volume * A**2 * B * N**2 / G)
60
+
61
+
62
+ def diffusion(op, temperature):
63
+ """Integrated divergence; constant redshifted temperature is exactly null."""
64
+ radial = op.radial * jnp.diff(temperature, axis=0)
65
+ angular = op.angular * jnp.diff(temperature, axis=1)
66
+ return (jnp.pad(radial, ((0, 1), (0, 0)))
67
+ - jnp.pad(radial, ((1, 0), (0, 0)))
68
+ + jnp.pad(angular, ((0, 0), (0, 1)))
69
+ - jnp.pad(angular, ((0, 0), (1, 0))))
70
+
71
+
72
+ def implicit_step(op, redshifted_temperature, dt, source=0., tol=1e-11,
73
+ maxiter=2000):
74
+ """Backward Euler solve, including a prescribed local heating Q (negative loss).
75
+
76
+ Uses capacity scaling for an SPD system. JAX CG differentiates the solve
77
+ implicitly; callers must check the returned relative residual. source
78
+ is not evaluated implicitly as a temperature-dependent emissivity.
79
+ """
80
+ root = jnp.sqrt(op.capacity)
81
+ apply = lambda z: z - dt * diffusion(op, z / root) / root
82
+ rhs = root * redshifted_temperature + dt * op.source_weight * source / root
83
+ z, _ = cg(apply, rhs, tol=tol, atol=0., maxiter=maxiter)
84
+ residual = jnp.linalg.norm(apply(z) - rhs) / jnp.maximum(
85
+ jnp.linalg.norm(rhs), jnp.finfo(rhs.dtype).tiny)
86
+ return z / root, residual
@@ -0,0 +1,15 @@
1
+ """TOV solver and stellar-sequence tools."""
2
+ from .solver import solve_structure, solve_profile, TOVPoint, TOVProfile
3
+ from .family import (
4
+ build_family, Family, default_hc_grid, m_max, dhc_dM,
5
+ lambda_of_mass, radius_of_mass,
6
+ )
7
+ from .phase_transition import solve_hybrid, hybrid_sequence
8
+ from .central import CentralFamily, family_central, central_at_mass
9
+
10
+ __all__ = [
11
+ "solve_structure", "solve_profile", "TOVPoint", "TOVProfile",
12
+ "build_family", "Family", "default_hc_grid", "m_max", "dhc_dM",
13
+ "lambda_of_mass", "radius_of_mass",
14
+ "solve_hybrid", "hybrid_sequence",
15
+ ]
@@ -0,0 +1,72 @@
1
+ """Central (core) properties along a TOV family.
2
+
3
+ Exposes the quantities the IPAD-TOV analysis needs per stellar model:
4
+ central energy density / pressure / sound speed, the central EOS parameter
5
+ X = P_c/eps_c, and the log-stability slope Psi = 2 dlnM/dln eps_c
6
+ (dM/dh_c from the family's forward-mode AD; d eps_c/dh_c by a fine finite
7
+ difference of the table's eps(h) interpolant).
8
+
9
+ Numpy outputs (post-processing layer, not differentiable end-to-end; the
10
+ underlying dM/dh_c IS the AD derivative from ``build_family``).
11
+ """
12
+ from typing import NamedTuple
13
+
14
+ import numpy as np
15
+
16
+ __all__ = ["CentralFamily", "family_central", "central_at_mass"]
17
+
18
+
19
+ class CentralFamily(NamedTuple):
20
+ """Central quantities along the family grid (same order as Family)."""
21
+ h_c: np.ndarray
22
+ eps_c: np.ndarray # geometric km^-2
23
+ p_c: np.ndarray # geometric km^-2
24
+ cs2_c: np.ndarray # c^2
25
+ X: np.ndarray # P_c/eps_c
26
+ Psi: np.ndarray # 2 dlnM/dln eps_c
27
+ M_msun: np.ndarray
28
+ Lambda: np.ndarray
29
+ stable: np.ndarray
30
+
31
+
32
+ def family_central(table, fam, dh: float = 1e-5) -> CentralFamily:
33
+ """Central properties for every model in ``fam`` (built on ``table``)."""
34
+ hc = np.asarray(fam.h_c, dtype=float)
35
+ M = np.asarray(fam.M_msun, dtype=float)
36
+ lam = np.asarray(fam.Lambda, dtype=float)
37
+ dM_dhc = np.asarray(fam.dM_dhc, dtype=float)
38
+ stable = np.asarray(fam.stable, dtype=bool)
39
+
40
+ eps, p, cs2 = (np.asarray(v, dtype=float) for v in table.at_h(hc))
41
+ eps_hi = np.asarray(table.at_h(hc + dh)[0], dtype=float)
42
+ eps_lo = np.asarray(table.at_h(hc - dh)[0], dtype=float)
43
+ deps_dhc = (eps_hi - eps_lo) / (2.0 * dh)
44
+ with np.errstate(divide="ignore", invalid="ignore"):
45
+ Psi = 2.0 * (dM_dhc / M) * (eps / deps_dhc)
46
+ return CentralFamily(hc, eps, p, cs2, p / eps, Psi, M, lam, stable)
47
+
48
+
49
+ def central_at_mass(cf: CentralFamily, m_msun: float) -> dict:
50
+ """Interpolate central quantities at mass ``m_msun`` on the stable branch.
51
+
52
+ Returns a dict with h_c, eps_c, p_c, cs2_c, X, Psi, Lambda; raises
53
+ ValueError if the stable branch does not cover the requested mass.
54
+ """
55
+ s = cf.stable
56
+ if s.sum() < 4:
57
+ raise ValueError("stable branch too short")
58
+ M = cf.M_msun[s]
59
+ order = np.argsort(M)
60
+ M = M[order]
61
+ if not (M.min() <= m_msun <= M.max()):
62
+ raise ValueError(
63
+ f"mass {m_msun} outside stable branch [{M.min():.3f}, {M.max():.3f}]")
64
+
65
+ def at(v):
66
+ return float(np.interp(m_msun, M, v[s][order]))
67
+
68
+ return dict(
69
+ h_c=at(cf.h_c), eps_c=at(cf.eps_c), p_c=at(cf.p_c),
70
+ cs2_c=at(cf.cs2_c), X=at(cf.X), Psi=at(cf.Psi),
71
+ Lambda=at(cf.Lambda),
72
+ )
@@ -0,0 +1,155 @@
1
+ """M-R-Lambda sequences, stable-branch detection, and dM/dh_c, dh_c/dM.
2
+
3
+ The planning notes ask us to parameterize stellar sequences by *central* variable
4
+ (pseudo-enthalpy / entropy) rather than mass, and to expose dm/dh and dh/dm so a
5
+ user can do inference "as if parameterized by mass" while we integrate in h. This
6
+ module builds the sequence by ``vmap``-ing the TOV solver over central enthalpy,
7
+ computes dM/dh_c by AD, splits stable (dM/dh_c > 0) from unstable branches, and
8
+ provides interpolators on the stable branch.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import NamedTuple
13
+ import jax
14
+ import jax.numpy as jnp
15
+
16
+ from .solver import solve_structure, TOVPoint
17
+ from ..eos.base import EOSTable
18
+
19
+
20
+ class Family(NamedTuple):
21
+ h_c: jnp.ndarray
22
+ M_msun: jnp.ndarray
23
+ R_km: jnp.ndarray
24
+ Lambda: jnp.ndarray
25
+ C: jnp.ndarray
26
+ dM_dhc: jnp.ndarray # dM[Msun]/dh_c along the sequence
27
+ stable: jnp.ndarray # bool mask: dM/dh_c > 0
28
+
29
+
30
+ def _mass_and_slope(table, hc):
31
+ return jax.jvp(lambda h: solve_structure(table, h, tidal=False, rtol=1e-6,
32
+ atol=1e-8).M_msun,
33
+ (hc,), (jnp.ones_like(hc),))
34
+
35
+
36
+ # jitted at module level with the table as an argument: one compile per
37
+ # table length, not one per table
38
+ _probe_masses = jax.jit(jax.vmap(_mass_and_slope, in_axes=(None, 0)))
39
+
40
+
41
+ def default_hc_grid(table: EOSTable, n_models: int = 120, frac_lo: float = 0.02,
42
+ frac_hi: float = 0.92, n_c_min: float = 0.07,
43
+ n_c_probe: float = 0.25, n_probe: int = 16):
44
+ """A central-enthalpy grid from the minimum-mass star to near-maximum
45
+ central density.
46
+
47
+ The search starts at the larger of ``frac_lo`` h_max and h(n = ``n_c_min``
48
+ fm^-3); with a crust table, frac_lo h_max alone falls deep in the crust.
49
+ The minimum-mass star can still lie above n_c_min (n_c = 0.093 fm^-3 for
50
+ the MetaModel crust), so ``n_probe`` structure-only solves up to
51
+ h(n = ``n_c_probe``) locate it and the grid starts at the first probe on
52
+ the rising branch. ``n_probe=0`` skips the probe."""
53
+ hmax = table.h[-1]
54
+ h_lo = jnp.maximum(frac_lo * hmax,
55
+ jnp.interp(jnp.log(n_c_min), jnp.log(table.n), table.h))
56
+ if n_probe:
57
+ h_top = jnp.minimum(
58
+ frac_hi * hmax,
59
+ jnp.interp(jnp.log(n_c_probe), jnp.log(table.n), table.h))
60
+ probe = jnp.linspace(h_lo, jnp.maximum(h_top, h_lo), n_probe)
61
+ M, dM = _probe_masses(table, probe)
62
+ i = jnp.argmin(M)
63
+ h_lo = jnp.where(dM[i] > 0.0, probe[i],
64
+ probe[jnp.minimum(i + 1, n_probe - 1)])
65
+ return jnp.linspace(h_lo, frac_hi * hmax, n_models)
66
+
67
+
68
+ def build_family(table: EOSTable, h_c_grid=None, *, backend: str = "diffrax",
69
+ rtol: float = 1e-7, atol: float = 1e-9,
70
+ n_steps: int = 2000, jump_nodes: bool = True) -> Family:
71
+ """TOV sequence over ``h_c_grid`` (default :func:`default_hc_grid`).
72
+
73
+ ``jump_nodes=False`` is the value-only opt-out of
74
+ :func:`nmbackend.tov.solver.solve_structure` for bulk scans of very dense
75
+ tables (biased parameter tangents; with the tidal sector no longer cheaper
76
+ and ~1e4x less accurate Lambda since 2026-10-14 -- see solve_structure);
77
+ the ``default_hc_grid`` probe always uses the default."""
78
+ if h_c_grid is None:
79
+ h_c_grid = default_hc_grid(table)
80
+
81
+ kw = dict(backend=backend, rtol=rtol, atol=atol, n_steps=n_steps,
82
+ jump_nodes=jump_nodes)
83
+
84
+ def M_of_hc(hc):
85
+ return solve_structure(table, hc, **kw).M_msun
86
+
87
+ solve_all = jax.vmap(lambda hc: solve_structure(table, hc, **kw))
88
+ pts: TOVPoint = solve_all(h_c_grid)
89
+
90
+ # forward-mode along the sequence (clean through the tidal variable)
91
+ dM_dhc = jax.vmap(jax.jacfwd(M_of_hc))(h_c_grid)
92
+ # the neutron-star branch runs from the minimum-mass star to M_max; with a
93
+ # crust table the lowest h_c can lie below the minimum-mass star, on the
94
+ # extended (R ~ 10^3 km) configurations that also have dM/dh_c > 0
95
+ rising = dM_dhc > 0.0
96
+ order = jnp.arange(h_c_grid.shape[0])
97
+ i_max = jnp.argmax(jnp.where(rising, pts.M_msun, -jnp.inf))
98
+ i_min = jnp.argmin(jnp.where(order <= i_max, pts.M_msun, jnp.inf))
99
+ stable = rising & (order >= i_min)
100
+
101
+ return Family(
102
+ h_c=h_c_grid, M_msun=pts.M_msun, R_km=pts.R_km, Lambda=pts.Lambda,
103
+ C=pts.C, dM_dhc=dM_dhc, stable=stable,
104
+ )
105
+
106
+
107
+ def m_max(family: Family):
108
+ """Maximum gravitational mass (Msun) over the (stable part of the) sequence."""
109
+ M = jnp.where(family.stable, family.M_msun, -jnp.inf)
110
+ return jnp.max(M)
111
+
112
+
113
+ def dhc_dM(family: Family):
114
+ """Inverse Jacobian dh_c/dM on the sequence (NaN where dM/dh_c ~ 0)."""
115
+ # convert dM[Msun]/dh_c into dh_c/dM
116
+ return 1.0 / family.dM_dhc
117
+
118
+
119
+ _BIG_M = 1.0e3 # finite "above the branch" mass sentinel (avoids 0*inf -> nan in AD)
120
+
121
+
122
+ def _stable_branch_sort(family: Family):
123
+ """Indices sorting the masses on the stable rising branch (minimum-mass
124
+ star to M_max) to the front.
125
+
126
+ Off-branch masses are pushed to a large *finite* value so reverse-mode AD does
127
+ not hit 0*inf -> nan. Returns (M_sorted, sort_idx, idx_max).
128
+ """
129
+ M = family.M_msun
130
+ idx_max = jnp.argmax(jnp.where(family.stable, M, -jnp.inf))
131
+ idx_min = jnp.argmax(family.stable) # first stable star (minimum mass)
132
+ order = jnp.arange(M.shape[0])
133
+ on_branch = (order >= idx_min) & (order <= idx_max)
134
+ Mb = jnp.where(on_branch, M, _BIG_M)
135
+ srt = jnp.argsort(Mb)
136
+ return Mb[srt], srt, idx_max
137
+
138
+
139
+ def lambda_of_mass(family: Family, m_msun):
140
+ """Interpolate Lambda(M) on the stable rising branch.
141
+
142
+ Above M_max the off-branch sentinel makes the interpolant HOLD near
143
+ Lambda(M_max) (reaching 0 only beyond the sentinel mass) -- callers must
144
+ range-guard m <= m_max(family) themselves.
145
+ """
146
+ Ms, srt, _ = _stable_branch_sort(family)
147
+ Ls = family.Lambda[srt]
148
+ return jnp.interp(m_msun, Ms, Ls, left=Ls[0], right=0.0)
149
+
150
+
151
+ def radius_of_mass(family: Family, m_msun):
152
+ """Interpolate R(M) on the stable rising branch."""
153
+ Ms, srt, _ = _stable_branch_sort(family)
154
+ Rs = family.R_km[srt]
155
+ return jnp.interp(m_msun, Ms, Rs, left=Rs[0], right=Rs[-1])
@@ -0,0 +1,93 @@
1
+ """TOV solver for EOS with first-order phase transitions (density discontinuities).
2
+
3
+ A first-order transition is a density jump at constant pressure. In the
4
+ pseudo-enthalpy variable the transition sits at a single enthalpy ``h_t`` (because
5
+ dh = dp/(eps+p) and dp = 0 across the jump). The metric perturbation H is
6
+ continuous there, but the tidal variable y is **discontinuous** -- the
7
+ (eps+p)/cs^2 term in the y-equation becomes a delta function as cs^2 -> 0.
8
+ Integrating across it gives the junction condition (Damour & Nagar 2009;
9
+ Postnikov, Prakash & Lattimer 2010; Takatsy & Kovacs 2020):
10
+
11
+ y_out = y_in - 4 pi r_d^3 (eps_in - eps_out) / (m_d + 4 pi r_d^3 p_t)
12
+
13
+ with r_d, m_d the radius/mass at the transition, ``in`` the inner (higher-density)
14
+ side and ``out`` the outer (lower-density) side. Since eps_out < eps_in this
15
+ LOWERS y across the transition going outward: it is the zero-width limit of the
16
+ tidal term, and the Newtonian self-bound-star case (Delta y = -3 at a surface
17
+ with finite density) is its limit. Until 2026-10-14 the sign was reversed here
18
+ and in ``reference.scipy_tov.solve_reference_hybrid`` (so the two agreed), and
19
+ hybrid Lambda was too low -- at fixed mass on HybridEOS(80, 250, 1) by
20
+ 0 / 0 / 0.5 / 9.9 / 18.6% at 1.2 / 1.4 / 1.6 / 1.8 / 2.0 Msun (more with a larger
21
+ quark core);
22
+ ``tests/test_phase_transition.py::
23
+ test_junction_matches_smeared_transition`` now checks the sign against the
24
+ ``HybridEOS.eos_table_smeared`` limit.
25
+
26
+ We integrate each smooth phase as a separate adaptive (diffrax) segment and apply
27
+ the junction between them, so the genuine matter sound speed is used inside each
28
+ phase and the discontinuity is handled analytically (no cs^2 clipping/smearing).
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import math
33
+
34
+ import jax
35
+ import jax.numpy as jnp
36
+
37
+ from .solver import (_adaptive_tov, _k2_from_y_C, _central_start, TOVPoint,
38
+ _HAVE_DIFFRAX, solve_structure)
39
+ from ..constants import GMSUN_KM
40
+
41
+ _FOURPI = 4.0 * math.pi
42
+
43
+
44
+ def _diffrax_segment(table, t0, t1, state0, rtol, atol, adjoint=None,
45
+ max_steps=100000):
46
+ """Integrate (r, m, y) in enthalpy from t0 down to t1 with a given start.
47
+
48
+ Steps are cut at the segment table's nodes and the start is frozen against
49
+ differentiation, as in :func:`nmbackend.tov.solver._adaptive_tov`."""
50
+ t0, t1 = jnp.asarray(t0), jnp.asarray(t1) # a Python float here is a jit key
51
+ sol = _adaptive_tov(table, t0, t1, state0, rtol, atol, True,
52
+ -(t0 - t1) * 1e-3, adjoint, max_steps)
53
+ return sol.ys[0]
54
+
55
+
56
+ def solve_hybrid(hybrid, h_c, rtol: float = 1e-7, atol: float = 1e-9) -> TOVPoint:
57
+ """TOV solve for a :class:`~nmbackend.eos.hybrid.HybridEOS` (one transition).
58
+
59
+ Applies the tidal junction condition at the density discontinuity.
60
+ """
61
+ if not _HAVE_DIFFRAX: # pragma: no cover
62
+ raise ImportError("solve_hybrid requires diffrax")
63
+ inner, outer = hybrid.segments
64
+ tr = hybrid.transition
65
+ h_c = float(h_c)
66
+
67
+ # low-mass star with no quark core: purely hadronic
68
+ if h_c <= tr.h_t:
69
+ return solve_structure(outer, h_c, backend="diffrax", rtol=rtol, atol=atol)
70
+
71
+ # 1) inner (quark) core: central series start -> integrate down to h_t
72
+ _, _, dh0, state0 = _central_start(inner, h_c)
73
+ state_t = _diffrax_segment(inner, h_c - dh0, tr.h_t, state0, rtol, atol)
74
+ r_d, m_d, y_in = state_t[0], state_t[1], state_t[2]
75
+
76
+ # 2) tidal junction at the discontinuity
77
+ y_out = y_in - _FOURPI * r_d**3 * (tr.eps_in - tr.eps_out) / (
78
+ m_d + _FOURPI * r_d**3 * tr.p_t)
79
+
80
+ # 3) outer (hadronic) envelope: h_t -> surface, starting from junction state
81
+ state_surf = _diffrax_segment(
82
+ outer, tr.h_t, outer.h[0], jnp.stack([r_d, m_d, y_out]), rtol, atol)
83
+ R, M, y = state_surf[0], state_surf[1], state_surf[2]
84
+ C = M / R
85
+ k2 = _k2_from_y_C(y, C)
86
+ Lam = (2.0 / 3.0) * k2 / C**5
87
+ return TOVPoint(h_c=jnp.asarray(h_c), R_km=R, M_km=M, M_msun=M / GMSUN_KM,
88
+ C=C, y=y, k2=k2, Lambda=Lam)
89
+
90
+
91
+ def hybrid_sequence(hybrid, h_c_array, rtol=1e-7, atol=1e-9):
92
+ """List of TOVPoint over central enthalpies (handles the transition)."""
93
+ return [solve_hybrid(hybrid, float(hc), rtol, atol) for hc in h_c_array]