# opencr.inference

*module*

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.

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/__init__.py#L1-L1)

## opencr.inference.Fit

*class* · *dataclass*

```python
class Fit
```

Re-exported from: `opencr.inference.inverse`

The maximum of the posterior.

**Attributes**

- `parameters` (`dict[str, float]`) — The best values by name.
- `log_std` (`dict[str, float]`) — The standard deviation of each parameter's logarithm from the curvature (the Gauss-Newton covariance), by name.
- `chi2` (`float`) — The chi^2 at the best values.
- `success` (`bool`) — Whether the least-squares solver converged.

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L161-L176)

### opencr.inference.Fit.chi2

*attribute* · *instance attribute*

```python
chi2: float
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L175-L175)

### opencr.inference.Fit.log_std

*attribute* · *instance attribute*

```python
log_std: dict[str, float]
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L174-L174)

### opencr.inference.Fit.parameters

*attribute* · *instance attribute*

```python
parameters: dict[str, float]
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L173-L173)

### opencr.inference.Fit.success

*attribute* · *instance attribute*

```python
success: bool
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L176-L176)

## opencr.inference.Observation

*class* · *dataclass*

```python
class Observation
```

Re-exported from: `opencr.inference.inverse`

A measured quantity.

**Attributes**

- `quantity` (`str`) — The name of the quantity.
- `value` (`float`) — The measured value.
- `uncertainty` (`float`) — The standard deviation of its logarithm (about the relative uncertainty).

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L40-L60)

### opencr.inference.Observation.quantity

*attribute* · *instance attribute*

```python
quantity: str
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L51-L51)

### opencr.inference.Observation.uncertainty

*attribute* · *class attribute* · *instance attribute*

```python
uncertainty: float = 0.1
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L53-L53)

### opencr.inference.Observation.value

*attribute* · *instance attribute*

```python
value: float
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L52-L52)

## opencr.inference.Propagation

*class* · *dataclass*

```python
class Propagation
```

Re-exported from: `opencr.inference.sensitivity`

The propagated uncertainty of some quantities.

**Attributes**

- `outputs` (`tuple[str, ...]`) — The quantity names.
- `nominal` (`np.ndarray`) — The nominal values.
- `relative` (`np.ndarray`) — The relative (log) standard deviations, ``sigma(ln q)``.
- `contributions` (`xr.DataArray | None`) — For the linear method, ``(S_qr sigma_r)^2`` over (``output``, ``reaction``); ``None`` for Monte Carlo.
- `samples` (`np.ndarray | None`) — For Monte Carlo, the sampled values (sample, output).
- `method` (`str`) — ``"linear"`` or ``"monte-carlo"``.

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L155-L209)

### opencr.inference.Propagation.contributions

*attribute* · *instance attribute*

```python
contributions: xr.DataArray | None
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L172-L172)

### opencr.inference.Propagation.method

*attribute* · *instance attribute*

```python
method: str
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L174-L174)

### opencr.inference.Propagation.nominal

*attribute* · *instance attribute*

```python
nominal: np.ndarray
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L170-L170)

### opencr.inference.Propagation.outputs

*attribute* · *instance attribute*

```python
outputs: tuple[str, ...]
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L169-L169)

### opencr.inference.Propagation.relative

*attribute* · *instance attribute*

```python
relative: np.ndarray
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L171-L171)

### opencr.inference.Propagation.samples

*attribute* · *instance attribute*

```python
samples: np.ndarray | None
```

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L173-L173)

### opencr.inference.Propagation.dominant

*method*

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

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

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L185-L198)

### opencr.inference.Propagation.interval

*method*

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

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

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L176-L183)

### opencr.inference.Propagation.to_dataset

*method*

```python
def to_dataset() -> xr.Dataset
```

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

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L200-L209)

## opencr.inference.data_uncertainties

*function*

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

Re-exported from: `opencr.inference.sensitivity`

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.

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L138-L152)

## opencr.inference.fit

*function*

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

Re-exported from: `opencr.inference.inverse`

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

**Parameters**

- `forward` (`Forward`) — The forward model, taking the parameters in the order of ``bounds``.
- `observations` (`Sequence[Observation]`) — The measurements.
- `bounds` (`Mapping[str, tuple[float, float]]`) — The prior range of each parameter; a condition field's in its unit (eV, m^-3) or as quantities.
- `start` (`Mapping[str, float] | None`) (default: `None`) — Starting values (default: the geometric centre of each range), in the units of ``bounds``.

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L179-L222)

## opencr.inference.forward_model

*function*

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

Re-exported from: `opencr.inference.inverse`

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

**Parameters**

- `model` (`Model`) — The model.
- `conditions` (`Conditions`) — The conditions the parameters are set in.
- `parameters` (`Sequence[str]`) — The condition fields (as for `opencr.scan`).
- `outputs` (`Sequence[str]`) — The quantities.
- `mode` (`str`) (default: `'quasi-static'`) — The steady-state mode.

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L63-L88)

## opencr.inference.posterior_grid

*function*

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

Re-exported from: `opencr.inference.inverse`

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

**Parameters**

- `forward` (`Forward`) — The forward model, taking the parameters in the order of ``bounds``.
- `observations` (`Sequence[Observation]`) — The measurements.
- `bounds` (`Mapping[str, tuple[float, float]]`) — The prior range of each parameter; a condition field's in its unit (eV, m^-3) or as quantities.
- `points` (`int`) (default: `25`) — The 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.

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/inverse.py#L111-L158)

## opencr.inference.propagate

*function*

```python
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
```

Re-exported from: `opencr.inference.sensitivity`

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

**Parameters**

- `model` (`Model`) — The model.
- `conditions` (`Conditions`) — The conditions of the steady state.
- `outputs` (`Sequence[str]`) — Names of quantities.
- `uncertainties` (`Mapping[str, float] | None`) (default: `None`) — Relative (1 sigma, log-normal) uncertainty by reaction name; by default `data_uncertainties` of the model.
- `method` (`str`) (default: `'linear'`) — ``"linear"`` (first order, through `sensitivities`) or ``"monte-carlo"`` (independent log-normal factors).
- `samples` (`int`) (default: `200`) — The number of Monte Carlo samples.
- `seed` (`int`) (default: `0`) — The seed of the Monte Carlo samples.
- `mode` (`str`) (default: `'quasi-static'`) — The steady-state mode.
- `**options` (`Any`) (default: `{}`) — Passed on to `sensitivities` (``step``).

**Numerics**

*linear*

$$
\sigma^2(\ln q) = \sum_r S_{qr}^2\, \sigma_r^2
$$

*monte carlo*

$$
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*

$$
\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 $\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`

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L212-L274)

## opencr.inference.sensitivities

*function*

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

Re-exported from: `opencr.inference.sensitivity`

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

**Parameters**

- `model` (`Model`) — The model.
- `conditions` (`Conditions`) — The conditions of the steady state.
- `outputs` (`Sequence[str]`) — Names of quantities (`opencr.analysis.quantities`).
- `reactions` (`Sequence[str] | None`) (default: `None`) — The reactions to perturb; by default every reaction that is not a detailed-balance inverse.
- `mode` (`str`) (default: `'quasi-static'`) — The steady-state mode.
- `step` (`float`) (default: `0.01`) — The step in ``ln k``.

**Returns**

- (`xr.DataArray`) — A DataArray over (``output``, ``reaction``).

**Numerics**

*sensitivity*

$$
S_{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 k_r$, step $h$ = `step` (0.01 by default); the order is in $h$
- a detailed-balance inverse moves with its forward reaction (`Model.scaled_rates`), so detailed balance holds

Built from:

- `opencr.model.Model.scaled_rates`

[View source](https://github.com/max-models/OpenCR/blob/devel/src/opencr/inference/sensitivity.py#L82-L135)

**Modules**

- `opencr.inference.inverse`
- `opencr.inference.sensitivity`
