Metadata-Version: 2.4
Name: pycausalsim
Version: 0.7.0
Summary: Causal Discovery and Inference Through Simulation
Author-email: Brian Curry <brian@vector1.ai>
License: Apache-2.0
Project-URL: Homepage, https://github.com/Bodhi8/pycausalsim
Project-URL: Documentation, https://pycausalsim.readthedocs.io
Project-URL: Repository, https://github.com/Bodhi8/pycausalsim
Project-URL: Issues, https://github.com/Bodhi8/pycausalsim/issues
Keywords: causal inference,causal discovery,counterfactual,simulation,machine learning,data science,a/b testing,marketing attribution,uplift modeling,forecasting,scenario analysis,structural causal model
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: numpy>=1.20.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: scipy>=1.7.0
Requires-Dist: scikit-learn>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=3.0.0; extra == "dev"
Requires-Dist: black>=22.0.0; extra == "dev"
Requires-Dist: flake8>=4.0.0; extra == "dev"
Requires-Dist: mypy>=0.950; extra == "dev"
Requires-Dist: isort>=5.10.0; extra == "dev"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.5.0; extra == "viz"
Requires-Dist: networkx>=2.6.0; extra == "viz"
Requires-Dist: seaborn>=0.11.0; extra == "viz"
Provides-Extra: neural
Requires-Dist: torch>=1.10.0; extra == "neural"
Provides-Extra: integrations
Requires-Dist: dowhy>=0.8; extra == "integrations"
Requires-Dist: econml>=0.12.0; extra == "integrations"
Provides-Extra: all
Requires-Dist: matplotlib>=3.5.0; extra == "all"
Requires-Dist: networkx>=2.6.0; extra == "all"
Requires-Dist: seaborn>=0.11.0; extra == "all"
Requires-Dist: dowhy>=0.8; extra == "all"
Requires-Dist: econml>=0.12.0; extra == "all"
Dynamic: license-file

# PyCausalSim

![PyCausalSim: data condensing into a causal graph that unrolls into simulated futures](docs/images/pycausalsim-hero.jpg)

[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![tests](https://github.com/Bodhi8/pycausalsim/actions/workflows/test.yml/badge.svg)](https://github.com/Bodhi8/pycausalsim/actions/workflows/test.yml)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

**PyCausalSim** is a Python framework for causal discovery and inference through simulation. It answers two kinds of question with the same machinery.

**Backward:** what caused the outcome already in your data? Discover the graph, estimate interventions, validate against unmeasured confounding.

**Forward:** what happens under a policy nobody has tried yet? Specify a graph, unroll it over a horizon, and simulate scenarios far outside observed support, with the extrapolation declared rather than silent.

Most causal libraries do only the first. The second needs time, declared mechanism, interventions on structure rather than value, and a way to score predictions after the fact. That is `pycausalsim.futures`.

## Why PyCausalSim?

Traditional analytics tell you *what* happened. PyCausalSim tells you *why* it happened and *what would happen if* you changed something.

```python
from pycausalsim import CausalSimulator

# Your conversion rate increased after reducing load time
# But did load time CAUSE the increase? Or was it just correlation?

simulator = CausalSimulator(data, target='conversion_rate')
simulator.discover_graph()  # Learn causal structure

# Simulate: What if we reduce load time to 2 seconds?
effect = simulator.simulate_intervention('page_load_time', 2.0)
print(f"Expected conversion lift: {effect.point_estimate:.2%}")
print(f"95% CI: [{effect.ci_lower:.2%}, {effect.ci_upper:.2%}]")

# Rank all causal drivers
drivers = simulator.rank_drivers()
# Returns: [(page_load_time, 0.15), (price, 0.12), (design, 0.03), ...]
```

## Key Features

### 1. Simulation-Based Causal Discovery

- Generate synthetic "what-if" scenarios
- Test interventions before deploying them
- Understand non-linear and interaction effects

### 2. Multiple Discovery Methods

- **Constraint-based**: PC (PC-stable, Fisher-z tests)
- **Score-based**: GES with the BIC score (`"fges"` is accepted as an alias for the same search)
- **Functional**: DirectLiNGAM, for linear models with non-Gaussian noise
- **Continuous optimization**: linear NOTEARS
- **Hybrid**: the GES graph without the edges PC's independence tests reject

PC, GES and hybrid return an equivalence class: an edge whose direction the data
cannot determine is listed in both directions instead of being guessed. What you
know about ordering settles more of them:

```python
from pycausalsim.discovery import CausalDiscovery, undirected_edges

graph = CausalDiscovery().discover(
    data, method="ges",
    tiers={"age": 0, "dose": 1, "recovery": 2},   # nothing causes an earlier tier
)
undirected_edges(graph)   # the edges still undetermined
```

`CausalSimulator.discover_graph()` passes the declared confounders and target as
this ordering, and warns about any edge it then has to orient by assumption.

FCI, which allows for latent confounders, is not implemented yet.

#### Graded against known answers

[`benchmarks/known_answers.py`](benchmarks/known_answers.py) simulates data from graphs
and channel effects that are known in advance and grades every method against them. It
uses only the public API, so any release can be run through it. On 12 random five-node
graphs, 0.7.0 recovers the exact equivalence class 10 times with PC, 11 with GES and 11
with hybrid, against 1, 2 and 0 for 0.6.0. Full results, including attribution, are in
[`benchmarks/results/known_answers.md`](benchmarks/results/known_answers.md).

### 3. Structural Causal Models (SCM)

```python
from pycausalsim.models import StructuralCausalModel

scm = StructuralCausalModel()
scm.fit(data)

# Generate counterfactuals
counterfactuals = scm.counterfactual(
    intervention={'price': 0.9 * current_price},
    evidence={'traffic_source': 'paid'}
)
```

### 4. Marketing Attribution

```python
from pycausalsim import MarketingAttribution

attr = MarketingAttribution(
    data,
    conversion_col='converted',
    touchpoint_cols=['email', 'display', 'search', 'social'],
    covariate_cols=['prior_purchases'],   # what drives both exposure and conversion
)
attr.fit(method='shapley')

attr.get_attribution()            # shares of the conversions marketing added
attr.get_contributions()          # signed, in conversion-rate points
attr.get_baseline()               # conversion rate with no marketing
attr.incremental_effects_table()  # effect of an exposure, with confidence intervals
```

The incremental methods (`shapley`, `logistic`, `linear`, `uplift`) model
conversion and ask what would have happened without each channel. Conversions
that would have happened anyway are credited to no one, a channel with no effect
earns nothing, and a channel that lowers conversion shows a negative
contribution. They assume the drivers of both exposure and conversion are
measured and passed as `covariate_cols`; only an experiment removes that
assumption.

`markov`, `first_touch` and `last_touch` describe where converting journeys went
and are not causal. They use the order in `path_col` (for example
`"search > email"`).

`optimize_budget(total_budget)` splits a budget in proportion to attribution per
unit cost, within any limits you set. It is a rule of thumb: exposure flags say
nothing about diminishing returns.

### 5. A/B Test Analysis

```python
from pycausalsim import ExperimentAnalysis

exp = ExperimentAnalysis(data, treatment='new_feature', outcome='engagement')
effect = exp.estimate_effect(method='dr')  # Doubly robust estimator

# Check for heterogeneous effects
het = exp.analyze_heterogeneity(covariates=['user_tenure', 'activity_level'])
```

### 6. Uplift Modeling

```python
from pycausalsim.uplift import UpliftModeler

uplift = UpliftModeler(data, treatment='campaign', outcome='conversion')
uplift.fit()

# Segment users: persuadables, sure_things, lost_causes, sleeping_dogs
segments = uplift.segment_by_effect()
```

### 7. Built-in Validation

```python
# Sensitivity analysis
sensitivity = simulator.validate('price')
print(sensitivity.summary())
sensitivity.robustness_value     # confounding needed to explain the effect away (0 fragile, 1 robust)
sensitivity.confounding_bounds   # range of the effect under a hidden confounder of given strength
sensitivity.placebo_results      # a shuffled treatment should show no significant effect
sensitivity.refutation_results   # random common cause, placebo treatment, data subsets
```

### 8. Futures and Scenario Simulation

Causal discovery is retrodictive. It learns a graph from existing data and estimates interventions within that data's support. Forecasting inverts both halves, and `pycausalsim.futures` supplies what the inversion needs.

```python
from pycausalsim.futures import TemporalSCM, Scenario, SI, compare, rank_drivers

scm = TemporalSCM(horizon=range(2026, 2042), draws=4000, seed=7)

scm.parameter("attrition", "normal", loc=0.045, scale=0.008)
scm.lever("apprenticeship", default=0.05)

# lags make the unrolled graph acyclic, so identification carries over
scm.state("senior_stock",
          lambda c: (c.lag("senior_stock", 1) * (1 - c.p.attrition)
                     + c.p.conversion * c.lag("junior", 10)),
          parents=["junior:lag(10)", "senior_stock:lag(1)"],
          init=lambda p: p.conversion / p.attrition * 100.0)

# extrapolation is declared, never silent
scm.mechanism("automation ~ token_price", form="logistic",
              valid_range=(0.0005, 100.0), outside="flag")

# interventions on structure, not only on value
scm.structural_rule(when="automation > 0.55",
                    apply=SI.remove_edge("junior", "senior_stock"),
                    note="training stops being a free byproduct")

funded = Scenario("Funded apprenticeship")
funded.at(2027).set("apprenticeship", ramp_to=0.72, over=4)

cmp = compare(scm, [Scenario("Drift"), funded], target="wellbeing")
print(cmp.table())
rank_drivers(scm, Scenario("Drift"), target="wellbeing")
```

**What it adds**

- **`TemporalSCM`** unrolls a graph over a horizon. Parents are written `"name"` or `"name:lag(k)"`. State variables carry memory. A cycle at lag zero is an error, because feedback in a dynamic system is feedback across time.
- **`MechanismPrior`** requires a declared functional form and validity range on any edge that will be driven outside observed data. Every excursion is recorded, so results report which conclusions rest on data and which rest on assumed mechanism.
- **`StructuralIntervention`** adds, removes and rewires edges, and rules fire per draw. `do()` sets a value; it does not delete an edge, and the most consequential futures questions are structural.
- **`Scenario`** is a declarative bundle of timed interventions, readable and editable by people who do not write Python.
- **`ClaimSet`** emits dated, checkable claims with probabilities and a named source, exports them to JSON, and scores them later with a Brier score.
- **`backtest`** scores the model against observed anchors and reports whether the stated intervals are calibrated. **`rolling_backtest`** does the same from many forecast origins and pools the result.
- **`empirical_path`** resamples whole episodes from history, such as past winters, so the correlation across steps survives. Optional weights let outside probabilities, a seasonal outlook for example, steer the draws.
- **`RunResult.window`** aggregates a node over a span per draw, and claims can test it: "the November to March average settles below the strip."
- Steps need not be years. Any sortable integer label works, such as `202611` for November 2026, and `c.step` and `scm.steps` name them that way.

One habit matters more than any feature: take every quantity for one analysis from **one run**. Each `scm.run()` draws fresh parameters, so mixing months from separate runs breaks the correlation inside a draw and makes ranges too narrow. `compare` and `RunResult.window` keep you on the right side of this.

Full documentation: [`pycausalsim/futures/README.md`](pycausalsim/futures/README.md). Worked examples:

- [`examples/henry_hub_winter.py`](examples/henry_hub_winter.py): Henry Hub natural gas for winter 2026-27, monthly, anchored on the NYMEX futures curve, with storage surprises as the causal channel, whole-winter weather resampling, LNG and freeze-off scenarios, a hedge-to-budget decision and a leave-one-winter-out backtest on bundled EIA data.
- [`examples/postlabor_futures.py`](examples/postlabor_futures.py): a fifteen-year post-labor transition model with four policy levers and a ten-year apprenticeship lag.

### 9. Grading marketing mix models (0.5)

```python
from pycausalsim.futures import marketing_worlds, worlds_from_graph, lift_test, leaderboard
from pycausalsim.futures import papilon_estimator, ols_estimator

worlds = marketing_worlds(60, hard=True, seed=7)             # 60 brands, each with an answer key
worlds = marketing_worlds(60, response="s_curve", competitor=True)   # harder: S-curves, competitor shocks
worlds = worlds_from_graph(graph, 60, hide=["launch"])       # your own structure, a driver withheld

test = lift_test(worlds, 0, "paid_search", weeks=8)          # measured return, standard error, truth
leaderboard({"papilon": papilon_estimator(), "ols": ols_estimator()}, worlds, ids=range(12))
```

An estimator is any function `(df, info) -> {"roas": {channel: (estimate, p05, p95)},
"plan": spend}`, so a model from any library can be scored on the same brands:
interval coverage, error and bias on return, share of the best possible budget gain
captured, and share of brands where its plan lost money. `worlds_from_graph` takes a
`papilon.MarketingGraph`, so the worlds a model is graded on share the structure the
analyst declared for the real brand.

The [open leaderboard](https://github.com/Bodhi8/papilon/blob/main/benchmarks/LEADERBOARD.md)
in the Papilon repository is built on these functions and accepts entries for any model.

## Installation

```bash
pip install pycausalsim
```

Or the latest from GitHub:

```bash
pip install git+https://github.com/Bodhi8/pycausalsim.git
```

Or clone and install locally:

```bash
git clone https://github.com/Bodhi8/pycausalsim.git
cd pycausalsim
pip install -e ".[dev]"
```

## Quick Start

```python
import pandas as pd
from pycausalsim import CausalSimulator

# Load your data
data = pd.read_csv('conversion_data.csv')

# Initialize simulator
simulator = CausalSimulator(
    data=data,
    target='conversion_rate',
    treatment_vars=['page_load_time', 'price', 'design_variant'],
    confounders=['traffic_source', 'device_type', 'time_of_day']
)

# Step 1: Discover causal structure
simulator.discover_graph(method='ges')
simulator.plot_graph()  # Visualize learned causal relationships

# Step 2: Simulate interventions
load_time_effect = simulator.simulate_intervention(
    variable='page_load_time',
    value=2.0,  # seconds
    n_simulations=1000
)
print(load_time_effect.summary())

# Step 3: Rank all causal drivers
drivers = simulator.rank_drivers()
for var, effect in drivers:
    print(f"{var}: {effect:.3f}")

# Step 4: Find optimal policy
optimal = simulator.optimize_policy(
    objective='maximize',
    constraints={'price': (10, 50)}
)
```

## Use Cases

1. **Conversion Rate Optimization**: Identify true drivers of conversion vs. correlated factors
2. **Marketing Attribution**: Move beyond last-touch to understand true incremental value
3. **Product Feature Impact**: Understand which features actually drive engagement
4. **Pricing Optimization**: Understand causal price elasticity (not just correlation)
5. **Retention Analysis**: Identify causal drivers of churn
6. **Policy Scenario Analysis**: Compare interventions over a horizon, rank levers by causal effect, and publish claims that can be scored later
7. **Strategic Forecasting**: Simulate futures outside observed support with the extrapolation declared rather than hidden

## Why Simulation for Causality?

### The Problem with Correlation

```python
# Traditional approach - WRONG!
from sklearn.ensemble import RandomForestRegressor

rf = RandomForestRegressor()
rf.fit(X, y)
feature_importance = rf.feature_importances_

# Feature importance != causal importance
# Tells you what predicts, not what causes
# Fails with confounding, selection bias, reverse causation
```

### The PyCausalSim Approach

```python
from pycausalsim import CausalSimulator

sim = CausalSimulator(data, target='conversion')
sim.discover_graph()  # Learn causal structure

# Explicitly models confounding
# Distinguishes correlation from causation
# Validates assumptions
# Provides counterfactual predictions

drivers = sim.rank_drivers()  # TRUE causal importance
```

## Project Structure

```
pycausalsim/
├── pycausalsim/
│   ├── __init__.py         # Package exports
│   ├── simulator.py        # Main CausalSimulator class
│   ├── attribution.py      # Marketing Attribution
│   ├── experiment.py       # A/B Test Analysis
│   ├── results.py          # Result classes
│   ├── models/             # Structural Causal Models
│   ├── discovery/          # Causal discovery algorithms
│   ├── uplift/             # Uplift modeling
│   ├── agents/             # Agent-based simulation
│   ├── validation/         # Sensitivity analysis
│   ├── adapters/           # DoWhy/EconML integration
│   ├── futures/            # Temporal SCMs and scenario forecasting
│   │   ├── temporal.py     #   TemporalSCM, Context, RunResult
│   │   ├── mechanism.py    #   MechanismPrior, SupportReport
│   │   ├── structural.py   #   StructuralIntervention, StructuralRule
│   │   ├── scenario.py     #   Scenario language
│   │   ├── results.py      #   Comparison, rank_drivers, ClaimSet
│   │   └── backtest.py     #   Retrodiction scoring
│   ├── utils/              # Utilities
│   └── visualization/      # Plotting
├── tests/                  # Test suite
├── examples/               # Example scripts
├── pyproject.toml          # Package configuration
└── README.md
```

## Roadmap

**Shipped in 0.3**

- `empirical_path` for resampling whole historical episodes, with optional weights
- `choice` priors, `Scenario.path` for step-by-step lever values, `RunResult.window` and window claims
- `rolling_backtest` for pooled multi-origin backtests
- Monthly and other non-annual horizons, named with `c.step` and `scm.steps`
- A Henry Hub natural gas example with bundled EIA data and a regression test
- NumPy 2 compatibility for uplift metrics, Python 3.10+, a single version source

**Shipped in 0.2**

- Temporal SCMs with lags, state variables and per-draw structural rules
- Declared mechanism priors with out-of-support reporting
- Scenario language, paired comparison, driver ranking
- Falsifiable claim sets with Brier scoring
- Backtesting against observed anchors

**Next**

- **Agent layer for futures.** `agents/` exists but does not yet plug into `TemporalSCM`. Aggregate models report population means, which cannot distinguish two people with identical material conditions and non-comparable lives. Heterogeneous institution access, geography and cohort would recover that.
- **Geography.** No spatial dimension today, which is the largest omission in the post-labor example. Regional bottleneck prices and migration between regions are the first two edges to add.
- **Structural uncertainty.** The Monte Carlo covers coefficients, not structure. Sampling over a distribution of graphs is the honest version and is considerably harder.
- **Scenario DSL in YAML**, so scenarios can be authored and reviewed without touching Python at all.
- **A public claim ledger.** Exported claim sets are only useful if someone scores them. A registry of dated predictions with resolution sources would give forecasting the accountability mechanism it has never had.

## Dependencies

**Core:**

- numpy >= 1.20.0
- pandas >= 1.3.0
- scipy >= 1.7.0
- scikit-learn >= 1.0.0

**Optional:**

- matplotlib, networkx, seaborn (visualization)
- dowhy, econml (integrations)

`pycausalsim.futures` needs numpy only. The Henry Hub example also uses pandas. Python 3.10 or later.

## Contributing

We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

```bash
git clone https://github.com/Bodhi8/pycausalsim.git
cd pycausalsim
pip install -e ".[dev]"
pytest tests/
```

## License


Apache License 2.0, free for commercial use. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
Versions 0.4.0 and earlier were released under the MIT License and remain available
under it.

PyCausalSim, Papilon and Vector1 are trademarks of Brian Curry. The license covers the
code, not the names: see [TRADEMARKS.md](TRADEMARKS.md).

## Acknowledgments

PyCausalSim builds on research from:

- Pearl, J. (2009). *Causality: Models, Reasoning and Inference*
- Peters, J., Janzing, D., & Schölkopf, B. (2017). *Elements of Causal Inference*
- Imbens, G. W., & Rubin, D. B. (2015). *Causal Inference for Statistics, Social, and Biomedical Sciences*

And integrates with:

- [DoWhy](https://github.com/py-why/dowhy) - Microsoft's causal inference library
- [EconML](https://github.com/py-why/EconML) - Heterogeneous treatment effects
- [CausalML](https://github.com/uber/causalml) - Uber's uplift modeling library

## Citation

```bibtex
@software{pycausalsim2025,
  title = {PyCausalSim: Causal Discovery Through Simulation},
  author = {Brian Curry},
  year = {2025},
  url = {https://github.com/Bodhi8/pycausalsim}
}
```

## Contact

- GitHub: [github.com/Bodhi8/pycausalsim](https://github.com/Bodhi8/pycausalsim)
- Email: brian@vector1.ai
- Website: [Vector1 AI](https://vector1.ai)
