Skip to content

uncertainty.propagation

The propagation of uncertain values through simulations.

propagate runs the variables of an UncertaintyModel through one simulation or several scenarios: the draws of the variables (correlated, quasi-random, see sbmlsim.uncertainty.draws) are one dimension draw of a Scan, which Simulator.run simulates, so a model is compiled once and the points run in the pool. The result does not depend on the number of workers.

Scenarios with common random numbers. Several simulations, e.g. a control and a treatment, are run with the same draws, so a difference or a ratio of an output between them is paired and its Monte Carlo variance is much smaller than with independent draws (Glasserman 2003). An input variable is applied to the scenarios which declare it, at the same quantile of the distribution of every scenario, a parameter to every scenario.

Adaptive number of draws. Without n the propagation draws batches of quasi-random points, doubling their number (powers of two keep the balance of the Sobol points), until the half widths of the 95 % intervals of the mean, the standard deviation and the 5 % and 95 % quantiles of every output are at most rel_tol times the standard deviation of the output (0.1 by default, which takes about 2000 draws of a normal output and more of a skewed one, whose tail quantiles are less precise), after the adaptive Monte Carlo procedure of the GUM (JCGM 101:2008, 7.9), with the errors of sbmlsim.uncertainty.statistics, which are conservative for quasi-random draws; with hypotheses it draws until every hypothesis is decided after the adjustment for their multiplicity, which the anytime-valid statements of sbmlsim.uncertainty.testing allow (more draws never reverse a decision). At n_max (the last batch is cut to it) a warning says that the tolerance was not reached or which hypotheses are undecided. The history of the batches is recorded, and the result of the batches is the one of a single scan of all the draws: the same draws of Sobol or random points, the labels, the values and the errors of every batch.

Blocks and checkpoints. A Propagation of a given number of draws runs in blocks of draws (block_size), which run separately, e.g. as units on several machines, and merge to the result of the whole propagation: every block takes its rows of the points of the design of all the draws, so a Latin hypercube stays one hypercube. With a checkpoint directory every block, and every batch of the adaptive number of draws, is written as netCDF (<checkpoint>/<scenario>/draws-<start>-<stop>.nc, the name of the scenario percent-encoded) and read instead of simulated when it exists, so the blocks of separate instances merge and an interrupted propagation resumes with the same result; a block of another propagation (another model, engine, integrator settings, observables, kept timecourses, grid of times or draws) is refused. A ragged timecourse is padded to the longest block, as a run pads it to its longest point. Consecutive blocks of one instance run in spans of a block per worker of its simulator (Propagation.run_blocks), whose result is cut into the results of the blocks, each the one a block run alone gives.

The UncertaintyResult has the results of the scenarios, the variables and the record (seed, design, number of draws, history, covariances), and gives the summaries with their Monte Carlo errors, the values of an output over the draws and the contrasts between scenarios.

Glasserman P (2003). Monte Carlo Methods in Financial Engineering. Springer. JCGM 101:2008. Evaluation of measurement data, Supplement 1 to the Guide to the expression of uncertainty in measurement: propagation of distributions using a Monte Carlo method.

CheckpointMismatch

Bases: ValueError

A checkpoint file is the block of another propagation.

UncertaintyResult dataclass

UncertaintyResult(results, variables=list(), record=dict())

The result of a propagation, see the module.

Attributes:

Name Type Description
results dict[str, ScanResult]

scenario -> the result of the scan over the draws.

variables list[Variable]

the variables of the analysis.

record dict[str, Any]

what the propagation did, JSON types: the seed, the design, the number of draws, the history, the variables and the covariances.

scenarios property

scenarios

Get the names of the scenarios.

values

values(output, scenario=None)

Get the values of an output over the draws.

Parameters:

Name Type Description Default
output str

a variable of the result, e.g. pk.cmax or [C].

required
scenario str | None

the scenario, the only one by default.

None

Returns:

Type Description
DataArray

The values with the dimension draw (and the time of a

DataArray

timecourse), the unit in attrs["units"].

Raises:

Type Description
ValueError

for an output which the result does not have.

contrast

contrast(output, a, b, kind='ratio')

Get the paired contrast of an output between two scenarios.

The draws of the scenarios are the same, so the contrast of a draw is the effect of the scenarios for these values of the variables.

Parameters:

Name Type Description Default
output str

the output.

required
a str

the scenario of the numerator, or the minuend.

required
b str

the scenario of the denominator, or the subtrahend.

required
kind Literal['ratio', 'difference']

ratio (a / b) or difference (a - b).

'ratio'

Returns:

Type Description
DataArray

The contrast over the draws, named <output>:<a>/<b> or

DataArray

<output>:<a>-<b>.

Raises:

Type Description
ValueError

for another kind.

probability

probability(output, *, scenario=None, **kwargs)

Get the probability that an output satisfies a hypothesis.

Parameters:

Name Type Description Default
output str | DataArray

an output, or values over the draws, e.g. a contrast.

required
scenario str | None

the scenario of an output, the only one by default.

None
kwargs Any

the hypothesis and the threshold, see sbmlsim.uncertainty.testing.probability.

{}

Returns:

Type Description
TestResult

The statement with its Monte Carlo interval, which names the

TestResult

output of a given scenario <output>:<scenario>, as a contrast

TestResult

names its scenarios.

hypothesis_values

hypothesis_values(hypothesis)

Get the values of the output of a hypothesis: of its scenario or contrast.

The values are named <output>:<scenario> for a hypothesis with a scenario and as the contrast for one with a contrast, so its statement names them.

test

test(hypotheses, adjust='bonferroni')

Get the statements of hypotheses, adjusted for their multiplicity.

Parameters:

Name Type Description Default
hypotheses Sequence[Hypothesis]

the hypotheses.

required
adjust Literal['bonferroni', 'none']

the adjustment, see sbmlsim.uncertainty.testing.TestReport.

'bonferroni'

Returns:

Type Description
TestReport

The report of the statements.

outputs

outputs()

Get the outputs which are a value per draw, the values per simulation.

summary

summary(outputs=None, quantiles=QUANTILES, level=0.95)

Get the summaries of outputs with their Monte Carlo errors.

Parameters:

Name Type Description Default
outputs Sequence[str] | None

the outputs, values per draw; every one by default.

None
quantiles Sequence[float]

the quantiles.

QUANTILES
level float

the level of the intervals of the quantiles.

0.95

Returns:

Type Description
DataFrame

One row per scenario and output: scenario, output, unit,

DataFrame

n (the draws which did not fail), n_failed, mean, mean_se, sd,

DataFrame

sd_se and per quantile q<q> with q<q>_low and q<q>_high,

DataFrame

the ends of its distribution-free interval, see

DataFrame

sbmlsim.uncertainty.statistics.

contributions

contributions(output, scenario=None)

Get the contribution of every variable to the variance of an output.

The first-order index of every variable from the draws of the propagation, see statistics.first_order_given_data; no further simulations. A variable of a covariance is flagged correlated: its index includes the effect of the variables it is correlated with.

Parameters:

Name Type Description Default
output str

an output which is a value per draw.

required
scenario str | None

the scenario, the only one by default.

None

Returns:

Type Description
DataFrame

The variables, variable, index and correlated, the largest

DataFrame

index first.

to_netcdf

to_netcdf(path)

Write the result into a directory: a netCDF file per scenario and the record.

Parameters:

Name Type Description Default
path str | Path

the directory, created if it does not exist.

required

from_netcdf classmethod

from_netcdf(path)

Read a result written by to_netcdf.

Propagation

Propagation(
    model,
    simulation,
    uq,
    observables=(),
    *,
    outputs=None,
    hypotheses=(),
    adjust="bonferroni",
    n=None,
    rel_tol=0.1,
    n_start=256,
    n_max=16384,
    design=None,
    seed=None,
    simulator=None,
    keep=None,
    time=None,
    on_error="flag",
    checkpoint=None,
    block_size=None,
)

A propagation of uncertain values in blocks of draws, see the module.

A propagation of a given number of draws n runs in blocks of draws, blocks, which run separately, e.g. on several machines, and merge to the result of the whole propagation (run): every block takes its rows of the n points of the design, so a Latin hypercube stays one hypercube, and the result of the blocks is the one of a single block of all the draws. The adaptive number of draws runs its rounds one after the other, every round a block of the continued sequence.

With a checkpoint directory every block is written as <checkpoint>/<scenario>/draws-<start>-<stop>.nc once it ran, atomically, and a block whose files exist for every scenario is read instead of simulated, so the blocks of separate instances merge and a run resumes from the blocks it finished. The directory of a scenario is its name percent-encoded (urllib.parse.quote, . and .. as %2E and %2E%2E). A file has the configuration of its block, which a read compares and removes, see _read. A checkpointed block is used as it is read, so its result does not depend on whether it was simulated or read.

Attributes:

Name Type Description
scenarios dict[str, Simulation]

the simulations by the name of their scenario.

variables list[Variable]

the uncertain variables.

seed int

the seed, drawn when none was given.

design Literal['sobol', 'lhs', 'random']

the design of the draws.

n int | None

the number of draws, None for the adaptive number.

block_size int | None

the draws of a block, None for one block of n.

checkpoint Path | None

the directory of the checkpoints, None for none.

Check the propagation and load its model, see propagate.

Parameters:

Name Type Description Default
model Any

the model, loaded or a source.

required
simulation Simulation | Mapping[str, Simulation]

the simulation, or the scenarios by their name.

required
uq UncertaintyModel

what is uncertain.

required
observables Sequence[Any]

the observables of the run, e.g. a PK.

()
outputs Sequence[str] | None

the outputs of the adaptive stopping and of the summary.

None
hypotheses Sequence[Hypothesis]

the hypotheses of the adaptive stopping.

()
adjust Literal['bonferroni', 'none']

the adjustment of the hypotheses, see TestReport.

'bonferroni'
n int | None

the number of draws; None for the adaptive number.

None
rel_tol float

the tolerance of the adaptive stopping.

0.1
n_start int

the draws of the first round of the adaptive stopping.

256
n_max int

the most draws of the adaptive stopping.

16384
design Literal['sobol', 'lhs', 'random'] | None

sobol, lhs (only with n) or random.

None
seed int | None

the seed, None draws one, which seed keeps.

None
simulator Simulator | None

the simulator, Simulator() by default.

None
keep Sequence[str] | None

the timecourses the results keep, see Simulator.run.

None
time Any

a grid of times the timecourses are interpolated onto.

None
on_error Literal['raise', 'flag']

flag (a failed draw is NaN and counted) or raise.

'flag'
checkpoint str | Path | None

the directory of the checkpoints of the blocks.

None
block_size int | None

the draws of a block of n; one block by default.

None

Raises:

Type Description
ValueError

see propagate.

blocks

blocks()

Get the blocks of the draws of n.

Returns:

Type Description
list[range]

The draws [k * block_size, min(n, (k + 1) * block_size)), one

list[range]

block of all n draws without a block size.

Raises:

Type Description
ValueError

without n, whose rounds are not known before they run.

checkpointed

checkpointed(block)

Check whether a block has its checkpoint files for every scenario.

Parameters:

Name Type Description Default
block range

consecutive draws.

required

Returns:

Type Description
bool

Whether the propagation has a checkpoint and the files of the block

bool

exist in it for every scenario; whether they are blocks of this

bool

propagation is checked when they are read.

run_block

run_block(block)

Run the draws of a block in every scenario.

A block which ran or was read before is not run again. With a checkpoint a block whose files exist for every scenario is read, else it is simulated and written, see the class.

Parameters:

Name Type Description Default
block range

consecutive draws, within n if given.

required

Raises:

Type Description
ValueError

for a block which is no consecutive draws of the propagation.

CheckpointMismatch

for a checkpoint of another propagation.

run_blocks

run_blocks(blocks)

Run blocks of draws in every scenario, consecutive ones in one run.

A block which ran or was read before is not run again, and with a checkpoint a block whose files exist for every scenario is read, see run_block. The other blocks which follow each other without a gap run in spans of as many blocks as the simulator has workers (one for a serial simulator), a span one run of its draws per scenario on the workers, so the blocks of a propagation run in parallel whatever their size and are kept once their span ran; a block given twice runs once. The result of a span is cut into the results of its blocks, each bitwise the result of run_block of the block alone, which are written as their checkpoints. A block whose messages of failed draws the span does not keep (LostErrors) runs alone.

Parameters:

Name Type Description Default
blocks Sequence[range]

consecutive draws each, within n if given.

required

Raises:

Type Description
ValueError

for a block which is no consecutive draws of the propagation.

CheckpointMismatch

for a checkpoint of another propagation.

run

run()

Run the propagation: every block of n or the adaptive rounds.

Returns:

Type Description
UncertaintyResult

The result, see propagate.

Raises:

Type Description
ValueError

see propagate.

propagate

propagate(
    model,
    simulation,
    uq,
    observables=(),
    *,
    outputs=None,
    hypotheses=(),
    adjust="bonferroni",
    n=None,
    rel_tol=0.1,
    n_start=256,
    n_max=16384,
    design=None,
    seed=None,
    simulator=None,
    keep=None,
    time=None,
    on_error="flag",
    checkpoint=None,
    block_size=None,
)

Propagate the uncertain values through a simulation or scenarios, see the module.

Parameters:

Name Type Description Default
model Any

the model, loaded or a source.

required
simulation Simulation | Mapping[str, Simulation]

the simulation, or the scenarios by their name.

required
uq UncertaintyModel

what is uncertain.

required
observables Sequence[Any]

the observables of the run, e.g. a PK.

()
outputs Sequence[str] | None

the outputs of the adaptive stopping and of the summary, values per simulation; every value per simulation by default, none with hypotheses.

None
hypotheses Sequence[Hypothesis]

the hypotheses of the adaptive stopping, which draws until every one is decided after the adjustment for their multiplicity.

()
adjust Literal['bonferroni', 'none']

the adjustment of the hypotheses, see TestReport.

'bonferroni'
n int | None

the number of draws; None for the adaptive number.

None
rel_tol float

the tolerance of the adaptive stopping, the half width of the intervals of the statistics relative to the standard deviation of an output.

0.1
n_start int

the draws of the first batch of the adaptive stopping.

256
n_max int

the most draws of the adaptive stopping.

16384
design Literal['sobol', 'lhs', 'random'] | None

sobol, lhs (only with n, a Latin hypercube has no continuation) or random; by default random with hypotheses, whose statements assume independent draws, else sobol.

None
seed int | None

the seed, None draws one, which the record keeps.

None
simulator Simulator | None

the simulator, Simulator() by default.

None
keep Sequence[str] | None

the timecourses the results keep, see Simulator.run.

None
time Any

a grid of times the timecourses are interpolated onto.

None
on_error Literal['raise', 'flag']

flag (a failed draw is NaN and counted) or raise.

'flag'
checkpoint str | Path | None

the directory the blocks are written into and read from, see Propagation; None keeps them in memory only.

None
block_size int | None

the draws of a block of n, see Propagation; one block of all the draws by default.

None

Returns:

Type Description
UncertaintyResult

The result.

Raises:

Type Description
ValueError

without uncertain values, see UncertaintyModel.variables, for outputs which are no values per draw, without outputs or hypotheses for the adaptive stopping, for an output of the adaptive stopping without a draw which did not fail, for a Latin hypercube of an adaptive number of draws, for a number of draws or a block size, n_start or n_max which is not positive, for a block size without n, with a checkpoint for an empty scenario name or two which differ only in case, or for a checkpoint of another propagation.