Skip to content

Experiments

Define experiments, the functions that study a system through many runs.

They are sweeps, ensembles, scenarios, sensitivity, basin stability, orbit diagrams, calibration, posterior coverage, identifiability, virtual populations, and the calibration of individuals. Each is a function of a system, as the model selection functions of scikit-learn are, and returns a frozen result. As cross_val_score fits clones of an estimator, an experiment clones the system, sets parameters with set_params, prepares the clone, and simulates it, and it prepares once when only initial states or random streams change.

BasinStabilityResult(rows, labels, fractions, errors) dataclass

A result of basin_stability, the share of initial states per final behaviour.

It holds the random initial states, the final behaviour each one ended in, and the share of the states that reached each behaviour with its standard error, such as {'capacity': 1.0} when every population grows to its capacity. It reports how often a power grid stays in step, how often a species survives, and how often a genetic switch ends on.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
rows list[Row]

The initial states, one mapping from dotted path to value per run.

required
labels list[object]

The attractor label of every initial state.

required
fractions dict[object, float]

The fraction of initial states per attractor label.

required
errors dict[object, float]

The standard error of every fraction.

required
See Also

basin_stability: Returns this result.

Examples:

>>> from skcomplex.core.experiments import BasinStabilityResult
>>> BasinStabilityResult([], [], {'capacity': 1.0}, {'capacity': 0.0}).fractions
{'capacity': 1.0}

CalibrationResult(system, estimates, r2, rmse, mae, mape, covariance, simulated, success, samples=None, weights=None, diagnostics=dict(), predictive=None) dataclass

A result of calibrate, the fitted parameters and system, with measures of fit.

It holds the system with the fitted parameters, the estimates, and how well the runs match the data, such as r2, the share of the variation of the data the fit explains. A method that samples the likely values also holds the samples, their weights, its own checks, and a band of simulated series around the data. It reports the fitted rates of an epidemic, the constants of a reaction, and the growth of a firm.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
system AnySystem

The system with the fitted model parameters.

required
estimates dict[str, float]

The fitted value of every parameter, the posterior median for the posterior methods.

required
r2 float

The coefficient of determination over all data points.

required
rmse float

The root mean squared error.

required
mae float

The mean absolute error.

required
mape float

The mean absolute percentage error, over data points that are not zero.

required
covariance Array | None

The covariance of the estimates, from the Jacobian of the residuals for a point fit and from the weighted samples for a posterior method, or None when it is singular or there are no residuals.

required
simulated dict[str, Array]

The simulated values at the data times, by path.

required
success bool

Whether the method converged, such as the optimiser of a point fit, the split R-hat of every parameter of MCMC, or a finite loss of variational calibration.

required
samples dict[str, Array] | None

The samples of every parameter of a posterior method, or None for a point fit.

None
weights Array | None

The normalised weights of the samples, or None for a point fit.

None
diagnostics dict[str, object]

The diagnostics of the method, such as the tolerances and acceptance rates of ABC-SMC, the split R-hat and effective sample sizes of MCMC, or the loss history of variational calibration.

dict()
predictive dict[str, object] | None

The 5%, 50%, and 95% quantiles of the simulated series of posterior draws at the data times by path, under q05, q50, and q95, and the share of observed points inside the band under coverage, or None for a point fit.

None
See Also

calibrate: Returns this result. IndividualCalibrationResult: Holds one calibration per individual.

Examples:

>>> from skcomplex.core.experiments import calibrate
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> trajectory = LogisticGrowthSystem(r=0.5).prepare().simulate(until=20, dt=1.0)
>>> data = {'population.x': (trajectory.times, trajectory.get_values('population.x'))}
>>> round(calibrate(LogisticGrowthSystem(), data, {'r': (0.1, 2.0)}).r2, 3)
1.0

CoverageResult(levels, coverage, ranks, truths, results) dataclass

A result of posterior_coverage, how often the intervals hold the true values.

It holds, for every level and parameter, the share of the simulated data sets whose central interval holds the true value, such as 0.9 for a level of 0.9 when the intervals are right. It also holds the rank of every true value among its samples, which is uniform for a sound method. It checks the intervals of the rates of an epidemic, the constants of a reaction, and the parameters of a climate model.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
levels tuple[float, ...]

The levels of the central credible intervals.

required
coverage dict[float, dict[str, float]]

The share of the data sets whose interval holds the true value, by level and parameter.

required
ranks dict[str, Array]

The weighted share of the samples below the true value, one per data set, by parameter.

required
truths dict[str, Array]

The true value of every data set, by parameter.

required
results tuple[CalibrationResult, ...]

The calibration of every data set.

required
See Also

posterior_coverage: Returns this result.

Examples:

>>> from skcomplex.core.experiments import CoverageResult
>>> CoverageResult((0.9,), {0.9: {'r': 0.85}}, {}, {}, ()).coverage[0.9]['r']
0.85

ExperimentResult(runs) dataclass

A result of an experiment, with one row per run and the series it kept.

It holds the runs of sweep, ensemble, and compare_scenarios as a tidy table, one row per run and one column per parameter, scenario, replicate, seed, and output, which to_frame returns as a data frame. It also reads the kept series together as an ensemble and a summary across replicates. It holds the runs of an epidemic over its rate of infection, of a magnet over its temperature, and of a market over its tax.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
runs tuple[_RunResultSpec, ...]

The results of every run, in the experiment's order.

required
See Also

sweep: Returns this result for rows of values. ensemble: Returns this result for random streams.

Examples:

>>> from skcomplex.core.experiments import sweep
>>> from skcomplex.systems.biology.epidemiology import SIRSystem
>>> result = sweep(SIRSystem(), {'gamma': [0.1, 0.2]}, until=10)
>>> [row['gamma'] for row in result.rows]
[0.1, 0.2]

rows property

One row per run with its values and outputs.

A row holds its design values, scenario, replicate, seed, and scalar outputs.

convert_to_frame()

Return the rows as a pandas data frame.

Returns:

Name Type Description
frame DataFrame

The data frame.

Source code in src/skcomplex/core/experiments/_results.py
162
163
164
165
166
167
168
169
def convert_to_frame(self) -> pd.DataFrame:
    """Return the rows as a pandas data frame.

    Returns:
        frame:
            The data frame.
    """
    return pd.DataFrame(self.rows)

get_column(name)

Return one column of the rows.

Parameters:

Name Type Description Default
name str

The name of a design value, scenario, replicate, seed, or a scalar output.

required

Returns:

Name Type Description
values NDArray[generic]

One value per run.

Source code in src/skcomplex/core/experiments/_results.py
57
58
59
60
61
62
63
64
65
66
67
68
def get_column(self, name: str) -> npt.NDArray[np.generic]:
    """Return one column of the rows.

    Args:
        name:
            The name of a design value, `scenario`, `replicate`, `seed`, or a scalar output.

    Returns:
        values:
            One value per run.
    """
    return np.asarray([row[name] for row in self.rows])

get_ensemble(name)

Return a kept series of every run on common times, with the seeds of the runs.

The series are interpolated on the times of the shortest run.

Parameters:

Name Type Description Default
name str

The path of the kept series.

required

Returns:

Name Type Description
times NDArray[float64]

The common times.

values NDArray[float64]

One row per run and one column per common time.

seeds NDArray[int64]

The seed of the run of every row.

Examples:

>>> from skcomplex.core.experiments import ensemble
>>> from skcomplex.systems.biology.epidemiology import SIRSystem
>>> result = ensemble(SIRSystem(stochastic=True), replicates=3, until=10, random_state=0)
>>> times, values, seeds = result.get_ensemble('I.x')
>>> values.shape == (3, times.size), seeds.tolist()
(True, [0, 1, 2])
Source code in src/skcomplex/core/experiments/_results.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def get_ensemble(
    self,
    name: str,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.int64]]:
    """Return a kept series of every run on common times, with the seeds of the runs.

    The series are interpolated on the times of the shortest run.

    Args:
        name:
            The path of the kept series.

    Returns:
        times:
            The common times.

        values:
            One row per run and one column per common time.

        seeds:
            The seed of the run of every row.

    Examples:
        >>> from skcomplex.core.experiments import ensemble
        >>> from skcomplex.systems.biology.epidemiology import SIRSystem
        >>> result = ensemble(SIRSystem(stochastic=True), replicates=3, until=10, random_state=0)
        >>> times, values, seeds = result.get_ensemble('I.x')
        >>> values.shape == (3, times.size), seeds.tolist()
        (True, [0, 1, 2])
    """
    times = min((np.asarray(run.times, dtype=float) for run in self.runs), key=len)
    values = np.asarray(
        [
            np.interp(times, np.asarray(run.times, dtype=float), np.asarray(run.series[name], dtype=float))
            for run in self.runs
        ],
    )
    seeds = np.asarray([run.seed for run in self.runs], dtype=np.int64)
    return times, values, seeds

get_series(name)

Return a kept series of every run.

The series are stacked when all runs have the same number of frames.

Parameters:

Name Type Description Default
name str

The path of the kept series.

required

Returns:

Name Type Description
series NDArray[generic]

One row per run, or an object array of per-run series of different lengths.

Source code in src/skcomplex/core/experiments/_results.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def get_series(self, name: str) -> npt.NDArray[np.generic]:
    """Return a kept series of every run.

    The series are stacked when all runs have the same number of frames.

    Args:
        name:
            The path of the kept series.

    Returns:
        series:
            One row per run, or an object array of per-run series of different lengths.
    """
    values = [run.series[name] for run in self.runs]
    if len({value.shape for value in values}) == 1:
        return np.stack(values)
    array = np.empty(len(values), dtype=object)
    array[:] = values
    return array

get_summary(quantiles=(0.05, 0.5, 0.95))

Return statistics of every numeric scalar output per row and scenario.

They are the mean, the standard deviation, and the quantiles.

Parameters:

Name Type Description Default
quantiles Sequence[float]

The quantiles to report.

(0.05, 0.5, 0.95)

Returns:

Name Type Description
summary list[dict[str, object]]

One row per design row and scenario, with <output>.mean, <output>.std, and <output>.q<quantile> columns and the number of replicates as runs.

Source code in src/skcomplex/core/experiments/_results.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def get_summary(self, quantiles: Sequence[float] = (0.05, 0.5, 0.95)) -> list[dict[str, object]]:
    """Return statistics of every numeric scalar output per row and scenario.

    They are the mean, the standard deviation, and the quantiles.

    Args:
        quantiles:
            The quantiles to report.

    Returns:
        summary:
            One row per design row and scenario, with `<output>.mean`, `<output>.std`, and `<output>.q<quantile>`
            columns and the number of replicates as `runs`.
    """
    groups: dict[tuple[tuple[tuple[str, object], ...], str], list[_RunResultSpec]] = defaultdict(list)
    for run in self.runs:
        groups[(tuple(run.row.items()), run.scenario)].append(run)
    summary = []
    for (row, scenario), runs in groups.items():
        entry: dict[str, object] = {**dict(row), 'scenario': scenario, 'runs': len(runs)}
        for name in runs[0].scalars:
            values = np.asarray([run.scalars[name] for run in runs])
            if values.ndim != 1 or not np.issubdtype(values.dtype, np.number):
                continue
            values = values.astype(float)
            entry[f'{name}.mean'] = float(values.mean())
            entry[f'{name}.std'] = float(values.std(ddof=1)) if values.size > 1 else 0.0
            for quantile in quantiles:
                entry[f'{name}.q{quantile:g}'] = float(np.quantile(values, quantile))
        summary.append(entry)
    return summary

IdentifiabilityResult(estimates, verdicts, profiles, intervals, errors) dataclass

A result of identifiability, the best fit and a verdict per parameter.

It holds the best fit and whether the data pin down each parameter, such as {'r': 'strong'}. A profile also holds the profile and the interval of every parameter, with the verdicts 'identifiable' and 'not identifiable'. Refits hold the average error of every parameter per level of noise, with the verdicts 'strong', 'weak', and 'none'. It tells whether case counts fix the rates of an epidemic, counts fix the capacity of a population, and blood samples fix the clearance of a drug.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
estimates dict[str, float]

The best-fit value of every parameter.

required
verdicts dict[str, str]

The verdict of every parameter.

required
profiles dict[str, tuple[Array, Array]] | None

The values of the profiled parameter and the likelihood ratio along its profile, by parameter, or None for refits.

required
intervals dict[str, tuple[float, float]] | None

The (low, high) likelihood-ratio interval of every parameter, with nan for a side that reaches its bound, or None for refits.

required
errors dict[str, dict[float, float]] | None

The average relative error of every parameter by noise level, or None for a profile.

required
See Also

identifiability: Returns this result.

Examples:

>>> from skcomplex.core.experiments import IdentifiabilityResult
>>> IdentifiabilityResult({'r': 0.5}, {'r': 'strong'}, None, None, {'r': {0.01: 0.004}}).verdicts
{'r': 'strong'}

IndividualCalibrationResult(calibrations, estimates) dataclass

A result of calibrate_individuals, the calibration of every individual.

It holds the calibration of every individual and a table of their estimates, one row per individual and one column per parameter, such as the growth rate r of the regions 'north' and 'south'. It reports the fitted tumour of every patient, the rates of an epidemic in every region, and the demand of every firm.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
calibrations dict[Hashable, CalibrationResult]

The calibration of every individual.

required
estimates DataFrame

The estimates, with one row per individual and one column per parameter.

required
See Also

calibrate_individuals: Returns this result. CalibrationResult: Holds the calibration of one system.

Examples:

>>> import pandas as pd
>>> from skcomplex.core.experiments import IndividualCalibrationResult
>>> table = pd.DataFrame({'r': [0.5, 0.7]}, index=pd.Index(['north', 'south'], name='individual'))
>>> float(IndividualCalibrationResult({}, table).estimates.loc['south', 'r'])
0.7

OrbitDiagramResult(points, periods) dataclass

A result of orbit_diagram, the values visited for every value of a parameter.

It holds the values a run keeps visiting after it settles, for every value of the parameter, and how many distinct values each run visits, so a period of 2 means a cycle between two values. It shows the period doubling of a population, the route to chaos of a forced pendulum, and the pulses of a laser.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
points list[Array]

The kept values of the observable for every value of the parameter.

required
periods NDArray[int64]

The number of distinct kept values for every value of the parameter, the period of periodic orbits.

required
See Also

orbit_diagram: Returns this result.

Examples:

>>> from skcomplex.core.experiments import orbit_diagram
>>> from skcomplex.systems.mathematics.dynamical_systems import LogisticMapSystem
>>> orbit_diagram(LogisticMapSystem(), 'r', [2.9, 3.2], 'map.x', transient=1000, keep=20).periods.tolist()
[1, 2]

ScenarioSpec(name='baseline', overrides=None, schedule=(), system=None) dataclass

Bases: BaseSpec

A spec of a named variant of a system, such as an intervention.

It changes values before the run, changes parameters at given times, or replaces the system, such as ScenarioSpec('distancing', overrides={'beta': 0.0001}) for a lower rate of infection. Every scenario of an experiment runs with the same random streams, so scenarios differ only through what they change. An epidemic compares early and late lockdowns, a climate model compares paths of emissions, and an economy compares tax policies.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
name str

The name of the scenario.

'baseline'
overrides Mapping[str, object] | None

A mapping from a name set_params takes, such as beta or growth__r, or a dotted path, to the value it takes before the run.

None
schedule Sequence[tuple[float, str, object]]

The changes during the run, as (time, dotted parameter path, value), applied from the first frame at or after their time.

()
system AnySystem | None

A system that replaces the one the factory builds, for structural changes, or None.

None
See Also

compare_scenarios: Runs the scenarios of a system.

Examples:

>>> from skcomplex.core.experiments import ScenarioSpec
>>> ScenarioSpec('reduced', schedule=[(50.0, 'source.rate', 0.025)]).schedule
[(50.0, 'source.rate', 0.025)]

SensitivityResult(names, inputs, outputs, ranking, effects=None, mu_star=None, mu_star_conf=None, sigma=None, first_order=None, first_order_conf=None, total_order=None, total_order_conf=None) dataclass

A result of sensitivity, the effect of each input on a scalar output.

It holds the inputs and the output of every run, the effects the method measures, and the inputs ranked from the most to the least influential, such as 'growth.K' first when the capacity sets the final size. It ranks the rates of an epidemic by their effect on its peak, the inputs of a climate model by their effect on warming, and the costs of a supply chain by their effect on profit.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
names list[str]

The inputs, names set_params takes or dotted paths.

required
inputs Array

The values of the inputs of every run, one column per input.

required
outputs Array

The output of every run.

required
ranking list[str]

The inputs from the most to the least influential, by effects, mu_star, or total_order.

required
effects dict[str, float] | None

The one-at-a-time effect of every input, for 'oat'.

None
mu_star dict[str, float] | None

The mean absolute elementary effect of every input, for 'morris'.

None
mu_star_conf dict[str, float] | None

The confidence interval of mu_star, for 'morris'.

None
sigma dict[str, float] | None

The standard deviation of the elementary effects of every input, for 'morris'.

None
first_order dict[str, float] | None

The first-order Sobol index of every input, for 'sobol'.

None
first_order_conf dict[str, float] | None

The confidence interval of first_order, for 'sobol'.

None
total_order dict[str, float] | None

The total Sobol index of every input, for 'sobol'.

None
total_order_conf dict[str, float] | None

The confidence interval of total_order, for 'sobol'.

None
See Also

sensitivity: Returns this result.

Examples:

>>> from skcomplex.core.experiments import sensitivity
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> bounds = {'growth.r': (0.1, 1.0), 'growth.K': (50, 150)}
>>> sensitivity(LogisticGrowthSystem(), bounds, output='population.x', method='oat', until=20).ranking[0]
'growth.K'

VirtualPopulationResult(plausible, acceptance, selected, inclusion) dataclass

A result of virtual_population, the plausible rows and those selected.

It holds the sampled parameter rows whose runs look plausible, with their outputs, the share of samples that passed, and the rows selected to match observed values with their chance of selection. It holds virtual patients of a trial, plausible economies, and plausible ecosystems.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
plausible DataFrame

The plausible rows, with one column per parameter and per output.

required
acceptance float

The share of the sampled rows that are plausible.

required
selected DataFrame | None

The plausible rows selected to match the target, or None without a target.

required
inclusion Array | None

The probability of inclusion of every plausible row, or None without a target.

required
See Also

virtual_population: Returns this result.

Examples:

>>> import pandas as pd
>>> from skcomplex.core.experiments import VirtualPopulationResult
>>> result = VirtualPopulationResult(pd.DataFrame({'r': [0.5], 'size': [2.0]}), 0.25, None, None)
>>> result.acceptance
0.25

basin_stability(system, bounds, classifier, *, n=500, until=None, dt=None, random_state=None, executor='serial', vectorized=False)

Return the share of random initial states that end in each final behaviour.

It draws initial states at random within bounds, runs each one to until, and asks classifier which final behaviour the run settled into, such as a resting state or a cycle. The share of each behaviour says how well it withstands large disturbances. With vectorized, every initial state runs as one member of a single simulation. It measures how often a power grid stays in step after a fault, how often a population survives, and how often a genetic switch ends on rather than off.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
system SystemSource

The system, or a factory of systems, such as a system class.

required
bounds Mapping[str, tuple[float, float]]

A mapping from dotted state path to the (low, high) bounds of its initial value.

required
classifier Callable[[Trajectory], object]

A function of a trajectory that returns the label of the attractor it ends in.

required
n int

The number of initial states.

500
until float | None

The end time of every run, or None for the tuned end time of the system.

None
dt float | None

The time between frames, or None for the tuned one.

None
random_state int | None

The seed of the initial states and the runs.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor of the separate runs.

'serial'
vectorized bool

Whether to run every initial state as a member of one simulation of the replicated system.

False

Returns:

Name Type Description
result BasinStabilityResult

The initial states, their attractor labels, and the fraction and its error per attractor.

Raises:

Type Description
ValidationError

No bounds are given, the number of initial states is not a positive integer, or a vectorised run does not compile to a general problem.

ExperimentError

The system is a name.

See Also

orbit_diagram: Shows the values a run visits over a range of a parameter. ensemble: Runs a system many times with independent random streams.

Examples:

>>> from skcomplex.core.experiments import basin_stability
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> bounds = {'population.x': (0.1, 10)}
>>> basin_stability(LogisticGrowthSystem(), bounds, lambda run: 'capacity', n=5, until=5).fractions
{'capacity': 1.0}
Source code in src/skcomplex/core/experiments/_basin_stability.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def basin_stability(
    system: SystemSource,
    bounds: Mapping[str, tuple[float, float]],
    classifier: Callable[[Trajectory], object],
    *,
    n: int = 500,
    until: float | None = None,
    dt: float | None = None,
    random_state: int | None = None,
    executor: str | Executor = 'serial',
    vectorized: bool = False,
) -> BasinStabilityResult:
    """Return the share of random initial states that end in each final behaviour.

    It draws initial states at random within `bounds`, runs each one to `until`, and asks `classifier` which final
    behaviour the run settled into, such as a resting state or a cycle. The share of each behaviour says how well it
    withstands large disturbances. With `vectorized`, every initial state runs as one member of a single simulation. It
    measures how often a power grid stays in step after a fault, how often a population survives, and how often a
    genetic switch ends on rather than off.

    Read more in the user guide, under Run experiments.

    Args:
        system:
            The system, or a factory of systems, such as a system class.

        bounds:
            A mapping from dotted state path to the `(low, high)` bounds of its initial value.

        classifier:
            A function of a trajectory that returns the label of the attractor it ends in.

        n:
            The number of initial states.

        until:
            The end time of every run, or `None` for the tuned end time of the system.

        dt:
            The time between frames, or `None` for the tuned one.

        random_state:
            The seed of the initial states and the runs.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor of the separate runs.

        vectorized:
            Whether to run every initial state as a member of one simulation of the replicated system.

    Returns:
        result:
            The initial states, their attractor labels, and the fraction and its error per attractor.

    Raises:
        ValidationError:
            No bounds are given, the number of initial states is not a positive integer, or a vectorised run does not
            compile to a general problem.

        ExperimentError:
            The system is a name.

    See Also:
        orbit_diagram: Shows the values a run visits over a range of a parameter.
        ensemble: Runs a system many times with independent random streams.

    Examples:
        >>> from skcomplex.core.experiments import basin_stability
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> bounds = {'population.x': (0.1, 10)}
        >>> basin_stability(LogisticGrowthSystem(), bounds, lambda run: 'capacity', n=5, until=5).fractions
        {'capacity': 1.0}
    """
    _check_source(system)
    if not bounds:
        error_msg = 'Basin stability needs the bounds of at least one initial state.'
        raise ValidationError(error_msg)
    _check_count('n', n)
    states = get_problem(build_system(system, {})).states
    integers = [path for path in bounds if states.has(path) and states.get_entry(path).kind in INTEGER_KINDS]
    rows = _get_rows(bounds, 'random', n, random_state, integers)
    if vectorized:
        values = {path: np.asarray([row[path] for row in rows], dtype=float) for path in bounds}
        trajectory, problem = _run_replicated(system, values, until, dt, random_state)
        if not isinstance(problem, ProblemSpec):
            error_msg = f'A vectorised basin reads the members of a general problem, not of a {type(problem).__name__}.'
            raise ValidationError(error_msg)
        labels = [classifier(trajectory.get_member(index, problem)) for index in range(n)]
    else:

        def attractor(trajectory: Trajectory) -> object:
            return classifier(trajectory)

        result = _run_experiment(
            system,
            rows,
            [ScenarioSpec()],
            1,
            analyses=None,
            until=until,
            dt=dt,
            solver=None,
            outputs=[attractor],
            warmup=0.0,
            observables=(),
            random_state=random_state,
            executor=executor,
        )
        labels = [row['attractor'] for row in result.rows]
    fractions = {label: count / n for label, count in Counter(labels).items()}
    errors = {label: float(np.sqrt(fraction * (1 - fraction) / n)) for label, fraction in fractions.items()}
    return BasinStabilityResult(rows, labels, fractions, errors)

calibrate(system, data, bounds, *, method='local', initial=None, loss='squares', summary=None, n_samples=1000, budget=None, chains=4, replicates=1, dt=None, solver=None, random_state=None)

Return the fit of the model parameters of a system to observed time series.

It searches the parameters within bounds for the run that best matches data, a mapping from a path such as 'population.x' to its observed times and values, and returns a copy of the system with them. Every candidate runs the system to the last data time and reads its values at the data times, and a random system averages replicates runs with fixed seeds. A point method returns one estimate, and a method that samples the likely values returns their median with the samples. It fits the rates of an epidemic to case counts, the constants of a reaction to measured concentrations, and a predator and prey model to the pelts traded by trappers.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take the parameters through set_params, or a factory of systems, such as a system class, which takes them as keyword arguments.

required
data Mapping[str, tuple[ArrayLike, ArrayLike]] | Trajectory

A mapping from state or observable path to its observed (times, values), or a trajectory recorded with its draws for the loss 'events'.

required
bounds Bounds

A mapping from a parameter of the system, such as r or the nested growth__r, to its (low, high) bounds or its SciPy prior. A pair reads as a uniform prior, and a point fit searches the pair or the central 99.9% of the prior.

required
method str

How to search or sample. 'local' is a local SciPy fit, with the covariance from the Jacobian of the residuals. 'global' keeps the best of budget evaluations, 200 by default, chosen by the seeded tree-structured Parzen estimator of Optuna, which copes with the rough losses of random runs. 'abc_smc' samples by approximate Bayesian computation with pyabc, comparing summaries of every run with the observed ones, and stops after budget runs, 20000 by default. 'mcmc' draws chains chains of n_samples with numpyro, by NUTS through JAX for a system tagged differentiable with the Gaussian likelihood, and by an ensemble sampler otherwise. 'variational' fits a normal posterior by numpyro over budget steps, 2000 by default, through JAX. A sampling method returns the samples, their medians as the estimates, and a check of at most 200 simulated draws at the data times.

'local'
initial Mapping[str, float] | None

The starting values of the parameters of a local fit, or None for the medians of their priors.

None
loss str

What scores a candidate, as the method allows. 'squares' sums the squared gaps, 'likelihood' is the Gaussian likelihood with an unknown variance, and 'events' is the log-probability of the draws of a trajectory recorded with simulate(..., record_draws=True), replayed under every candidate with random_state, the seed of the recorded run.

'squares'
summary Summary | None

The function from simulated or observed series by path to summary statistics that ABC-SMC compares, or None for the concatenated series.

None
n_samples int

The number of samples of a posterior method, per chain for MCMC.

1000
budget int | None

The number of evaluations of a global fit, simulations of ABC-SMC, or steps of variational calibration, or None for the default of the method.

None
chains int

The number of chains of MCMC.

4
replicates int

The number of runs averaged per evaluation.

1
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
random_state int | None

The seed of the runs and of the method.

None

Returns:

Name Type Description
result CalibrationResult

The fitted system, the estimates, and the goodness of fit.

Raises:

Type Description
ValidationError

The system is a system name, the method or the loss is unknown or they do not fit, there is no data, the replicates are bad, or a bound is neither a pair nor a SciPy distribution or has a dotted path.

See Also

calibrate_individuals: Fits each individual to its own data. identifiability: Tells which parameters the data determine. posterior_coverage: Checks the intervals of a method that samples.

Examples:

>>> from skcomplex.core.experiments import calibrate
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> trajectory = LogisticGrowthSystem(r=0.5).prepare().simulate(until=20, dt=1.0)
>>> data = {'population.x': (trajectory.times, trajectory.get_values('population.x'))}
>>> round(calibrate(LogisticGrowthSystem(), data, {'r': (0.1, 2.0)}).estimates['r'], 2)
0.5
Source code in src/skcomplex/core/experiments/_calibration.py
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
def calibrate(
    system: SystemSource,
    data: Mapping[str, tuple[npt.ArrayLike, npt.ArrayLike]] | Trajectory,
    bounds: Bounds,
    *,
    method: str = 'local',
    initial: Mapping[str, float] | None = None,
    loss: str = 'squares',
    summary: Summary | None = None,
    n_samples: int = 1000,
    budget: int | None = None,
    chains: int = 4,
    replicates: int = 1,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    random_state: int | None = None,
) -> CalibrationResult:
    """Return the fit of the model parameters of a system to observed time series.

    It searches the parameters within `bounds` for the run that best matches `data`, a mapping from a path such as
    `'population.x'` to its observed times and values, and returns a copy of the system with them. Every candidate runs
    the system to the last data time and reads its values at the data times, and a random system averages `replicates`
    runs with fixed seeds. A point method returns one estimate, and a method that samples the likely values returns
    their median with the samples. It fits the rates of an epidemic to case counts, the constants of a reaction to
    measured concentrations, and a predator and prey model to the pelts traded by trappers.

    Read more in the user guide, under Calibrate.

    Args:
        system:
            The system, whose clones take the parameters through `set_params`, or a factory of systems, such as
            a system class, which takes them as keyword arguments.

        data:
            A mapping from state or observable path to its observed `(times, values)`, or a trajectory recorded with
            its draws for the loss `'events'`.

        bounds:
            A mapping from a parameter of the system, such as `r` or the nested `growth__r`, to its `(low, high)` bounds
            or its SciPy prior. A pair reads as a uniform prior, and a point fit searches the pair or the central
            99.9% of the prior.

        method:
            How to search or sample. `'local'` is a local SciPy fit, with the covariance from the Jacobian of the
            residuals. `'global'` keeps the best of `budget` evaluations, 200 by default, chosen by the seeded
            tree-structured Parzen estimator of Optuna, which copes with the rough losses of random runs. `'abc_smc'`
            samples by approximate Bayesian computation with pyabc, comparing summaries of every run with the observed
            ones, and stops after `budget` runs, 20000 by default. `'mcmc'` draws `chains` chains of `n_samples` with
            numpyro, by NUTS through JAX for a system tagged `differentiable` with the Gaussian likelihood, and by an
            ensemble sampler otherwise. `'variational'` fits a normal posterior by numpyro over `budget` steps, 2000 by
            default, through JAX. A sampling method returns the samples, their medians as the estimates, and a check of
            at most 200 simulated draws at the data times.

        initial:
            The starting values of the parameters of a local fit, or `None` for the medians of their priors.

        loss:
            What scores a candidate, as the method allows. `'squares'` sums the squared gaps, `'likelihood'` is the
            Gaussian likelihood with an unknown variance, and `'events'` is the log-probability of the draws of a
            trajectory recorded with `simulate(..., record_draws=True)`, replayed under every candidate with
            `random_state`, the seed of the recorded run.

        summary:
            The function from simulated or observed series by path to summary statistics that ABC-SMC compares, or
            `None` for the concatenated series.

        n_samples:
            The number of samples of a posterior method, per chain for MCMC.

        budget:
            The number of evaluations of a global fit, simulations of ABC-SMC, or steps of variational calibration, or
            `None` for the default of the method.

        chains:
            The number of chains of MCMC.

        replicates:
            The number of runs averaged per evaluation.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        random_state:
            The seed of the runs and of the method.

    Returns:
        result:
            The fitted system, the estimates, and the goodness of fit.

    Raises:
        ValidationError:
            The system is a system name, the method or the loss is unknown or they do not fit, there is no data, the
            replicates are bad, or a bound is neither a pair nor a SciPy distribution or has a dotted path.

    See Also:
        calibrate_individuals: Fits each individual to its own data.
        identifiability: Tells which parameters the data determine.
        posterior_coverage: Checks the intervals of a method that samples.

    Examples:
        >>> from skcomplex.core.experiments import calibrate
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> trajectory = LogisticGrowthSystem(r=0.5).prepare().simulate(until=20, dt=1.0)
        >>> data = {'population.x': (trajectory.times, trajectory.get_values('population.x'))}
        >>> round(calibrate(LogisticGrowthSystem(), data, {'r': (0.1, 2.0)}).estimates['r'], 2)
        0.5
    """
    _check_source(system)
    _check_settings(method, loss, data, bounds, replicates)
    priors = _check_priors(bounds)
    objective = _CalibrationObjective(
        system,
        _series_of(data),
        priors,
        replicates=replicates,
        dt=dt,
        solver=solver,
        random_state=random_state,
        recorded=data if loss == 'events' and isinstance(data, Trajectory) else None,
        summary=summary,
    )
    budget = BUDGETS[method] if budget is None else budget
    _check_count('n_samples', n_samples)
    _check_count('chains', chains)
    if method == 'variational':
        _check_differentiable(objective)
    if method in {'mcmc', 'variational'}:
        for name, prior in priors.items():
            _numpyro_prior(name, prior)
    if method == 'abc_smc':
        samples, weights, diagnostics = _fit_abc(objective, n_samples, budget, random_state)
        return _posterior_result(
            objective,
            loss,
            samples,
            weights,
            diagnostics=diagnostics,
            success=True,
            random_state=random_state,
        )
    if method in {'mcmc', 'variational'}:
        if method == 'mcmc':
            samples, diagnostics, success = _fit_mcmc(objective, loss, n_samples, chains, random_state)
        else:
            samples, diagnostics, success = _fit_variational(objective, loss, n_samples, budget, random_state)
        weights = np.full(len(samples), 1 / len(samples))
        return _posterior_result(
            objective,
            loss,
            samples,
            weights,
            diagnostics=diagnostics,
            success=success,
            random_state=random_state,
        )
    if method == 'global':
        estimate = _fit_global(objective, loss, budget, random_state)
        return _result(objective, estimate, objective.get_covariance(estimate, loss), success=True)
    start = np.asarray(
        [(initial or {}).get(name, float(prior.median())) for name, prior in priors.items()],
        dtype=float,
    )
    estimate, success = _fit_local(objective, loss, start)
    return _result(objective, estimate, objective.get_covariance(estimate, loss), success)

calibrate_individuals(system, data, bounds, *, known=None, method='local', loss='squares', initial=None, n_samples=1000, budget=None, chains=4, replicates=1, dt=None, solver=None, random_state=None, executor='serial')

Return the fit of the model parameters of a system to each individual's data.

Each individual has its own data and may have known parameters, such as the dose a patient received. The function sets the known parameters on a copy of the system and calls calibrate on the data of that individual, so each fitted copy is the digital twin of one individual. The calibrations run on executor, each with its own seed. It fits the tumour of every patient of a trial, the rates of an epidemic in every region, and the demand of every firm of a market.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take the parameters through set_params, or a factory of systems.

required
data Mapping[Hashable, Data]

A mapping from individual to its data, a mapping from state or observable path to (times, values).

required
bounds Bounds

A mapping from model parameter to its (low, high) bounds or its SciPy prior, shared by all individuals.

required
known Mapping[Hashable, Mapping[str, object]] | None

A mapping from individual to its known model parameters by name, or None for none.

None
method str

The method of calibrate.

'local'
loss str

The loss of calibrate.

'squares'
initial Mapping[str, float] | None

The starting values of a local fit, or None for the medians of the priors.

None
n_samples int

The number of samples of a posterior method.

1000
budget int | None

The budget of the method, or None for its default.

None
chains int

The number of chains of MCMC.

4
replicates int

The number of runs averaged per evaluation.

1
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
random_state int | None

The seed of the seeds of the individuals.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor that runs the calibrations.

'serial'

Returns:

Name Type Description
result IndividualCalibrationResult

The calibration of every individual and the table of their estimates.

Raises:

Type Description
ValidationError

There is no individual, a known parameter is also fitted or belongs to an individual without data, or calibrate rejects a setting.

ExperimentError

The system is a name.

See Also

calibrate: Fits one system to one set of data.

Examples:

>>> from skcomplex.core.experiments import calibrate_individuals
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> runs = {k: LogisticGrowthSystem(r=r).prepare().simulate(until=20) for k, r in [('a', 0.4), ('b', 0.7)]}
>>> data = {k: {'population.x': (run.times, run.get_values('population.x'))} for k, run in runs.items()}
>>> calibrate_individuals(LogisticGrowthSystem(), data, {'r': (0.1, 2.0)}).estimates['r'].round(2).to_dict()
{'a': 0.4, 'b': 0.7}
Source code in src/skcomplex/core/experiments/_individuals.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def calibrate_individuals(
    system: SystemSource,
    data: Mapping[Hashable, Data],
    bounds: Bounds,
    *,
    known: Mapping[Hashable, Mapping[str, object]] | None = None,
    method: str = 'local',
    loss: str = 'squares',
    initial: Mapping[str, float] | None = None,
    n_samples: int = 1000,
    budget: int | None = None,
    chains: int = 4,
    replicates: int = 1,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> IndividualCalibrationResult:
    """Return the fit of the model parameters of a system to each individual's data.

    Each individual has its own data and may have known parameters, such as the dose a patient received. The function
    sets the known parameters on a copy of the system and calls `calibrate` on the data of that individual, so each
    fitted copy is the digital twin of one individual. The calibrations run on `executor`, each with its own seed. It
    fits the tumour of every patient of a trial, the rates of an epidemic in every region, and the demand of every firm
    of a market.

    Read more in the user guide, under Calibrate.

    Args:
        system:
            The system, whose clones take the parameters through `set_params`, or a factory of systems.

        data:
            A mapping from individual to its data, a mapping from state or observable path to `(times, values)`.

        bounds:
            A mapping from model parameter to its `(low, high)` bounds or its SciPy prior, shared by all individuals.

        known:
            A mapping from individual to its known model parameters by name, or `None` for none.

        method:
            The method of `calibrate`.

        loss:
            The loss of `calibrate`.

        initial:
            The starting values of a local fit, or `None` for the medians of the priors.

        n_samples:
            The number of samples of a posterior method.

        budget:
            The budget of the method, or `None` for its default.

        chains:
            The number of chains of MCMC.

        replicates:
            The number of runs averaged per evaluation.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        random_state:
            The seed of the seeds of the individuals.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor that runs the calibrations.

    Returns:
        result:
            The calibration of every individual and the table of their estimates.

    Raises:
        ValidationError:
            There is no individual, a known parameter is also fitted or belongs to an individual without data, or
            `calibrate` rejects a setting.

        ExperimentError:
            The system is a name.

    See Also:
        calibrate: Fits one system to one set of data.

    Examples:
        >>> from skcomplex.core.experiments import calibrate_individuals
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> runs = {k: LogisticGrowthSystem(r=r).prepare().simulate(until=20) for k, r in [('a', 0.4), ('b', 0.7)]}
        >>> data = {k: {'population.x': (run.times, run.get_values('population.x'))} for k, run in runs.items()}
        >>> calibrate_individuals(LogisticGrowthSystem(), data, {'r': (0.1, 2.0)}).estimates['r'].round(2).to_dict()
        {'a': 0.4, 'b': 0.7}
    """
    source = _check_source(system)
    if not data:
        error_msg = 'Calibrating individuals needs the data of at least one individual.'
        raise ValidationError(error_msg)
    known = known or {}
    for individual, values in known.items():
        if individual not in data:
            error_msg = f'The individual {individual!r} has known parameters but no data.'
            raise ValidationError(error_msg)
        fitted = sorted(set(values) & set(bounds))
        if fitted:
            error_msg = (
                f'The parameter {", ".join(fitted)} of the individual {individual!r} is both known and fitted. Remove '
                'it from `known` or from `bounds`.'
            )
            raise ValidationError(error_msg)
    sources: list[SystemSource] = []
    for individual in data:
        values = dict(known.get(individual, {}))
        if isinstance(source, BaseSystem | _CompositeSystem):
            sources.append(build_system(source, values))
        else:
            sources.append(functools.partial(source, **values))
    rng = np.random.default_rng(random_state)
    seeds = [None if random_state is None else int(seed) for seed in rng.integers(SEED_RANGE, size=len(data))]
    fits = [
        functools.partial(
            calibrate,
            individual_source,
            individual_data,
            bounds,
            method=method,
            loss=loss,
            initial=initial,
            n_samples=n_samples,
            budget=budget,
            chains=chains,
            replicates=replicates,
            dt=dt,
            solver=solver,
            random_state=seed,
        )
        for individual_source, individual_data, seed in zip(sources, data.values(), seeds, strict=True)
    ]
    calibrations = dict(zip(data, _map_calls(operator.call, fits, executor), strict=True))
    table = pd.DataFrame(
        [result.estimates for result in calibrations.values()],
        index=pd.Index(list(calibrations), name='individual'),
    )
    return IndividualCalibrationResult(calibrations, table)

compare_scenarios(system, scenarios, *, replicates=1, analyses=None, until=None, dt=None, solver=None, outputs=None, warmup=0.0, observables=(), random_state=None, executor='serial')

Return the runs of every scenario of a system.

It runs every ScenarioSpec on a copy of the system, replicates times, and every scenario of a replicate draws the same random numbers, so the scenarios differ only through what they change. A scenario overrides values before the run, changes parameters at given times, or replaces the system. It compares early and late lockdowns of an epidemic, paths of emissions of a climate model, and tax policies of an economy.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take parameters through set_params, or a factory of systems, such as a system class, which takes them as keyword arguments.

required
scenarios Sequence[ScenarioSpec]

The scenarios to compare.

required
replicates int

The number of runs per scenario.

1
analyses Sequence[Callable[[Trajectory], object]] | None

The analyses of every run, functions of a trajectory that return a frozen result, such as analysis functions bound with bind_analysis, or None. Every field of a result that is set becomes the output <function name>.<field>, numbered -1, -2, ... when several analyses share a function.

None
until float | None

The end time of every run, or None for the tuned end time of the system.

None
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
outputs Sequence[Output] | None

The state and observable paths to keep as series, whose last values are scalar outputs, and functions of a trajectory that return a scalar or a mapping of scalars. None keeps every observable, or every state when the system declares none.

None
warmup float

The simulated time before which kept series are discarded.

0.0
observables Sequence[Observable]

The observables of every run, or none for the tuned ones.

()
random_state int | None

The seed of the random streams, one per row and replicate.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor, in the role of n_jobs.

'serial'

Returns:

Name Type Description
result ExperimentResult

The results of every run, one tidy row per run with the name of its scenario.

Raises:

Type Description
ValidationError

No scenario is given, a scenario is not a ScenarioSpec, or a setting is not valid.

ExperimentError

The system is a name, or the worker processes stop before finishing.

See Also

ScenarioSpec: Names one variant of a system. sweep: Runs a system over values of its parameters.

Examples:

>>> from skcomplex.core.experiments import ScenarioSpec, compare_scenarios
>>> from skcomplex.systems.biology.epidemiology import SIRSystem
>>> scenarios = [ScenarioSpec(), ScenarioSpec('distancing', overrides={'beta': 0.0001})]
>>> result = compare_scenarios(SIRSystem(), scenarios, until=50, outputs=['I.x'])
>>> [row['scenario'] for row in result.rows]
['baseline', 'distancing']
Source code in src/skcomplex/core/experiments/_scenarios.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def compare_scenarios(
    system: SystemSource,
    scenarios: Sequence[ScenarioSpec],
    *,
    replicates: int = 1,
    analyses: Sequence[Callable[[Trajectory], object]] | None = None,
    until: float | None = None,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    outputs: Sequence[Output] | None = None,
    warmup: float = 0.0,
    observables: Sequence[Observable] = (),
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> ExperimentResult:
    """Return the runs of every scenario of a system.

    It runs every `ScenarioSpec` on a copy of the system, `replicates` times, and every scenario of a replicate draws
    the same random numbers, so the scenarios differ only through what they change. A scenario overrides values before
    the run, changes parameters at given times, or replaces the system. It compares early and late lockdowns of an
    epidemic, paths of emissions of a climate model, and tax policies of an economy.

    Read more in the user guide, under Run experiments.

    Args:
        system:
            The system, whose clones take parameters through `set_params`, or a factory of systems, such as a
            system class, which takes them as keyword arguments.

        scenarios:
            The scenarios to compare.

        replicates:
            The number of runs per scenario.

        analyses:
            The analyses of every run, functions of a trajectory that return a frozen result, such as analysis
            functions bound with `bind_analysis`, or `None`. Every field of a result that is set becomes the output
            `<function name>.<field>`, numbered `-1`, `-2`, ... when several analyses share a function.

        until:
            The end time of every run, or `None` for the tuned end time of the system.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        outputs:
            The state and observable paths to keep as series, whose last values are scalar outputs, and functions of
            a trajectory that return a scalar or a mapping of scalars. `None` keeps every observable, or every state
            when the system declares none.

        warmup:
            The simulated time before which kept series are discarded.

        observables:
            The observables of every run, or none for the tuned ones.

        random_state:
            The seed of the random streams, one per row and replicate.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor, in the role of `n_jobs`.

    Returns:
        result:
            The results of every run, one tidy row per run with the name of its scenario.

    Raises:
        ValidationError:
            No scenario is given, a scenario is not a `ScenarioSpec`, or a setting is not valid.

        ExperimentError:
            The system is a name, or the worker processes stop before finishing.

    See Also:
        ScenarioSpec: Names one variant of a system.
        sweep: Runs a system over values of its parameters.

    Examples:
        >>> from skcomplex.core.experiments import ScenarioSpec, compare_scenarios
        >>> from skcomplex.systems.biology.epidemiology import SIRSystem
        >>> scenarios = [ScenarioSpec(), ScenarioSpec('distancing', overrides={'beta': 0.0001})]
        >>> result = compare_scenarios(SIRSystem(), scenarios, until=50, outputs=['I.x'])
        >>> [row['scenario'] for row in result.rows]
        ['baseline', 'distancing']
    """
    if not scenarios or not all(isinstance(scenario, ScenarioSpec) for scenario in scenarios):
        error_msg = f'compare_scenarios takes a nonempty sequence of ScenarioSpec, not {scenarios!r}.'
        raise ValidationError(error_msg)
    return _run_experiment(
        system,
        [{}],
        list(scenarios),
        replicates,
        analyses=analyses,
        until=until,
        dt=dt,
        solver=solver,
        outputs=outputs,
        warmup=warmup,
        observables=observables,
        random_state=random_state,
        executor=executor,
    )

ensemble(system, *, replicates=10, analyses=None, until=None, dt=None, solver=None, outputs=None, warmup=0.0, observables=(), random_state=None, executor='serial')

Return the runs of a system with independent random streams.

It runs a random system replicates times, each with its own random stream spawned from random_state, so the runs are independent and repeatable, and the result reads them as one row per run. Only the streams change, so the system is prepared once. A system with no randomness and a solver that draws nothing gives the same run every time and raises an error. It estimates the spread of the outcomes of an epidemic, of a weather forecast, and of the wealth of traders in a market.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take parameters through set_params, or a factory of systems, such as a system class, which takes them as keyword arguments.

required
replicates int

The number of runs.

10
analyses Sequence[Callable[[Trajectory], object]] | None

The analyses of every run, functions of a trajectory that return a frozen result, such as analysis functions bound with bind_analysis, or None. Every field of a result that is set becomes the output <function name>.<field>, numbered -1, -2, ... when several analyses share a function.

None
until float | None

The end time of every run, or None for the tuned end time of the system.

None
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
outputs Sequence[Output] | None

The state and observable paths to keep as series, whose last values are scalar outputs, and functions of a trajectory that return a scalar or a mapping of scalars. None keeps every observable, or every state when the system declares none.

None
warmup float

The simulated time before which kept series are discarded.

0.0
observables Sequence[Observable]

The observables of every run, or none for the tuned ones.

()
random_state int | None

The seed of the random streams, one per row and replicate.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor, in the role of n_jobs.

'serial'

Returns:

Name Type Description
result ExperimentResult

The results of every run, one tidy row per run, whose ensemble and summary read the runs together.

Raises:

Type Description
ValidationError

The number of runs is not a positive integer, or a setting is not valid.

ExperimentError

The system is a name, or the worker processes stop before finishing.

TagError

The system has the randomness deterministic and the solver does not draw.

See Also

sweep: Runs a system over values of its parameters. compare_scenarios: Runs named variants of a system with shared streams.

Examples:

>>> from skcomplex.core.experiments import ensemble
>>> from skcomplex.systems.biology.epidemiology import SIRSystem
>>> result = ensemble(SIRSystem(stochastic=True), replicates=3, until=10, random_state=0)
>>> result.get_column('seed').tolist()
[0, 1, 2]
Source code in src/skcomplex/core/experiments/_ensemble.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def ensemble(
    system: SystemSource,
    *,
    replicates: int = 10,
    analyses: Sequence[Callable[[Trajectory], object]] | None = None,
    until: float | None = None,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    outputs: Sequence[Output] | None = None,
    warmup: float = 0.0,
    observables: Sequence[Observable] = (),
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> ExperimentResult:
    """Return the runs of a system with independent random streams.

    It runs a random system `replicates` times, each with its own random stream spawned from `random_state`, so the runs
    are independent and repeatable, and the result reads them as one row per run. Only the streams change, so the system
    is prepared once. A system with no randomness and a solver that draws nothing gives the same run every time and
    raises an error. It estimates the spread of the outcomes of an epidemic, of a weather forecast, and of the wealth of
    traders in a market.

    Read more in the user guide, under Run experiments.

    Args:
        system:
            The system, whose clones take parameters through `set_params`, or a factory of systems, such as a
            system class, which takes them as keyword arguments.

        replicates:
            The number of runs.

        analyses:
            The analyses of every run, functions of a trajectory that return a frozen result, such as analysis
            functions bound with `bind_analysis`, or `None`. Every field of a result that is set becomes the output
            `<function name>.<field>`, numbered `-1`, `-2`, ... when several analyses share a function.

        until:
            The end time of every run, or `None` for the tuned end time of the system.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        outputs:
            The state and observable paths to keep as series, whose last values are scalar outputs, and functions of
            a trajectory that return a scalar or a mapping of scalars. `None` keeps every observable, or every state
            when the system declares none.

        warmup:
            The simulated time before which kept series are discarded.

        observables:
            The observables of every run, or none for the tuned ones.

        random_state:
            The seed of the random streams, one per row and replicate.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor, in the role of `n_jobs`.

    Returns:
        result:
            The results of every run, one tidy row per run, whose `ensemble` and `summary` read the runs together.

    Raises:
        ValidationError:
            The number of runs is not a positive integer, or a setting is not valid.

        ExperimentError:
            The system is a name, or the worker processes stop before finishing.

        TagError:
            The system has the randomness `deterministic` and the solver does not draw.

    See Also:
        sweep: Runs a system over values of its parameters.
        compare_scenarios: Runs named variants of a system with shared streams.

    Examples:
        >>> from skcomplex.core.experiments import ensemble
        >>> from skcomplex.systems.biology.epidemiology import SIRSystem
        >>> result = ensemble(SIRSystem(stochastic=True), replicates=3, until=10, random_state=0)
        >>> result.get_column('seed').tolist()
        [0, 1, 2]
    """
    built = build_system(_check_source(system), {}, solver)
    stepper = solver if solver is not None else _get_solver(built)
    if built.get_tags().randomness == 'deterministic' and not getattr(stepper, 'draws', False):
        error_msg = (
            f'ensemble needs the randomness stochastic, but {type(built).__name__} has the randomness deterministic. '
            'Its runs repeat one another, so run it once with `simulate`, or give it a component or a solver that '
            'draws.'
        )
        raise TagError(error_msg)
    return _run_experiment(
        system,
        [{}],
        [ScenarioSpec()],
        replicates,
        analyses=analyses,
        until=until,
        dt=dt,
        solver=solver,
        outputs=outputs,
        warmup=warmup,
        observables=observables,
        random_state=random_state,
        executor=executor,
    )

identifiability(system, data, bounds, *, method='profile', level=0.95, n_starts=5, noise=(0.01,), n=100, dt=None, solver=None, random_state=None, executor='serial')

Return which model parameters of a system the observed time series determine.

A calibration returns estimates even when the data cannot pin them down, and this function tells whether they do. A profile fixes each parameter at values around the best fit and fits the others again, and the parameter is identifiable when the fit worsens enough on both sides within its bounds. Refits add noise to the best run, fit again, and judge each parameter by how far its estimates stray. It tells whether counts fix the growth rate and capacity of a population, whether case counts fix the rates of an epidemic, and whether blood samples fix the clearance of a drug.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take the parameters through set_params, or a factory of systems.

required
data Data

A mapping from state or observable path to its observed (times, values).

required
bounds Bounds

A mapping from model parameter to its (low, high) bounds or its SciPy prior, as calibrate takes them. The profiles stop at the bounds.

required
method str

'profile' or 'refits'. A profile, with pyPESTO, takes the best of n_starts local fits of the Gaussian likelihood, then fixes each parameter on both sides of it and fits the others again until the likelihood ratio falls below the threshold of level or the bound is reached. A parameter is 'identifiable' when both ends of its interval lie inside its bounds. Refits, after Liyanage et al. (2025), add noise at every level of noise to n copies of the best run and fit each again. A parameter is 'strong' when its average relative error is at most the level, 'weak' when it is at most ten times the level, and 'none' above, taking its worst verdict over the levels.

'profile'
level float

The confidence level of the likelihood-ratio intervals of a profile, between 0 and 1.

0.95
n_starts int

The number of local fits of a profile whose best is the best fit.

5
noise Sequence[float]

The relative noise levels of the refits, such as 0.01 for 1% of every value.

(0.01,)
n int

The number of noisy copies per level of the refits.

100
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
random_state int | None

The seed of the start points, the runs, and the noise.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor that runs the refits.

'serial'

Returns:

Name Type Description
result IdentifiabilityResult

The best fit, the verdicts, and the profiles and intervals or the relative errors.

Raises:

Type Description
ValidationError

The method is unknown, the level is not between 0 and 1, a noise level is not positive, a count is not a positive integer, there is no data, or a bound is not valid.

ExperimentError

The system is a name.

See Also

calibrate: Fits the parameters of a system to data.

Examples:

>>> from skcomplex.core.experiments import identifiability
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> trajectory = LogisticGrowthSystem(r=0.5).prepare().simulate(until=20, dt=1.0)
>>> data = {'population.x': (trajectory.times, trajectory.get_values('population.x'))}
>>> identifiability(LogisticGrowthSystem(), data, {'r': (0.1, 2.0), 'K': (50.0, 500.0)}).verdicts
{'r': 'identifiable', 'K': 'identifiable'}
Source code in src/skcomplex/core/experiments/_identifiability.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def identifiability(
    system: SystemSource,
    data: Data,
    bounds: Bounds,
    *,
    method: str = 'profile',
    level: float = 0.95,
    n_starts: int = 5,
    noise: Sequence[float] = (0.01,),
    n: int = 100,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> IdentifiabilityResult:
    """Return which model parameters of a system the observed time series determine.

    A calibration returns estimates even when the data cannot pin them down, and this function tells whether they do. A
    profile fixes each parameter at values around the best fit and fits the others again, and the parameter is
    identifiable when the fit worsens enough on both sides within its bounds. Refits add noise to the best run, fit
    again, and judge each parameter by how far its estimates stray. It tells whether counts fix the growth rate and
    capacity of a population, whether case counts fix the rates of an epidemic, and whether blood samples fix the
    clearance of a drug.

    Read more in the user guide, under Calibrate.

    Args:
        system:
            The system, whose clones take the parameters through `set_params`, or a factory of systems.

        data:
            A mapping from state or observable path to its observed `(times, values)`.

        bounds:
            A mapping from model parameter to its `(low, high)` bounds or its SciPy prior, as `calibrate` takes them.
            The profiles stop at the bounds.

        method:
            `'profile'` or `'refits'`. A profile, with pyPESTO, takes the best of `n_starts` local fits of the
            Gaussian likelihood, then fixes each parameter on both sides of it and fits the others again until the
            likelihood ratio falls below the threshold of `level` or the bound is reached. A parameter is
            `'identifiable'` when both ends of its interval lie inside its bounds. Refits, after Liyanage et al.
            (2025), add noise at every level of `noise` to `n` copies of the best run and fit each again. A parameter
            is `'strong'` when its average relative error is at most the level, `'weak'` when it is at most ten times
            the level, and `'none'` above, taking its worst verdict over the levels.

        level:
            The confidence level of the likelihood-ratio intervals of a profile, between 0 and 1.

        n_starts:
            The number of local fits of a profile whose best is the best fit.

        noise:
            The relative noise levels of the refits, such as 0.01 for 1% of every value.

        n:
            The number of noisy copies per level of the refits.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        random_state:
            The seed of the start points, the runs, and the noise.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor that runs the refits.

    Returns:
        result:
            The best fit, the verdicts, and the profiles and intervals or the relative errors.

    Raises:
        ValidationError:
            The method is unknown, the level is not between 0 and 1, a noise level is not positive, a count is not a
            positive integer, there is no data, or a bound is not valid.

        ExperimentError:
            The system is a name.

    See Also:
        calibrate: Fits the parameters of a system to data.

    Examples:
        >>> from skcomplex.core.experiments import identifiability
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> trajectory = LogisticGrowthSystem(r=0.5).prepare().simulate(until=20, dt=1.0)
        >>> data = {'population.x': (trajectory.times, trajectory.get_values('population.x'))}
        >>> identifiability(LogisticGrowthSystem(), data, {'r': (0.1, 2.0), 'K': (50.0, 500.0)}).verdicts
        {'r': 'identifiable', 'K': 'identifiable'}
    """
    source = _check_source(system)
    if method not in METHODS:
        error_msg = f'Unknown method {method!r}. Use one of {", ".join(repr(item) for item in METHODS)}.'
        raise ValidationError(error_msg)
    if not 0 < level < 1:
        error_msg = f'The level of the intervals must lie between 0 and 1, not {level!r}.'
        raise ValidationError(error_msg)
    if not noise or any(not float(item) > 0 for item in noise):
        error_msg = f'The noise levels of the refits must be positive, not {tuple(noise)!r}.'
        raise ValidationError(error_msg)
    _check_count('n', n)
    _check_count('n_starts', n_starts)
    _check_settings('local', 'likelihood', data, bounds, 1)
    if method == 'refits':
        return _get_refits(
            source,
            data,
            bounds,
            noise=tuple(float(item) for item in noise),
            n=n,
            dt=dt,
            solver=solver,
            random_state=random_state,
            executor=executor,
        )
    objective = _CalibrationObjective(
        source,
        _series_of(data),
        _check_priors(bounds),
        dt=dt,
        solver=solver,
        random_state=random_state,
    )
    return _get_profiles(objective, level, n_starts, random_state)

orbit_diagram(system, parameter, values, observable, *, transient, keep, dt=None, decimals=6, random_state=None, executor='serial', vectorized=False)

Return the values an observable visits after a transient, per parameter value.

It runs the system for every value of parameter to transient + (keep - 1) * dt and keeps the values of observable from transient on, so a settled cycle shows as the few values it repeats. With vectorized, every value runs as one member of a single simulation. It shows the period doubling of the logistic map of a population, the route to chaos of a forced pendulum, and the pulses of a laser.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
system SystemSource

The system, or a factory of systems, such as a system class.

required
parameter str

The parameter to sweep, a name set_params takes such as r or growth__r, or a dotted path such as map.r, which runs one prepared clone.

required
values Sequence[float]

The values of the parameter.

required
observable str

The state or observable path whose values are kept.

required
transient float

The simulated time discarded before keeping values.

required
keep int

The number of frames kept after the transient.

required
dt float | None

The time between frames, or None for the tuned one of the system. The kept window is counted in steps of dt, or of 1, the step of maps, when it is None.

None
decimals int

The decimals the kept values are rounded to before counting the period of every orbit.

6
random_state int | None

The seed of stochastic runs.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor of the separate runs.

'serial'
vectorized bool

Whether to run every value as a member of one simulation of the replicated system.

False

Returns:

Name Type Description
result OrbitDiagramResult

The kept values and the period of the orbit of every value of the parameter.

Raises:

Type Description
ValidationError

No value is given, or the number of kept frames is not a positive integer.

ExperimentError

The system is a name.

See Also

basin_stability: Gives the share of initial states per final behaviour. sweep: Runs a system over values of its parameters.

Examples:

>>> from skcomplex.core.experiments import orbit_diagram
>>> from skcomplex.systems.mathematics.dynamical_systems import LogisticMapSystem
>>> diagram = orbit_diagram(LogisticMapSystem(), 'r', [2.9, 3.2], 'map.x', transient=1000, keep=20)
>>> diagram.periods.tolist()
[1, 2]
Source code in src/skcomplex/core/experiments/_orbit_diagram.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def orbit_diagram(
    system: SystemSource,
    parameter: str,
    values: Sequence[float],
    observable: str,
    *,
    transient: float,
    keep: int,
    dt: float | None = None,
    decimals: int = 6,
    random_state: int | None = None,
    executor: str | Executor = 'serial',
    vectorized: bool = False,
) -> OrbitDiagramResult:
    """Return the values an observable visits after a transient, per parameter value.

    It runs the system for every value of `parameter` to `transient + (keep - 1) * dt` and keeps the values of
    `observable` from `transient` on, so a settled cycle shows as the few values it repeats. With `vectorized`, every
    value runs as one member of a single simulation. It shows the period doubling of the logistic map of a population,
    the route to chaos of a forced pendulum, and the pulses of a laser.

    Read more in the user guide, under Run experiments.

    Args:
        system:
            The system, or a factory of systems, such as a system class.

        parameter:
            The parameter to sweep, a name `set_params` takes such as `r` or `growth__r`, or a dotted path such as
            `map.r`, which runs one prepared clone.

        values:
            The values of the parameter.

        observable:
            The state or observable path whose values are kept.

        transient:
            The simulated time discarded before keeping values.

        keep:
            The number of frames kept after the transient.

        dt:
            The time between frames, or `None` for the tuned one of the system. The kept window is counted in steps of
            `dt`, or of 1, the step of maps, when it is `None`.

        decimals:
            The decimals the kept values are rounded to before counting the period of every orbit.

        random_state:
            The seed of stochastic runs.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor of the separate runs.

        vectorized:
            Whether to run every value as a member of one simulation of the replicated system.

    Returns:
        result:
            The kept values and the period of the orbit of every value of the parameter.

    Raises:
        ValidationError:
            No value is given, or the number of kept frames is not a positive integer.

        ExperimentError:
            The system is a name.

    See Also:
        basin_stability: Gives the share of initial states per final behaviour.
        sweep: Runs a system over values of its parameters.

    Examples:
        >>> from skcomplex.core.experiments import orbit_diagram
        >>> from skcomplex.systems.mathematics.dynamical_systems import LogisticMapSystem
        >>> diagram = orbit_diagram(LogisticMapSystem(), 'r', [2.9, 3.2], 'map.x', transient=1000, keep=20)
        >>> diagram.periods.tolist()
        [1, 2]
    """
    _check_source(system)
    if not len(values):
        error_msg = 'An orbit diagram needs at least one value of the parameter.'
        raise ValidationError(error_msg)
    _check_count('keep', keep)
    step = dt if dt is not None else 1.0
    until = transient + (keep - 1) * step
    if vectorized:
        trajectory, _ = _run_replicated(system, {parameter: list(values)}, until, step, random_state)
        observed = np.asarray(trajectory.get_values(observable), dtype=np.float64)
        series = observed[np.asarray(trajectory.times) >= transient - 1e-9]
        points = [series[:, index] for index in range(len(values))]
    else:
        result = _run_experiment(
            system,
            [{parameter: value} for value in values],
            [ScenarioSpec()],
            1,
            analyses=None,
            until=until,
            dt=dt,
            solver=None,
            outputs=[observable],
            warmup=transient,
            observables=(),
            random_state=random_state,
            executor=executor,
        )
        points = [np.asarray(run.series[observable], dtype=float) for run in result.runs]
    periods = np.asarray([np.unique(np.round(series, decimals)).size for series in points], dtype=np.int64)
    return OrbitDiagramResult(points, periods)

posterior_coverage(system, bounds, times, *, paths=None, method='mcmc', loss='likelihood', n=40, levels=(0.5, 0.9), noise=0.0, summary=None, n_samples=500, budget=None, chains=4, dt=None, solver=None, random_state=None, executor='serial')

Return how often the intervals of a sampling calibration hold the true values.

It draws n sets of true parameters from the priors that bounds give, simulates noisy data from each, calibrates every data set, and counts how often the central interval of every level holds the true value. A sound method covers the truth with its 90% interval in 90% of the data sets. It also ranks every true value among its samples, the check of Talts et al. (2018). It is run before trusting a calibration of an epidemic, a climate model, or a chemical reaction on real data.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
system SystemSource

The system, or a factory of systems.

required
bounds Bounds

A pair (low, high) or a SciPy prior per model parameter, as calibrate takes them.

required
times ArrayLike

The times of the simulated data.

required
paths Sequence[str] | None

The state or observable paths of the data, or None for every scalar state.

None
method str

'abc_smc', 'mcmc', or 'variational'.

'mcmc'
loss str

The loss of the method.

'likelihood'
n int

The number of true parameter vectors.

40
levels Sequence[float]

The levels of the central credible intervals, between 0 and 1.

(0.5, 0.9)
noise float

The standard deviation of the Gaussian noise added to the simulated data.

0.0
summary Summary | None

The summary statistics of ABC-SMC, or None.

None
n_samples int

The number of samples of every calibration, per chain for MCMC.

500
budget int | None

The budget of every calibration, or None for the default of the method.

None
chains int

The number of chains of MCMC.

4
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
random_state int | None

The seed of the true values, the noise, and the calibrations.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor that runs the calibrations. MCMC and variational calibration run numpyro, whose effect handlers are global, so they do not run on threads.

'serial'

Returns:

Name Type Description
result CoverageResult

The coverage by level and parameter, the ranks, the true values, and the calibrations.

Raises:

Type Description
ValidationError

The method is not a posterior method, the loss does not fit it, a level is not between 0 and 1, n is not a positive integer, or the executor is unknown or runs numpyro on threads.

See Also

calibrate: Fits the parameters of a system to data.

Examples:

>>> from skcomplex.core.experiments import posterior_coverage
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> settings = dict(method='variational', n=3, levels=(0.9,), noise=5.0, n_samples=100, budget=300)
>>> result = posterior_coverage(LogisticGrowthSystem(n=10.0), {'r': (0.5, 1.0)}, list(range(11)), **settings)
>>> result.ranks['r'].shape
(3,)
Source code in src/skcomplex/core/experiments/_coverage.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def posterior_coverage(
    system: SystemSource,
    bounds: Bounds,
    times: npt.ArrayLike,
    *,
    paths: Sequence[str] | None = None,
    method: str = 'mcmc',
    loss: str = 'likelihood',
    n: int = 40,
    levels: Sequence[float] = (0.5, 0.9),
    noise: float = 0.0,
    summary: Summary | None = None,
    n_samples: int = 500,
    budget: int | None = None,
    chains: int = 4,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> CoverageResult:
    """Return how often the intervals of a sampling calibration hold the true values.

    It draws `n` sets of true parameters from the priors that `bounds` give, simulates noisy data from each, calibrates
    every data set, and counts how often the central interval of every level holds the true value. A sound method covers
    the truth with its 90% interval in 90% of the data sets. It also ranks every true value among its samples, the check
    of Talts et al. (2018). It is run before trusting a calibration of an epidemic, a climate model, or a chemical
    reaction on real data.

    Read more in the user guide, under Calibrate.

    Args:
        system:
            The system, or a factory of systems.

        bounds:
            A pair `(low, high)` or a SciPy prior per model parameter, as `calibrate` takes them.

        times:
            The times of the simulated data.

        paths:
            The state or observable paths of the data, or `None` for every scalar state.

        method:
            `'abc_smc'`, `'mcmc'`, or `'variational'`.

        loss:
            The loss of the method.

        n:
            The number of true parameter vectors.

        levels:
            The levels of the central credible intervals, between 0 and 1.

        noise:
            The standard deviation of the Gaussian noise added to the simulated data.

        summary:
            The summary statistics of ABC-SMC, or `None`.

        n_samples:
            The number of samples of every calibration, per chain for MCMC.

        budget:
            The budget of every calibration, or `None` for the default of the method.

        chains:
            The number of chains of MCMC.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        random_state:
            The seed of the true values, the noise, and the calibrations.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor that runs the calibrations. MCMC
            and variational calibration run numpyro, whose effect handlers are global, so they do not run on threads.

    Returns:
        result:
            The coverage by level and parameter, the ranks, the true values, and the calibrations.

    Raises:
        ValidationError:
            The method is not a posterior method, the loss does not fit it, a level is not between 0 and 1, `n` is not
            a positive integer, or the executor is unknown or runs numpyro on threads.

    See Also:
        calibrate: Fits the parameters of a system to data.

    Examples:
        >>> from skcomplex.core.experiments import posterior_coverage
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> settings = dict(method='variational', n=3, levels=(0.9,), noise=5.0, n_samples=100, budget=300)
        >>> result = posterior_coverage(LogisticGrowthSystem(n=10.0), {'r': (0.5, 1.0)}, list(range(11)), **settings)
        >>> result.ranks['r'].shape
        (3,)
    """
    source = _check_source(system)
    if method not in POSTERIOR_METHODS:
        error_msg = f'Posterior coverage calibrates by a posterior method. Use one of {", ".join(POSTERIOR_METHODS)}.'
        raise ValidationError(error_msg)
    if loss not in LOSSES[method] or loss == 'events':
        allowed = ', '.join(item for item in LOSSES[method] if item != 'events')
        error_msg = f'Posterior coverage with the method {method!r} takes the losses {allowed}.'
        raise ValidationError(error_msg)
    _check_count('n', n)
    checked = tuple(float(level) for level in levels)
    if not checked or any(not 0 < level < 1 for level in checked):
        error_msg = f'The levels of posterior coverage must lie between 0 and 1, not {tuple(levels)!r}.'
        raise ValidationError(error_msg)
    if isinstance(executor, str) and executor not in ExecutorKind:
        error_msg = f"executor = {executor!r} must be 'serial', 'thread', 'process', or an executor."
        raise ValidationError(error_msg)
    if (executor == 'thread' or isinstance(executor, ThreadPoolExecutor)) and method != 'abc_smc':
        error_msg = (
            f'The method {method!r} runs numpyro, whose effect handlers are global, so it cannot run on threads. Use '
            "executor='process' or executor='serial'."
        )
        raise ValidationError(error_msg)
    priors = _check_priors(bounds)
    rng = np.random.default_rng(random_state)
    draws = {name: np.asarray(prior.rvs(size=n, random_state=rng), dtype=float) for name, prior in priors.items()}
    truths = [{name: float(values[index]) for name, values in draws.items()} for index in range(n)]
    seeds = [int(seed) for seed in rng.integers(2**31, size=n)]
    task = functools.partial(
        _calibrate_truth,
        source=source,
        bounds=bounds,
        times=np.asarray(times, dtype=float),
        paths=paths,
        noise=noise,
        method=method,
        loss=loss,
        summary=summary,
        n_samples=n_samples,
        budget=budget,
        chains=chains,
        dt=dt,
        solver=solver,
    )
    results = tuple(_map_calls(task, list(zip(truths, seeds, strict=True)), executor))
    coverage: dict[float, dict[str, float]] = {level: {} for level in checked}
    ranks: dict[str, Array] = {}
    for name in priors:
        pairs = [((result.samples or {})[name], np.asarray(result.weights)) for result in results]
        values = [truth[name] for truth in truths]
        below = [np.sum(weights[samples < value]) for (samples, weights), value in zip(pairs, values, strict=True)]
        ranks[name] = np.asarray(below) / np.asarray([np.sum(weights) for _, weights in pairs])
        for level in checked:
            intervals = [_interval(samples, weights, level) for samples, weights in pairs]
            inside = [low <= value <= high for (low, high), value in zip(intervals, values, strict=True)]
            coverage[level][name] = float(np.mean(inside))
    return CoverageResult(checked, coverage, ranks, draws, results)

sensitivity(system, bounds, *, output, method='sobol', n=None, until=None, dt=None, solver=None, observables=(), random_state=None, executor='serial')

Return the sensitivity of a scalar output of a system to its inputs, with SALib.

It varies the inputs within bounds, runs the system once per row of the design of the method, as sweep does, and measures how much each input moves the last value of output. One at a time moves each input alone, Morris averages many such moves, and Sobol splits the variance of the output among the inputs. It ranks the rates of an epidemic by their effect on its peak, the inputs of a climate model by their effect on warming, and the costs of a supply chain by their effect on profit.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take parameters through set_params, or a factory of systems, such as a system class, which takes them as keyword arguments.

required
bounds Bounds

A pair (low, high) per input, a name set_params takes or a dotted path of a state or a parameter of a component.

required
output str

The state or observable path whose last value is the scalar output.

required
method str

'oat' moves every input from its lower to its upper bound with the others at their midpoints. 'morris' runs n Morris trajectories on four levels, 10 by default, and gives the elementary effects. 'sobol' runs the sample of Saltelli of n base points, 1024 by default and best a power of 2, and gives the first-order and total Sobol indices.

'sobol'
n int | None

The number of Morris trajectories or of base points of Saltelli's sample, or None for the default.

None
until float | None

The end time of every run, or None for the tuned end time of the system.

None
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
observables Sequence[Observable]

The observables of every run, or none for the tuned ones.

()
random_state int | None

The seed of the design, of the runs, and of the bootstrap confidence intervals.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor.

'serial'

Returns:

Name Type Description
result SensitivityResult

The inputs of every run, the outputs, the indices of the method, and the ranking of the inputs.

Raises:

Type Description
AnalysisError

The method is unknown or the output is not a name.

ValidationError

A bound is not a pair, or an input is no parameter of the system and no state or parameter of a component.

See Also

sweep: Runs a system over values of its parameters.

Examples:

>>> from skcomplex.core.experiments import sensitivity
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> bounds = {'growth.r': (0.1, 1.0), 'growth.K': (50, 150)}
>>> result = sensitivity(LogisticGrowthSystem(), bounds, output='population.x', method='oat', until=20)
>>> result.ranking[0]
'growth.K'
Source code in src/skcomplex/core/experiments/_sensitivity.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def sensitivity(
    system: SystemSource,
    bounds: Bounds,
    *,
    output: str,
    method: str = 'sobol',
    n: int | None = None,
    until: float | None = None,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    observables: Sequence[Observable] = (),
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> SensitivityResult:
    """Return the sensitivity of a scalar output of a system to its inputs, with SALib.

    It varies the inputs within `bounds`, runs the system once per row of the design of the method, as `sweep` does, and
    measures how much each input moves the last value of `output`. One at a time moves each input alone, Morris averages
    many such moves, and Sobol splits the variance of the output among the inputs. It ranks the rates of an epidemic by
    their effect on its peak, the inputs of a climate model by their effect on warming, and the costs of a supply chain
    by their effect on profit.

    Read more in the user guide, under Run experiments.

    Args:
        system:
            The system, whose clones take parameters through `set_params`, or a factory of systems, such as a
            system class, which takes them as keyword arguments.

        bounds:
            A pair `(low, high)` per input, a name `set_params` takes or a dotted path of a state or a parameter of a
            component.

        output:
            The state or observable path whose last value is the scalar output.

        method:
            `'oat'` moves every input from its lower to its upper bound with the others at their midpoints.
            `'morris'` runs `n` Morris trajectories on four levels, 10 by default, and gives the elementary effects.
            `'sobol'` runs the sample of Saltelli of `n` base points, 1024 by default and best a power of 2, and gives
            the first-order and total Sobol indices.

        n:
            The number of Morris trajectories or of base points of Saltelli's sample, or `None` for the default.

        until:
            The end time of every run, or `None` for the tuned end time of the system.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        observables:
            The observables of every run, or none for the tuned ones.

        random_state:
            The seed of the design, of the runs, and of the bootstrap confidence intervals.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor.

    Returns:
        result:
            The inputs of every run, the outputs, the indices of the method, and the ranking of the inputs.

    Raises:
        AnalysisError:
            The method is unknown or the output is not a name.

        ValidationError:
            A bound is not a pair, or an input is no parameter of the system and no state or parameter of a component.

    See Also:
        sweep: Runs a system over values of its parameters.

    Examples:
        >>> from skcomplex.core.experiments import sensitivity
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> bounds = {'growth.r': (0.1, 1.0), 'growth.K': (50, 150)}
        >>> result = sensitivity(LogisticGrowthSystem(), bounds, output='population.x', method='oat', until=20)
        >>> result.ranking[0]
        'growth.K'
    """
    if method not in METHODS:
        error_msg = f'Unknown sensitivity method {method!r}. Use one of {", ".join(METHODS)}.'
        raise AnalysisError(error_msg)
    if not isinstance(output, str):
        error_msg = f'output = {output!r} must be the name of a state or an observable of the system.'
        raise AnalysisError(error_msg)
    size = n if n is not None else SIZES[method]
    rows = _get_sensitivity_rows(bounds, method, size, random_state)
    result = _run_experiment(
        system,
        rows,
        [ScenarioSpec()],
        1,
        analyses=None,
        until=until,
        dt=dt,
        solver=solver,
        outputs=[output],
        warmup=0.0,
        observables=observables,
        random_state=random_state,
        executor=executor,
    )
    names = list(bounds)
    inputs = np.asarray([[row[name] for name in names] for row in rows], dtype=float)
    outputs = np.asarray(result.get_column(output), dtype=float)
    problem = {'num_vars': len(names), 'names': names}
    if method == 'oat':
        effects = dict(zip(names, map(float, outputs[1::2] - outputs[0::2]), strict=True))
        return SensitivityResult(names, inputs, outputs, _rank(names, effects), effects=effects)
    if method == 'morris':
        indices = morris_analysis.analyze(problem, inputs, outputs, seed=random_state)
        mu_star = _by_name(names, indices['mu_star'])
        return SensitivityResult(
            names,
            inputs,
            outputs,
            _rank(names, mu_star),
            mu_star=mu_star,
            mu_star_conf=_by_name(names, indices['mu_star_conf']),
            sigma=_by_name(names, indices['sigma']),
        )
    indices = sobol_analysis.analyze(problem, outputs, calc_second_order=False, seed=random_state)
    total_order = _by_name(names, indices['ST'])
    return SensitivityResult(
        names,
        inputs,
        outputs,
        _rank(names, total_order),
        first_order=_by_name(names, indices['S1']),
        first_order_conf=_by_name(names, indices['S1_conf']),
        total_order=total_order,
        total_order_conf=_by_name(names, indices['ST_conf']),
    )

sweep(system, parameters, *, design='grid', n=64, replicates=1, analyses=None, until=None, dt=None, solver=None, outputs=None, warmup=0.0, observables=(), random_state=None, executor='serial')

Return the runs of a system over rows of values.

It runs a copy of the system for every row of values, as validation_curve of scikit-learn does, such as sweep(system, {'r': [0.5, 1.0]}) for two growth rates. A name without a dot, such as r or the nested growth__r, is set with set_params and the copy is prepared again, and a dotted path, such as population.x, sets a value of a component on one prepared copy. The rows come from a grid or a random design, and the system passed in is left unchanged. It maps the change of state of a magnet over temperature, the final size of an epidemic over its rate of infection, and the clusters of opinions over the confidence of the voters.

Read more in the user guide, under Run experiments.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take parameters through set_params, or a factory of systems, such as a system class, which takes them as keyword arguments.

required
parameters Bounds | Sequence[Mapping[str, object]]

What the design reads by name, or the rows to run.

required
design str

The design of the rows. 'grid' runs every combination of a sequence of values per name, the last name varying fastest. 'random' draws n samples, uniform within a pair (low, high) or from a SciPy distribution. 'latin_hypercube' draws n samples with one in every stratum of every name. 'sobol' takes n points of a scrambled Sobol sequence, best with n a power of 2. A sequence of rows, each a mapping from name to value, runs as it is.

'grid'
n int

The number of rows of a sampled design.

64
replicates int

The number of runs per row, each with its own random stream.

1
analyses Sequence[Callable[[Trajectory], object]] | None

The analyses of every run, functions of a trajectory that return a frozen result, such as analysis functions bound with bind_analysis, or None. Every field of a result that is set becomes the output <function name>.<field>, numbered -1, -2, ... when several analyses share a function.

None
until float | None

The end time of every run, or None for the tuned end time of the system.

None
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
outputs Sequence[Output] | None

The state and observable paths to keep as series, whose last values are scalar outputs, and functions of a trajectory that return a scalar or a mapping of scalars. None keeps every observable, or every state when the system declares none.

None
warmup float

The simulated time before which kept series are discarded.

0.0
observables Sequence[Observable]

The observables of every run, or none for the tuned ones.

()
random_state int | None

The seed of the random streams, one per row and replicate.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor, in the role of n_jobs.

'serial'

Returns:

Name Type Description
result ExperimentResult

The results of every run, one tidy row per run.

Raises:

Type Description
ValidationError

The design is unknown, the values do not fit it, a name is no parameter of the system and no state or parameter of a component, or a setting is not valid.

ExperimentError

The system is a name, or the worker processes stop before finishing.

See Also

ensemble: Runs a system many times with independent random streams. sensitivity: Ranks the inputs of a system by their effect on an output.

Examples:

>>> from skcomplex.core.experiments import sweep
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> result = sweep(LogisticGrowthSystem(), {'r': [0.5, 1.0]}, until=5, outputs=['population.x'])
>>> result.get_column('r').tolist()
[0.5, 1.0]
Source code in src/skcomplex/core/experiments/_sweep.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def sweep(
    system: SystemSource,
    parameters: Bounds | Sequence[Mapping[str, object]],
    *,
    design: str = 'grid',
    n: int = 64,
    replicates: int = 1,
    analyses: Sequence[Callable[[Trajectory], object]] | None = None,
    until: float | None = None,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    outputs: Sequence[Output] | None = None,
    warmup: float = 0.0,
    observables: Sequence[Observable] = (),
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> ExperimentResult:
    """Return the runs of a system over rows of values.

    It runs a copy of the system for every row of values, as `validation_curve` of scikit-learn does, such as
    `sweep(system, {'r': [0.5, 1.0]})` for two growth rates. A name without a dot, such as `r` or the nested
    `growth__r`, is set with `set_params` and the copy is prepared again, and a dotted path, such as `population.x`,
    sets a value of a component on one prepared copy. The rows come from a grid or a random design, and the system
    passed in is left unchanged. It maps the change of state of a magnet over temperature, the final size of an epidemic
    over its rate of infection, and the clusters of opinions over the confidence of the voters.

    Read more in the user guide, under Run experiments.

    Args:
        system:
            The system, whose clones take parameters through `set_params`, or a factory of systems, such as a
            system class, which takes them as keyword arguments.

        parameters:
            What the design reads by name, or the rows to run.

        design:
            The design of the rows. `'grid'` runs every combination of a sequence of values per name, the last name
            varying fastest. `'random'` draws `n` samples, uniform within a pair `(low, high)` or from a SciPy
            distribution. `'latin_hypercube'` draws `n` samples with one in every stratum of every name. `'sobol'`
            takes `n` points of a scrambled Sobol sequence, best with `n` a power of 2. A sequence of rows, each a
            mapping from name to value, runs as it is.

        n:
            The number of rows of a sampled design.

        replicates:
            The number of runs per row, each with its own random stream.

        analyses:
            The analyses of every run, functions of a trajectory that return a frozen result, such as analysis
            functions bound with `bind_analysis`, or `None`. Every field of a result that is set becomes the output
            `<function name>.<field>`, numbered `-1`, `-2`, ... when several analyses share a function.

        until:
            The end time of every run, or `None` for the tuned end time of the system.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        outputs:
            The state and observable paths to keep as series, whose last values are scalar outputs, and functions of
            a trajectory that return a scalar or a mapping of scalars. `None` keeps every observable, or every state
            when the system declares none.

        warmup:
            The simulated time before which kept series are discarded.

        observables:
            The observables of every run, or none for the tuned ones.

        random_state:
            The seed of the random streams, one per row and replicate.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor, in the role of `n_jobs`.

    Returns:
        result:
            The results of every run, one tidy row per run.

    Raises:
        ValidationError:
            The design is unknown, the values do not fit it, a name is no parameter of the system and no state or
            parameter of a component, or a setting is not valid.

        ExperimentError:
            The system is a name, or the worker processes stop before finishing.

    See Also:
        ensemble: Runs a system many times with independent random streams.
        sensitivity: Ranks the inputs of a system by their effect on an output.

    Examples:
        >>> from skcomplex.core.experiments import sweep
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> result = sweep(LogisticGrowthSystem(), {'r': [0.5, 1.0]}, until=5, outputs=['population.x'])
        >>> result.get_column('r').tolist()
        [0.5, 1.0]
    """
    rows = _get_rows(parameters, design, n, random_state)
    return _run_experiment(
        system,
        rows,
        [ScenarioSpec()],
        replicates,
        analyses=analyses,
        until=until,
        dt=dt,
        solver=solver,
        outputs=outputs,
        warmup=warmup,
        observables=observables,
        random_state=random_state,
        executor=executor,
    )

virtual_population(system, bounds, outputs, constraints, *, n=1000, target=None, design='random', until=None, dt=None, solver=None, random_state=None, executor='serial')

Return plausible parameter sets of a system, and those matching observed values.

It draws n rows of parameters from the priors that bounds give, runs the system once per row with sweep, and keeps the rows whose outputs all lie in their constraints ranges. With target, the observed values of one output, it picks among them with the chance of Allen et al. (2016), so the picked outputs follow the observed spread. It samples virtual patients whose tumours look like those of a trial, economies whose growth lies in historical ranges, and ecosystems whose populations stay within observed counts.

Read more in the user guide, under Calibrate.

Parameters:

Name Type Description Default
system SystemSource

The system, whose clones take the parameters through set_params, or a factory of systems.

required
bounds Bounds

A mapping from model parameter or dotted path to its (low, high) bounds or its SciPy prior.

required
outputs Sequence[Output]

The outputs of every run, state and observable paths whose last values are the outputs, and functions of a trajectory that return a scalar, named by the function.

required
constraints Mapping[str, Sequence[float]]

A mapping from output name to its plausible (low, high) range.

required
n int

The number of sampled rows.

1000
target Mapping[str, ArrayLike] | None

A mapping from one output name to its observed values, or None for no selection.

None
design str

'random' or 'latin_hypercube'.

'random'
until float | None

The end time of every run, or None for the tuned end time of the system.

None
dt float | None

The time between frames, or None for the tuned one.

None
solver BaseSolver | None

The solver, or None for the tuned one.

None
random_state int | None

The seed of the rows, the runs, and the selection.

None
executor str | Executor

'serial', 'thread', 'process', or a concurrent.futures executor that runs the rows.

'serial'

Returns:

Name Type Description
result VirtualPopulationResult

The plausible rows, the acceptance rate, and the selected rows and their probabilities of inclusion.

Raises:

Type Description
ValidationError

The design is not a sampled one, a constraint or the target names no output, a range is not increasing, the target names more than one output, or n is not a positive integer.

ExperimentError

No row is plausible, or fewer than ten rows are plausible with a target.

See Also

sweep: Runs a system over rows of values. calibrate: Fits the parameters of a system to data.

Examples:

>>> from skcomplex.core.experiments import virtual_population
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> bounds, ranges, system = {'r': (0.1, 1.0)}, {'population.x': (50.0, 100.0)}, LogisticGrowthSystem()
>>> result = virtual_population(system, bounds, list(ranges), ranges, n=20, until=5.0, random_state=0)
>>> result.acceptance
0.65
Source code in src/skcomplex/core/experiments/_virtual_population.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def virtual_population(
    system: SystemSource,
    bounds: Bounds,
    outputs: Sequence[Output],
    constraints: Mapping[str, Sequence[float]],
    *,
    n: int = 1000,
    target: Mapping[str, npt.ArrayLike] | None = None,
    design: str = 'random',
    until: float | None = None,
    dt: float | None = None,
    solver: BaseSolver | None = None,
    random_state: int | None = None,
    executor: str | Executor = 'serial',
) -> VirtualPopulationResult:
    """Return plausible parameter sets of a system, and those matching observed values.

    It draws `n` rows of parameters from the priors that `bounds` give, runs the system once per row with `sweep`, and
    keeps the rows whose outputs all lie in their `constraints` ranges. With `target`, the observed values of one
    output, it picks among them with the chance of Allen et al. (2016), so the picked outputs follow the observed
    spread. It samples virtual patients whose tumours look like those of a trial, economies whose growth lies in
    historical ranges, and ecosystems whose populations stay within observed counts.

    Read more in the user guide, under Calibrate.

    Args:
        system:
            The system, whose clones take the parameters through `set_params`, or a factory of systems.

        bounds:
            A mapping from model parameter or dotted path to its `(low, high)` bounds or its SciPy prior.

        outputs:
            The outputs of every run, state and observable paths whose last values are the outputs, and functions of a
            trajectory that return a scalar, named by the function.

        constraints:
            A mapping from output name to its plausible `(low, high)` range.

        n:
            The number of sampled rows.

        target:
            A mapping from one output name to its observed values, or `None` for no selection.

        design:
            `'random'` or `'latin_hypercube'`.

        until:
            The end time of every run, or `None` for the tuned end time of the system.

        dt:
            The time between frames, or `None` for the tuned one.

        solver:
            The solver, or `None` for the tuned one.

        random_state:
            The seed of the rows, the runs, and the selection.

        executor:
            `'serial'`, `'thread'`, `'process'`, or a `concurrent.futures` executor that runs the rows.

    Returns:
        result:
            The plausible rows, the acceptance rate, and the selected rows and their probabilities of inclusion.

    Raises:
        ValidationError:
            The design is not a sampled one, a constraint or the target names no output, a range is not increasing,
            the target names more than one output, or `n` is not a positive integer.

        ExperimentError:
            No row is plausible, or fewer than ten rows are plausible with a target.

    See Also:
        sweep: Runs a system over rows of values.
        calibrate: Fits the parameters of a system to data.

    Examples:
        >>> from skcomplex.core.experiments import virtual_population
        >>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
        >>> bounds, ranges, system = {'r': (0.1, 1.0)}, {'population.x': (50.0, 100.0)}, LogisticGrowthSystem()
        >>> result = virtual_population(system, bounds, list(ranges), ranges, n=20, until=5.0, random_state=0)
        >>> result.acceptance
        0.65
    """
    _check_count('n', n)
    if design not in DESIGNS:
        error_msg = f'Unknown design {design!r}. A virtual population samples with one of {", ".join(DESIGNS)}.'
        raise ValidationError(error_msg)
    if target is not None and len(target) != 1:
        error_msg = f'The target holds the observed values of one output, not of {len(target)}.'
        raise ValidationError(error_msg)
    names = list(_check_priors(bounds))
    result = sweep(
        system,
        bounds,
        design=design,
        n=n,
        until=until,
        dt=dt,
        solver=solver,
        outputs=outputs,
        random_state=random_state,
        executor=executor,
    )
    frame = result.convert_to_frame()
    kept = [column for column in frame.columns if column not in {*names, 'scenario', 'replicate', 'seed'}]
    frame = frame[[*names, *kept]]
    ranges = _check_constraints(constraints, kept)
    inside = {name: frame[name].between(low, high).to_numpy() for name, (low, high) in ranges.items()}
    plausible_rows = np.logical_and.reduce([*inside.values(), np.ones(len(frame), dtype=bool)])
    if not plausible_rows.any():
        worst = min(inside, key=lambda name: int(inside[name].sum()))
        low, high = ranges[worst]
        error_msg = (
            f'No row of the virtual population is plausible. The constraint {worst!r} in ({low:g}, {high:g}) rejected '
            f'{int((~inside[worst]).sum())} of {n} rows.'
        )
        raise ExperimentError(error_msg)
    plausible = frame[plausible_rows].reset_index(drop=True)
    acceptance = len(plausible) / n
    if target is None:
        return VirtualPopulationResult(plausible, acceptance, None, None)
    [(name, observed)] = target.items()
    if name not in kept:
        error_msg = f'The target {name!r} names no output. The outputs are {", ".join(kept)}.'
        raise ValidationError(error_msg)
    if len(plausible) < MIN_PLAUSIBLE:
        error_msg = (
            f'Selection by inclusion estimates densities and needs at least {MIN_PLAUSIBLE} plausible rows, not '
            f'{len(plausible)}. Sample more rows or widen the constraints.'
        )
        raise ExperimentError(error_msg)
    inclusion = _get_inclusion(np.asarray(observed, dtype=float), plausible[name].to_numpy(dtype=float))
    rng = np.random.default_rng(np.random.SeedSequence(random_state).spawn(1)[0])
    selected = plausible[rng.random(len(plausible)) < inclusion].reset_index(drop=True)
    return VirtualPopulationResult(plausible, acceptance, selected, inclusion)