opencr 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 (81) hide show
  1. opencr/__init__.py +39 -0
  2. opencr/_profiling.py +9 -0
  3. opencr/analysis/__init__.py +6 -0
  4. opencr/analysis/emission.py +226 -0
  5. opencr/analysis/quantities.py +129 -0
  6. opencr/analysis/results.py +264 -0
  7. opencr/analysis/scan.py +164 -0
  8. opencr/analysis/transient.py +144 -0
  9. opencr/backends/__init__.py +27 -0
  10. opencr/backends/batched.py +351 -0
  11. opencr/backends/jax_backend.py +254 -0
  12. opencr/cli.py +74 -0
  13. opencr/constants.py +142 -0
  14. opencr/core/__init__.py +47 -0
  15. opencr/core/conditions.py +186 -0
  16. opencr/core/network.py +275 -0
  17. opencr/core/rates.py +443 -0
  18. opencr/core/reactions.py +179 -0
  19. opencr/core/species.py +212 -0
  20. opencr/data/__init__.py +32 -0
  21. opencr/data/checks.py +194 -0
  22. opencr/data/hydrogen.py +359 -0
  23. opencr/data/importers.py +201 -0
  24. opencr/data/molecular_hydrogen.py +137 -0
  25. opencr/data/native.py +187 -0
  26. opencr/data/provenance.py +162 -0
  27. opencr/inference/__init__.py +34 -0
  28. opencr/inference/inverse.py +222 -0
  29. opencr/inference/sensitivity.py +274 -0
  30. opencr/kinetics/__init__.py +8 -0
  31. opencr/kinetics/eedf.py +304 -0
  32. opencr/kinetics/effective.py +286 -0
  33. opencr/kinetics/radiation.py +240 -0
  34. opencr/kinetics/rates.py +728 -0
  35. opencr/kinetics/system.py +359 -0
  36. opencr/ml/__init__.py +19 -0
  37. opencr/ml/dataset.py +132 -0
  38. opencr/ml/surrogate.py +141 -0
  39. opencr/model.py +320 -0
  40. opencr/models/__init__.py +107 -0
  41. opencr/models/argon.py +248 -0
  42. opencr/models/hydrogen_atomic.py +252 -0
  43. opencr/models/hydrogen_molecular.py +487 -0
  44. opencr/py.typed +0 -0
  45. opencr/solvers/__init__.py +6 -0
  46. opencr/solvers/diagnostics.py +104 -0
  47. opencr/solvers/steady.py +335 -0
  48. opencr/solvers/transient.py +213 -0
  49. opencr/tables.py +211 -0
  50. opencr/tests/backends/__init__.py +0 -0
  51. opencr/tests/backends/test_batched.py +187 -0
  52. opencr/tests/backends/test_jax.py +186 -0
  53. opencr/tests/integration/__init__.py +0 -0
  54. opencr/tests/integration/test_analysis.py +166 -0
  55. opencr/tests/integration/test_argon_model.py +57 -0
  56. opencr/tests/integration/test_hydrogen_model.py +155 -0
  57. opencr/tests/integration/test_inference.py +127 -0
  58. opencr/tests/integration/test_ml.py +61 -0
  59. opencr/tests/integration/test_molecular_model.py +157 -0
  60. opencr/tests/integration/test_tables.py +67 -0
  61. opencr/tests/reference/__init__.py +0 -0
  62. opencr/tests/reference/test_verification.py +137 -0
  63. opencr/tests/unit/__init__.py +0 -0
  64. opencr/tests/unit/test_check_pypi_dependencies.py +158 -0
  65. opencr/tests/unit/test_cli.py +38 -0
  66. opencr/tests/unit/test_conditions.py +60 -0
  67. opencr/tests/unit/test_core.py +270 -0
  68. opencr/tests/unit/test_data.py +362 -0
  69. opencr/tests/unit/test_method_cards.py +5 -0
  70. opencr/tests/unit/test_profiling.py +74 -0
  71. opencr/tests/unit/test_radiation.py +192 -0
  72. opencr/tests/unit/test_rates.py +318 -0
  73. opencr/tests/unit/test_steady.py +209 -0
  74. opencr/tests/unit/test_system.py +245 -0
  75. opencr/tests/unit/test_transient.py +161 -0
  76. opencr/tests/unit/test_units.py +245 -0
  77. opencr-0.1.0.dist-info/METADATA +196 -0
  78. opencr-0.1.0.dist-info/RECORD +81 -0
  79. opencr-0.1.0.dist-info/WHEEL +5 -0
  80. opencr-0.1.0.dist-info/entry_points.txt +5 -0
  81. opencr-0.1.0.dist-info/top_level.txt +1 -0
opencr/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """OpenCR: collisional-radiative models of low-temperature plasmas.
2
+
3
+ OpenCR builds collisional-radiative (CR) models from explicit states and
4
+ reactions with traceable data, and solves their population equations: steady
5
+ states, quasi-static excited states with effective rate coefficients, and time
6
+ evolution. The physics is defined independently of the numerical backend; the
7
+ reference implementation uses NumPy and SciPy, cunumpy and JAX are optional.
8
+ Cross sections and Maxwellian rates come from `plasmacoll`.
9
+ """
10
+
11
+ from importlib.metadata import PackageNotFoundError, version
12
+
13
+ import scope_profiler as sp
14
+
15
+ from opencr._profiling import PROFILE_TAGS
16
+
17
+ try:
18
+ __version__ = version("opencr")
19
+ except PackageNotFoundError: # not installed, e.g. run from a source tree
20
+ __version__ = "0.0.0+unknown"
21
+
22
+ from opencr.analysis.results import Result
23
+ from opencr.analysis.scan import scan
24
+ from opencr.core.conditions import Conditions, RadiationTrapping
25
+ from opencr.model import Model
26
+ from opencr.models import available_models, load_model
27
+
28
+ __all__ = [
29
+ "Conditions",
30
+ "Model",
31
+ "RadiationTrapping",
32
+ "Result",
33
+ "available_models",
34
+ "load_model",
35
+ "scan",
36
+ ]
37
+
38
+ # The decorated functions pick the tag up, so registering after the imports is in time.
39
+ sp.register_opt_in_tag(*PROFILE_TAGS)
opencr/_profiling.py ADDED
@@ -0,0 +1,9 @@
1
+ """The scope-profiler tag of opencr's profiling regions.
2
+
3
+ The regions are opt-in: `opencr` registers the tag on import, so they
4
+ record nothing unless the application enables it, e.g. with
5
+ ``scope_profiler.setup(enable_tags=["opencr"])``.
6
+ """
7
+
8
+ #: Tags of every opencr region; the first is the opt-in tag.
9
+ PROFILE_TAGS = ("opencr",)
@@ -0,0 +1,6 @@
1
+ """Results and what can be read from them.
2
+
3
+ Populations, reaction fluxes and dominant processes, emission and spectra
4
+ (`emission`), parameter scans
5
+ (`scan`) and export (`Result`).
6
+ """
@@ -0,0 +1,226 @@
1
+ """Line emission and synthetic spectra.
2
+
3
+ Each spontaneous emission ``u -> l`` of a network is a line of photon energy
4
+ ``E_u - E_l`` with emissivity ``eps = n_u A_ul`` (photons m^-3 s^-1; the escape
5
+ factor is already in ``A``). In a quasi-static solve the upper population is a
6
+ sum over the drivers, ``n_u = sum_d C_ud n_d``, so the emissivity splits into
7
+ photon emissivity coefficients ``PEC_d = A_ul C_ud / n_e`` (m^3/s) with
8
+ ``eps = n_e sum_d PEC_d n_d``.
9
+
10
+ A synthetic spectrum puts each line on a wavelength grid as a Gaussian of the
11
+ Doppler width at the gas temperature (or a given instrumental FWHM, or both
12
+ added in quadrature).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+
19
+ import numpy as np
20
+ import xarray as xr
21
+ from methodcard import Rule, method
22
+
23
+ from opencr.constants import (
24
+ ATOMIC_MASS,
25
+ ELEMENTARY_CHARGE,
26
+ SPEED_OF_LIGHT,
27
+ air_wavelength,
28
+ photon_wavelength,
29
+ )
30
+ from opencr.core.network import ReactionNetwork
31
+
32
+ __all__ = ["doppler_fwhm", "hydrogen_line_name", "line_table", "spectrum"]
33
+
34
+ _SERIES = {1: "Ly", 2: "H", 3: "Pa", 4: "Br", 5: "Pf", 6: "Hu"}
35
+ _GREEK = "αβγδεζηθικλμ"
36
+
37
+
38
+ def hydrogen_line_name(upper: int, lower: int) -> str:
39
+ """Return the spectroscopic name of an H line, e.g. ``"H-α"`` for 3 -> 2, ``"Ly-β"`` for 3 -> 1.
40
+
41
+ Lines past the Greek alphabet's twelfth member, or of series beyond
42
+ Humphreys, are named ``"<upper>-<lower>"``.
43
+ """
44
+ step = upper - lower
45
+ if lower in _SERIES and 1 <= step <= len(_GREEK):
46
+ return f"{_SERIES[lower]}-{_GREEK[step - 1]}"
47
+ return f"{upper}-{lower}"
48
+
49
+
50
+ def _label(network: ReactionNetwork, name: str) -> str:
51
+ reaction = network.reaction(name)
52
+ upper, lower = reaction.reactants[0], reaction.products[0]
53
+ n_u, n_l = upper.quantum_numbers.get("n"), lower.quantum_numbers.get("n")
54
+ if (
55
+ upper.species.composition.keys() <= {"H", "D"}
56
+ and n_u
57
+ and n_l
58
+ and upper.charge == 0
59
+ ):
60
+ return hydrogen_line_name(n_u, n_l)
61
+ return f"{upper.name}->{lower.name}"
62
+
63
+
64
+ def _doppler_rules() -> dict:
65
+ """The SymPy rule of `doppler_fwhm` (for the tests)."""
66
+ import sympy
67
+
68
+ lam, t, m = sympy.symbols("wavelength temperature mass", positive=True)
69
+ e, c = sympy.Float(ELEMENTARY_CHARGE), sympy.Float(SPEED_OF_LIGHT)
70
+ rule = lam * 2 * sympy.sqrt(2 * sympy.log(2)) * sympy.sqrt(t * e / m) / c
71
+ ranges = {
72
+ "wavelength": (100.0, 1000.0),
73
+ "temperature": (0.02, 10.0),
74
+ "mass": (1.6e-27, 7e-26),
75
+ }
76
+ return {"fwhm": Rule(rule, ranges=ranges)}
77
+
78
+
79
+ @method(
80
+ equations={
81
+ "fwhm": r"\Delta\lambda_{\mathrm{FWHM}} = \lambda\, 2\sqrt{2\ln 2}\, \frac{\sigma_v}{c}, \qquad \sigma_v = \sqrt{\frac{kT}{m}}",
82
+ },
83
+ assumptions=(
84
+ r"a Maxwellian of the emitters at $T$: $\sigma_v$ per velocity component",
85
+ ),
86
+ symbolic=_doppler_rules,
87
+ )
88
+ def doppler_fwhm(wavelength: np.ndarray, temperature: float, mass: float) -> np.ndarray:
89
+ """Return the Doppler FWHM in nm of lines at ``wavelength`` (nm), ``kT`` in eV, mass in kg."""
90
+ sigma_v = math.sqrt(temperature * ELEMENTARY_CHARGE / mass)
91
+ return (
92
+ np.asarray(wavelength)
93
+ * 2.0
94
+ * math.sqrt(2.0 * math.log(2.0))
95
+ * sigma_v
96
+ / SPEED_OF_LIGHT
97
+ )
98
+
99
+
100
+ @method(
101
+ equations={
102
+ "line": r"E = E_u - E_l, \qquad \lambda = \frac{hc}{E}, \qquad \epsilon = g\,A_{ul}\, n_u \ [\mathrm{photons\ m^{-3}\,s^{-1}}], \qquad P = \epsilon\, E\, e \ [\mathrm{W\,m^{-3}}]",
103
+ },
104
+ assumptions=(
105
+ r"every spontaneous emission $u \to l$ is a line; the escape factor $g$ is already in the rate",
106
+ r"photon energies from the state energies; vacuum wavelengths, or in air above 200 nm",
107
+ ),
108
+ components=(
109
+ "opencr.constants.photon_wavelength",
110
+ "opencr.constants.air_wavelength",
111
+ ),
112
+ )
113
+ def line_table(
114
+ network: ReactionNetwork,
115
+ rates: np.ndarray,
116
+ populations: dict[str, float],
117
+ air: bool = False,
118
+ ) -> xr.Dataset:
119
+ """Return every line's wavelength, emissivity and power.
120
+
121
+ Args:
122
+ network: The network.
123
+ rates: The rate coefficients (the escape factors applied).
124
+ populations: Every state's density.
125
+ air: Wavelengths in standard air above 200 nm instead of vacuum.
126
+
127
+ Returns:
128
+ A dataset over ``line`` (the reaction names) with ``wavelength`` (nm),
129
+ ``photon_energy`` (eV), ``emissivity`` (photons m^-3 s^-1), ``power``
130
+ (W m^-3), ``upper``, ``lower`` and ``label``.
131
+ """
132
+ names, energy, emissivity, upper, lower, labels = [], [], [], [], [], []
133
+ for i, reaction in enumerate(network.reactions):
134
+ if reaction.kind != "spontaneous_emission":
135
+ continue
136
+ names.append(reaction.name)
137
+ energy.append(reaction.photon_energy)
138
+ u = reaction.reactants[0].name
139
+ emissivity.append(rates[i] * populations[u])
140
+ upper.append(u)
141
+ lower.append(reaction.products[0].name)
142
+ labels.append(_label(network, reaction.name))
143
+ energy_array = np.asarray(energy, dtype=float)
144
+ wavelength = photon_wavelength(energy_array) if names else np.zeros(0)
145
+ if air:
146
+ wavelength = air_wavelength(wavelength)
147
+ emissivity_array = np.asarray(emissivity, dtype=float)
148
+ return xr.Dataset(
149
+ {
150
+ "wavelength": (
151
+ "line",
152
+ wavelength,
153
+ {"units": "nm", "medium": "air" if air else "vacuum"},
154
+ ),
155
+ "photon_energy": ("line", energy_array, {"units": "eV"}),
156
+ "emissivity": ("line", emissivity_array, {"units": "photons m^-3 s^-1"}),
157
+ "power": (
158
+ "line",
159
+ emissivity_array * energy_array * ELEMENTARY_CHARGE,
160
+ {"units": "W m^-3"},
161
+ ),
162
+ "upper": ("line", np.asarray(upper, dtype=object)),
163
+ "lower": ("line", np.asarray(lower, dtype=object)),
164
+ "label": ("line", np.asarray(labels, dtype=object)),
165
+ },
166
+ coords={"line": np.asarray(names, dtype=object)},
167
+ )
168
+
169
+
170
+ @method(
171
+ equations={
172
+ "spectrum": r"\epsilon_\lambda(\lambda) = \sum_{\mathrm{lines}} \frac{\epsilon}{\sigma\sqrt{2\pi}}\, e^{-(\lambda - \lambda_0)^2/2\sigma^2}, \qquad \sigma = \frac{\Delta\lambda_{\mathrm{FWHM}}}{2\sqrt{2\ln 2}}",
173
+ "width": r"\Delta\lambda_{\mathrm{FWHM}}^2 = \Delta\lambda_{\mathrm{Doppler}}^2 + \Delta\lambda_{\mathrm{instrument}}^2",
174
+ },
175
+ assumptions=(
176
+ r"Gaussian lines only: no Stark, Zeeman or natural broadening",
177
+ r"a line without either width raises",
178
+ ),
179
+ components=(doppler_fwhm,),
180
+ )
181
+ def spectrum(
182
+ lines: xr.Dataset,
183
+ wavelength: np.ndarray,
184
+ temperature: float | None = None,
185
+ mass: float = 1.00794 * ATOMIC_MASS,
186
+ fwhm: float = 0.0,
187
+ quantity: str = "power",
188
+ ) -> xr.DataArray:
189
+ """Return the spectral emissivity of ``lines`` on the grid ``wavelength`` (nm).
190
+
191
+ Each line is a normalised Gaussian whose FWHM is the Doppler width at
192
+ ``temperature`` (eV, of an emitter of ``mass``) and the instrumental
193
+ ``fwhm`` (nm) added in quadrature.
194
+
195
+ Args:
196
+ lines: The output of `line_table`.
197
+ wavelength: The grid in nm.
198
+ temperature: The emitters' ``kT`` in eV; no Doppler broadening if ``None``.
199
+ mass: The emitters' mass in kg.
200
+ fwhm: The instrumental FWHM in nm.
201
+ quantity: ``"power"`` (W m^-3 nm^-1) or ``"emissivity"`` (photons m^-3 s^-1 nm^-1).
202
+ """
203
+ if quantity not in ("power", "emissivity"):
204
+ raise ValueError("quantity must be 'power' or 'emissivity'")
205
+ grid = np.asarray(wavelength, dtype=float)
206
+ centres = lines["wavelength"].values
207
+ width2 = np.full(centres.shape, float(fwhm) ** 2)
208
+ if temperature is not None:
209
+ width2 = width2 + doppler_fwhm(centres, temperature, mass) ** 2
210
+ if np.any(width2 <= 0.0):
211
+ raise ValueError(
212
+ "lines need a width: give a temperature or an instrumental fwhm"
213
+ )
214
+ sigma = np.sqrt(width2) / (2.0 * math.sqrt(2.0 * math.log(2.0)))
215
+ profile = np.exp(-0.5 * ((grid[:, None] - centres[None, :]) / sigma) ** 2) / (
216
+ sigma * math.sqrt(2.0 * math.pi)
217
+ )
218
+ values = profile @ lines[quantity].values
219
+ unit = "W m^-3 nm^-1" if quantity == "power" else "photons m^-3 s^-1 nm^-1"
220
+ return xr.DataArray(
221
+ values,
222
+ coords={"wavelength": ("wavelength", grid, {"units": "nm"})},
223
+ dims="wavelength",
224
+ name=f"spectral_{quantity}",
225
+ attrs={"units": unit},
226
+ )
@@ -0,0 +1,129 @@
1
+ """Scalar quantities of a steady state, named by strings.
2
+
3
+ The surrogates (`opencr.ml`), the sensitivities and the inverse
4
+ modelling (`opencr.inference`) all ask a `Result`
5
+ for named scalars:
6
+
7
+ ========================================== ===============================================
8
+ name quantity
9
+ ========================================== ===============================================
10
+ ``population:<state>`` the density of a state (m^-3)
11
+ ``effective_rate:<source>><target>`` an effective rate coefficient (m^3/s), quasi-static
12
+ ``emissivity:<reaction>`` the photon emissivity of a line (photons m^-3 s^-1)
13
+ ``electron_cooling:<driver>`` the electron energy loss per electron and per
14
+ particle of a driver (eV m^3/s), quasi-static
15
+ ``ratio:<quantity>/<quantity>`` the ratio of two of the above
16
+ ========================================== ===============================================
17
+
18
+ For example ``"effective_rate:H(n=1)>H+"`` is the CR ionization coefficient
19
+ of atomic hydrogen and ``"ratio:emissivity:A:3-2/emissivity:A:4-2"`` the
20
+ Balmer alpha to beta ratio.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from collections.abc import Sequence
26
+ from typing import Any
27
+
28
+ import numpy as np
29
+ from methodcard import method
30
+
31
+ __all__ = ["KINDS", "check_quantity", "electron_cooling", "quantities", "quantity"]
32
+
33
+ #: The kinds of quantity.
34
+ KINDS = ("population", "effective_rate", "emissivity", "electron_cooling", "ratio")
35
+
36
+
37
+ def check_quantity(model: Any, name: str) -> None:
38
+ """Raise ``ValueError`` (or ``KeyError``) if ``name`` is not a quantity of ``model``."""
39
+ kind, _, rest = name.partition(":")
40
+ if kind not in KINDS or not rest:
41
+ raise ValueError(f"{name!r}: a quantity is <kind>:<what> with kind in {KINDS}")
42
+ if kind == "ratio":
43
+ top, slash, bottom = rest.partition("/")
44
+ if not slash:
45
+ raise ValueError(f"{name!r}: a ratio is ratio:<quantity>/<quantity>")
46
+ check_quantity(model, top)
47
+ check_quantity(model, bottom)
48
+ elif kind in ("population", "electron_cooling"):
49
+ model.network.state(rest)
50
+ elif kind == "effective_rate":
51
+ source, arrow, target = rest.partition(">")
52
+ if not arrow:
53
+ raise ValueError(
54
+ f"{name!r}: an effective rate is effective_rate:<source>><target>"
55
+ )
56
+ model.network.state(source)
57
+ model.network.state(target)
58
+ else:
59
+ if model.network.reaction(rest).kind != "spontaneous_emission":
60
+ raise ValueError(f"{name!r}: {rest} is not a spontaneous emission")
61
+
62
+
63
+ @method(
64
+ equations={
65
+ "cooling": r"L_d = \sum_r k_r\, n_e^{a_{re} - 1}\, c_{X_r, d}\, \Delta E_r \quad [\mathrm{eV\,m^3/s}]",
66
+ },
67
+ assumptions=(
68
+ r"over the electron-impact, non-radiative reactions with one heavy reactant $X_r$",
69
+ r"$c_{X,d}$ the quasi-static population of $X$ per particle of driver $d$ (1 for $d$ itself, 0 for the other drivers)",
70
+ r"$\Delta E_r$ the internal energy the heavy particles gain: negative for de-excitation and three-body recombination; radiative recombination is not counted",
71
+ ),
72
+ components=("opencr.kinetics.effective.quasi_static",),
73
+ )
74
+ def electron_cooling(result: Any, driver: str) -> float:
75
+ """Return the electron energy loss due to ``driver`` per electron and particle (eV m^3/s).
76
+
77
+ The sum over the electron-impact reactions (an electron among the
78
+ reactants, not radiative) of ``k n_e^(a-1) c_X Delta E``, where ``c_X`` is
79
+ the quasi-static population of the reaction's heavy reactant per particle
80
+ of ``driver`` (1 for the driver itself, 0 for the other drivers) and
81
+ ``Delta E`` the energy the heavy particles gain: the excitation and
82
+ ionization energies, negative for de-excitation and three-body
83
+ recombination. Radiative recombination (the electron's kinetic energy) is
84
+ not counted.
85
+ """
86
+ from opencr.core.reactions import RADIATIVE_KINDS
87
+ from opencr.core.species import ELECTRON
88
+
89
+ reduction = result.reduction
90
+ column = reduction.drivers.index(driver)
91
+ ne = reduction.electron_density
92
+ share = {d: 0.0 for d in reduction.drivers}
93
+ share[driver] = 1.0
94
+ for name, row in zip(reduction.excited, reduction.coefficients, strict=True):
95
+ share[name] = float(row[column])
96
+ total = 0.0
97
+ for k, reaction in zip(result.rates, result.model.network.reactions, strict=True):
98
+ electrons = reaction.reactant_counts.get(ELECTRON.name, 0)
99
+ if not electrons or reaction.kind in RADIATIVE_KINDS:
100
+ continue
101
+ heavy = [s.name for s in reaction.reactants if s.species != ELECTRON]
102
+ if len(heavy) != 1:
103
+ continue
104
+ total += k * ne ** (electrons - 1) * share[heavy[0]] * reaction.energy_change
105
+ return total
106
+
107
+
108
+ def quantity(result: Any, name: str) -> float:
109
+ """Return the quantity ``name`` of a steady state (see the module docstring)."""
110
+ kind, _, rest = name.partition(":")
111
+ if kind == "ratio":
112
+ top, _, bottom = rest.partition("/")
113
+ return quantity(result, top) / quantity(result, bottom)
114
+ if kind == "population":
115
+ return float(result.population(rest))
116
+ if kind == "effective_rate":
117
+ source, _, target = rest.partition(">")
118
+ return float(result.reduction.effective_rate(source, target))
119
+ if kind == "emissivity":
120
+ return float(result.fluxes[rest])
121
+ if kind == "electron_cooling":
122
+ return electron_cooling(result, rest)
123
+ check_quantity(result.model, name)
124
+ raise AssertionError("unreachable") # pragma: no cover
125
+
126
+
127
+ def quantities(result: Any, names: Sequence[str]) -> np.ndarray:
128
+ """Return the quantities ``names`` of a steady state as an array."""
129
+ return np.array([quantity(result, n) for n in names])
@@ -0,0 +1,264 @@
1
+ """The result of a steady-state solve, and what can be read from it.
2
+
3
+ A `Result` keeps the model, the conditions, the rate coefficients, the
4
+ population equations and the densities of every state, with the solver's
5
+ report. From it: the reaction fluxes and the dominant gains and losses of a
6
+ state, the lines and their photon emissivity coefficients, a synthetic
7
+ spectrum, and everything as an xarray dataset (`Result.to_dataset`) or a
8
+ NetCDF file with the model's manifest (`Result.export`).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from functools import cached_property
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ import numpy as np
19
+ import xarray as xr
20
+ from methodcard import method
21
+
22
+ from opencr.analysis.emission import line_table, spectrum
23
+ from opencr.core.conditions import Conditions
24
+ from opencr.kinetics.system import PopulationSystem
25
+ from opencr.solvers.diagnostics import SolverReport
26
+
27
+ if TYPE_CHECKING:
28
+ from opencr.kinetics.effective import QuasiStatic
29
+ from opencr.model import Model
30
+
31
+ __all__ = ["Result"]
32
+
33
+
34
+ def _opencr_version() -> str:
35
+ import opencr
36
+
37
+ return opencr.__version__
38
+
39
+
40
+ class Result:
41
+ """A steady state.
42
+
43
+ Attributes:
44
+ model: The model solved.
45
+ conditions: The conditions.
46
+ rates: The rate coefficient of every reaction (SI), in network order.
47
+ system: The population equations.
48
+ evolving: The steady densities of the evolving states (m^-3).
49
+ report: The solver's report.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ model: Model,
55
+ conditions: Conditions,
56
+ rates: np.ndarray,
57
+ system: PopulationSystem,
58
+ evolving: np.ndarray,
59
+ report: SolverReport,
60
+ ) -> None:
61
+ """Store the solution."""
62
+ self.model = model
63
+ self.conditions = conditions
64
+ self.rates = rates
65
+ self.system = system
66
+ self.evolving = np.asarray(evolving, dtype=float)
67
+ self.report = report
68
+
69
+ @property
70
+ def mode(self) -> str:
71
+ """The solve: ``"quasi-static"`` or ``"full"``."""
72
+ return self.report.mode
73
+
74
+ @cached_property
75
+ def populations(self) -> dict[str, float]:
76
+ """The density of every state in m^-3, by name, in network order."""
77
+ densities = self.system.densities(self.evolving)
78
+ return {name: densities[name] for name in self.model.state_names}
79
+
80
+ def population(self, state: str) -> float:
81
+ """Return the density of ``state`` in m^-3."""
82
+ return self.populations[state]
83
+
84
+ @property
85
+ def electron_density(self) -> float:
86
+ """``n_e`` in m^-3."""
87
+ return self.system.electron_density(self.evolving)
88
+
89
+ @cached_property
90
+ def reduction(self) -> QuasiStatic:
91
+ """The quasi-static reduction at these conditions (population and effective coefficients)."""
92
+ from opencr.kinetics.effective import quasi_static
93
+
94
+ conditions = self.conditions
95
+ if conditions.quasi_neutral:
96
+ conditions = conditions.replace(electron_density=self.electron_density)
97
+ return quasi_static(self.model.network, self.rates, conditions)
98
+
99
+ @cached_property
100
+ def fluxes(self) -> dict[str, float]:
101
+ """The rate of every reaction in m^-3 s^-1, by name."""
102
+ w = self.system.reaction_rates(self.evolving)
103
+ return dict(zip(self.model.evaluator.names, w.tolist(), strict=True))
104
+
105
+ def dominant_processes(self, state: str, number: int = 5) -> list[dict[str, Any]]:
106
+ """Return the largest gains and losses of ``state``.
107
+
108
+ Each entry has the reaction ``name``, its ``equation``, the ``rate`` of
109
+ change of the state (m^-3 s^-1; negative for a loss) and its ``fraction``
110
+ of the state's total gain or total loss. Sorted by ``|rate|``.
111
+ """
112
+ entries = []
113
+ for reaction in self.model.network.reactions_of(state):
114
+ rate = reaction.net[state] * self.fluxes[reaction.name]
115
+ entries.append(
116
+ {"name": reaction.name, "equation": reaction.equation, "rate": rate}
117
+ )
118
+ gain = sum(e["rate"] for e in entries if e["rate"] > 0)
119
+ loss = -sum(e["rate"] for e in entries if e["rate"] < 0)
120
+ for entry in entries:
121
+ total = gain if entry["rate"] > 0 else loss
122
+ entry["fraction"] = abs(entry["rate"]) / total if total > 0 else 0.0
123
+ entries.sort(key=lambda e: -abs(e["rate"]))
124
+ return entries[:number]
125
+
126
+ def emission(self, air: bool = False) -> xr.Dataset:
127
+ """Return the lines: wavelength, emissivity and power (`line_table`)."""
128
+ return line_table(self.model.network, self.rates, self.populations, air)
129
+
130
+ @method(
131
+ equations={
132
+ "pec": r"\mathrm{PEC}_d = \frac{g\, A_{ul}\, C_{ud}}{n_e} \quad [\mathrm{m^3/s}], \qquad \epsilon = n_e \sum_d \mathrm{PEC}_d\, n_d",
133
+ },
134
+ assumptions=(
135
+ r"a quasi-static solve: $n_u = \sum_d C_{ud} n_d$; zero for a line whose upper state is a driver",
136
+ r"for atomic hydrogen the H(n=1) part is the excitation component, the H$^+$ part the recombination one",
137
+ ),
138
+ references=(
139
+ "[Summers et al., Plasma Phys. Control. Fusion 48, 263 (2006)](https://doi.org/10.1088/0741-3335/48/2/007)",
140
+ ),
141
+ components=(
142
+ "opencr.kinetics.effective.quasi_static",
143
+ "opencr.analysis.emission.line_table",
144
+ ),
145
+ )
146
+ def photon_emissivity_coefficients(self) -> xr.DataArray:
147
+ """Return ``PEC_d`` of every line per driver in m^3/s (quasi-static only).
148
+
149
+ ``emissivity = n_e sum_d PEC_d n_d``; for atomic hydrogen the ``H(n=1)``
150
+ part is the excitation component and the ``H+`` part the recombination one.
151
+ """
152
+ reduction = self.reduction
153
+ lines = self.emission()
154
+ values = np.zeros((lines.sizes["line"], len(reduction.drivers)))
155
+ names = self.model.evaluator.names
156
+ for i, (line, upper) in enumerate(
157
+ zip(lines["line"].values, lines["upper"].values, strict=True)
158
+ ):
159
+ if upper in reduction.drivers:
160
+ continue
161
+ row = reduction.coefficients[reduction.excited.index(upper)]
162
+ values[i] = self.rates[names.index(line)] * row / reduction.electron_density
163
+ return xr.DataArray(
164
+ values,
165
+ coords={
166
+ "line": lines["line"].values,
167
+ "driver": list(reduction.drivers),
168
+ "label": ("line", lines["label"].values),
169
+ },
170
+ dims=("line", "driver"),
171
+ name="pec",
172
+ attrs={"units": "m^3 s^-1"},
173
+ )
174
+
175
+ def emission_spectrum(
176
+ self,
177
+ wavelength: np.ndarray | None = None,
178
+ fwhm: float = 0.0,
179
+ air: bool = False,
180
+ quantity: str = "power",
181
+ ) -> xr.DataArray:
182
+ """Return a synthetic spectrum: the lines Doppler broadened at the gas temperature.
183
+
184
+ Args:
185
+ wavelength: The grid in nm; by default 2000 points around the visible
186
+ lines (350-700 nm).
187
+ fwhm: An instrumental FWHM in nm, added in quadrature.
188
+ air: Wavelengths in air.
189
+ quantity: ``"power"`` or ``"emissivity"``.
190
+ """
191
+ if wavelength is None:
192
+ wavelength = np.linspace(350.0, 700.0, 2000)
193
+ lines = self.emission(air)
194
+ mass = self.model.network.species[0].mass
195
+ return spectrum(
196
+ lines, wavelength, self.conditions.gas_temperature, mass, fwhm, quantity
197
+ )
198
+
199
+ def to_dataset(self) -> xr.Dataset:
200
+ """Return the populations, rates, fluxes and lines as one xarray dataset.
201
+
202
+ The conditions, the solver report and the model's manifest are in the
203
+ attributes, as JSON.
204
+ """
205
+ names = list(self.model.state_names)
206
+ reactions = list(self.model.evaluator.names)
207
+ lines = self.emission()
208
+ data = xr.Dataset(
209
+ {
210
+ "population": (
211
+ "state",
212
+ [self.populations[n] for n in names],
213
+ {"units": "m^-3"},
214
+ ),
215
+ "rate_coefficient": (
216
+ "reaction",
217
+ self.rates,
218
+ {"units": "SI (m^3(k-1)/s)"},
219
+ ),
220
+ "flux": (
221
+ "reaction",
222
+ [self.fluxes[r] for r in reactions],
223
+ {"units": "m^-3 s^-1"},
224
+ ),
225
+ "line_wavelength": (
226
+ "line",
227
+ lines["wavelength"].values,
228
+ {"units": "nm"},
229
+ ),
230
+ "line_emissivity": (
231
+ "line",
232
+ lines["emissivity"].values,
233
+ {"units": "photons m^-3 s^-1"},
234
+ ),
235
+ },
236
+ coords={
237
+ "state": names,
238
+ "reaction": reactions,
239
+ "line": lines["line"].values.astype(str),
240
+ },
241
+ attrs={
242
+ "model": self.model.name,
243
+ "solve": self.mode,
244
+ "electron_density": self.electron_density,
245
+ "conditions": json.dumps(self.conditions.to_dict()),
246
+ "report": self.report.summary(),
247
+ "manifest": json.dumps(self.model.manifest()),
248
+ "opencr_version": _opencr_version(),
249
+ },
250
+ )
251
+ return data
252
+
253
+ def export(self, path: str | Path) -> Path:
254
+ """Write `to_dataset` to a NetCDF file and return its path."""
255
+ path = Path(path)
256
+ self.to_dataset().to_netcdf(path, engine="scipy")
257
+ return path
258
+
259
+ def __repr__(self) -> str:
260
+ """The model, the mode and the conditions."""
261
+ return (
262
+ f"Result({self.model.name!r}, {self.report.mode}, "
263
+ f"Te={self.conditions.electron_temperature:g} eV, ne={self.electron_density:.3g} m^-3)"
264
+ )