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 tofloat64. A DataFrame’s column names become each regime structure’slabels.n_regimes (
int) – The number of regimes, at least2.max_transitions (
int) – The maximum switches on or off per regime over the series, at least1: the cap onsum_t |gamma_k(t + 1) - gamma_k(t)|for each regimek. For regimes that lastmsteps on average, aboutn_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): steptjoins regimekwhengamma_k(t) > switch_threshold, with the weight rounded to 9 decimals. The first weights are drawn in[0, 1), so1would leave every regime empty.tau_max (
int) – The largest lag tested, at least1: links at lags1totau_maxare 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 abovepc1_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 mostalpha.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 mostalpha."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| + 3against|S| + 4for|S|conditions); it gives up agreement with the p-values ofpcmci()’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 atalpha=0.01rejects 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 least1, each with a random regime assignment; the start with the lowest objective is returned.max_iter (
int) – Maximum iterations per start, at least1; one iteration learns every regime’s graph and then reassigns the steps.seed (
int|None) –None, the default, is the configured seed,ANDREY_SEEDor0when it is unset, not a fresh random one, so a fit repeats. Start0draws its first regime weights fromseed, starta > 0fromSeedSequence(seed, spawn_key=(a,)), so each start depends onseedandaonly.metadata["seed"]records the seed used.
- Returns:
regimesholds each time step’s largest-weight regime,0ton_regimes - 1, andweightsthe(n_regimes, n_samples)weights the linear program returned. The firsttau_maxsteps have no prediction, so their regime carries no evidence.outputs[k]wraps atemporalTemporalStructureof regimekwith lags1totau_maxand no lag 0, aspcmci()returns it:structure.lag(j)is adigraphwhose edgei -> his the link from variableiat timet - jto variablehat timet, and itsmetadata["p_values"],metadata["statistics"], andmetadata["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 onmax_iter, andmetadata["failed_starts"]the number of starts that failed (see Notes).metadata["algorithm"]is"rpcmci"andmetadata["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:
- 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
datais not a usable 2-D matrix with at least2 * tau_max * (n_variables + 1) + 3rows, 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 to2 * tau_maxsteps 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_iteriterations 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
1totau_maxper regime. When the links do not change over time, usepcmci(); when the regimes are known, runpcmci()on each, or usejpcmciplus()on series from known contexts.A start draws its regime weights uniformly in
[0, 1)and repeats two steps [1]. First, for each regimek, PCMCI runs on the stepstwithgamma_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 fromtau_maxon. Second, withc_k(t)the squared residuals of regimekat steptsummed 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 minimizessum_k sum_t gamma_k(t) c_k(t)over weights in[0, 1]that sum to1at every step and change by at mostmax_transitionsin total in each regime. The dual simplex method solves it exactly and returns a vertex, whose weights are mostly0or1. A start stops when the weights no longer change, or from its sixth iteration on when their summed absolute change is at most2 * n_regimes * n_samples // 100, as the authors’ code does, and otherwise aftermax_iteriterations. 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 inpcmci(), and the residuals enter the cost in rank order, so reordering columns only relabels the result.Missing values. A
NaNindataraisesValueError: a missing value would remove its step from every regime’s fit and leave its regime unknown. Usepcmci(),pcmciplus(), orlpcmci(), 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_startsguards 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 andmax_transitionsare not learned. Each iteration runs PCMCI once per regime and solves one linear program over2 * n_regimes * n_samplesvariables. 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,))