exomol-opacity 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.
- exomol_opacity/__init__.py +6 -0
- exomol_opacity/__main__.py +4 -0
- exomol_opacity/calculation.py +444 -0
- exomol_opacity/plotting.py +74 -0
- exomol_opacity/src/bin_doppler_grid.cpp +111 -0
- exomol_opacity/src/exomol_reader.hpp +54 -0
- exomol_opacity/src/line_range.cpp +51 -0
- exomol_opacity-0.1.0.dist-info/METADATA +238 -0
- exomol_opacity-0.1.0.dist-info/RECORD +12 -0
- exomol_opacity-0.1.0.dist-info/WHEEL +5 -0
- exomol_opacity-0.1.0.dist-info/entry_points.txt +3 -0
- exomol_opacity-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""Local ExoMol LTE opacity calculations with persistent molecule caches."""
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
import argparse
|
|
4
|
+
import bz2
|
|
5
|
+
try:
|
|
6
|
+
import fcntl
|
|
7
|
+
except ImportError: # Plotting is still available on native Windows.
|
|
8
|
+
fcntl = None
|
|
9
|
+
import hashlib
|
|
10
|
+
from html.parser import HTMLParser
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
import warnings
|
|
19
|
+
from urllib.parse import urljoin, urlparse
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import requests
|
|
23
|
+
|
|
24
|
+
ROOT = Path(__file__).resolve().parent
|
|
25
|
+
SITE = "https://www.exomol.com"
|
|
26
|
+
PRESETS = {
|
|
27
|
+
"H3+": ("1H3_p", "MiZATeP"),
|
|
28
|
+
"H3O+": ("1H3-16O_p", "eXeL"),
|
|
29
|
+
"CO": ("12C-16O", "Li2015"),
|
|
30
|
+
"CO2": ("12C-16O2", "UCL-4000"),
|
|
31
|
+
"SiO": ("28Si-16O", "SiOUVenIR"),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def digest(path):
|
|
36
|
+
with Path(path).open("rb") as stream:
|
|
37
|
+
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def write_json(path, value):
|
|
41
|
+
path = Path(path)
|
|
42
|
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
|
43
|
+
temporary.write_text(json.dumps(value, indent=2) + "\n")
|
|
44
|
+
temporary.replace(path)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def safe_name(value):
|
|
48
|
+
if not re.fullmatch(r"[A-Za-z0-9_+.-]+", value) or value in (".", ".."):
|
|
49
|
+
raise ValueError(f"Invalid molecule or dataset identifier: {value!r}")
|
|
50
|
+
return value
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@contextmanager
|
|
54
|
+
def locked(path):
|
|
55
|
+
if fcntl is None:
|
|
56
|
+
raise RuntimeError("Opacity calculations require macOS or Linux (including WSL on Windows)")
|
|
57
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
with path.open("a") as stream:
|
|
59
|
+
fcntl.flock(stream, fcntl.LOCK_EX)
|
|
60
|
+
yield
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def download(url, path):
|
|
64
|
+
"""Reuse verified local files; resume interrupted downloads when supported."""
|
|
65
|
+
path = Path(path)
|
|
66
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
receipt = path.with_name(path.name + ".download.json")
|
|
68
|
+
if path.exists() and receipt.exists():
|
|
69
|
+
meta = json.loads(receipt.read_text())
|
|
70
|
+
if meta["url"] == url and path.stat().st_size == meta["bytes"]:
|
|
71
|
+
if digest(path) == meta["sha256"]:
|
|
72
|
+
print(f"Cached: {path.name}", flush=True)
|
|
73
|
+
return meta
|
|
74
|
+
partial = path.with_name(path.name + ".part")
|
|
75
|
+
offset = partial.stat().st_size if partial.exists() else 0
|
|
76
|
+
headers = {"Range": f"bytes={offset}-"} if offset else {}
|
|
77
|
+
with requests.get(url, headers=headers, stream=True, timeout=(30, 180)) as response:
|
|
78
|
+
response.raise_for_status()
|
|
79
|
+
append = offset > 0 and response.status_code == 206
|
|
80
|
+
if append and not response.headers.get("Content-Range", "").startswith(f"bytes {offset}-"):
|
|
81
|
+
raise RuntimeError("Server returned an inconsistent byte range")
|
|
82
|
+
expected = response.headers.get("Content-Length")
|
|
83
|
+
if expected is not None and int(expected) + 512 * 1024**2 > shutil.disk_usage(path.parent).free:
|
|
84
|
+
raise OSError(f"Not enough local disk space to download {path.name}; "
|
|
85
|
+
f"requires {int(expected)/1024**3:.2f} GiB plus a 512 MiB reserve")
|
|
86
|
+
received = 0
|
|
87
|
+
print(f"Downloading: {path.name}", flush=True)
|
|
88
|
+
with partial.open("ab" if append else "wb") as stream:
|
|
89
|
+
for chunk in response.iter_content(4 * 1024 * 1024):
|
|
90
|
+
stream.write(chunk)
|
|
91
|
+
received += len(chunk)
|
|
92
|
+
if expected is not None and received != int(expected):
|
|
93
|
+
raise IOError(f"Incomplete download: {url}; rerun to resume")
|
|
94
|
+
partial.replace(path)
|
|
95
|
+
meta = {"url": url, "bytes": path.stat().st_size, "sha256": digest(path)}
|
|
96
|
+
write_json(receipt, meta)
|
|
97
|
+
return meta
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def catalogue(root):
|
|
101
|
+
"""Read ExoMol's labelled master-file records without assuming isotope order."""
|
|
102
|
+
path = root / "cache" / "exomol.all"
|
|
103
|
+
with locked(root / "cache" / ".catalogue.lock"):
|
|
104
|
+
download(SITE + "/db/exomol.all", path)
|
|
105
|
+
rows = []
|
|
106
|
+
molecule = isotope = None
|
|
107
|
+
for line in path.read_text().splitlines():
|
|
108
|
+
value, separator, label = line.partition("#")
|
|
109
|
+
if not separator:
|
|
110
|
+
continue
|
|
111
|
+
value, label = value.strip(), label.strip()
|
|
112
|
+
if label == "Molecule chemical formula":
|
|
113
|
+
molecule = value.replace("_p", "+").replace("_m", "-")
|
|
114
|
+
elif label == "Iso-slug":
|
|
115
|
+
isotope = value
|
|
116
|
+
elif label == "Isotopologue dataset name" and molecule and isotope:
|
|
117
|
+
rows.append((molecule, isotope, value))
|
|
118
|
+
if not rows:
|
|
119
|
+
raise ValueError("No datasets recognised in the ExoMol master file")
|
|
120
|
+
return rows
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def resolve_dataset(molecule, isotopologue, dataset, root):
|
|
124
|
+
if isotopologue and dataset:
|
|
125
|
+
return safe_name(isotopologue), safe_name(dataset)
|
|
126
|
+
if molecule in PRESETS and isotopologue is None and dataset is None:
|
|
127
|
+
return PRESETS[molecule]
|
|
128
|
+
choices = sorted(set((iso, name) for mol, iso, name in catalogue(root)
|
|
129
|
+
if mol == molecule and (not isotopologue or iso == isotopologue)
|
|
130
|
+
and (not dataset or name == dataset)))
|
|
131
|
+
if len(choices) != 1:
|
|
132
|
+
raise ValueError(f"Specify isotopologue and dataset for {molecule}. Available choices: {choices}")
|
|
133
|
+
return choices[0]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class Links(HTMLParser):
|
|
137
|
+
def __init__(self):
|
|
138
|
+
super().__init__()
|
|
139
|
+
self.links = []
|
|
140
|
+
|
|
141
|
+
def handle_starttag(self, tag, attrs):
|
|
142
|
+
if tag == "a":
|
|
143
|
+
self.links.append(dict(attrs).get("href", ""))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def transition_urls(page, base_url, stem, expected_count):
|
|
147
|
+
parser = Links()
|
|
148
|
+
parser.feed(page)
|
|
149
|
+
urls = sorted(set(urljoin(SITE, href) for href in parser.links))
|
|
150
|
+
# Supplementary lists (e.g. CO __E2 quadrupole lines) are not the primary dataset.
|
|
151
|
+
pattern = re.compile(re.escape(stem) + r"(?:__\d+(?:\.\d+)?-\d+(?:\.\d+)?)?\.trans\.bz2$")
|
|
152
|
+
urls = [url for url in urls if url.startswith(base_url)
|
|
153
|
+
and pattern.fullmatch(Path(urlparse(url).path).name)]
|
|
154
|
+
if len(urls) != expected_count:
|
|
155
|
+
raise ValueError(f"Expected {expected_count} bzip2 transition files; found {len(urls)}. "
|
|
156
|
+
"This dataset's layout is not supported; no partial spectrum will be calculated.")
|
|
157
|
+
return urls
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def select_transitions(urls, low, high, mass, temperature):
|
|
161
|
+
# Include neighbouring transition blocks reached by the engine's Doppler wings.
|
|
162
|
+
margin = 8 * math.sqrt(1.380649e-23 * temperature / (mass * 1.66053906660e-27)) / 299792458
|
|
163
|
+
selected = []
|
|
164
|
+
for url in urls:
|
|
165
|
+
match = re.search(r"__(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)\.trans\.bz2$", url)
|
|
166
|
+
if match:
|
|
167
|
+
left, right = map(float, match.groups())
|
|
168
|
+
if right * (1 + margin) < low or left * (1 - margin) > high:
|
|
169
|
+
continue
|
|
170
|
+
selected.append(url)
|
|
171
|
+
if not selected:
|
|
172
|
+
raise ValueError("No transition files overlap the requested wavelength interval")
|
|
173
|
+
return selected
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def build_engine(root, scan=False):
|
|
177
|
+
name = "line_range" if scan else "bin_doppler_grid"
|
|
178
|
+
sources = [ROOT / "src" / (name + ".cpp"), ROOT / "src" / "exomol_reader.hpp"]
|
|
179
|
+
key = hashlib.sha256(b"".join(path.read_bytes() for path in sources)).hexdigest()
|
|
180
|
+
binary = root / "build" / (name + "_" + key[:16])
|
|
181
|
+
with locked(root / "build" / ".build.lock"):
|
|
182
|
+
if not binary.exists():
|
|
183
|
+
compiler = shutil.which("c++")
|
|
184
|
+
if not compiler:
|
|
185
|
+
raise RuntimeError("Install a C++ compiler first (macOS: xcode-select --install)")
|
|
186
|
+
temporary = binary.with_suffix(".tmp")
|
|
187
|
+
subprocess.run([compiler, "-O3", "-std=c++17", str(sources[0]), "-lbz2", "-o", str(temporary)], check=True)
|
|
188
|
+
temporary.replace(binary)
|
|
189
|
+
return binary, key
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def scan_line_range(states, transitions, cache, root, source_hashes):
|
|
193
|
+
"""Cache each file's extrema, keyed by both source files and the scanner code."""
|
|
194
|
+
binary, engine_hash = build_engine(root, scan=True)
|
|
195
|
+
reports = []
|
|
196
|
+
for index, path in enumerate(transitions, 1):
|
|
197
|
+
signature = dict(states_sha256=source_hashes[states.name],
|
|
198
|
+
transitions_sha256=source_hashes[path.name], scanner_sha256=engine_hash)
|
|
199
|
+
receipt = cache / (path.name + ".range.json")
|
|
200
|
+
saved = json.loads(receipt.read_text()) if receipt.exists() else {}
|
|
201
|
+
if saved.get("signature") == signature:
|
|
202
|
+
report = saved["range"]
|
|
203
|
+
else:
|
|
204
|
+
print(f"Scanning line limits: {index}/{len(transitions)} ({path.name})", flush=True)
|
|
205
|
+
run = subprocess.run([str(binary), str(states), str(path)], capture_output=True, text=True)
|
|
206
|
+
if run.returncode:
|
|
207
|
+
raise RuntimeError(run.stderr)
|
|
208
|
+
report = json.loads(run.stdout)
|
|
209
|
+
write_json(receipt, dict(signature=signature, range=report))
|
|
210
|
+
reports.append(report)
|
|
211
|
+
active = [report for report in reports if report["active_transitions"]]
|
|
212
|
+
if not active:
|
|
213
|
+
raise ValueError("No positive-frequency absorption transitions in this dataset")
|
|
214
|
+
return dict(min_wavenumber_cm1=min(r["min_wavenumber_cm1"] for r in active),
|
|
215
|
+
max_wavenumber_cm1=max(r["max_wavenumber_cm1"] for r in active),
|
|
216
|
+
transitions_read=sum(r["transitions_read"] for r in reports),
|
|
217
|
+
active_transitions=sum(r["active_transitions"] for r in reports))
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def padded_wavelength_range(line_range, mass, temperature, resolution):
|
|
221
|
+
margin = max(8 * math.sqrt(1.380649e-23 * temperature / (mass * 1.66053906660e-27)) / 299792458,
|
|
222
|
+
math.expm1(min(1 / resolution, 0.5)), 1e-12)
|
|
223
|
+
if margin >= 1:
|
|
224
|
+
raise ValueError("Doppler width is too large for a positive-frequency grid")
|
|
225
|
+
return (1e4 / (line_range["max_wavenumber_cm1"] * (1 + margin)),
|
|
226
|
+
1e4 / (line_range["min_wavenumber_cm1"] * (1 - margin)))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def grid_size(lower, upper, resolution):
|
|
230
|
+
bins = math.ceil(resolution * (math.log(upper) - math.log(lower)))
|
|
231
|
+
if bins > 5_000_000:
|
|
232
|
+
raise ValueError("More than five million bins: reduce the range or resolving power")
|
|
233
|
+
return max(1, bins)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def partitions(states, pf, temperatures, direct=False):
|
|
237
|
+
if direct:
|
|
238
|
+
# H3+ tables round low-temperature values; retain the original state-sum treatment.
|
|
239
|
+
with bz2.open(states, "rt") as stream:
|
|
240
|
+
energy, weight = np.loadtxt(stream, usecols=(1, 2), unpack=True)
|
|
241
|
+
return [1.0 if t == 0 else float(np.sum(weight * np.exp(-1.4387768775039338 * energy / t)))
|
|
242
|
+
for t in temperatures]
|
|
243
|
+
table = np.loadtxt(pf, ndmin=2)
|
|
244
|
+
if table.shape[1] < 2 or not np.all(np.diff(table[:, 0]) > 0):
|
|
245
|
+
raise ValueError("Invalid partition-function table")
|
|
246
|
+
if any(t > 0 and not table[0, 0] <= t <= table[-1, 0] for t in temperatures):
|
|
247
|
+
raise ValueError(f"Positive temperatures must lie in the partition table range {table[0, 0]}--{table[-1, 0]} K")
|
|
248
|
+
return [1.0 if t == 0 else float(np.interp(t, table[:, 0], table[:, 1])) for t in temperatures]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def calculate_opacity(molecule="H3+", temperatures=(0, 10, 100, 300, 400, 1000),
|
|
252
|
+
wavelength_range=(0.4, 100), resolution=100000,
|
|
253
|
+
isotopologue=None, dataset=None, output_root=None):
|
|
254
|
+
"""Return saved NPZ paths. All wavelengths are microns; temperatures are K.
|
|
255
|
+
|
|
256
|
+
resolution is bin resolving power, not instrumental broadening. The model
|
|
257
|
+
is LTE, pure-isotopologue absorption with thermal Doppler profiles only.
|
|
258
|
+
Existing downloads and identical finished calculations are reused locally.
|
|
259
|
+
output_root defaults to ./opacity_output, never the installed package directory.
|
|
260
|
+
For molecules without a preset, ambiguous isotope/dataset choices must be explicit.
|
|
261
|
+
wavelength_range="all" scans all primary transition files and includes their
|
|
262
|
+
actual line centres plus Doppler-wing margins; the scan results are cached.
|
|
263
|
+
"""
|
|
264
|
+
molecule = safe_name(molecule)
|
|
265
|
+
temperatures = [float(t) for t in temperatures]
|
|
266
|
+
all_lines = isinstance(wavelength_range, str) and wavelength_range == "all"
|
|
267
|
+
if isinstance(wavelength_range, str) and not all_lines:
|
|
268
|
+
raise ValueError('wavelength_range must be "all" or a pair of wavelengths')
|
|
269
|
+
resolution = float(resolution)
|
|
270
|
+
if not temperatures or any(not math.isfinite(t) or t < 0 for t in temperatures):
|
|
271
|
+
raise ValueError("Supply finite temperatures >= 0 K")
|
|
272
|
+
if len(set(temperatures)) != len(temperatures):
|
|
273
|
+
raise ValueError("Temperatures must be unique")
|
|
274
|
+
if not math.isfinite(resolution) or resolution <= 0:
|
|
275
|
+
raise ValueError("Require a finite positive resolution")
|
|
276
|
+
lower = upper = bins = None
|
|
277
|
+
if not all_lines:
|
|
278
|
+
lower, upper = map(float, wavelength_range)
|
|
279
|
+
if not all(math.isfinite(v) for v in (lower, upper)) or not 0 < lower < upper:
|
|
280
|
+
raise ValueError("Require 0 < wavelength_min < wavelength_max")
|
|
281
|
+
bins = grid_size(lower, upper, resolution)
|
|
282
|
+
root = (Path(output_root) if output_root is not None else Path.cwd() / "opacity_output").resolve()
|
|
283
|
+
iso, name = resolve_dataset(molecule, isotopologue, dataset, root)
|
|
284
|
+
with locked(root / "cache" / molecule / ".lock"):
|
|
285
|
+
return _calculate(molecule, iso, name, temperatures, lower, upper, resolution, bins, root, all_lines)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _calculate(molecule, iso, name, temperatures, lower, upper, resolution, bins, root, all_lines=False):
|
|
289
|
+
slug = molecule.replace("+", "_p").replace("-", "_m")
|
|
290
|
+
base = f"{SITE}/db/{slug}/{iso}/{name}/"
|
|
291
|
+
stem = f"{iso}__{name}"
|
|
292
|
+
cache = root / "cache" / molecule / iso / name
|
|
293
|
+
cache.mkdir(parents=True, exist_ok=True)
|
|
294
|
+
definition = cache / (stem + ".def.json")
|
|
295
|
+
download(base + definition.name, definition)
|
|
296
|
+
meta = json.loads(definition.read_text())
|
|
297
|
+
if meta["isotopologue"]["iso_slug"] != iso or meta["dataset"]["name"] != name:
|
|
298
|
+
raise ValueError("Dataset definition does not match the requested isotope/dataset")
|
|
299
|
+
max_temperature = meta["dataset"]["max_temperature"]
|
|
300
|
+
temperature_warning = (
|
|
301
|
+
f"{molecule} / {name}: requested temperature {max(temperatures):g} K exceeds "
|
|
302
|
+
f"the line-list maximum temperature of {max_temperature:g} K. "
|
|
303
|
+
"Continuing the calculation, but the line list may be incomplete and "
|
|
304
|
+
"opacity accuracy is not established above this limit."
|
|
305
|
+
) if max(temperatures) > max_temperature else None
|
|
306
|
+
if temperature_warning:
|
|
307
|
+
warnings.warn(temperature_warning, UserWarning, stacklevel=3)
|
|
308
|
+
max_nu = meta["dataset"]["transitions"]["max_wavenumber"]
|
|
309
|
+
# Preserve the original MiZATeP calculation range; its metadata is not a completeness guarantee.
|
|
310
|
+
if molecule == "H3+" and name == "MiZATeP":
|
|
311
|
+
max_nu = max(max_nu, 25000)
|
|
312
|
+
if not all_lines and 1e4 / lower > max_nu * (1 + 1e-12):
|
|
313
|
+
raise ValueError(f"Requested short-wavelength boundary exceeds dataset coverage; use >= {1e4/max_nu:g} microns")
|
|
314
|
+
mass = float(meta["isotopologue"]["mass_in_Da"])
|
|
315
|
+
if not math.isfinite(mass) or mass <= 0:
|
|
316
|
+
raise ValueError("Missing or invalid isotopologue mass")
|
|
317
|
+
page = cache / "dataset.html"
|
|
318
|
+
download(f"{SITE}/data/molecules/{slug}/{iso}/{name}/", page)
|
|
319
|
+
urls = transition_urls(page.read_text(), base, stem, meta["dataset"]["transitions"]["number_of_transition_files"])
|
|
320
|
+
if not all_lines:
|
|
321
|
+
urls = select_transitions(urls, 1e4 / upper, 1e4 / lower, mass, max(temperatures))
|
|
322
|
+
states, pf = cache / (stem + ".states.bz2"), cache / (stem + ".pf")
|
|
323
|
+
records = [download(base + p.name, p) for p in (states, pf)]
|
|
324
|
+
Q = partitions(states, pf, temperatures, direct=molecule == "H3+" and name == "MiZATeP")
|
|
325
|
+
binary, engine_hash = build_engine(root)
|
|
326
|
+
for url in urls:
|
|
327
|
+
records.append(download(url, cache / Path(urlparse(url).path).name))
|
|
328
|
+
write_json(cache / "cache.json", {"molecule": molecule, "isotopologue": iso, "dataset": name,
|
|
329
|
+
"files": [json.loads(p.read_text()) for p in sorted(cache.glob("*.download.json"))]})
|
|
330
|
+
line_range = None
|
|
331
|
+
if all_lines:
|
|
332
|
+
transitions = [cache / Path(urlparse(url).path).name for url in urls]
|
|
333
|
+
source_hashes = {Path(urlparse(record["url"]).path).name: record["sha256"] for record in records}
|
|
334
|
+
line_range = scan_line_range(states, transitions, cache, root, source_hashes)
|
|
335
|
+
expected = meta["dataset"]["transitions"]["number_of_transitions"]
|
|
336
|
+
if line_range["transitions_read"] != expected:
|
|
337
|
+
raise ValueError(f"Expected {expected} transitions; read {line_range['transitions_read']}")
|
|
338
|
+
lower, upper = padded_wavelength_range(line_range, mass, max(temperatures), resolution)
|
|
339
|
+
bins = grid_size(lower, upper, resolution)
|
|
340
|
+
print(f"All primary lines: {line_range['active_transitions']:,}; "
|
|
341
|
+
f"wavelength range including wings: {lower:.8g}--{upper:.8g} microns", flush=True)
|
|
342
|
+
settings = dict(molecule=molecule, isotopologue=iso, dataset=name,
|
|
343
|
+
temperatures_K=temperatures, wavelength_range_um=[lower, upper],
|
|
344
|
+
line_list_max_temperature_K=max_temperature,
|
|
345
|
+
temperature_warning=temperature_warning,
|
|
346
|
+
wavelength_range_mode="all" if all_lines else "explicit", line_range=line_range,
|
|
347
|
+
resolving_power=resolution, bins=bins, engine_sha256=engine_hash,
|
|
348
|
+
pipeline_sha256=digest(Path(__file__)), definition_sha256=digest(definition),
|
|
349
|
+
source_files=records)
|
|
350
|
+
key = hashlib.sha256(json.dumps(settings, sort_keys=True).encode()).hexdigest()[:16]
|
|
351
|
+
output = root / "results" / molecule / iso / name / key
|
|
352
|
+
output.mkdir(parents=True, exist_ok=True)
|
|
353
|
+
paths = [output / f"{molecule}_T{t:g}K.npz" for t in temperatures]
|
|
354
|
+
manifest = output / "calculation.json"
|
|
355
|
+
if manifest.exists():
|
|
356
|
+
saved = json.loads(manifest.read_text())
|
|
357
|
+
if all((output / f).exists() and digest(output / f) == checksum for f, checksum in saved["outputs"].items()):
|
|
358
|
+
print(f"Reusing calculated spectra: {output}", flush=True)
|
|
359
|
+
return paths
|
|
360
|
+
integrated = np.zeros((bins, len(temperatures)))
|
|
361
|
+
reports = []
|
|
362
|
+
for index, url in enumerate(urls, 1):
|
|
363
|
+
transitions = cache / Path(urlparse(url).path).name
|
|
364
|
+
print(f"Calculating {molecule}: block {index}/{len(urls)} ({transitions.name})", flush=True)
|
|
365
|
+
with tempfile.TemporaryDirectory(dir=output) as temporary:
|
|
366
|
+
result = Path(temporary) / "bins.txt"
|
|
367
|
+
command = [binary, states, transitions, result, ",".join(map(str, temperatures)),
|
|
368
|
+
",".join(map(str, Q)), mass, 1e4 / upper, 1e4 / lower, bins]
|
|
369
|
+
run = subprocess.run(list(map(str, command)), capture_output=True, text=True)
|
|
370
|
+
if run.returncode:
|
|
371
|
+
raise RuntimeError(run.stderr)
|
|
372
|
+
reports.append(json.loads(run.stdout))
|
|
373
|
+
integrated += np.loadtxt(result, ndmin=2)
|
|
374
|
+
edges = np.geomspace(1e4 / upper, 1e4 / lower, bins + 1)
|
|
375
|
+
wavelength = (1e4 / np.sqrt(edges[:-1] * edges[1:]))[::-1]
|
|
376
|
+
for j, (temperature, path) in enumerate(zip(temperatures, paths)):
|
|
377
|
+
sigma = (integrated[:, j] / np.diff(edges))[::-1]
|
|
378
|
+
if not np.all(np.isfinite(sigma)) or np.any(sigma < 0):
|
|
379
|
+
raise RuntimeError("Nonfinite or negative computed cross section")
|
|
380
|
+
metadata = dict(settings, temperature_K=temperature, mass_amu=mass,
|
|
381
|
+
above_line_list_max_temperature=temperature > max_temperature,
|
|
382
|
+
temperature_warning=temperature_warning if temperature > max_temperature else None,
|
|
383
|
+
partition_function=reports[0]["temperatures"][j]["partition_function"],
|
|
384
|
+
profile="Doppler only; LTE; 8-sigma profile support; no instrumental convolution",
|
|
385
|
+
zero_temperature_limit=temperature == 0, isotopologue_abundance=1.0,
|
|
386
|
+
cross_section_units="cm^2 molecule^-1", mass_opacity_units="cm^2 g^-1",
|
|
387
|
+
coverage_note="Coverage is limited by the selected line list; its boundaries do not guarantee completeness.")
|
|
388
|
+
kappa = sigma / (mass * 1.66053906660e-24)
|
|
389
|
+
with path.with_suffix(".tmp").open("wb") as stream:
|
|
390
|
+
np.savez_compressed(stream, wavelength_um=wavelength, cross_section_cm2_molecule=sigma,
|
|
391
|
+
mass_opacity_cm2_g=kappa, wavenumber_edges_cm1=edges,
|
|
392
|
+
metadata_json=json.dumps(metadata))
|
|
393
|
+
path.with_suffix(".tmp").replace(path)
|
|
394
|
+
csv = path.with_suffix(".csv")
|
|
395
|
+
np.savetxt(csv.with_suffix(".tmp"), np.column_stack((wavelength, 1e4/wavelength, sigma, kappa)),
|
|
396
|
+
delimiter=",", header="wavelength_um,wavenumber_cm-1,cross_section_cm2_molecule,mass_opacity_cm2_g", comments="")
|
|
397
|
+
csv.with_suffix(".tmp").replace(csv)
|
|
398
|
+
write_json(path.with_suffix(".json"), metadata)
|
|
399
|
+
files = [p for path in paths for p in (path, path.with_suffix(".csv"), path.with_suffix(".json"))]
|
|
400
|
+
write_json(manifest, dict(settings, reports=reports, outputs={p.name: digest(p) for p in files}))
|
|
401
|
+
print(f"Saved spectra: {output}", flush=True)
|
|
402
|
+
return paths
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def main(default_output_root=None):
|
|
406
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
407
|
+
parser.add_argument("--output-dir", type=Path,
|
|
408
|
+
default=default_output_root or Path.cwd() / "opacity_output",
|
|
409
|
+
help="Folder for downloads, builds and results (default: ./opacity_output)")
|
|
410
|
+
parser.add_argument("--version", action="version", version="%(prog)s 0.1.0")
|
|
411
|
+
parser.add_argument("molecule", nargs="?", default="H3+")
|
|
412
|
+
parser.add_argument("--temperatures", nargs="+", type=float, default=[0, 10, 100, 300, 400, 1000])
|
|
413
|
+
parser.add_argument("--wavelength-range", nargs="+", default=["0.4", "100"], metavar="RANGE",
|
|
414
|
+
help='Two wavelengths in microns, or "all" for every primary transition')
|
|
415
|
+
parser.add_argument("--resolution", type=float, default=100000)
|
|
416
|
+
parser.add_argument("--isotopologue")
|
|
417
|
+
parser.add_argument("--dataset")
|
|
418
|
+
parser.add_argument("--list", action="store_true", help="List ExoMol isotopologues and datasets for the molecule")
|
|
419
|
+
parser.add_argument("--plot", action="store_true")
|
|
420
|
+
parser.add_argument("--no-show", action="store_true")
|
|
421
|
+
args = parser.parse_args()
|
|
422
|
+
if args.list:
|
|
423
|
+
for mol, iso, name in catalogue(args.output_dir):
|
|
424
|
+
if mol == args.molecule:
|
|
425
|
+
print(mol, iso, name)
|
|
426
|
+
return
|
|
427
|
+
if args.wavelength_range == ["all"]:
|
|
428
|
+
wavelength_range = "all"
|
|
429
|
+
else:
|
|
430
|
+
try:
|
|
431
|
+
if len(args.wavelength_range) != 2:
|
|
432
|
+
raise ValueError
|
|
433
|
+
wavelength_range = tuple(map(float, args.wavelength_range))
|
|
434
|
+
except ValueError:
|
|
435
|
+
parser.error('--wavelength-range requires "all" or two numeric wavelengths')
|
|
436
|
+
paths = calculate_opacity(args.molecule, args.temperatures, wavelength_range,
|
|
437
|
+
args.resolution, args.isotopologue, args.dataset, output_root=args.output_dir)
|
|
438
|
+
if args.plot:
|
|
439
|
+
from .plotting import plot_opacity
|
|
440
|
+
plot_opacity(paths, show=not args.no_show)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
if __name__ == "__main__":
|
|
444
|
+
main()
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Plot saved opacity spectra without downloading or recalculating anything."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def plot_opacity(paths, show=True, save=True, quantity="cross-section"):
|
|
10
|
+
"""Make one figure per saved temperature, optionally saving PNG and PDF."""
|
|
11
|
+
import matplotlib
|
|
12
|
+
if not show:
|
|
13
|
+
matplotlib.use("Agg")
|
|
14
|
+
import matplotlib.pyplot as plt
|
|
15
|
+
|
|
16
|
+
if quantity not in ("cross-section", "mass-opacity"):
|
|
17
|
+
raise ValueError("quantity must be cross-section or mass-opacity")
|
|
18
|
+
figures = []
|
|
19
|
+
for path in map(Path, paths):
|
|
20
|
+
with np.load(path, allow_pickle=False) as data:
|
|
21
|
+
metadata = json.loads(str(data["metadata_json"]))
|
|
22
|
+
wavelength = data["wavelength_um"]
|
|
23
|
+
values = data["cross_section_cm2_molecule" if quantity == "cross-section" else "mass_opacity_cm2_g"]
|
|
24
|
+
fig, ax = plt.subplots(figsize=(12, 7), layout="constrained")
|
|
25
|
+
temperature = metadata["temperature_K"]
|
|
26
|
+
positive = values > 0
|
|
27
|
+
if positive.any():
|
|
28
|
+
ceiling = 10 ** np.ceil(np.log10(values[positive].max()))
|
|
29
|
+
floor = ceiling * 1e-14
|
|
30
|
+
if temperature == 0:
|
|
31
|
+
ax.vlines(wavelength[positive], floor, values[positive], color="#AA3377", linewidth=0.7)
|
|
32
|
+
else:
|
|
33
|
+
ax.plot(wavelength, np.where(positive, values, np.nan), color="#AA3377",
|
|
34
|
+
linewidth=0.7, marker=".", markersize=1.3)
|
|
35
|
+
ax.set_yscale("log")
|
|
36
|
+
ax.set_ylim(floor, ceiling)
|
|
37
|
+
else:
|
|
38
|
+
ax.text(0.5, 0.5, "No populated absorption transitions in this interval",
|
|
39
|
+
ha="center", transform=ax.transAxes)
|
|
40
|
+
ylabel = (r"Absorption cross section [cm$^2$ molecule$^{-1}$]" if quantity == "cross-section"
|
|
41
|
+
else r"Mass absorption coefficient [cm$^2$ g$^{-1}$]")
|
|
42
|
+
title_temperature = f"{temperature:g} K" if temperature else "0 K (formal limit)"
|
|
43
|
+
ax.set(xscale="log", xlim=metadata["wavelength_range_um"], xlabel="Wavelength [micron]",
|
|
44
|
+
ylabel=ylabel, title=f"{metadata['molecule']} | {metadata['isotopologue']} | {metadata['dataset']}\n"
|
|
45
|
+
f"{title_temperature} | Doppler only | Bin resolving power {metadata['resolving_power']:g}")
|
|
46
|
+
ax.grid(alpha=0.2)
|
|
47
|
+
if save:
|
|
48
|
+
directory = path.parent / "figures"
|
|
49
|
+
directory.mkdir(exist_ok=True)
|
|
50
|
+
for extension in ("png", "pdf"):
|
|
51
|
+
fig.savefig(directory / f"{path.stem}_{quantity}.{extension}", dpi=200)
|
|
52
|
+
figures.append(fig)
|
|
53
|
+
if not show:
|
|
54
|
+
plt.close(fig)
|
|
55
|
+
if show:
|
|
56
|
+
plt.show()
|
|
57
|
+
return figures
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def main():
|
|
61
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
62
|
+
parser.add_argument("results_folder", type=Path, help="Folder containing the desired NPZ spectra")
|
|
63
|
+
parser.add_argument("--no-show", action="store_true")
|
|
64
|
+
parser.add_argument("--no-save", action="store_true")
|
|
65
|
+
parser.add_argument("--quantity", choices=["cross-section", "mass-opacity"], default="cross-section")
|
|
66
|
+
args = parser.parse_args()
|
|
67
|
+
paths = sorted(args.results_folder.glob("*.npz"))
|
|
68
|
+
if not paths:
|
|
69
|
+
parser.error("No NPZ spectra found in that folder")
|
|
70
|
+
plot_opacity(paths, show=not args.no_show, save=not args.no_save, quantity=args.quantity)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
if __name__ == "__main__":
|
|
74
|
+
main()
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Multiple LTE temperatures in one pass through an ExoMol transition file.
|
|
2
|
+
#include "exomol_reader.hpp"
|
|
3
|
+
#include <sstream>
|
|
4
|
+
|
|
5
|
+
std::vector<double> csv_numbers(const char* text) {
|
|
6
|
+
std::vector<double> values; std::stringstream stream(text); std::string field;
|
|
7
|
+
while(std::getline(stream,field,',')) {
|
|
8
|
+
size_t used; double v=std::stod(field,&used);
|
|
9
|
+
if(used!=field.size() || !std::isfinite(v)) throw std::runtime_error("Invalid numeric list");
|
|
10
|
+
values.push_back(v);
|
|
11
|
+
}
|
|
12
|
+
return values;
|
|
13
|
+
}
|
|
14
|
+
struct TemperatureGrid {
|
|
15
|
+
double temperature, Q, frac, sum=0, deposited=0;
|
|
16
|
+
unsigned long long selected=0, underflow=0;
|
|
17
|
+
std::vector<double> population, bins;
|
|
18
|
+
};
|
|
19
|
+
int main(int argc,char** argv) {
|
|
20
|
+
try {
|
|
21
|
+
if(argc!=10) throw std::runtime_error("Usage: bin_doppler_grid states.bz2 trans.bz2 output temperatures_csv Q_csv mass nu_min nu_max n_bins");
|
|
22
|
+
auto temperatures=csv_numbers(argv[4]), partitions=csv_numbers(argv[5]);
|
|
23
|
+
double mass=std::stod(argv[6]), lo=std::stod(argv[7]), hi=std::stod(argv[8]);
|
|
24
|
+
int n=std::stoi(argv[9]);
|
|
25
|
+
if(temperatures.empty() || temperatures.size()!=partitions.size() || !(mass>0 && lo>0 && hi>lo && n>0)) throw std::runtime_error("Invalid grid parameters");
|
|
26
|
+
const double c=2.99792458e10, c2=1.4387768775039338;
|
|
27
|
+
const double loglo=std::log(lo), dx=std::log(hi/lo)/n;
|
|
28
|
+
std::vector<double> energy(1,NAN), g(1,0), edges(n+1);
|
|
29
|
+
for(int j=0;j<=n;++j) edges[j]=lo*std::exp(j*dx);
|
|
30
|
+
char* line; double ground=INFINITY;
|
|
31
|
+
{ Lines states(argv[1]);
|
|
32
|
+
while(states.next(line)) {
|
|
33
|
+
char* p=line; long id=integer(p); double e=number(p), weight=number(p);
|
|
34
|
+
if(id<=0 || weight<0) throw std::runtime_error("Invalid state");
|
|
35
|
+
if(static_cast<size_t>(id)>=energy.size()) {energy.resize(id+1,NAN);g.resize(id+1);}
|
|
36
|
+
energy[id]=e;g[id]=weight;if(weight>0)ground=std::min(ground,e);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if(!std::isfinite(ground))throw std::runtime_error("No populated ground state");
|
|
40
|
+
double ground_g=0;
|
|
41
|
+
for(size_t j=1;j<energy.size();++j) if(g[j]>0 && std::abs(energy[j]-ground)<1e-10) ground_g+=g[j];
|
|
42
|
+
std::vector<TemperatureGrid> grids;
|
|
43
|
+
double largest_frac=0;
|
|
44
|
+
for(size_t t=0;t<temperatures.size();++t) {
|
|
45
|
+
double T=temperatures[t],Q=T==0?ground_g:partitions[t];
|
|
46
|
+
if(T<0 || Q<=0)throw std::runtime_error("Require T >= 0 and Q > 0");
|
|
47
|
+
TemperatureGrid grid;
|
|
48
|
+
grid.temperature=T;grid.Q=Q;
|
|
49
|
+
grid.frac=std::sqrt(1.380649e-23*T/(mass*1.66053906660e-27))/2.99792458e8;
|
|
50
|
+
largest_frac=std::max(largest_frac,grid.frac);
|
|
51
|
+
grid.population.resize(energy.size(),0);grid.bins.resize(n,0);
|
|
52
|
+
for(size_t j=1;j<energy.size();++j) if(g[j]>0 && std::isfinite(energy[j])) {
|
|
53
|
+
double boltzmann=T==0 ? (std::abs(energy[j]-ground)<1e-10 ? 1. : 0.) : std::exp(-c2*energy[j]/T);
|
|
54
|
+
grid.population[j]=boltzmann/(8*M_PI*c*Q);
|
|
55
|
+
}
|
|
56
|
+
grids.push_back(std::move(grid));
|
|
57
|
+
}
|
|
58
|
+
unsigned long long total=0;
|
|
59
|
+
Lines transitions(argv[2]);
|
|
60
|
+
while(transitions.next(line)) {
|
|
61
|
+
char* p=line;long u=integer(p),l=integer(p);double A=number(p);++total;
|
|
62
|
+
if(u<=0 || l<=0 || static_cast<size_t>(std::max(u,l))>=energy.size() || !std::isfinite(energy[u]) || !std::isfinite(energy[l]) || A<0) throw std::runtime_error("Invalid transition/state reference");
|
|
63
|
+
double nu=energy[u]-energy[l];
|
|
64
|
+
if(nu<=0 || nu*(1+8*largest_frac)<lo || nu*(1-8*largest_frac)>hi || A==0 || g[u]==0)continue;
|
|
65
|
+
double base=A*g[u]/(nu*nu);
|
|
66
|
+
for(auto& grid:grids) {
|
|
67
|
+
if(nu*(1+8*grid.frac)<lo || nu*(1-8*grid.frac)>hi)continue;
|
|
68
|
+
double S=base*grid.population[l];
|
|
69
|
+
if(grid.temperature>0) S *= -std::expm1(-c2*nu/grid.temperature);
|
|
70
|
+
if(S==0) {++grid.underflow;continue;}
|
|
71
|
+
++grid.selected;grid.sum+=S;
|
|
72
|
+
if(grid.temperature==0) {
|
|
73
|
+
// The T -> 0+ Gaussian limit assigns half a line to each side
|
|
74
|
+
// when its center lies precisely on a bin edge.
|
|
75
|
+
double index=(std::log(nu)-loglo)/dx;
|
|
76
|
+
int nearest=static_cast<int>(std::round(index));
|
|
77
|
+
if(nearest>=0 && nearest<=n && std::abs(nu-edges[nearest]) <= 8*2.220446049250313e-16*nu) {
|
|
78
|
+
if(nearest>0)grid.bins[nearest-1]+=.5*S;
|
|
79
|
+
if(nearest<n)grid.bins[nearest]+=.5*S;
|
|
80
|
+
} else {
|
|
81
|
+
int j=static_cast<int>(std::floor(index));
|
|
82
|
+
if(j>=0 && j<n)grid.bins[j]+=S;
|
|
83
|
+
}
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
double sd=nu*grid.frac;
|
|
87
|
+
int first=std::max(0,static_cast<int>(std::floor((std::log(nu-8*sd)-loglo)/dx)));
|
|
88
|
+
int last=std::min(n-1,static_cast<int>(std::floor((std::log(nu+8*sd)-loglo)/dx)));
|
|
89
|
+
for(int j=first;j<=last;++j) {
|
|
90
|
+
double a=(edges[j]-nu)/(sd*std::sqrt(2.)),b=(edges[j+1]-nu)/(sd*std::sqrt(2.));
|
|
91
|
+
double fraction=a>=0 ? .5*(std::erfc(a)-std::erfc(b)) : b<=0 ? .5*(std::erfc(-b)-std::erfc(-a)) : .5*(std::erf(b)-std::erf(a));
|
|
92
|
+
grid.bins[j]+=S*fraction;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
std::ofstream out(argv[3]);out<<std::setprecision(17);
|
|
97
|
+
for(int j=0;j<n;++j) {
|
|
98
|
+
for(size_t t=0;t<grids.size();++t) {if(t)out<<' ';out<<grids[t].bins[j];grids[t].deposited+=grids[t].bins[j];}
|
|
99
|
+
out<<'\n';
|
|
100
|
+
}
|
|
101
|
+
if(!out)throw std::runtime_error("Output write failed");
|
|
102
|
+
std::cout<<std::setprecision(17)<<"{\"transitions_read\":"<<total<<",\"ground_energy_cm1\":"<<ground<<",\"temperatures\":[";
|
|
103
|
+
for(size_t t=0;t<grids.size();++t) {
|
|
104
|
+
if(t)std::cout<<',';auto& v=grids[t];
|
|
105
|
+
std::cout<<"{\"temperature_K\":"<<v.temperature<<",\"partition_function\":"<<v.Q<<",\"lines_deposited\":"<<v.selected
|
|
106
|
+
<<",\"zero_or_underflow_strength_lines\":"<<v.underflow<<",\"selected_strength_cm_per_molecule\":"<<v.sum
|
|
107
|
+
<<",\"deposited_strength_cm_per_molecule\":"<<v.deposited<<"}";
|
|
108
|
+
}
|
|
109
|
+
std::cout<<"]}\n";
|
|
110
|
+
} catch(const std::exception& e) {std::cerr<<e.what()<<'\n';return 1;}
|
|
111
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
// Stream original ExoMol states/transitions and integrate Gaussian profiles over bins.
|
|
3
|
+
#include <bzlib.h>
|
|
4
|
+
#include <algorithm>
|
|
5
|
+
#include <cmath>
|
|
6
|
+
#include <cstdio>
|
|
7
|
+
#include <cstdlib>
|
|
8
|
+
#include <cstring>
|
|
9
|
+
#include <fstream>
|
|
10
|
+
#include <iomanip>
|
|
11
|
+
#include <iostream>
|
|
12
|
+
#include <stdexcept>
|
|
13
|
+
#include <string>
|
|
14
|
+
#include <vector>
|
|
15
|
+
|
|
16
|
+
class Lines {
|
|
17
|
+
FILE* file; BZFILE* bz; int error = BZ_OK;
|
|
18
|
+
std::vector<char> buffer; size_t start = 0, end = 0;
|
|
19
|
+
public:
|
|
20
|
+
explicit Lines(const char* path): buffer(4*1024*1024+1) {
|
|
21
|
+
file = fopen(path, "rb");
|
|
22
|
+
if (!file) throw std::runtime_error(std::string("Cannot open ")+path);
|
|
23
|
+
bz = BZ2_bzReadOpen(&error, file, 0, 0, nullptr, 0);
|
|
24
|
+
if (error != BZ_OK) throw std::runtime_error("Cannot initialize bzip2");
|
|
25
|
+
}
|
|
26
|
+
~Lines() { int e; BZ2_bzReadClose(&e, bz); fclose(file); }
|
|
27
|
+
bool next(char*& line) {
|
|
28
|
+
for (;;) {
|
|
29
|
+
char* nl = static_cast<char*>(memchr(buffer.data()+start, '\n', end-start));
|
|
30
|
+
if (nl) { line = buffer.data()+start; *nl = 0; start = nl-buffer.data()+1; return true; }
|
|
31
|
+
if (error == BZ_STREAM_END) {
|
|
32
|
+
if (end > start) { buffer[end]=0; line=buffer.data()+start; start=end; return true; }
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
size_t left=end-start;
|
|
36
|
+
memmove(buffer.data(), buffer.data()+start, left);
|
|
37
|
+
start=0; end=left;
|
|
38
|
+
if (left == buffer.size()-1) throw std::runtime_error("Unexpectedly long input line");
|
|
39
|
+
int n=BZ2_bzRead(&error,bz,buffer.data()+left,static_cast<int>(buffer.size()-1-left));
|
|
40
|
+
if (error != BZ_OK && error != BZ_STREAM_END) throw std::runtime_error("Corrupt/truncated bzip2 input");
|
|
41
|
+
end += n;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
long integer(char*& p) {
|
|
46
|
+
char* old=p; long v=strtol(p,&p,10);
|
|
47
|
+
if (p==old) throw std::runtime_error("Invalid integer field");
|
|
48
|
+
return v;
|
|
49
|
+
}
|
|
50
|
+
double number(char*& p) {
|
|
51
|
+
char* old=p; double v=strtod(p,&p);
|
|
52
|
+
if (p==old || !std::isfinite(v)) throw std::runtime_error("Invalid numeric field");
|
|
53
|
+
return v;
|
|
54
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Discover the actual positive-frequency absorption range without a strength cutoff.
|
|
2
|
+
#include "exomol_reader.hpp"
|
|
3
|
+
|
|
4
|
+
int main(int argc, char** argv) {
|
|
5
|
+
try {
|
|
6
|
+
if (argc != 3) throw std::runtime_error("Usage: line_range states.bz2 trans.bz2");
|
|
7
|
+
std::vector<double> energy(1, NAN), weight(1, 0);
|
|
8
|
+
char* line;
|
|
9
|
+
{
|
|
10
|
+
Lines states(argv[1]);
|
|
11
|
+
while (states.next(line)) {
|
|
12
|
+
char* p = line;
|
|
13
|
+
long id = integer(p);
|
|
14
|
+
double e = number(p), g = number(p);
|
|
15
|
+
if (id <= 0 || g < 0) throw std::runtime_error("Invalid state");
|
|
16
|
+
if (static_cast<size_t>(id) >= energy.size()) {
|
|
17
|
+
energy.resize(id + 1, NAN);
|
|
18
|
+
weight.resize(id + 1);
|
|
19
|
+
}
|
|
20
|
+
energy[id] = e;
|
|
21
|
+
weight[id] = g;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
double low = INFINITY, high = 0;
|
|
25
|
+
unsigned long long total = 0, active = 0;
|
|
26
|
+
Lines transitions(argv[2]);
|
|
27
|
+
while (transitions.next(line)) {
|
|
28
|
+
char* p = line;
|
|
29
|
+
long u = integer(p), l = integer(p);
|
|
30
|
+
double A = number(p);
|
|
31
|
+
++total;
|
|
32
|
+
if (u <= 0 || l <= 0 || static_cast<size_t>(std::max(u, l)) >= energy.size()
|
|
33
|
+
|| !std::isfinite(energy[u]) || !std::isfinite(energy[l]) || A < 0)
|
|
34
|
+
throw std::runtime_error("Invalid transition/state reference");
|
|
35
|
+
double nu = energy[u] - energy[l];
|
|
36
|
+
if (nu <= 0 || A == 0 || weight[u] == 0 || weight[l] == 0) continue;
|
|
37
|
+
low = std::min(low, nu);
|
|
38
|
+
high = std::max(high, nu);
|
|
39
|
+
++active;
|
|
40
|
+
}
|
|
41
|
+
std::cout << std::setprecision(17) << "{\"transitions_read\":" << total
|
|
42
|
+
<< ",\"active_transitions\":" << active << ",\"min_wavenumber_cm1\":";
|
|
43
|
+
if (active) std::cout << low; else std::cout << "null";
|
|
44
|
+
std::cout << ",\"max_wavenumber_cm1\":";
|
|
45
|
+
if (active) std::cout << high; else std::cout << "null";
|
|
46
|
+
std::cout << "}\n";
|
|
47
|
+
} catch (const std::exception& error) {
|
|
48
|
+
std::cerr << error.what() << '\n';
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: exomol-opacity
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Independent LTE molecular opacity calculations and plots from ExoMol line lists
|
|
5
|
+
Author: Nikolas Valsamidis
|
|
6
|
+
Keywords: opacity,spectroscopy,exomol,astrophysics,molecular-spectra
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Science/Research
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Programming Language :: C++
|
|
12
|
+
Classifier: Operating System :: MacOS
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Astronomy
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
Requires-Dist: numpy>=1.24
|
|
19
|
+
Requires-Dist: matplotlib>=3.7
|
|
20
|
+
Requires-Dist: requests>=2.28
|
|
21
|
+
|
|
22
|
+
# exomol-opacity
|
|
23
|
+
|
|
24
|
+
Calculate wavelength-dependent molecular absorption cross sections and pure-species
|
|
25
|
+
mass opacities from downloaded ExoMol line lists. Includes a Python API, command-line
|
|
26
|
+
calculator, and plotting tool. This is an independent project, not an official
|
|
27
|
+
ExoMol software release.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
Requires Python 3.11 or newer. Calculations support macOS and Linux, including Linux
|
|
32
|
+
under WSL on Windows. A C++17 compiler and bzip2 development headers/library are
|
|
33
|
+
needed to compile the bundled engine on the first calculation.
|
|
34
|
+
|
|
35
|
+
macOS (if Command Line Tools are not already installed):
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
xcode-select --install
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Debian/Ubuntu:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
sudo apt-get install g++ libbz2-dev
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Install the Python package and its Python dependencies:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
python -m pip install exomol-opacity
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Native Windows calculation is not supported; use WSL. Plotting saved NPZ spectra
|
|
54
|
+
needs only the Python dependencies, without a compiler or network connection.
|
|
55
|
+
|
|
56
|
+
## Quick start
|
|
57
|
+
|
|
58
|
+
Calculate H3+ spectra and open separate plot windows:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
exomol-opacity 'H3+' --temperatures 300 1000 --plot
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Above the H3+ MiZATeP stated 5000 K maximum, calculation continues with a warning:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
exomol-opacity 'H3+' --temperatures 6000 --plot
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Specify where files are stored, or export plots without interactive windows:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
exomol-opacity CO --temperatures 300 --output-dir ./co_results --plot --no-show
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
By default, downloads, compiled engines and results are stored under
|
|
77
|
+
`./opacity_output` in the current working directory. They are never written into
|
|
78
|
+
the installed Python package. The first run downloads original ExoMol data;
|
|
79
|
+
line lists can require gigabytes of disk space. Subsequent matching calculations
|
|
80
|
+
reuse checked local files. Internet access is needed for uncached source data.
|
|
81
|
+
The ExoMol line lists themselves are not included in this distribution.
|
|
82
|
+
|
|
83
|
+
## Python API
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from exomol_opacity import calculate_opacity, plot_opacity
|
|
87
|
+
|
|
88
|
+
paths = calculate_opacity(
|
|
89
|
+
molecule="H3+",
|
|
90
|
+
temperatures=[300, 1000, 6000],
|
|
91
|
+
wavelength_range=(0.4, 100), # micrometres; or "all"
|
|
92
|
+
resolution=10000,
|
|
93
|
+
output_root="./my_opacity_results",
|
|
94
|
+
)
|
|
95
|
+
plot_opacity(paths, show=True, save=True)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`calculate_opacity` returns paths to saved NPZ spectra. Each spectrum also has a
|
|
99
|
+
CSV table and JSON metadata file. Temperatures are in kelvin; wavelength-bin
|
|
100
|
+
resolving power is approximately lambda/delta-lambda.
|
|
101
|
+
|
|
102
|
+
## Running the source folder
|
|
103
|
+
|
|
104
|
+
To work from the source distribution instead of installing from PyPI:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
python -m pip install -r requirements.txt
|
|
108
|
+
python run_opacity.py
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Edit the molecule and temperatures at the top of `run_opacity.py`. The source
|
|
112
|
+
wrappers preserve storage inside the source folder. The engine sources live in
|
|
113
|
+
`exomol_opacity/src/` and are included in both the wheel and source distribution.
|
|
114
|
+
|
|
115
|
+
## Choosing a Molecule
|
|
116
|
+
|
|
117
|
+
The editable `run_opacity.py` source example uses `WAVELENGTH_RANGE = "all"`. This downloads every primary
|
|
118
|
+
transition file for the selected dataset, scans the actual upper-minus-lower-state
|
|
119
|
+
line positions, and covers all positive-frequency absorption lines with a margin
|
|
120
|
+
for Doppler wings. It applies no line-strength threshold. The limits are cached
|
|
121
|
+
per transition file, keyed to source checksums and scanner code. Zero-probability
|
|
122
|
+
or zero-statistical-weight entries cannot produce absorption and do not set limits.
|
|
123
|
+
Lines with negligible thermal populations can still be invisible in a given plot.
|
|
124
|
+
The numerical range, line counts, and selection mode are recorded in the results.
|
|
125
|
+
|
|
126
|
+
The initial scan adds work and may require very large downloads. It does not mix
|
|
127
|
+
isotopologues or add supplementary datasets. For a restricted range, use a pair
|
|
128
|
+
such as `WAVELENGTH_RANGE = (0.46, 100)` instead. Command-line equivalent:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
exomol-opacity CO --wavelength-range all --resolution 100000 --plot
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Presets select the original datasets for H3+ (MiZATeP), H3O+ (eXeL), CO
|
|
135
|
+
(Li2015), CO2 (UCL-4000), and SiO (SiOUVenIR). These are deliberate presets,
|
|
136
|
+
not a claim that each is the newest available dataset. Select other ExoMol
|
|
137
|
+
isotopologues/datasets explicitly when needed:
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
exomol-opacity H2O --list
|
|
141
|
+
exomol-opacity CO --temperatures 100 300 1000 --wavelength-range 1 30 --resolution 100000 --plot
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
For a molecule without a preset, use the isotopologue and dataset names from
|
|
145
|
+
`--list` with `--isotopologue NAME --dataset NAME`. If there is exactly one
|
|
146
|
+
available choice, it is selected automatically. Ambiguous choices are never
|
|
147
|
+
silently resolved to an arbitrary isotope. The master catalogue is cached too.
|
|
148
|
+
|
|
149
|
+
The reader supports ExoMol datasets with a JSON definition, partition table,
|
|
150
|
+
and standard bzip2-compressed states/transitions files. It discovers the
|
|
151
|
+
transition blocks from the official dataset page and checks their count.
|
|
152
|
+
Supplementary lists such as CO quadrupole transitions are not mixed into the
|
|
153
|
+
primary dataset. Other file layouts fail explicitly rather than producing a partial calculation.
|
|
154
|
+
This is not a universal reader for HITRAN, arbitrary CSVs, or every molecule.
|
|
155
|
+
|
|
156
|
+
## Cache and Results
|
|
157
|
+
|
|
158
|
+
Paths below are relative to your output directory (`./opacity_output` by default).
|
|
159
|
+
|
|
160
|
+
- `cache/MOLECULE/ISOTOPOLOGUE/DATASET/cache.json`: local download inventory.
|
|
161
|
+
- That same folder contains the source files and individual SHA-256 receipts.
|
|
162
|
+
- Completed source files are checked and reused without contacting the server.
|
|
163
|
+
- Interrupted downloads use `.part` files and resume when the server supports it.
|
|
164
|
+
- `results/MOLECULE/ISOTOPOLOGUE/DATASET/SETTINGS_ID/`: CSV, NPZ, and JSON spectra.
|
|
165
|
+
- `figures/` within that results folder contains the PNG and PDF plots.
|
|
166
|
+
- Different temperatures, ranges, resolutions, source data, or calculation code
|
|
167
|
+
get separate result folders. Identical completed calculations are reused.
|
|
168
|
+
|
|
169
|
+
The cache is pinned for reproducibility: it does not silently update a dataset.
|
|
170
|
+
Remove the relevant cached files and their receipts to intentionally download
|
|
171
|
+
fresh versions. Do not edit source files in the cache. A lock prevents two runs
|
|
172
|
+
from writing the same molecule cache at once.
|
|
173
|
+
|
|
174
|
+
## Plot Existing Results
|
|
175
|
+
|
|
176
|
+
No compiler, source line lists, or internet connection is needed to plot saved
|
|
177
|
+
NPZ spectra. Install `exomol-opacity` and share the desired results folder.
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
exomol-opacity-plot "opacity_output/results/CO/12C-16O/Li2015/SETTINGS_ID"
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Replace SETTINGS_ID with the folder printed by the calculation. Add `--no-show`
|
|
184
|
+
to save figures without opening windows, or `--no-save` to only display them.
|
|
185
|
+
Use `--quantity mass-opacity` for pure-isotopologue mass opacity.
|
|
186
|
+
Plots show the upper 14 orders of magnitude, as in the H3+ figures; saved spectra
|
|
187
|
+
retain the full calculated values.
|
|
188
|
+
|
|
189
|
+
## Physical Scope
|
|
190
|
+
|
|
191
|
+
The calculation retains the original H3+ engine: LTE populations, Einstein-A
|
|
192
|
+
line strengths, thermal Doppler profiles, and analytic integrals over logarithmic
|
|
193
|
+
wavenumber bins. It does not add pressure broadening, continuum opacity, natural
|
|
194
|
+
isotope mixtures, or instrumental broadening. Bin resolution is approximately
|
|
195
|
+
lambda/delta-lambda; changing it requires recalculation.
|
|
196
|
+
|
|
197
|
+
Cross sections are cm^2 per molecule. Mass opacity is cm^2 per gram of the pure
|
|
198
|
+
chosen isotopologue, not per gram of an atmospheric mixture. Zero kelvin means
|
|
199
|
+
the formal ground-state, zero-Doppler-width limit. Positive temperatures use the
|
|
200
|
+
published partition table; H3+ MiZATeP retains the direct state sum used in the
|
|
201
|
+
original calculation to avoid low-temperature rounding. Requests above the dataset's
|
|
202
|
+
stated maximum temperature are allowed with a warning before large downloads.
|
|
203
|
+
The warning explains that line-list completeness and opacity accuracy are not
|
|
204
|
+
established above that limit; this includes H3+ MiZATeP above 5000 K. The dataset
|
|
205
|
+
limit and an above-limit flag are saved in each spectrum's metadata, with the
|
|
206
|
+
warning also recorded for affected spectra and in `calculation.json`.
|
|
207
|
+
For example, `exomol-opacity 'H3+' --temperatures 6000 --plot`
|
|
208
|
+
calculates a 6000 K spectrum with a warning. The H3+ partition function is still
|
|
209
|
+
computed from the available states; extending the temperature does not add
|
|
210
|
+
missing states or transitions. For other datasets using a partition table,
|
|
211
|
+
temperatures must still be covered by that table; it is not extrapolated.
|
|
212
|
+
Explicit short-wavelength requests are checked before large downloads.
|
|
213
|
+
The original H3+ 0.4--100 micron range remains available as an explicit range;
|
|
214
|
+
`"all"` instead uses the actual line positions, even outside metadata boundaries.
|
|
215
|
+
Dataset coverage does not guarantee
|
|
216
|
+
line-list completeness at every wavelength or temperature.
|
|
217
|
+
|
|
218
|
+
Source: https://www.exomol.com/ (original source URLs and checksums accompany results).
|
|
219
|
+
|
|
220
|
+
## Tests
|
|
221
|
+
|
|
222
|
+
```bash
|
|
223
|
+
python -m unittest discover -s tests -v
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
## Development
|
|
227
|
+
|
|
228
|
+
```bash
|
|
229
|
+
python -m unittest discover -s tests -v
|
|
230
|
+
python -m pip install build twine
|
|
231
|
+
python -m build
|
|
232
|
+
python -m twine check dist/*
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## License
|
|
236
|
+
|
|
237
|
+
No software license has been specified for this release. ExoMol data are downloaded
|
|
238
|
+
separately and remain subject to their own terms and citation requirements.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
exomol_opacity/__init__.py,sha256=MUUIgS51SfsyL9W2TB97VesEwyU7dQVxmIS0HHFJRUA,241
|
|
2
|
+
exomol_opacity/__main__.py,sha256=cN9x9pQ4AiX1yHPqn80PdiN-rgmaJxHcx0u-JYcHdXg,69
|
|
3
|
+
exomol_opacity/calculation.py,sha256=9kxkfZHAYBmNbrn59jXY2ngNehwlVNmMsOexFcCW4RI,23020
|
|
4
|
+
exomol_opacity/plotting.py,sha256=qVeE0KWB3gyUjGNVtH66y5qWtCMnBHwN_JzCCytEGvE,3375
|
|
5
|
+
exomol_opacity/src/bin_doppler_grid.cpp,sha256=vsntCo3bOSyfsI0qvtS0yY0cNHGrJa6-4J1WN7yYNWk,6053
|
|
6
|
+
exomol_opacity/src/exomol_reader.hpp,sha256=6ONXr_0YEGmfLgoB0w3BN15l2DdABAQLUSpAPljoqBM,2073
|
|
7
|
+
exomol_opacity/src/line_range.cpp,sha256=U-3Uz4CugjB3-vo1jlib3wto7jII6jpFdgFMzihjrVs,1972
|
|
8
|
+
exomol_opacity-0.1.0.dist-info/METADATA,sha256=mxvbuPuqYd37VE643Q1tjb9gfi-3ya-bunxblmcnlJw,9880
|
|
9
|
+
exomol_opacity-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
exomol_opacity-0.1.0.dist-info/entry_points.txt,sha256=qMbodfuevgYnVxocpW1UxI8IBHj0m8F0njhye73Mfgs,118
|
|
11
|
+
exomol_opacity-0.1.0.dist-info/top_level.txt,sha256=zfBaGd_egpbQyJcy6ZeAJBC1Y99n4U-GQthSOuvJquY,15
|
|
12
|
+
exomol_opacity-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exomol_opacity
|