Skip to content

BasinStabilityStudy

pybasin.basin_stability_study.BasinStabilityStudy

Basin Stability Study.

Attributes

studied_parameter_names property

studied_parameter_names: list[str]

Names of the parameters varied in this study.

Returns:

Type Description
list[str]

List of parameter names extracted from the study labels.

Functions

__init__

__init__(
    n: int,
    ode_system: ODESystemProtocol,
    sampler: Sampler,
    solver: SolverProtocol,
    feature_extractor: FeatureExtractor,
    estimator: Any,
    study_params: StudyParams,
    template_integrator: TemplateIntegrator | None = None,
    compute_orbit_data: list[int] | bool = True,
    output_dir: str | Path | None = "results",
    verbose: bool = False,
)

Initialize the Basin Stability Study.

Sets up the estimator for a parameter study where one or more parameters are systematically varied across multiple values. Parameters can be in any component (ODE system, sampler, solver, feature extractor, or predictor).

Parameters:

Name Type Description Default
n int

Number of initial conditions (samples) to generate for each parameter value.

required
ode_system ODESystemProtocol

The ODE system model (ODESystem or JaxODESystem).

required
sampler Sampler

The Sampler object to generate initial conditions.

required
solver SolverProtocol

The Solver object to integrate the ODE system (Solver or JaxSolver).

required
feature_extractor FeatureExtractor

The FeatureExtractor object to extract features from trajectories.

required
estimator Any

Any sklearn-compatible estimator (classifier or clusterer).

required
study_params StudyParams

Parameter study specification (SweepStudyParams, GridStudyParams, etc.).

required
template_integrator TemplateIntegrator | None

Template integrator for supervised classifiers.

None
compute_orbit_data list[int] | bool

Enable orbit data computation for orbit diagram plotting: - True (default): Compute for all state dimensions. - False: Disabled. - list[int]: Compute for specific state indices (e.g., [0, 1]).

True
output_dir str | Path | None

Directory path for saving results (JSON, plots), or None to disable.

'results'
verbose bool

If True, show detailed logs from BasinStabilityEstimator instances. If False, suppress INFO logs to reduce output clutter during parameter sweeps.

False

run

run() -> list[StudyResult]

Estimate basin stability for each parameter combination in the study.

Performs basin stability estimation by systematically varying parameters across the provided combinations. For each configuration:

  1. Applies all parameter assignments from the RunConfig
  2. Creates a new BasinStabilityEstimator instance
  3. Estimates basin stability and computes error estimates
  4. Stores results including basin stability values, errors, and solution metadata

Uses GPU acceleration automatically when available for significant performance gains. Memory is explicitly freed after each iteration to prevent accumulation.

Returns:

Type Description
list[StudyResult]

List of StudyResult dicts, one per parameter combination, containing study_label, basin_stability, errors, n_samples, labels, and orbit_data (if compute_orbit_data is set).

save

save() -> None

Save the basin stability results to a JSON file. Handles numpy arrays and Solution objects by converting them to standard Python types.


Study Parameters

pybasin.study_params.StudyParams

Bases: ABC

Base class for study parameter generators.

Subclasses must implement iter to yield RunConfig objects and len to return the total number of runs.

Functions

__iter__ abstractmethod

__iter__() -> Iterator[RunConfig]

Yield RunConfig for each parameter combination.

__len__ abstractmethod

__len__() -> int

Return the total number of runs.

to_list

to_list() -> list[RunConfig]

Return all RunConfig objects as a list.

Useful for inspecting the generated parameter combinations before running the study.

Returns:

Type Description
list[RunConfig]

List of all RunConfig objects that would be yielded by iteration.

options: heading_level: 3


pybasin.study_params.SweepStudyParams

Bases: StudyParams

Single parameter sweep.

Iterates over a single parameter's values, yielding one RunConfig per value. Accepts exactly one keyword argument whose key is the parameter path and whose value is the list of values to sweep.

Example:

study_params = SweepStudyParams(**{'ode_system.params["T"]': np.arange(0.01, 0.97, 0.05)})

Attributes:

Name Type Description
name str

The parameter path to vary.

values list[Any]

List of values to sweep through.

Functions

__init__

__init__(**params: list[Any]) -> None

Initialize the sweep study parameters.

Parameters:

Name Type Description Default
params list[Any]

Exactly one keyword argument mapping the parameter path to its list of values, e.g., SweepStudyParams(**{'ode_system.params["T"]': t_values}).

{}

Raises:

Type Description
ValueError

If not exactly one keyword argument is provided.

__iter__

__iter__() -> Iterator[RunConfig]

Yield RunConfig for each parameter value.

__len__

__len__() -> int

Return the number of parameter values.

options: heading_level: 3


pybasin.study_params.GridStudyParams

Bases: StudyParams

Cartesian product of multiple parameters.

Creates all combinations of the provided parameter values (grid study).

Example:

study_params = GridStudyParams(
    **{
        'ode_system.params["K"]': k_values,
        'ode_system.params["sigma"]': sigma_values,
    }
)
# Runs: K[0]×sigma[0], K[0]×sigma[1], ..., K[n]×sigma[m]

Functions

__init__

__init__(**params: list[Any]) -> None

Initialize the grid study parameters.

Parameters:

Name Type Description Default
params list[Any]

Keyword arguments mapping parameter names to value arrays. e.g., GridStudyParams(**{'ode_system.params["T"]': t_values})

{}

__iter__

__iter__() -> Iterator[RunConfig]

Yield RunConfig for each parameter combination (Cartesian product).

__len__

__len__() -> int

Return the total number of combinations.

options: heading_level: 3


pybasin.study_params.ZipStudyParams

Bases: StudyParams

Parallel iteration of multiple parameters (must have same length).

Iterates through parameters in parallel (like Python's zip), where values at the same index are used together.

Example:

t_values = np.arange(0.01, 0.97, 0.05)
samplers = [CsvSampler(f"gt_T_{t:.2f}.csv") for t in t_values]

study_params = ZipStudyParams(
    **{
        'ode_system.params["T"]': t_values,
        "sampler": samplers,
    }
)

Functions

__init__

__init__(**params: list[Any]) -> None

Initialize the zip study parameters.

Parameters:

Name Type Description Default
params list[Any]

Keyword arguments mapping parameter names to value arrays. All arrays must have the same length.

{}

Raises:

Type Description
ValueError

If parameter arrays have different lengths.

__iter__

__iter__() -> Iterator[RunConfig]

Yield RunConfig for each parameter tuple (parallel iteration).

__len__

__len__() -> int

Return the number of parameter tuples.

options: heading_level: 3


pybasin.study_params.CustomStudyParams

Bases: StudyParams

User-provided list of configurations.

Allows full control over parameter combinations by providing explicit RunConfig objects.

Example:

configs = [
    RunConfig(
        assignments=[
            ParamAssignment("ode_system", ode),
            ParamAssignment('ode_system.params["K"]', K),
        ],
        study_label={"K": K, "p": p},
    )
    for K, p in product(k_values, p_values)
]
study_params = CustomStudyParams(configs)

Functions

__init__

__init__(configs: list[RunConfig]) -> None

Initialize with a list of RunConfig objects.

Parameters:

Name Type Description Default
configs list[RunConfig]

List of RunConfig objects defining each run.

required

__iter__

__iter__() -> Iterator[RunConfig]

Yield each RunConfig.

__len__

__len__() -> int

Return the number of configurations.

from_dicts classmethod

from_dicts(
    param_dicts: list[dict[str, Any]],
) -> CustomStudyParams

Create from a list of {param_name: value} dictionaries.

Example:

study_params = CustomStudyParams.from_dicts(
    [
        {'ode_system.params["K"]': 0.1, "n": 500},
        {'ode_system.params["K"]': 0.2, "n": 1000},
    ]
)

Parameters:

Name Type Description Default
param_dicts list[dict[str, Any]]

List of dictionaries where each dict maps parameter names to values for one run.

required

Returns:

Type Description
CustomStudyParams

CustomStudyParams instance.

options: heading_level: 3


Configuration Types

pybasin.study_params.ParamAssignment dataclass

A single parameter assignment.

Attributes:

Name Type Description
name str

The parameter path, e.g., 'ode_system.params["T"]' or 'sampler'.

value Any

The value to assign to the parameter.

options: heading_level: 3


pybasin.study_params.RunConfig dataclass

Configuration for a single BSE run with multiple parameter assignments.

Attributes:

Name Type Description
assignments list[ParamAssignment]

List of parameter assignments to apply for this run.

study_label dict[str, Any]

Dictionary identifying this run's parameter combination, e.g., {"T": 0.5} or {"K": 0.1, "sigma": 0.3}.

options: heading_level: 3


Result Types

pybasin.types.StudyResult

Bases: TypedDict

Results for a single parameter combination in a parameter study.

Contains complete information about basin stability estimation at one parameter combination, including the study label identifying the run, basin stability values, error estimates, sample metadata, and optional detailed solution data.

Attributes:

Name Type Description
study_label dict[str, Any]

Label identifying this run. For standalone BSE runs this is {"baseline": True}; for study runs it maps parameter names to values (e.g. {"K": 0.1}).

basin_stability dict[str, float]

Dictionary mapping attractor labels to their basin stability values (fraction of samples).

errors dict[str, ErrorInfo]

Dictionary mapping attractor labels to their ErrorInfo (absolute and relative errors).

n_samples int

Number of initial conditions actually used (may differ from requested N due to grid rounding).

labels ndarray[Any, Any] | None

Array of attractor labels for each initial condition, or None if not available.

orbit_data OrbitData | None

Peak amplitude data for orbit diagram plotting, or None if not computed.

options: heading_level: 3


pybasin.types.ErrorInfo

Bases: TypedDict

Standard error information for basin stability estimates.

Basin stability errors are computed using Bernoulli experiment statistics:

  • e_abs = sqrt(S_B(A) * (1 - S_B(A)) / N) - absolute standard error
  • e_rel = 1 / sqrt(N * S_B(A)) - relative standard error

Attributes:

Name Type Description
e_abs float

Absolute standard error of the basin stability estimate.

e_rel float

Relative standard error of the basin stability estimate.

options: heading_level: 3 heading_level: 3