Skip to content
Projects

opencr.inference

Sensitivities, uncertainty propagation and inverse modelling on top of the solver.

  • sensitivities and propagate (opencr.inference.sensitivity): how results depend on the rate data, and their uncertainty from the data’s;
  • posterior_grid and fit (opencr.inference.inverse): plasma parameters from measured quantities such as line ratios.

Classes

NameDescription
FitThe maximum of the posterior.
ObservationA measured quantity.
PropagationThe propagated uncertainty of some quantities.

Functions

NameDescription
data_uncertaintiesReturn the relative uncertainty of each reaction's data from its provenance.
fitReturn the maximum of the posterior by least squares in the log parameters.
forward_modelReturn the forward model theta -> quantities of a CR model.
posterior_gridReturn the posterior on a log-spaced grid of the parameters.
propagatePropagate the uncertainties of the rate data to the quantities outputs.
sensitivitiesReturn d ln q / d ln k_r of the quantities outputs.

Modules

  • inverseInverse modelling: plasma parameters from measured quantities such as line ratios.
  • sensitivitySensitivities of CR results to the rate data, and the propagation of their uncertainties.

Fitclassdataclass#

class Fit(parameters: dict[str, float], log_std: dict[str, float], chi2: float, success: bool)

The maximum of the posterior.

Attributes

NameTypeDescription
parametersdict[str, float]The best values by name.
log_stddict[str, float]The standard deviation of each parameter’s logarithm from the curvature (the Gauss-Newton covariance), by name.
chi2floatThe chi^2 at the best values.
successboolWhether the least-squares solver converged.

chi2attributeinstance attribute#

chi2: float

log_stdattributeinstance attribute#

log_std: dict[str, float]

parametersattributeinstance attribute#

parameters: dict[str, float]

successattributeinstance attribute#

success: bool

Observationclassdataclass#

class Observation(quantity: str, value: float, uncertainty: float = 0.1)

A measured quantity.

Attributes

NameTypeDescription
quantitystrThe name of the quantity.
valuefloatThe measured value.
uncertaintyfloatThe standard deviation of its logarithm (about the relative uncertainty).

quantityattributeinstance attribute#

quantity: str

uncertaintyattributeclass attributeinstance attribute#

uncertainty: float = 0.1

valueattributeinstance attribute#

value: float

Propagationclassdataclass#

class Propagation(outputs: tuple[str, ...], nominal: np.ndarray, relative: np.ndarray, contributions: xr.DataArray | None, samples: np.ndarray | None, method: str)

The propagated uncertainty of some quantities.

Attributes

NameTypeDescription
outputstuple[str, ...]The quantity names.
nominalnp.ndarrayThe nominal values.
relativenp.ndarrayThe relative (log) standard deviations, sigma(ln q).
contributionsxr.DataArray | NoneFor the linear method, (S_qr sigma_r)^2 over (output, reaction); None for Monte Carlo.
samplesnp.ndarray | NoneFor Monte Carlo, the sampled values (sample, output).
methodstr"linear" or "monte-carlo".

contributionsattributeinstance attribute#

contributions: xr.DataArray | None

methodattributeinstance attribute#

method: str

nominalattributeinstance attribute#

nominal: np.ndarray

outputsattributeinstance attribute#

outputs: tuple[str, ...]

relativeattributeinstance attribute#

relative: np.ndarray

samplesattributeinstance attribute#

samples: np.ndarray | None

dominantmethod#

def dominant(output: str, number: int = 5) -> list[tuple[str, float]]

Return the reactions contributing most to the variance of output (linear only).

intervalmethod#

def interval(coverage: float = 0.68) -> tuple[np.ndarray, np.ndarray]

Return the (lower, upper) bounds of a log-normal interval of coverage.

to_datasetmethod#

def to_dataset() -> xr.Dataset

Return the nominal values and the relative uncertainties as a dataset.

data_uncertaintiesfunction#

def data_uncertainties(model: Model, default: float | None = None) -> dict[str, float]

Return the relative uncertainty of each reaction’s data from its provenance.

Reactions without a stated uncertainty get default (or are left out when it is None); detailed-balance inverses are never listed.

fitfunction#

def fit(forward: Forward, observations: Sequence[Observation], bounds: Mapping[str, tuple[float, float]], start: Mapping[str, float] | None = None) -> Fit

Return the maximum of the posterior by least squares in the log parameters.

Parameters

NameTypeDefaultDescription
forwardForwardrequiredThe forward model, taking the parameters in the order of bounds.
observationsSequence[Observation]requiredThe measurements.
boundsMapping[str, tuple[float, float]]requiredThe prior range of each parameter; a condition field’s in its unit (eV, m^-3) or as quantities.
startMapping[str, float] | NoneNoneStarting values (default: the geometric centre of each range), in the units of bounds.

forward_modelfunction#

def forward_model(model: Model, conditions: Conditions, parameters: Sequence[str], outputs: Sequence[str], mode: str = 'quasi-static') -> Forward

Return the forward model theta -> quantities of a CR model.

Parameters

NameTypeDefaultDescription
modelModelrequiredThe model.
conditionsConditionsrequiredThe conditions the parameters are set in.
parametersSequence[str]requiredThe condition fields (as for opencr.scan).
outputsSequence[str]requiredThe quantities.
modestr'quasi-static'The steady-state mode.

posterior_gridfunction#

def posterior_grid(forward: Forward, observations: Sequence[Observation], bounds: Mapping[str, tuple[float, float]], points: int = 25) -> xr.Dataset

Return the posterior on a log-spaced grid of the parameters.

Parameters

NameTypeDefaultDescription
forwardForwardrequiredThe forward model, taking the parameters in the order of bounds.
observationsSequence[Observation]requiredThe measurements.
boundsMapping[str, tuple[float, float]]requiredThe prior range of each parameter; a condition field’s in its unit (eV, m^-3) or as quantities.
pointsint25The grid points per parameter.

Returns

xr.Dataset
A dataset with posterior (normalised over the grid, per log cell),
xr.Dataset
chi2, and the attributes best (the grid maximum) and the
xr.Dataset
posterior mean and std of each parameter’s logarithm.

propagatefunction#

def propagate(model: Model, conditions: Conditions, outputs: Sequence[str], uncertainties: Mapping[str, float] | None = None, method: str = 'linear', samples: int = 200, seed: int = 0, mode: str = 'quasi-static', **options: Any) -> Propagation

Propagate the uncertainties of the rate data to the quantities outputs.

Parameters

NameTypeDefaultDescription
modelModelrequiredThe model.
conditionsConditionsrequiredThe conditions of the steady state.
outputsSequence[str]requiredNames of quantities.
uncertaintiesMapping[str, float] | NoneNoneRelative (1 sigma, log-normal) uncertainty by reaction name; by default data_uncertainties of the model.
methodstr'linear'"linear" (first order, through sensitivities) or "monte-carlo" (independent log-normal factors).
samplesint200The number of Monte Carlo samples.
seedint0The seed of the Monte Carlo samples.
modestr'quasi-static'The steady-state mode.
**optionsAny{}Passed on to sensitivities (step).

Numerics

linear

σ2(ln⁡q)=∑rSqr2 σr2\sigma^2(\ln q) = \sum_r S_{qr}^2\, \sigma_r^2

monte carlo

kr←kr eσrξr,ξr∼N(0,1),σ(ln⁡q)=std(ln⁡q)k_r \leftarrow k_r\, e^{\sigma_r \xi_r}, \quad \xi_r \sim \mathcal N(0, 1), \qquad \sigma(\ln q) = \mathrm{std}(\ln q)

interval

[q e−zσ, q ezσ],z=Φ−1(12+coverage2)\big[q\, e^{-z\sigma},\ q\, e^{z\sigma}\big], \qquad z = \Phi^{-1}\big(\tfrac12 + \tfrac{\mathrm{coverage}}{2}\big)

Assumptions:

  • independent, log-normal data uncertainties σr\sigma_r (1 sigma), from each reaction’s provenance by default
  • the uncertainty of the data only, not of a surrogate

Built from:

  • opencr.inference.sensitivity.sensitivities

sensitivitiesfunction#

def sensitivities(model: Model, conditions: Conditions, outputs: Sequence[str], reactions: Sequence[str] | None = None, mode: str = 'quasi-static', step: float = 0.01) -> xr.DataArray

Return d ln q / d ln k_r of the quantities outputs.

Parameters

NameTypeDefaultDescription
modelModelrequiredThe model.
conditionsConditionsrequiredThe conditions of the steady state.
outputsSequence[str]requiredNames of quantities (opencr.analysis.quantities).
reactionsSequence[str] | NoneNoneThe reactions to perturb; by default every reaction that is not a detailed-balance inverse.
modestr'quasi-static'The steady-state mode.
stepfloat0.01The step in ln k.

Returns

xr.DataArray
A DataArray over (output, reaction).

Numerics

sensitivity

Sqr=∂ln⁡q∂ln⁡kr≈ln⁡q(kreh)−ln⁡q(kre−h)2hS_{qr} = \frac{\partial \ln q}{\partial \ln k_r} \approx \frac{\ln q(k_r e^{h}) - \ln q(k_r e^{-h})}{2h}

Order of accuracy: 2.

Assumptions:

  • central differences in ln⁡kr\ln k_r, step hh = step (0.01 by default); the order is in hh
  • a detailed-balance inverse moves with its forward reaction (Model.scaled_rates), so detailed balance holds

Built from:

  • opencr.model.Model.scaled_rates