PiecewiseITS#
- class causalpy.experiments.piecewise_its.PiecewiseITS[source]#
Piecewise Interrupted Time Series (Segmented Regression) experiment.
This class implements segmented-regression / piecewise linear models for Interrupted Time Series analysis with known interruption dates. Unlike the standard
InterruptedTimeSerieswhich fits a model to pre-intervention data and forecasts a counterfactual, PiecewiseITS fits one model to the full time series and estimates explicit level and/or slope changes at each interruption.The model uses patsy formulas with custom step() and ramp() transforms:
step(time, threshold): Creates a binary indicator (1 if time >= threshold) for level changesramp(time, threshold): Creates a ramp function (max(0, time - threshold)) for slope changes
- Parameters:
data (
NativeDataFrame) – Time series data as any eager dataframe Narwhals supports, such as pandas, Polars, or PyArrow. The time axis comes from thestep()orramp()column in the formula, not from the index, so a dataframe without an index works here. Converted to pandas internally.formula (
str) – A patsy formula specifying the model. Must include at least onestep()orramp()term, and all such terms must use the same time variable. Example:"y ~ 1 + t + step(t, 50) + ramp(t, 50)"model (
PyMCModel|RegressorMixin|None) – A PyMC (Bayesian) or sklearn (OLS) model. If None, defaults to a PyMC LinearRegression model.
Notes
Lazy lifecycle
Construction only validates input and builds the design matrix — nothing is sampled. Call
fit()to run posterior inference (it returnsself, so construction and fitting chain in one expression), and optionallysample_prior_predictive()first for prior predictive checks (plot(group="prior"),effect_summary(group="prior")). Results live onexp.result/exp.prior_result.Estimate extraction
One model is fitted to the full time series. The no-intervention counterfactual is predicted after setting every
step()andramp()design-matrix column to zero, and the pointwise effect is the fitted conditional expectation minus that counterfactual expectation. Bayesian backends contrast posteriormuvalues, OLS contrasts point predictions, and the cumulative effect is the running sum.The step and ramp transforms are patsy stateful transforms that handle both numeric and datetime time columns. For datetime, thresholds can be specified as strings (e.g., ‘2020-06-01’) or pd.Timestamp objects.
Bare datetime predictors are represented as continuous elapsed days. Use
C(date)when date fixed effects are intended instead.References
Wagner AK, et al. (2002). Segmented regression analysis of interrupted time series studies in medication use research. Journal of Clinical Pharmacy and Therapeutics.
Lopez Bernal J, et al. (2017). Interrupted time series regression for the evaluation of public health interventions: a tutorial. Int J Epidemiol.
Examples
>>> import causalpy as cp >>> import pandas as pd >>> import numpy as np >>> # Generate simple piecewise data >>> np.random.seed(42) >>> t = np.arange(100) >>> y = ( ... 10 ... + 0.1 * t ... + 5 * (t >= 50) ... + 0.2 * np.maximum(0, t - 50) ... + np.random.normal(0, 1, 100) ... ) >>> df = pd.DataFrame({"t": t, "y": y}) >>> result = cp.PiecewiseITS( ... df, ... formula="y ~ 1 + t + step(t, 50) + ramp(t, 50)", ... model=cp.pymc_models.LinearRegression( ... sample_kwargs={"random_seed": 42, "progressbar": False} ... ), ... ).fit()
Different effects per intervention:
>>> # Level change only at t=50, level + slope change at t=100 >>> result = cp.PiecewiseITS( ... df, ... formula="y ~ 1 + t + step(t, 50) + step(t, 100) + ramp(t, 100)", ... model=..., ... )
With datetime thresholds:
>>> df["date"] = pd.date_range("2020-01-01", periods=100, freq="D") >>> result = cp.PiecewiseITS( ... df, ... formula="y ~ 1 + date + step(date, '2020-02-20') + ramp(date, '2020-02-20')", ... model=..., ... )
Methods
Construct the model graph without sampling anything.
PiecewiseITS.effect_summary(*[, group, ...])Generate a decision-ready summary of PiecewiseITS causal effects.
PiecewiseITS.fit(**kwargs)Run the posterior phase and populate
result.PiecewiseITS.generate_report(*[, ...])Generate a self-contained HTML report for this experiment.
PiecewiseITS.get_plot_data(*[, group, hdi_prob])Recover the data of the experiment along with prediction and effect information.
PiecewiseITS.plot(*[, group, round_to, ...])Plot the piecewise interrupted time-series results.
PiecewiseITS.print_coefficients([round_to])Ask the model to print its posterior coefficients.
PiecewiseITS.sample_prior_predictive(**kwargs)Run the optional prior phase and populate
prior_result.PiecewiseITS.set_maketables_options(*[, ...])Set optional maketables rendering options for this experiment.
PiecewiseITS.summary([round_to])Print summary of main results and model coefficients.
Attributes
has_prior_predictiveWhether the prior phase has run (draws, and bundle where kept).
idataReturn fitted DataTree when the model backend supports it.
is_builtWhether the model graph / fit design exists (no draws implied).
is_configureddesign matrices are ready.
is_fittedWhether posterior draws and the posterior result bundle exist.
modelThe underlying model instance.
prior_resultPrior-group result bundle; raises before prior sampling.
resultPosterior-group result bundle; raises before
fit().supports_bayessupports_olssupports_pymc_forecastdata- __init__(data, formula, model=None)[source]#
- Parameters:
data (DataFrameLike)
formula (str)
model (PyMCModel | RegressorMixin | None)
- Return type:
None
- classmethod __new__(*args, **kwargs)#