Skip to content
Projects

opencr

Type part of a name or a dotted path

OpenCR: collisional-radiative models of low-temperature plasmas.

OpenCR builds collisional-radiative (CR) models from explicit states and reactions with traceable data, and solves their population equations: steady states, quasi-static excited states with effective rate coefficients, and time evolution. The physics is defined independently of the numerical backend; the reference implementation uses NumPy and SciPy, cunumpy and JAX are optional. Cross sections and Maxwellian rates come from plasmacoll.

Classes

NameDescription
ConditionsPlasma conditions, SI with temperatures in eV.
ModelA reaction network with its default drivers.
RadiationTrappingThe escape-factor configuration of a solve (see opencr.kinetics.radiation).
ResultA steady state.

Functions

NameDescription
available_modelsReturn the names of the predefined models with one sentence each.
load_modelReturn the predefined model name built with options.
scanSolve model on a grid of conditions.

Modules

  • analysisResults and what can be read from them.
  • backendsThe array layer: cunumpy, with explicit execution boundaries.
  • cliThe opencr command: list the predefined models and print their manifests.
  • constantsPhysical constants (CODATA 2018, through scipy.constants) and unit helpers.
  • coreModel definitions independent of any array backend.
  • dataPhysical data with provenance.
  • inferenceSensitivities, uncertainty propagation and inverse modelling on top of the solver.
  • kineticsFrom a network and conditions to numbers.
  • mlOptional machine-learning surrogates of the CR solver. Imports scikit-learn only when used.
  • modelA CR model: a reaction network with its drivers, and the solves on it.
  • modelsPredefined models, loaded by name with load_model.
  • solversSteady-state solutions of the population equations.
  • tablesEffective-rate tables for the codes that use OpenCR's results.

Conditionsclassdataclass#

class Conditions(electron_temperature: float = unit_field('eV'), electron_density: float | None = unit_field('m-3', None), eedf: Any = None, densities: Mapping[str, float] = unit_field('m-3', default_factory=dict), totals: Mapping[str, float] = unit_field('m-3', default_factory=dict), ion_temperature: float | None = unit_field('eV', None), gas_temperature: float = unit_field('eV', 0.026), escape: Mapping[str, float] = dict(), trapping: RadiationTrapping | None = None)

Plasma conditions, SI with temperatures in eV.

The temperatures and densities take quantities (see the module docstring): Conditions("300 K", 1e12 * u.cm**-3).

Attributes

NameTypeDescription
electron_temperaturefloatkT_e in eV. With a non-Maxwellian eedf it is the temperature of the rates that are not cross sections and of detailed balance; from_eedf sets it to 2/3 <eps>.
electron_densityfloat | Nonen_e in m^-3, or None for quasi-neutrality, n_e = sum z_i n_i over every charged state (evolving and prescribed).
eedfAnyThe electron energy distribution (an opencr.kinetics.eedf.EEDF), or None for a Maxwellian at electron_temperature.
densitiesMapping[str, float]Densities in m^-3 of the prescribed states, by name: the drivers of a quasi-static solve (e.g. H(n=1) and H+) and fixed backgrounds (e.g. H2 in an atomic model).
totalsMapping[str, float]For a closed steady state, the total density of each element in m^-3 over the evolving states, e.g. {"H": 1e19}.
ion_temperaturefloat | NonekT_i in eV; the gas temperature if None.
gas_temperaturefloatkT of the neutral gas in eV (0.026 eV is 300 K).
escapeMapping[str, float]Escape factors in [0, 1] by reaction name, overriding the reactions’ own and anything trapping computes.
trappingRadiationTrapping | NoneCompute the escape factors of the lines self-consistently from the populations (opencr.kinetics.radiation); None for an optically thin plasma (apart from escape).

densitiesattributeclass attributeinstance attribute#

densities: Mapping[str, float] = unit_field('m-3', default_factory=dict)

eedfattributeclass attributeinstance attribute#

eedf: Any = None

electron_densityattributeclass attributeinstance attribute#

electron_density: float | None = unit_field('m-3', None)

electron_temperatureattributeclass attributeinstance attribute#

electron_temperature: float = unit_field('eV')

escapeattributeclass attributeinstance attribute#

escape: Mapping[str, float] = field(default_factory=dict)

gas_temperatureattributeclass attributeinstance attribute#

gas_temperature: float = unit_field('eV', 0.026)

ion_temperatureattributeclass attributeinstance attribute#

ion_temperature: float | None = unit_field('eV', None)

totalsattributeclass attributeinstance attribute#

totals: Mapping[str, float] = unit_field('m-3', default_factory=dict)

trappingattributeclass attributeinstance attribute#

trapping: RadiationTrapping | None = None

heavy_temperatureproperty#

heavy_temperature: dict[str, float]

The temperature of each kind of rate dependence (see opencr.core.rates).

quasi_neutralproperty#

quasi_neutral: bool

Whether n_e follows from quasi-neutrality.

from_eedfmethodclassmethod#

def from_eedf(eedf: Any, **kwargs: Any) -> Conditions

Return conditions with eedf and its effective temperature 2/3 <eps>.

replacemethod#

def replace(**changes: Any) -> Conditions

Return a copy with changes applied.

to_dictmethod#

def to_dict() -> dict[str, Any]

Return the conditions as plain data (the EEDF by its description).

Modelclass#

Re-exported from opencr.modelView source
class Model(network: ReactionNetwork, drivers: Sequence[str] = (), description: str = '')

A reaction network with its default drivers.

Parameters

NameTypeDefaultDescription
networkReactionNetworkrequiredThe reaction network.
driversSequence[str]()The states a quasi-static solve needs densities for (for atomic hydrogen H(n=1) and H+); checked against the conditions.
descriptionstr''One sentence on what the model is.

descriptionattributeinstance attribute#

description = description

driversattributeinstance attribute#

drivers = tuple(drivers)

evaluatorattributeinstance attribute#

evaluator = RateEvaluator(network)

networkattributeinstance attribute#

network = network

nameproperty#

name: str

The network’s name.

state_namesproperty#

state_names: tuple[str, ...]

The state names.

effective_ratesmethod#

def effective_rates(conditions: Conditions) -> QuasiStatic

Return the quasi-static reduction with the prescribed states of conditions.

manifestmethod#

def manifest() -> dict[str, Any]

Return the network’s manifest with the drivers and the description.

rate_coefficientsmethod#

def rate_coefficients(conditions: Conditions) -> dict[str, float]

Return every reaction’s rate coefficient (SI) by name.

scaled_ratesmethod#

def scaled_rates(conditions: Conditions, factors: Mapping[str, float] | None = None) -> np.ndarray

Return the rate coefficients with some multiplied by factors (by name).

A detailed-balance inverse takes the factor of its forward reaction (unless it has its own), so the scaled network keeps detailed balance: this is what sensitivities and uncertainty propagation perturb.

Numerics

scaled

kr←fr kr,finv=ffwd for a detailed-balance inverse without a factor of its ownk_r \leftarrow f_r\, k_r, \qquad f_{\mathrm{inv}} = f_{\mathrm{fwd}} \ \text{for a detailed-balance inverse without a factor of its own}

Assumptions:

  • an inverse moves with its forward reaction, so the scaled network keeps detailed balance: what sensitivities and uncertainty propagation perturb

solve_steady_statemethod#

def solve_steady_state(conditions: Conditions, mode: str = 'quasi-static', initial: dict[str, float] | None = None, rtol: float = 1e-09, factors: Mapping[str, float] | None = None)

Return the steady state as a Result.

Parameters

NameTypeDefaultDescription
conditionsConditionsrequiredThe conditions. In "quasi-static" mode the drivers need densities; in "full" mode the conserved elements need totals.
modestr'quasi-static'One of MODES.
initialdict[str, float] | NoneNoneStarting densities by state name for a nonlinear solve, in m^-3 (or quantities).
rtolfloat1e-09The tolerance of the relative residual.
factorsMapping[str, float] | NoneNoneMultiply the rate coefficients of these reactions (by name) by these factors (see scaled_rates).

Numerics

fixed point

gnew(k)=g(τ0[nl(g(k))]),given factors override computed ones line by lineg^{(k)}_{\mathrm{new}} = g\big(\tau_0[n_l(g^{(k)})]\big), \qquad \text{given factors override computed ones line by line}

update

g(k+1)=g(k)+d (gnew(k)−g(k)),d=1→0.5 once the largest change growsg^{(k+1)} = g^{(k)} + d\,\big(g^{(k)}_{\mathrm{new}} - g^{(k)}\big), \qquad d = 1 \to 0.5 \ \text{once the largest change grows}

stop

max⁡lines∣gnew(k)−g(k)∣≤tolerance\max_{\mathrm{lines}} \big|g^{(k)}_{\mathrm{new}} - g^{(k)}\big| \le \texttt{tolerance}

Assumptions:

  • only with Conditions.trapping: the first solve is optically thin apart from the given factors (an absent gg counts as 1)
  • the result returned was solved with the previous factors; at max_iterations a ConvergenceError is raised
  • the damping never goes back to 1

Built from:

  • opencr.solvers.steady.solve_steady
  • opencr.kinetics.radiation.escape_factors

solve_transientmethod#

def solve_transient(conditions: Conditions | Callable[[float], Conditions], initial: dict[str, float], times: np.ndarray, method: str = 'BDF', rtol: float = 1e-06, atol: float | None = None)

Return the populations against time as a TransientResult.

The states with a density in the conditions stay prescribed (constant, or following conditions(t)); the others evolve from initial. initial, times and atol take astropy quantities or strings such as "1 us" as well as numbers in their documented units.

Parameters

NameTypeDefaultDescription
conditionsConditions | Callable[[float], Conditions]requiredThe conditions, or a function of the time in s returning them (same prescribed states at every time).
initialdict[str, float]requiredThe densities in m^-3 at times[0] by state name; an evolving state not listed starts empty.
timesnp.ndarrayrequiredThe output times in s, increasing.
methodstr'BDF'"BDF" (default), "Radau" or "LSODA".
rtolfloat1e-06The relative tolerance.
atolfloat | NoneNoneThe absolute tolerance in m^-3 (default 1e-12 of the largest initial, prescribed or total density).

systemmethod#

def system(conditions: Conditions, rates: np.ndarray | None = None) -> PopulationSystem

Return the population equations with the prescribed states of conditions.

RadiationTrappingclassdataclass#

class RadiationTrapping(length: float = unit_field('m'), model: str = 'mewe', lines: tuple[str, ...] | None = None, tolerance: float = 1e-06, max_iterations: int = 100)

The escape-factor configuration of a solve (see opencr.kinetics.radiation).

The length takes a quantity (see the module docstring).

Attributes

NameTypeDescription
lengthfloatThe absorption length L in m (the distance to the wall).
modelstrOne of ESCAPE_MODELS.
linestuple[str, ...] | NoneThe names of the spontaneous_emission reactions to trap, or None for all of them.
tolerancefloatThe self-consistent iteration stops when no escape factor changes by more than this.
max_iterationsintThe limit of that iteration.

lengthattributeclass attributeinstance attribute#

length: float = unit_field('m')

linesattributeclass attributeinstance attribute#

lines: tuple[str, ...] | None = None

max_iterationsattributeclass attributeinstance attribute#

max_iterations: int = 100

modelattributeclass attributeinstance attribute#

model: str = 'mewe'

toleranceattributeclass attributeinstance attribute#

tolerance: float = 1e-06

to_dictmethod#

def to_dict() -> dict[str, Any]

Return the configuration as plain data.

Resultclass#

class Result(model: Model, conditions: Conditions, rates: np.ndarray, system: PopulationSystem, evolving: np.ndarray, report: SolverReport)

A steady state.

Attributes

NameDescription
modelThe model solved.
conditionsThe conditions.
ratesThe rate coefficient of every reaction (SI), in network order.
systemThe population equations.
evolvingThe steady densities of the evolving states (m^-3).
reportThe solver’s report.

conditionsattributeinstance attribute#

conditions = conditions

evolvingattributeinstance attribute#

evolving = np.asarray(evolving, dtype=float)

modelattributeinstance attribute#

model = model

ratesattributeinstance attribute#

rates = rates

reportattributeinstance attribute#

report = report

systemattributeinstance attribute#

system = system

electron_densityproperty#

electron_density: float

n_e in m^-3.

fluxespropertycached#

fluxes: dict[str, float]

The rate of every reaction in m^-3 s^-1, by name.

modeproperty#

mode: str

The solve: "quasi-static" or "full".

populationspropertycached#

populations: dict[str, float]

The density of every state in m^-3, by name, in network order.

reductionpropertycached#

reduction: QuasiStatic

The quasi-static reduction at these conditions (population and effective coefficients).

dominant_processesmethod#

def dominant_processes(state: str, number: int = 5) -> list[dict[str, Any]]

Return the largest gains and losses of state.

Each entry has the reaction name, its equation, the rate of change of the state (m^-3 s^-1; negative for a loss) and its fraction of the state’s total gain or total loss. Sorted by |rate|.

emissionmethod#

def emission(air: bool = False) -> xr.Dataset

Return the lines: wavelength, emissivity and power (line_table).

emission_spectrummethod#

def emission_spectrum(wavelength: np.ndarray | None = None, fwhm: float = 0.0, air: bool = False, quantity: str = 'power') -> xr.DataArray

Return a synthetic spectrum: the lines Doppler broadened at the gas temperature.

Parameters

NameTypeDefaultDescription
wavelengthnp.ndarray | NoneNoneThe grid in nm; by default 2000 points around the visible lines (350-700 nm).
fwhmfloat0.0An instrumental FWHM in nm, added in quadrature.
airboolFalseWavelengths in air.
quantitystr'power'"power" or "emissivity".

exportmethod#

def export(path: str | Path) -> Path

Write to_dataset to a NetCDF file and return its path.

photon_emissivity_coefficientsmethod#

def photon_emissivity_coefficients() -> xr.DataArray

Return PEC_d of every line per driver in m^3/s (quasi-static only).

emissivity = n_e sum_d PEC_d n_d; for atomic hydrogen the H(n=1) part is the excitation component and the H+ part the recombination one.

Numerics

pec

PECd=g Aul Cudne[m3/s],ϵ=ne∑dPECd nd\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

Assumptions:

  • a quasi-static solve: nu=∑dCudndn_u = \sum_d C_{ud} n_d; zero for a line whose upper state is a driver
  • for atomic hydrogen the H(n=1) part is the excitation component, the H+^+ part the recombination one

References:

Built from:

  • opencr.kinetics.effective.quasi_static
  • opencr.analysis.emission.line_table

populationmethod#

def population(state: str) -> float

Return the density of state in m^-3.

to_datasetmethod#

def to_dataset() -> xr.Dataset

Return the populations, rates, fluxes and lines as one xarray dataset.

The conditions, the solver report and the model’s manifest are in the attributes, as JSON.

available_modelsfunction#

Re-exported from opencr.modelsView source
def available_models() -> dict[str, str]

Return the names of the predefined models with one sentence each.

load_modelfunction#

Re-exported from opencr.modelsView source
def load_model(name: str, **options: Any) -> Model

Return the predefined model name built with options.

scanfunction#

def scan(model: Model, conditions: Conditions, mode: str = 'quasi-static', effective: bool = True, lines: bool = True, **axes: Sequence[float]) -> xr.Dataset

Solve model on a grid of conditions.

Parameters

NameTypeDefaultDescription
modelModelrequiredThe model.
conditionsConditionsrequiredThe conditions every point starts from.
modestr'quasi-static'The steady-state mode.
effectiveboolTrueAdd effective_rate (target driver, source driver) and, with lines, pec (line, driver) for quasi-static solves.
linesboolTrueAdd the line emissivities.
**axesSequence[float]{}The condition fields to scan and their values, e.g. electron_temperature=np.geomspace(0.5, 50, 20). Use {"density:H(n=1)": [...]} or {"total:H": [...]} unpacked with **. The values are in eV or m^-3, or quantities.

Returns

xr.Dataset
A dataset over the axes (and state, line, driver).