API reference

andrey.rpcmci#

andrey.rpcmci(data, *, n_regimes=2, max_transitions=1, switch_threshold=0.5, tau_max=1, pc1_alpha=0.2, alpha=0.01, fdr_method='none', indep_test='student_t', n_starts=50, max_iter=20, seed=None)[source]#

Learn the regimes of one time series and the lagged causal links of each with Regime-PCMCI.

Regime-PCMCI [1] takes a series whose lagged causal graph switches between a few persistent regimes. It alternates two steps: PCMCI [2] learns each regime’s graph from its assigned time steps, and a linear program reassigns the steps to the regimes whose linear model, fitted on the graph’s links, predicts them best, with a cap on how often each regime may start or end. It returns each time step’s regime and one lagged graph per regime.

Parameters:
  • data (ArrayLike) – A multivariate time series, one row per time step. Coerced to float64. A DataFrame’s column names become each regime structure’s labels.

  • n_regimes (int) – The number of regimes, at least 2.

  • max_transitions (int) – The maximum switches on or off per regime over the series, at least 1: the cap on sum_t |gamma_k(t + 1) - gamma_k(t)| for each regime k. For regimes that last m steps on average, about n_samples / (m * n_regimes) [1]. The default, 1, the smallest that lets a regime start or end, allows one change point per regime; set it from the time scale of the regimes.

  • switch_threshold (float) – The weight above which a time step joins a regime’s PCMCI step and model fit, in (0, 1): step t joins regime k when gamma_k(t) > switch_threshold, with the weight rounded to 9 decimals. The first weights are drawn in [0, 1), so 1 would leave every regime empty.

  • tau_max (int) – The largest lag tested, at least 1: links at lags 1 to tau_max are tested.

  • pc1_alpha (float) – Significance level of each regime’s PC1 step, in (0, 1): a candidate parent is dropped when a test gives it a p-value above pc1_alpha.

  • alpha (float) – Significance level of each regime’s MCI step, in (0, 1), the level that decides the returned links: a link is in a regime’s graph when its p-value is at most alpha.

  • fdr_method (str) – How each regime’s MCI p-values are corrected for the number of links tested. "none" keeps each p-value as tested; "fdr_bh" replaces them with their Benjamini-Hochberg adjusted values [3] over all of the regime’s links together, and a link is then in the graph when its adjusted p-value is at most alpha. "none" favors true links; it gives up control of the extra ones. "fdr_bh" favors fewer extra links; it gives up some true ones. Not measured with Regime-PCMCI; pcmci() states the trade as measured there.

  • indep_test (str) – The conditional-independence test behind every p-value, a partial-correlation test for linear effects: "student_t" takes the p-value from the Student-t distribution, "fisherz" from Fisher’s z-transform and the normal distribution. metadata["indep_test"] names it. "student_t" favors an exact level on independent Gaussian rows and a test that runs with one row fewer (|S| + 3 against |S| + 4 for |S| conditions); it gives up agreement with the p-values of pcmci()’s default, "fisherz". "fisherz" favors that agreement; it gives up the exact level on a test with few rows. The two are nearly the same test: on independent Gaussian rows with two conditions, Fisher’s z at alpha=0.01 rejects a true independence with probability 1.13% on 20 rows, 1.05% on 50, and 1.02% on 100, calculated from the null distribution of the partial correlation, against 1% for "student_t". Their effect on Regime-PCMCI’s graphs was not measured.

  • n_starts (int) – The number of starts, at least 1, each with a random regime assignment; the start with the lowest objective is returned.

  • max_iter (int) – Maximum iterations per start, at least 1; one iteration learns every regime’s graph and then reassigns the steps.

  • seed (int | None) – None, the default, is the configured seed, ANDREY_SEED or 0 when it is unset, not a fresh random one, so a fit repeats. Start 0 draws its first regime weights from seed, start a > 0 from SeedSequence(seed, spawn_key=(a,)), so each start depends on seed and a only. metadata["seed"] records the seed used.

Returns:

regimes holds each time step’s largest-weight regime, 0 to n_regimes - 1, and weights the (n_regimes, n_samples) weights the linear program returned. The first tau_max steps have no prediction, so their regime carries no evidence. outputs[k] wraps a temporal TemporalStructure of regime k with lags 1 to tau_max and no lag 0, as pcmci() returns it: structure.lag(j) is a digraph whose edge i -> h is the link from variable i at time t - j to variable h at time t, and its metadata["p_values"], metadata["statistics"], and metadata["parents"] hold the regime’s MCI p-values, test statistics, and PC1 parents. Each regime’s graph is learned in the last iteration from steps selected by the weights before the last reassignment. metadata["objective"] is the linear program’s optimal value, metadata["start"] the index of the returned start, metadata["n_iterations"] its iterations, metadata["converged"] whether it stopped on its own rule rather than on max_iter, and metadata["failed_starts"] the number of starts that failed (see Notes). metadata["algorithm"] is "rpcmci" and metadata["seed"] the seed used, on the result and on each regime’s output. metadata["tie_break"] is the tie-break rule the fit ran under, andrey.config.tie_break.

Return type:

RegimeOutput

Raises:
  • TypeError – If an argument has the wrong type, such as a string for a number; the message names the method, the argument, what it accepts, and the value.

  • ValueError – If an argument lies outside its range or is not one of its choices; the message names the method, the argument, what it accepts, and the value. Also if data is not a usable 2-D matrix with at least 2 * tau_max * (n_variables + 1) + 3 rows, the length at which one regime’s tests keep a degree of freedom, or holds a missing value; if a variable repeats another up to scale and shift, at the same step or up to 2 * tau_max steps apart, before any test runs, with one message naming every group of copies; and if every start fails.

Warns:
  • ExperimentalWarning – On the first call in a process: the method is not supported (see Limitations), and its API may change without deprecation.

  • SearchLimitWarning – When the returned start ran max_iter iterations without stopping on its own rule.

  • DataTypeWarning – When a column holds at most 10 distinct whole numbers and so may hold category codes, which the fit reads as numbers. Each message warns once per process.

Notes

When to use. Regime-PCMCI suits one observational multivariate time series whose lagged causal links, linear in the variables, switch between a few regimes that each last many time steps, such as a seasonal or circulation regime in climate data [1]. Within a regime, it makes PCMCI’s assumptions: no unmeasured common cause, faithfulness, and every effect taking at least one time step. It is designed for few regimes and variables, with a known number of regimes and a known time scale of their switching [1], and returns the regime of each time step and a directed graph at each lag 1 to tau_max per regime. When the links do not change over time, use pcmci(); when the regimes are known, run pcmci() on each, or use jpcmciplus() on series from known contexts.

A start draws its regime weights uniformly in [0, 1) and repeats two steps [1]. First, for each regime k, PCMCI runs on the steps t with gamma_k(t) > switch_threshold: each test reads those steps as the time of its effect and the lagged values of every earlier step. Each variable is regressed by least squares, with an intercept, on its MCI parents in the regime over the same steps, and the fit predicts every step from tau_max on. Second, with c_k(t) the squared residuals of regime k at step t summed over the variables, each residual divided by the variable’s standard deviation over the regime’s steps, the weights become the solution of the linear program that minimizes sum_k sum_t gamma_k(t) c_k(t) over weights in [0, 1] that sum to 1 at every step and change by at most max_transitions in total in each regime. The dual simplex method solves it exactly and returns a vertex, whose weights are mostly 0 or 1. A start stops when the weights no longer change, or from its sixth iteration on when their summed absolute change is at most 2 * n_regimes * n_samples // 100, as the authors’ code does, and otherwise after max_iter iterations. A start fails when a regime is left with fewer than 6 time steps, the limit of the authors’ code, a variable constant over its steps, or a test that cannot run on its steps, such as one with more conditions than steps; failed starts are skipped. The returned start has the lowest successful objective, breaking ties at 9 decimals per time step by the earliest start.

The paper’s threshold for joining a regime is 0.5 [1], the default. The paper’s Eq. 11 reads >=, and Andrey follows the authors’ code, which uses >, so a step the linear program weighs half in each of two regimes joins neither fit. Each weight is rounded to 9 decimals before the comparison, so this holds when the solver returns half with an error in its last bits. Dividing each residual by its regime’s standard deviation follows the authors’ code, so rescaling a column changes no result. Equal PC1 strengths are ordered by each variable’s rank, as in pcmci(), and the residuals enter the cost in rank order, so reordering columns only relabels the result.

Missing values. A NaN in data raises ValueError: a missing value would remove its step from every regime’s fit and leave its regime unknown. Use pcmci(), pcmciplus(), or lpcmci(), whose tests delete rows per test and keep every time step, as dropping a step would join the steps around it.

Limitations. Not benchmarked yet; the tests run it on 2 to 3 variables, 2 to 3 regimes, and up to 1,000 time steps. The nonconvex objective can leave a regime holding steps from several true regimes, and some starts end with a regime too small to fit; n_starts guards against it at a cost that grows linearly with it [1]. Regimes whose models differ little, such as one link’s strength alone, are hard to tell apart [1]. On a series without regimes, each regime keeps the steps its model fits best, so a regime, most often a small one, can hold a spurious link. The number of regimes and max_transitions are not learned. Each iteration runs PCMCI once per regime and solves one linear program over 2 * n_regimes * n_samples variables. The numbers are a reference, not a hard limit: they change with the data generator, the density, the method’s settings, and the machine.

References

Examples

>>> import numpy as np
>>> from andrey import rpcmci
>>> rng = np.random.default_rng(0)
>>> x = np.zeros((600, 2))
>>> for t in range(1, 600):
...     sign = 1.0 if (t // 100) % 2 == 0 else -1.0
...     x[t] = [0.2 * x[t - 1, 0], 0.2 * x[t - 1, 1] + sign * 0.8 * x[t - 1, 0]]
...     x[t] += rng.standard_normal(2)
>>> out = rpcmci(x, max_transitions=6, n_starts=10, seed=0)
>>> out.n_regimes, out.regimes.shape
(2, (600,))