Getting Started
This guide walks you through your first causal analysis with cegraph. You'll create a causal graph, add variables and relationships, and estimate an average causal effect — all in under 5 minutes.
1. Create a Graph
Start by importing CausalEffectGraph and creating an empty graph:
from cegraph import CausalEffectGraph ceg = CausalEffectGraph()
2. Add Variables and Edges
Add directed edges to define causal relationships. Each edge represents a direct causal effect from one node to another:
ceg.add_edge("age", "treatment")
ceg.add_edge("age", "outcome")
ceg.add_edge("treatment", "outcome")
This creates a simple confounding structure where age confounds
the relationship between treatment and outcome.
3. Inspect the Graph
Query the graph to explore its structure:
print(ceg.has_edge("treatment", "outcome")) # True
print(ceg.parents("outcome")) # ['age', 'treatment']
print(ceg.children("age")) # ['treatment', 'outcome'] 4. Compute a Causal Effect
Generate some synthetic data and estimate the average causal effect:
import numpy as np
# Simulate data: age -> treatment, age -> outcome, treatment -> outcome
n = 1000
age = np.random.randn(n)
treatment = 0.5 * age + np.random.randn(n) * 0.5
outcome = 0.8 * treatment + 0.3 * age + np.random.randn(n) * 0.5
data = np.column_stack([age, treatment, outcome])
# Estimate ACE with backdoor adjustment
ace = ceg.average_causal_effect(
data=data,
treatment="treatment",
outcome="outcome",
covariates=["age"],
)
print(f"Average Causal Effect: {ace:.4f}") The estimated ACE should be close to the true effect of 0.8.
5. Find Adjustment Sets
Let the graph automatically find valid adjustment sets:
adj = ceg.backdoor_adjustment_set(
target="outcome",
cause="treatment",
)
print(f"Backdoor adjustment set: {adj}") Next Steps
- Explore the full API Reference
- Learn about cegraph's design philosophy
- Check the GitHub repository for examples and benchmarks