giantlayers 0.1.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 (74) hide show
  1. giantlayers/__init__.py +11 -0
  2. giantlayers/__main__.py +4 -0
  3. giantlayers/_chemistry_kernel.py +197 -0
  4. giantlayers/atlas9_odf.py +102 -0
  5. giantlayers/atlas_writer.py +118 -0
  6. giantlayers/atmos/__init__.py +1 -0
  7. giantlayers/atmos/cli.py +411 -0
  8. giantlayers/atmos/continuum.py +449 -0
  9. giantlayers/atmos/export.py +107 -0
  10. giantlayers/atmos/hydrogen.py +143 -0
  11. giantlayers/atmos/linelists.py +234 -0
  12. giantlayers/atmos/linetables.py +299 -0
  13. giantlayers/atmos/model.py +790 -0
  14. giantlayers/atmos/opacity.py +250 -0
  15. giantlayers/atmos/startgrid.py +84 -0
  16. giantlayers/atmos/transfer.py +427 -0
  17. giantlayers/atmos/xsec.py +51 -0
  18. giantlayers/audit_resolution.py +116 -0
  19. giantlayers/benchmark_sampling.py +86 -0
  20. giantlayers/cli.py +659 -0
  21. giantlayers/collision_induced.py +94 -0
  22. giantlayers/compare_atmospheres.py +58 -0
  23. giantlayers/compare_marcs_chemistry.py +72 -0
  24. giantlayers/compare_marcs_flux.py +101 -0
  25. giantlayers/data/__init__.py +1 -0
  26. giantlayers/data/atmos_startgrid.npz +0 -0
  27. giantlayers/data/atmos_template.dat +57 -0
  28. giantlayers/data/atmos_template_3000.dat +57 -0
  29. giantlayers/data/atmos_template_3500.dat +57 -0
  30. giantlayers/data/atmos_template_5000_g0.dat +57 -0
  31. giantlayers/data/atmos_template_cstar.dat +57 -0
  32. giantlayers/data/barklem_collet.json +127 -0
  33. giantlayers/data/continuum/CIA.H-He.dat +49 -0
  34. giantlayers/data/continuum/CIA.H2-H.dat +73 -0
  35. giantlayers/data/continuum/CIA.H2-H2.Yi.dat +1006 -0
  36. giantlayers/data/continuum/CIA.H2-He.dat +248 -0
  37. giantlayers/data/continuum/ionization_energies.dat +95 -0
  38. giantlayers/data/continuum/jonabs_vac_v07.3.dat +4477 -0
  39. giantlayers/depth_refinement.py +80 -0
  40. giantlayers/examples/__init__.py +1 -0
  41. giantlayers/examples/continuum-wavelengths.dat +81 -0
  42. giantlayers/examples/solar-gs98.json +94 -0
  43. giantlayers/exomol_import.py +115 -0
  44. giantlayers/gray_atmosphere.py +98 -0
  45. giantlayers/hminus.py +106 -0
  46. giantlayers/kurucz_atomic_lines.py +79 -0
  47. giantlayers/lte_chemistry.py +411 -0
  48. giantlayers/lte_opacity.py +296 -0
  49. giantlayers/marcs_atomic_lines.py +60 -0
  50. giantlayers/marcs_model.py +70 -0
  51. giantlayers/marcs_opacity.py +66 -0
  52. giantlayers/marcs_writer.py +154 -0
  53. giantlayers/mixing_length.py +243 -0
  54. giantlayers/molecular_cross_section.py +92 -0
  55. giantlayers/native_marcs.py +118 -0
  56. giantlayers/native_transfer.py +224 -0
  57. giantlayers/nonlinear_atmosphere.py +139 -0
  58. giantlayers/odf_transfer.py +269 -0
  59. giantlayers/opacity_table.py +66 -0
  60. giantlayers/profile_plot.py +51 -0
  61. giantlayers/spherical_heating.py +1071 -0
  62. giantlayers/spherical_hydrostatic.py +213 -0
  63. giantlayers/spherical_kernel.c +179 -0
  64. giantlayers/spherical_kernel.py +44 -0
  65. giantlayers/spherical_kernel_loader.py +58 -0
  66. giantlayers/spherical_transfer.py +155 -0
  67. giantlayers/transfer_cache.py +66 -0
  68. giantlayers/two_group_atmosphere.py +145 -0
  69. giantlayers-0.1.0.dist-info/METADATA +58 -0
  70. giantlayers-0.1.0.dist-info/RECORD +74 -0
  71. giantlayers-0.1.0.dist-info/WHEEL +5 -0
  72. giantlayers-0.1.0.dist-info/entry_points.txt +3 -0
  73. giantlayers-0.1.0.dist-info/licenses/LICENSE +21 -0
  74. giantlayers-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,11 @@
1
+ """Spherical LTE model atmospheres for cool giant stars."""
2
+
3
+ __all__ = ["initialize", "main", "restart_temperatures", "update_boundary", "write_checkpoint"]
4
+
5
+
6
+ def __getattr__(name):
7
+ if name in __all__:
8
+ from . import cli
9
+
10
+ return getattr(cli, name)
11
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,197 @@
1
+ """Compiled Newton solver for ``lte_chemistry`` (used when numba is installed).
2
+
3
+ The mass-action network is flattened into arrays by
4
+ ``Thermochemistry._flat_terms``; this module repeats exactly the residuals,
5
+ Jacobian, damped Newton step and pivoted elimination of the pure-Python
6
+ solver in ``lte_chemistry``.
7
+ """
8
+
9
+ import math
10
+
11
+ import numpy as np
12
+ from numba import njit
13
+
14
+ OK, STALLED, NOT_CONVERGED, SINGULAR = 0, 1, 2, 3
15
+
16
+
17
+ @njit(cache=True)
18
+ def _system(x, sp_c, pw_start, pw_idx, pw_val, et_start, et_k, et_m, pos_k, pos_m, neg_k, neg_m,
19
+ ao_ratio, ao_saha, log_ratios, log_particles, e_index, pops, ao_n, ao_c, res, jac):
20
+ size = x.shape[0]
21
+ ns = sp_c.shape[0]
22
+ for j in range(ns):
23
+ s = sp_c[j]
24
+ for t in range(pw_start[j], pw_start[j + 1]):
25
+ s += x[pw_idx[t]] * pw_val[t]
26
+ pops[j] = math.exp(s)
27
+ atomic_number = 0.0
28
+ net_positive = 0.0
29
+ positive_derivative = 0.0
30
+ nuclei = math.exp(x[size - 1])
31
+ xe = x[e_index]
32
+ for a in range(ao_ratio.shape[0]):
33
+ dens = nuclei * ao_ratio[a]
34
+ odds = math.exp(-abs(ao_saha[a] - xe))
35
+ minority = odds / (1 + odds)
36
+ majority = 1 / (1 + odds)
37
+ if ao_saha[a] > xe:
38
+ ao_n[a] = dens * minority
39
+ ao_c[a] = dens * majority
40
+ else:
41
+ ao_n[a] = dens * majority
42
+ ao_c[a] = dens * minority
43
+ atomic_number += dens
44
+ net_positive += ao_c[a]
45
+ positive_derivative -= dens * minority * majority
46
+ deriv = np.zeros(size)
47
+ nel = log_ratios.shape[0]
48
+ # element conservation rows
49
+ for r in range(nel):
50
+ for i in range(size):
51
+ deriv[i] = 0.0
52
+ amount = 0.0
53
+ for t in range(et_start[r], et_start[r + 1]):
54
+ j = et_k[t]
55
+ contrib = et_m[t] * pops[j]
56
+ amount += contrib
57
+ for u in range(pw_start[j], pw_start[j + 1]):
58
+ deriv[pw_idx[u]] += pw_val[u] * contrib
59
+ res[r] = math.log(amount) - log_ratios[r] - x[size - 1]
60
+ for i in range(size):
61
+ jac[r, i] = deriv[i] / amount
62
+ jac[r, size - 1] = -1.0
63
+ # charge row: log(positive) - log(negative)
64
+ for i in range(size):
65
+ deriv[i] = 0.0
66
+ deriv[e_index] = positive_derivative
67
+ deriv[size - 1] = net_positive
68
+ amount = net_positive
69
+ for t in range(pos_k.shape[0]):
70
+ j = pos_k[t]
71
+ contrib = pos_m[t] * pops[j]
72
+ amount += contrib
73
+ for u in range(pw_start[j], pw_start[j + 1]):
74
+ deriv[pw_idx[u]] += pw_val[u] * contrib
75
+ pos_amount = amount
76
+ pos_row = deriv / pos_amount
77
+ for i in range(size):
78
+ deriv[i] = 0.0
79
+ amount = 0.0
80
+ for t in range(neg_k.shape[0]):
81
+ j = neg_k[t]
82
+ contrib = neg_m[t] * pops[j]
83
+ amount += contrib
84
+ for u in range(pw_start[j], pw_start[j + 1]):
85
+ deriv[pw_idx[u]] += pw_val[u] * contrib
86
+ res[nel] = math.log(pos_amount) - math.log(amount)
87
+ for i in range(size):
88
+ jac[nel, i] = pos_row[i] - deriv[i] / amount
89
+ # particle number row
90
+ for i in range(size):
91
+ deriv[i] = 0.0
92
+ deriv[size - 1] = atomic_number
93
+ amount = atomic_number
94
+ for j in range(ns):
95
+ contrib = pops[j]
96
+ amount += contrib
97
+ for u in range(pw_start[j], pw_start[j + 1]):
98
+ deriv[pw_idx[u]] += pw_val[u] * contrib
99
+ res[nel + 1] = math.log(amount) - log_particles
100
+ for i in range(size):
101
+ jac[nel + 1, i] = deriv[i] / amount
102
+
103
+
104
+ @njit(cache=True)
105
+ def _linear_solve(m, rhs):
106
+ size = rhs.shape[0]
107
+ for i in range(size):
108
+ pivot = i
109
+ best = abs(m[i, i])
110
+ for j in range(i + 1, size):
111
+ if abs(m[j, i]) > best:
112
+ best = abs(m[j, i])
113
+ pivot = j
114
+ if pivot != i:
115
+ for k in range(size):
116
+ tmp = m[i, k]
117
+ m[i, k] = m[pivot, k]
118
+ m[pivot, k] = tmp
119
+ tmp = rhs[i]
120
+ rhs[i] = rhs[pivot]
121
+ rhs[pivot] = tmp
122
+ d = m[i, i]
123
+ if abs(d) < 1e-15:
124
+ return False
125
+ for j in range(i + 1, size):
126
+ if m[j, i] == 0:
127
+ continue
128
+ f = m[j, i] / d
129
+ for k in range(i + 1, size):
130
+ m[j, k] -= f * m[i, k]
131
+ rhs[j] -= f * rhs[i]
132
+ for i in range(size - 1, -1, -1):
133
+ s = rhs[i]
134
+ for j in range(i + 1, size):
135
+ s -= m[i, j] * rhs[j]
136
+ rhs[i] = s / m[i, i]
137
+ return True
138
+
139
+
140
+ @njit(cache=True)
141
+ def newton(x, tolerance, sp_c, pw_start, pw_idx, pw_val, et_start, et_k, et_m, pos_k, pos_m,
142
+ neg_k, neg_m, ao_ratio, ao_saha, log_ratios, log_particles, e_index):
143
+ """Return (status, x, populations, atomic neutrals, atomic ions, error)."""
144
+ size = x.shape[0]
145
+ ns = sp_c.shape[0]
146
+ na = ao_ratio.shape[0]
147
+ pops = np.empty(ns)
148
+ ao_n = np.empty(na)
149
+ ao_c = np.empty(na)
150
+ res = np.empty(size)
151
+ jac = np.empty((size, size))
152
+ tpops = np.empty(ns)
153
+ tao_n = np.empty(na)
154
+ tao_c = np.empty(na)
155
+ tres = np.empty(size)
156
+ tjac = np.empty((size, size))
157
+ trial = np.empty(size)
158
+ _system(x, sp_c, pw_start, pw_idx, pw_val, et_start, et_k, et_m, pos_k, pos_m, neg_k, neg_m,
159
+ ao_ratio, ao_saha, log_ratios, log_particles, e_index, pops, ao_n, ao_c, res, jac)
160
+ error = 0.0
161
+ for _ in range(60):
162
+ error = 0.0
163
+ for i in range(size):
164
+ error = max(error, abs(res[i]))
165
+ if error < tolerance:
166
+ return OK, x, pops, ao_n, ao_c, error
167
+ step = -res.copy()
168
+ mat = jac.copy()
169
+ if not _linear_solve(mat, step):
170
+ return SINGULAR, x, pops, ao_n, ao_c, error
171
+ biggest = 0.0
172
+ for i in range(size):
173
+ biggest = max(biggest, abs(step[i]))
174
+ scale = min(1.0, 4.0 / biggest)
175
+ accepted = False
176
+ for _ in range(20):
177
+ for i in range(size):
178
+ trial[i] = x[i] + scale * step[i]
179
+ _system(trial, sp_c, pw_start, pw_idx, pw_val, et_start, et_k, et_m, pos_k, pos_m,
180
+ neg_k, neg_m, ao_ratio, ao_saha, log_ratios, log_particles, e_index,
181
+ tpops, tao_n, tao_c, tres, tjac)
182
+ terr = 0.0
183
+ for i in range(size):
184
+ terr = max(terr, abs(tres[i]))
185
+ if terr < error:
186
+ x = trial.copy()
187
+ res[:] = tres
188
+ jac[:, :] = tjac
189
+ pops[:] = tpops
190
+ ao_n[:] = tao_n
191
+ ao_c[:] = tao_c
192
+ accepted = True
193
+ break
194
+ scale *= 0.5
195
+ if not accepted:
196
+ return STALLED, x, pops, ao_n, ao_c, error
197
+ return NOT_CONVERGED, x, pops, ao_n, ao_c, error
@@ -0,0 +1,102 @@
1
+ """Read the Castelli–Kurucz ATLAS9 BIG line-opacity distribution tables."""
2
+
3
+ from bisect import bisect_right
4
+ import math
5
+ from pathlib import Path
6
+ import struct
7
+
8
+ # Grid and weights from LINOP and BLOCKBIG in Castelli's ATLAS9 source:
9
+ # https://wwwuser.oats.inaf.it/fiorella.castelli/sources/atlas9g/atlas9mem.for
10
+ # LINOP overrides the last BLOCKBIG edge to 1,000,000 nm.
11
+ WAVELENGTH_EDGES_NM = (
12
+ 8.97666, 9.2, 9.5, 9.7173, 9.8159, 10.109, 10.3, 10.4645, 10.65, 10.8855, 11.2, 11.6, 11.9556,
13
+ 12.3, 12.6656, 12.7468, 12.935, 13.1603, 13.3172, 13.467, 13.8625, 14.1046, 14.5478, 14.9,
14
+ 15.3, 15.7487, 16.0035, 16.4, 16.8, 17.2509, 17.4326, 17.9366, 18.1011, 18.2444, 18.978,
15
+ 19.2242, 19.551, 20.1199, 20.2359, 20.8, 21.3, 21.9478, 22.0198, 22.5807, 22.7838, 23.2,
16
+ 23.6522, 24.3, 25.0074, 25.4661, 25.8924, 26.1432, 26.6, 27.1, 27.6, 28.0926, 28.6587, 29.3,
17
+ 29.9585, 30.2626, 31.3, 32.3, 33.3, 34.3, 35.2793, 36.141, 37, 38.016, 38.9664, 40, 41,
18
+ 41.8799, 42.5, 43.5, 44.7326, 45.5, 46.5, 47.5, 48.5018, 49.5, 50.4259, 50.8763, 52, 54, 56,
19
+ 57.4061, 59.5, 61.5, 63.5, 65.5379, 67, 69, 71, 72.2401, 74, 76, 78, 80, 82, 84, 86, 88, 90,
20
+ 91.1753, 94, 98, 102, 106, 110.031, 113, 116, 120, 123.929, 128, 132, 136, 140, 144.434, 148,
21
+ 151.435, 157, 162.151, 167.403, 171, 175, 180, 184, 188, 193, 197.47, 202, 207.132, 210, 215,
22
+ 220, 225, 230, 235, 240, 245, 251.126, 255, 260, 265, 270, 275, 280, 285, 290, 300, 310, 320,
23
+ 330, 340, 350, 360, 364.702, 370, 380, 390, 400, 410, 420, 430, 450, 460, 470, 480, 490, 500,
24
+ 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690,
25
+ 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800, 810, 820.583, 830, 840, 850, 860, 870,
26
+ 880, 890, 900, 910, 920, 930, 940, 950, 960, 970, 980, 990, 1000, 1025, 1050, 1075, 1100,
27
+ 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1458.82, 1475,
28
+ 1500, 1525, 1550, 1575, 1600, 1640, 1680, 1720, 1760, 1800, 1840, 1880, 1920, 1960, 2000,
29
+ 2050, 2100, 2150, 2200, 2250, 2279.4, 2300, 2350, 2400, 2450, 2500, 2550, 2600, 2650, 2700,
30
+ 2750, 2800, 2850, 2900, 2950, 3000, 3050, 3100, 3150, 3200, 3282.34, 3400, 3500, 3600, 3700,
31
+ 3800, 3900, 4000, 4100, 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900, 5000, 5100, 5200,
32
+ 5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100, 6200, 6300, 6400, 6600, 6800, 7000,
33
+ 7200, 7400, 7600, 7800, 8000, 8200, 8400, 8600, 8800, 9000, 9200, 9400, 9600, 9800, 1e+06,
34
+ )
35
+ LOG_T = tuple(
36
+ x / 100
37
+ for x in (*range(330, 371, 2), *range(373, 401, 3), *range(405, 531, 5))
38
+ )
39
+ LOG_P = tuple(x / 2 for x in range(-8, 17))
40
+
41
+ # The binary values are stored in ascending opacity order. LINOP visits
42
+ # them in reverse order and starts at the smallest weight.
43
+ RANK_WEIGHTS = (0.1,) * 9 + (3 / 60, 2 / 60, 1 / 60)
44
+ C_NM_PER_S = 2.99792458e17
45
+ STEPS = struct.Struct("<12h")
46
+ MARKER = struct.Struct("<I")
47
+ PAYLOAD_BYTES = len(LOG_P) * STEPS.size
48
+ RECORD_BYTES = PAYLOAD_BYTES + 2 * MARKER.size
49
+
50
+
51
+ def quadrature():
52
+ """Yield wavelength bounds in nm and the 12 frequency weights in Hz."""
53
+ for short, long in zip(WAVELENGTH_EDGES_NM, WAVELENGTH_EDGES_NM[1:]):
54
+ bandwidth = C_NM_PER_S * (1 / short - 1 / long)
55
+ yield short, long, tuple(bandwidth * weight for weight in RANK_WEIGHTS)
56
+
57
+
58
+ def _bracket(grid, value, name):
59
+ if not math.isfinite(value) or value <= 0:
60
+ raise ValueError(f"{name} must be positive and finite")
61
+ log_value = math.log10(value)
62
+ if not grid[0] <= log_value <= grid[-1]:
63
+ raise ValueError(f"log10({name}) outside the ATLAS9 grid: {log_value:g}")
64
+ i = min(bisect_right(grid, log_value) - 1, len(grid) - 2)
65
+ return i, (log_value - grid[i]) / (grid[i + 1] - grid[i])
66
+
67
+
68
+ class Atlas9ODF:
69
+ """Little-endian BIG ODF with unformatted Fortran record markers."""
70
+
71
+ def __init__(self, path):
72
+ self._data = Path(path).read_bytes()
73
+ records = (len(WAVELENGTH_EDGES_NM) - 1) * len(LOG_T)
74
+ if len(self._data) != records * RECORD_BYTES:
75
+ raise ValueError("Unexpected size for a 328-band ATLAS9 BIG ODF")
76
+ for start in range(0, len(self._data), RECORD_BYTES):
77
+ head = MARKER.unpack_from(self._data, start)[0]
78
+ tail = MARKER.unpack_from(self._data, start + MARKER.size + PAYLOAD_BYTES)[0]
79
+ if head != PAYLOAD_BYTES or tail != PAYLOAD_BYTES:
80
+ raise ValueError(f"Invalid ATLAS9 record markers at byte {start}")
81
+
82
+ def _packed(self, band, t, p):
83
+ record = band * len(LOG_T) + t
84
+ start = record * RECORD_BYTES + MARKER.size + p * STEPS.size
85
+ return STEPS.unpack_from(self._data, start)
86
+
87
+ def line_opacity(self, temperature, pressure):
88
+ """Yield one tuple of 12 line mass opacities in cm²/g per band."""
89
+ it, ft = _bracket(LOG_T, temperature, "temperature")
90
+ ip, fp = _bracket(LOG_P, pressure, "gas pressure")
91
+ for band in range(len(WAVELENGTH_EDGES_NM) - 1):
92
+ corners = (
93
+ self._packed(band, it, ip),
94
+ self._packed(band, it, ip + 1),
95
+ self._packed(band, it + 1, ip),
96
+ self._packed(band, it + 1, ip + 1),
97
+ )
98
+ yield tuple(
99
+ 10 ** (0.001 * ((1 - ft) * ((1 - fp) * a + fp * b)
100
+ + ft * ((1 - fp) * c + fp * d)))
101
+ for a, b, c, d in zip(*corners)
102
+ )
@@ -0,0 +1,118 @@
1
+ """Export native atmospheres as Kurucz ATLAS READ DECK6 records."""
2
+
3
+ import gzip
4
+ import math
5
+ from pathlib import Path
6
+
7
+ from .hminus import K_B
8
+ from .lte_opacity import LIGHT
9
+ from .native_marcs import exterior_column
10
+
11
+
12
+ DECK_COLUMNS = "RHOX,T,P,XNE,ABROSS,ACCRAD,VTURB"
13
+ # Conventional ATLAS9 deck flags. The originating opacities are described in TITLE.
14
+ OPACITY_FLAGS = (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0)
15
+
16
+
17
+ def abundance_records(abundances, *, atlas12=False):
18
+ """Write ATLAS number fractions for H and He and log fractions for metals."""
19
+ nuclei = [10**(value-12) if value > -99 else 0.0 for value in abundances]
20
+ total = math.fsum(nuclei)
21
+ records = [
22
+ "ABUNDANCE SCALE 1.00000 ABUNDANCE CHANGE"
23
+ + "".join(f"{i:2d}{fraction/total:8.5f}" for i, fraction in enumerate(nuclei[:2], 1))
24
+ ]
25
+ metals = [math.log10(value/total) if value else -99.0 for value in nuclei[2:]]
26
+ metals.extend([-99.0]*(99-len(nuclei)))
27
+ for start in range(0, len(metals), 6):
28
+ records.append(" ABUNDANCE CHANGE" + "".join(
29
+ f"{i:3d}{value:7.2f}" for i, value in enumerate(metals[start:start+6], start+3)
30
+ ))
31
+ if atlas12:
32
+ symbols = (
33
+ "H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni "
34
+ "Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te "
35
+ "I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os "
36
+ "Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es"
37
+ ).split()
38
+ records.extend((" ABUNDANCE TABLE",
39
+ f" 1H {nuclei[0]/total:10.6f} 2He{nuclei[1]/total:10.6f}"))
40
+ for start in range(0, len(metals), 5):
41
+ records.append("".join(
42
+ f"{i:5d}{symbols[i-1]:2s}{max(value, -99):7.3f}{0.0:6.3f}"
43
+ for i, value in enumerate(metals[start:start+5], start+3)
44
+ ))
45
+ return records
46
+
47
+
48
+ def sound_speed(temperature, pressure, density, convection, boundary):
49
+ """Evaluate the equilibrium adiabatic sound speed from the native EOS."""
50
+ adiabatic, q = convection[6], convection[8]
51
+ step = 0.002
52
+ low, high = (boundary.chemistry.solve(temperature, pressure*math.exp(sign*step),
53
+ boundary.abundances).mass_density for sign in (-1, 1))
54
+ derivative = math.log(high/low)/(2*step) - q*adiabatic
55
+ if derivative <= 0 or not math.isfinite(derivative):
56
+ raise ValueError("Invalid adiabatic compressibility for ATLAS sound speed")
57
+ return math.sqrt(pressure/(density*derivative))
58
+
59
+
60
+ def write_atlas(model, result, boundary, vmic, path, *, status, atlas12=False):
61
+ """Write a spherical GiantLayers solution as a depth-only ATLAS deck."""
62
+ path = Path(path)
63
+ layers = len(model.structure)
64
+ if atlas12 and layers > 72:
65
+ raise ValueError("The reference ATLAS12 reader supports at most 72 depth records")
66
+ if not 1 <= layers <= 999:
67
+ raise ValueError("ATLAS READ DECK6 permits 1–999 depth records")
68
+ if any(len(column) != layers for column in (
69
+ boundary.column_mass, model.thermodynamics, result[0], result[7], result[9]
70
+ )):
71
+ raise ValueError("ATLAS export requires complete transfer diagnostics")
72
+ teff = float(model.header[1].split()[0])
73
+ logg = math.log10(boundary.gravity)
74
+ alpha = float(model.header[9].split()[0])
75
+ teff_field, gravity_field = f"{teff:.0f}.", f"{logg:8.5f}"
76
+ alpha_field = f"{alpha:6.2f}"
77
+ if len(teff_field) > 7 or len(gravity_field) > 8 or len(alpha_field) > 6:
78
+ raise ValueError("Stellar parameters exceed ATLAS header field widths")
79
+ title = f"GiantLayers spherical LTE export, luminosity {status}, native opacity"
80
+ # The ATLAS12 card parser needs a delimiter before a full-width negative value.
81
+ gravity_separator = " " if atlas12 and gravity_field.startswith("-") else ""
82
+ records = [
83
+ f"TEFF {teff_field:>7} GRAVITY{gravity_separator}{gravity_field} LTE",
84
+ f"TITLE {title[:74]:74s}",
85
+ " OPACITY IFOP" + "".join(f"{flag:2d}" for flag in OPACITY_FLAGS),
86
+ f" CONVECTION {'ON' if alpha else 'OFF':<3}{alpha_field} TURBULENCE OFF"
87
+ + f"{0.:6.2f}"*4,
88
+ *abundance_records(model.abundances, atlas12=atlas12),
89
+ f"READ DECK6{layers:3d} {DECK_COLUMNS}" + ("" if atlas12 else ", FLXCNV,VCONV,VELSND"),
90
+ ]
91
+ exterior = exterior_column(model, boundary)
92
+ previous = 0.0
93
+ for mass, row, thermo, conv, acceleration in zip(
94
+ boundary.column_mass, model.structure, model.thermodynamics, result[7], result[9]
95
+ ):
96
+ temperature, electron_pressure, pressure = row[3:6]
97
+ rhox = mass + exterior
98
+ values = (pressure, electron_pressure/(K_B*temperature), conv[4], acceleration,
99
+ vmic*1e5, conv[11], conv[9])
100
+ if not atlas12:
101
+ values += (sound_speed(temperature, pressure, thermo[2], conv, boundary),)
102
+ if rhox <= previous or not all(map(math.isfinite, (rhox, temperature, *values))):
103
+ raise ValueError("ATLAS export requires finite fields and increasing positive column mass")
104
+ previous = rhox
105
+ fields = [f"{rhox:15.8E}", f"{temperature:9.1f}", *(f"{value:10.3E}" for value in values)]
106
+ if any(len(field) != width for field, width in zip(fields, (15, 9, *(10,)*len(values)))):
107
+ raise ValueError("Atmosphere values exceed ATLAS depth field widths")
108
+ records.append("".join(fields))
109
+ if not math.isfinite(result[0][0]) or result[0][0] < 0:
110
+ raise ValueError("ATLAS export requires a finite, nonnegative emergent radiative flux")
111
+ # Outgoing isotropic hemisphere, P_rad = (2/3) F_rad / c.
112
+ records.append(f"PRADK{2*result[0][0]/(3*LIGHT):11.4E}")
113
+ if atlas12:
114
+ # READ PUNCH closes the model stream when it reaches this card.
115
+ records.append("BEGIN")
116
+ opener = gzip.open if path.suffix == ".gz" else open
117
+ with opener(path, "wt", encoding="ascii", newline="\n") as stream:
118
+ stream.write("\n".join(records) + "\n")
@@ -0,0 +1 @@
1
+ """Opacity-sampling LTE model atmospheres (MARCS-like) for cool giants."""