API reference¶
Simulation¶
Constructors take the parameters listed on each model page.
make_trajectory returns time (T,), observations (T,D), and forcing (T,).
num_samplesincludes the initial sample;dt_samplemust be an integer multiple ofdt.Duration-normalized ramps change when
num_sampleschanges. Rate forcing uses absolute time.noisescales diffusion; SaddleNode instead takes a diffusion intensity.Initial states use
model.state_names; Ricker uses log population.noise=0removes process noise. Supplyinitial_statefor fixed initialization.Retain custom
forcingandinnovationsalongside the seed to replay a run.
- class tipbox.types.BoxModel(config=None, **parameters)¶
A configured box model with an exact-grid trajectory interface.
- Parameters:
config (dataclass or None) – Typed configuration for this model. Omit to use its documented defaults.
**parameters – Configuration field overrides, checked by the typed dataclass constructor.
model.configandmodel.get_parameters()expose all resolved values.
- property config¶
Immutable, typed model configuration.
- get_parameters()¶
Resolved configuration, including nested physical parameters.
- Return type:
dict
- abstractmethod is_tipped(trajectory, **kwargs)¶
Classify using the model’s configured transition marker.
- abstractmethod locate_transition(trajectory, **kwargs)¶
Return the reference index, or None when that reference is absent.
- make_trajectory(num_samples=None, *, dt=None, dt_sample=None, noise=0.01, initial_state=None, seed=0, innovations=None, null_simulation=False, param_end_multiplier=1.1, forcing=None)¶
Integrate exactly
num_samplesobservations from the configured start time.- Parameters:
num_samples (int or None, default=None) – Number of returned samples, including the initial state; at least 2. None uses the configured start/end interval and output spacing. An explicit num_samples overrides the configured end time.
dt (float or None, default=None) – Integration step. Defaults to config.dt, or config.dt_inner for AMOC. For Ricker this is the interval represented by one discrete map update.
dt_sample (float or None, default=None) – Output spacing; a positive integer multiple of dt. Defaults to 1.0 for MayHarvesting, RosenzweigMacArthur and SEIRx, 0.0005 for Thermoacoustic, and config.dt for the remaining models.
noise (float, default=0.01) – Nonnegative noise-strength parameter, with the same meaning as sigma_tilde in simulate. The model reference gives its exact diffusion formula; saddle-node uses an intensity and other models a multiplier. Zero disables process noise, but does not disable random initial states.
initial_state (array-like or None, default=None) – Initial model state in the order of model.state_names. Ricker uses log population, and Thermoacoustic uses pressure and scaled velocity. None uses the model’s sampler. A scalar is accepted for 1D models.
seed (int, default=0) – Local random seed; global random state is never changed.
innovations (array-like or None, default=None) – Standard-normal increments shaped (n_integration_steps, noise_dimension). These replace random increments and are multiplied by the model’s per-step scale. The physical and observed dimensions can differ.
null_simulation (bool, default=False) – Select the model’s null forcing schedule. This is a forcing choice, not a guarantee that the simulated state remains non-tipping.
param_end_multiplier (float, default=1.1) – For duration-normalized bifurcation ramps, the ratio of total duration to ramp duration. Rate schedules retain their absolute time origin.
forcing (callable or None, default=None) – Optional forcing(t) evaluated on the complete integration grid. It must return one finite scalar per time point, including RK4 midpoints, in the model’s forcing units.
- Returns:
Observations, time, forcing and per-step noise scale. Metadata includes the resolved parameters and sampled physical state trajectory.
- Return type:
- Raises:
ValueError – If the time grid is not finite and strictly increasing at the active JAX precision. Adjust the clock origin or step, or enable 64-bit mode.
- class tipbox.types.TrajectoryResult(time, trajectory, param_values, sigma, metadata)¶
Time, observed state, forcing, per-step noise scale, and provenance.
make_trajectoryalways returns observations shaped(n_time, n_observables).sigmais the standard deviation of an integration-step noise increment, including the square root of the integration step for continuous-time models. Discrete maps report their per-update state-noise scale instead.- Parameters:
time (Array)
trajectory (Array)
param_values (Array)
sigma (float | Array)
metadata (dict[str, Any] | None)
Indicators¶
Functions return NumPy arrays aligned to the input signal. Windows are trailing;
warm-up, skipped, and nonfinite windows produce NaN. Autocorrelation assumes
regular sampling. Use integer windows for streaming; fractional windows depend
on the series length. Analyze recovery intervals separately.
Argument |
Default |
Meaning |
|---|---|---|
|
|
Integer sample count, or fraction of the signal length in |
|
|
Spacing between evaluated window endpoints |
|
|
|
For centered lagged pairs \(u,v\), AR1 is \(S_{uv}/S_{uu}\);
Pearson correlation is \(S_{uv}/\sqrt{S_{uu}S_{vv}}\). AR1 may exceed
\([-1,1]\). Variance uses ddof=0; skewness and kurtosis use population
moments, with excess kurtosis by default. Constant windows have zero variance
and undefined normalized statistics.
Early-warning statistics on trailing windows of one scalar signal.
All functions return a NumPy array aligned with the input. Warm-up samples and windows containing nonfinite observations are NaN. Each window uses observations through its endpoint; linear detrending is fitted within that window. For streams, use an integer window: fractional windows depend on the full input length. These eager analysis functions accept NumPy and concrete JAX arrays.
- tipbox.indicators.rolling_acf(data, window=0.5, *, lag=1, step=1, detrend=None)¶
Trailing Pearson correlation of the two lagged, separately centered vectors.
This uses sqrt(Sxx * Syy) in the denominator; it is not the full-window autocovariance divided by the full-window variance. Require at least two pairs and nonzero variance in both vectors; undefined correlations are NaN. Arguments share the meanings in
rolling_ar1().
- tipbox.indicators.rolling_ar1(data, window=0.5, *, lag=1, step=1, detrend=None)¶
Trailing lagged OLS slope with an intercept, default lag=1 (AR1).
Regress x[t] on x[t-lag] inside each window, centering each paired vector separately. This slope can exceed [-1, 1]. Require at least two pairs and nonzero predictor variance; undefined slopes are NaN.
lagis a sample count, not a physical-time interval. The window, step and detrend arguments have the same meanings as inrolling_variance().
- tipbox.indicators.rolling_kurtosis(data, window=0.5, *, excess=True, step=1, detrend=None)¶
Trailing population kurtosis, without bias correction.
excess=True(default) returns m4 / m2**2 - 3, whose Gaussian limit is zero.excess=Falsereturns Pearson kurtosis, whose Gaussian limit is three. Constant windows are undefined (NaN). Other arguments share the meanings inrolling_variance().
- tipbox.indicators.rolling_skewness(data, window=0.5, *, step=1, detrend=None)¶
Trailing population skewness m3 / m2**1.5, without bias correction.
Constant windows have undefined skewness (NaN). Window, step and detrend arguments have the same meanings as in
rolling_variance().
- tipbox.indicators.rolling_variance(data, window=0.5, *, ddof=0, step=1, detrend=None)¶
Trailing variance;
ddof=0gives the population variance.- Parameters:
data (array-like, shape (num_samples,)) – One scalar signal, sampled at regular intervals. Analyze separate recovery segments separately; no interpolation or missing-value removal is applied.
window (int or float, default=0.5) – Integer sample count or float fraction of the input length, rounded down.
ddof (int, default=0) – Variance denominator is window_size - ddof. Require 0 <= ddof < window_size.
step (int, default=1) – Evaluate every step-th window, starting with the first complete window. Unevaluated output positions remain NaN.
detrend (None or "linear", default=None) – Subtract a least-squares line fitted within each window, or use raw values.
- Returns:
Values at the right edge of each evaluated window; NaN elsewhere. Constant finite windows have variance zero.
- Return type:
numpy.ndarray, shape (num_samples,)
- tipbox.indicators.window_size(num_samples, window)¶
Resolve a window to samples: integer count, or float fraction in (0, 1].
Fractions are rounded down, allowing one floating-point step at integer boundaries (e.g. 0.29 * 100). Require at least two samples and at most num_samples. In particular,
1is a one-sample count (invalid), while1.0selects the full series. Noninteger absolute counts such as10.5are invalid.- Parameters:
num_samples (int)
window (float)
- Return type:
int
Benchmarking¶
generate_dataset returns observations (N,T,D), labels (N,), and
per-row times, forcing, and metadata. lead_samples=1 ends the context one
sample before the model reference. Null references are comparison points;
a forcing crossing need not coincide with an observed state jump. Balanced,
outcome-selected batches do not estimate natural tipping probabilities.
Each indicator series contributes one Kendall tau-b trend score. Declare score
directions before evaluation; negate decreasing indicators. Nonfinite scores
are excluded and reported in n_missing. Input labels must include both
classes; AUROC is NaN if filtering removes a class. Report coverage with the score.
- tipbox.datasets.generate_dataset(model, context_samples, *, num_samples=None, num_tipping=100, num_controls=100, lead_samples=1, seed=0, max_attempts=100, **trajectory_kwargs)¶
Generate labeled pre-reference context using the shared model interface.
- Parameters:
model (BoxModel) – Configured named model. No configuration or time origin is changed.
context_samples (int) – Positive number of observations retained before each reference marker.
num_samples (int or None, default=None) – Full trajectory sample count, including the initial state. None uses the model’s configured duration and output spacing.
num_tipping (int, default=100 each) – Nonnegative class counts; require at least one trajectory overall. Label 1 passes model.is_tipped under forced simulation; label 0 fails it under null simulation. These are the model’s classification conventions, which can describe forcing crossings rather than observed state jumps. Null rows precede tipping rows; no shuffling is performed.
num_controls (int, default=100 each) – Nonnegative class counts; require at least one trajectory overall. Label 1 passes model.is_tipped under forced simulation; label 0 fails it under null simulation. These are the model’s classification conventions, which can describe forcing crossings rather than observed state jumps. Null rows precede tipping rows; no shuffling is performed.
lead_samples (int, default=1) – Positive sample distance from the final retained sample to the marker. One ends immediately before the marker.
seed (int, default=0) – Root seed in [0, 2**32). Draw i, attempt a (both zero based), uses seed + i * max_attempts + a. The entire reserved range must fit in uint32, ensuring distinct seeds without wraparound. Metadata records actual seeds.
max_attempts (int, default=100) – Maximum attempts per requested row. Rejections and invalid context are counted; exhausted attempts raise RuntimeError without returning a partial dataset. Exceptions from the model propagate immediately.
**trajectory_kwargs – Forwarded to model.make_trajectory: dt, dt_sample, noise, initial_state, innovations, param_end_multiplier, and forcing. Defaults remain the model’s defaults. seed and null_simulation are controlled by this function.
- Return type:
BenchmarkDataset
Notes
This is outcome-conditioned rejection sampling, not an unbiased sample of tipping probabilities. Null markers are comparison references. Equal context lengths need not mean matched forcing histories. Failed or nonfinite context is never silently relabeled. Null simulations must remain finite throughout; positive simulations may diverge after their finite reference crossing. Supplied innovations are reused for each draw; seeds then affect only the default initial-state sampler. Retain custom inputs for simulation replay.
Trajectory-level Kendall trends and binary ROC/AUROC for indicator ensembles.
- tipbox.metrics.binary_roc(y_true, scores)¶
ROC and AUROC from one scalar score per independent trajectory.
- Parameters:
y_true (array-like, shape (n_trajectories,)) – Binary labels: 1 for tipping, 0 for non-tipping. Both classes are required.
scores (array-like, shape (n_trajectories,)) – Larger means stronger evidence for tipping. Choose any direction change before evaluating labels; this function never maximizes over signs. NaN and infinite scores are excluded, with coverage counts returned.
- Return type:
BinaryRocResult
Notes
Tied scores share a threshold and contribute half credit to AUROC. If finite scores retain only one class, return NaN AUROC and empty curve arrays. Nonfinite scores never become negative predictions implicitly.
- tipbox.metrics.ensemble_roc(y_true, indicators)¶
Evaluate named indicator series or precomputed trajectory scores.
Each mapping value contains one item per trajectory. An item is either a scalar score or a one-dimensional indicator series reduced with
kendall_tau(). Series can differ in length. Input trajectories and labels must be aligned; higher scores always mean more evidence for tipping. Even undefined indicators remain in the result, with NaN AUROC and counts.- Parameters:
indicators (Mapping)
- Return type:
EnsembleRocResult
- tipbox.metrics.kendall_tau(series, *, time=None)¶
Kendall tau-b trend against time, dropping only nonfinite indicator values.
seriesmust be one dimensional.time=Noneuses sample indices; otherwise supply finite, strictly increasing times of the same shape. Fewer than two finite values or a constant indicator gives NaN. The result uses SciPy’s tie-corrected tau-b; the p-value is not used. Filtering warm-up NaNs does not assert that the underlying windows were independent.- Return type:
float
- tipbox.metrics.plot_roc(result, *, ax=None)¶
Plot defined ensemble ROC curves and coverage; return the Matplotlib axes.
Pass an existing axes to control the figure and styling. Undefined curves remain available in result.curves but are omitted from the plot. Raise ValueError if every curve is undefined. Matplotlib is imported on demand.
- Parameters:
result (EnsembleRocResult)
Observations¶
load() returns time (T,), observations (T,D), and source metadata.
Original ordering, missing values, and time coordinates are retained.
cache_dir=None uses $XDG_CACHE_HOME/tipbox or ~/.cache/tipbox;
download=False requires a cached file. Local source paths bypass downloads.
All loads verify the pinned source checksum. Source terms are listed in the
Empirical catalog and record metadata.
- class tipbox.datasets.Microcosm¶
Cyanobacterial chemostat observations, M1 and M2 (Veraart et al., 2012).
- load(*, cache_dir=None, download=True, source_path=None)¶
Load both chemostats, preserving source times and missing values.
cache_dir selects the cache; download=False requires a cached file. source_path reads a local, unmodified ODS instead. Files are verified against the published source checksum. Observations have columns M1, M2.
- Parameters:
cache_dir (str | Path | None)
download (bool)
source_path (str | Path | None)
- Return type:
- class tipbox.datasets.VoiceOnset¶
Subglottal pressure during voice onset, from the Grziwotz et al. archive.
- load(*, cache_dir=None, download=True, archive_path=None)¶
Load observations; cache_dir selects the cache, download=False uses it offline.
archive_path reads a local, unmodified source ZIP instead of the cache.
- Parameters:
cache_dir (str | Path | None)
download (bool)
archive_path (str | Path | None)
- Return type:
- class tipbox.datasets.CellularATP¶
Cellular fluorescence ratio; physical time units remain unresolved.
- load(*, cache_dir=None, download=True, archive_path=None)¶
Load observations; cache_dir selects the cache, download=False uses it offline.
archive_path reads a local, unmodified source ZIP instead of the cache.
- Parameters:
cache_dir (str | Path | None)
download (bool)
archive_path (str | Path | None)
- Return type:
- class tipbox.datasets.Paleoclimate¶
Greenhouse Earth CaCO3 record, retaining signed geological ages.
- load(*, cache_dir=None, download=True, archive_path=None)¶
Load observations; cache_dir selects the cache, download=False uses it offline.
archive_path reads a local, unmodified source ZIP instead of the cache.
- Parameters:
cache_dir (str | Path | None)
download (bool)
archive_path (str | Path | None)
- Return type:
- class tipbox.datasets.ElectricalBlackout¶
Electrical frequency around a blackout, from the Grziwotz et al. archive.
- load(*, cache_dir=None, download=True, archive_path=None)¶
Load observations; cache_dir selects the cache, download=False uses it offline.
archive_path reads a local, unmodified source ZIP instead of the cache.
- Parameters:
cache_dir (str | Path | None)
download (bool)
archive_path (str | Path | None)
- Return type:
- class tipbox.datasets.EmpiricalRecord(time, observations, metadata)¶
Time (T,), observations (T,D), and source/sampling metadata.
- Parameters:
time (ndarray)
observations (ndarray)
metadata (dict)
Discovery¶
- tipbox.registry.list_systems(system_type=None)¶
List available systems, optionally filtered by type.
- Parameters:
system_type (SystemType | None)
- Return type:
List[str]
- tipbox.registry.get_system_info(system_name)¶
Get a registered system’s configuration and model class.
- Parameters:
system_name (str)
- Return type:
SystemSpec