Your first causal study
Ask whether a job-training program raised earnings, and walk the Causal studio's seven steps from question to claim.
What runs in CodeSplash
- Matching (nearest neighbor, exact, coarsened exact) Verified in Python and R
You will be able to
- Say why a difference between groups isn't automatically an effect
- Name the seven steps of the Causal studio and what each one guards against
- Read an estimate alongside the strength of the claim it supports
Did training raise earnings?
ReadThe LaLonde data follow 185 people in a job-training program and 429 who weren't. People weren't assigned at random, so the two groups started out very different.
That's the difficulty. Any gap in 1978 earnings mixes the program's effect with who chose to join. Their largest imbalance on background characteristics was 0.72 standard deviations.
Will matching settle it?
PredictPredict first
Each participant is matched to a similar non-participant, comparing age, education, race, marital status and past earnings. What do you expect?
Reveal
The estimate is a gain of $894, but the interval runs from $−509 to $2,297 (p = .211). The data are compatible with a sizeable gain and with a modest loss.
Seven steps
ReadThe Causal studio takes you through Question, Design, DAG, Assumptions, Estimate, Robustness and Interpret.
The estimate comes fifth on purpose. Before any number appears, you say what you're estimating, what variation you can use and which causes you're assuming. Each of those is easier to fudge once you've seen a result you like.
Read the result
In the appAfter nearest-neighbor matching (1:1), 185 treated units are compared with 185 controls. The ATT of true vs false on earnings 1978 is 894.37 (95% CI [−508.50, 2297.24], p = .211). The largest standardized covariate difference fell from 0.721 to 0.216.
- ATT (matched difference)
- 894.37
- 95% CI
- [−508.50, 2297.24]
- p
- .211
- Matched treated / controls
- [185, 185]
- Max |SMD| after
- 0.2162
Plots
View data
| Covariate | Standardized mean difference | Stage |
|---|---|---|
| age | −0.3094 | before |
| educ | 0.0550 | before |
| race: hispan | −0.0827 | before |
| race: white | −0.5577 | before |
| married: true | −0.3236 | before |
| nodegree: true | 0.1114 | before |
| re74 | −0.7211 | before |
| re75 | −0.2903 | before |
| age | 0.0718 | matched |
| educ | −0.1290 | matched |
| race: hispan | −0.1568 | matched |
| race: white | −0.2162 | matched |
| married: true | −0.0216 | matched |
| nodegree: true | 0.0703 | matched |
| re74 | −0.0505 | matched |
| re75 | −0.0257 | matched |
View data
| treat | Propensity score | Matching weight |
|---|---|---|
| true | 0.6388 | 1 |
| true | 0.2246 | 1 |
| true | 0.6782 | 1 |
| true | 0.7763 | 1 |
| true | 0.7016 | 1 |
| true | 0.6991 | 1 |
| true | 0.6537 | 1 |
| true | 0.7897 | 1 |
| true | 0.7798 | 1 |
| true | 0.0429 | 1 |
| true | 0.6890 | 1 |
| true | 0.6824 | 1 |
| true | 0.6499 | 1 |
| true | 0.5624 | 1 |
| true | 0.6086 | 1 |
| true | 0.7225 | 1 |
| true | 0.7026 | 1 |
| true | 0.7350 | 1 |
| true | 0.7117 | 1 |
| true | 0.6643 | 1 |
| true | 0.7652 | 1 |
| true | 0.1390 | 1 |
| true | 0.1224 | 1 |
| true | 0.7680 | 1 |
| true | 0.7193 | 1 |
| true | 0.6092 | 1 |
| true | 0.7708 | 1 |
| true | 0.2692 | 1 |
| true | 0.7161 | 1 |
| true | 0.7680 | 1 |
| true | 0.7161 | 1 |
| true | 0.6098 | 1 |
| true | 0.5940 | 1 |
| true | 0.6429 | 1 |
| true | 0.6608 | 1 |
| true | 0.7786 | 1 |
| true | 0.5609 | 1 |
| true | 0.4509 | 1 |
| true | 0.5568 | 1 |
| true | 0.7380 | 1 |
| true | 0.6465 | 1 |
| true | 0.0937 | 1 |
| true | 0.6463 | 1 |
| true | 0.0915 | 1 |
| true | 0.7566 | 1 |
| true | 0.5940 | 1 |
| true | 0.6463 | 1 |
| true | 0.6822 | 1 |
| true | 0.5609 | 1 |
| true | 0.6537 | 1 |
| true | 0.6849 | 1 |
| true | 0.6167 | 1 |
| true | 0.7507 | 1 |
| true | 0.6608 | 1 |
| true | 0.6129 | 1 |
| true | 0.7161 | 1 |
| true | 0.7464 | 1 |
| true | 0.3785 | 1 |
| true | 0.6048 | 1 |
| true | 0.1301 | 1 |
First 60 of 614 rows.
Assumptions
- Overlap (positivity) — 25.7% of rows have propensity scores below .05 or above .95; 10.6% lie outside the common support [0.025, 0.789].
- Covariate balance — Largest |SMD| after adjustment is 0.216 (race: white) > 0.1: residual imbalance can bias the estimate. Also, the variance ratio for age is 0.46, outside 0.5–2.
- Common support — 0 of 185 treated units unmatched.
- No unmeasured confounding — The estimate is causal only if the covariates include every common cause of treatment and outcome; check how strong an omitted confounder would have to be with the sensitivity analysis.
Matched estimate
| Quantity | Estimate | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| ATT (true − false) | 894.37 | 715.76 | −508.50 | 2297.24 |
| Mean, matched true | 6349.14 | — | — | — |
| Weighted mean, matched false | 5454.78 | — | — | — |
Standard error clustered on matched sets (HC1).
Covariate balance
| Covariate | Type | Mean true | Mean false | SMD before | SMD matched | Variance ratio matched |
|---|---|---|---|---|---|---|
| age | continuous | 25.816 | 28.030 | −0.3094 | 0.0718 | 0.4568 |
| educ | continuous | 10.346 | 10.235 | 0.0550 | −0.1290 | 0.5721 |
| race: hispan | binary | 0.0595 | 0.1422 | −0.0827 | −0.1568 | — |
| race: white | binary | 0.0973 | 0.6550 | −0.5577 | −0.2162 | — |
| married: true | binary | 0.1892 | 0.5128 | −0.3236 | −0.0216 | — |
| nodegree: true | binary | 0.7081 | 0.5967 | 0.1114 | 0.0703 | — |
| re74 | continuous | 2095.57 | 5619.24 | −0.7211 | −0.0505 | 1.329 |
| re75 | continuous | 1532.06 | 2466.48 | −0.2903 | −0.0257 | 1.496 |
Standardized by the treated group's SD (ATT); binary covariates as differences in proportions.
- Estimand: ATT. Treated = true; covariates: age, educ, race, married, nodegree, re74, re75.
The exact R script · R R version 4.5.1 (2025-06-13)
# Matching (nearest neighbor, exact, coarsened exact)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.matching 2.0.1 · spec 4b8691687a698f55
# Dataset: c2_lalonde (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c2_lalonde.parquet", col_select = c("earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75")))
n_input <- nrow(df)
df[["treat"]] <- factor(df[["treat"]], levels = c("false", "true")) # stored level order
df[["race"]] <- factor(df[["race"]], levels = c("black", "hispan", "white")) # stored level order
df[["married"]] <- factor(df[["married"]], levels = c("false", "true")) # stored level order
df[["nodegree"]] <- factor(df[["nodegree"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75")) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment <- "treat"
outcome <- "earnings 1978"
covariates <- c("age", "educ", "race", "married", "nodegree", "re74", "re75")
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same folds and resamples
tr_info <- cs_causal_treatment(df, treatment, NULL)
t <- tr_info$t
treated_level <- tr_info$treated
control_level <- tr_info$control
y_info <- cs_causal_outcome(df, outcome)
y <- y_info$y
event_level <- y_info$event
des <- cs_causal_design(df, covariates)
X <- des$X
labels <- des$labels
binary <- des$binary
if (ncol(X) > 0) cs_causal_check_rank(X, labels)
n <- length(t)
n_treated <- as.integer(sum(t))
n_control <- as.integer(n - sum(t))
outcome_text <- if (!is.null(event_level)) sprintf("%s = %s", outcome, event_level) else outcome
contrast_text <- sprintf("%s = %s vs %s", treatment, treated_level, control_level)
method <- "nearest" # nearest | exact | cem
ratio <- as.integer(1)
replace <- FALSE
caliper <- NULL # SDs of the logit propensity score; NULL = no caliper
m_order <- "largest" # MatchIt's m.order: largest | smallest | data
cem_bins <- as.integer(5)
# %% Match (ATT)
ps <- NULL
converged <- TRUE
if (method == "nearest") {
# = MatchIt::matchit(treat ~ ..., method = "nearest", distance = "glm", link = "linear.logit",
# ratio, replace, caliper, m.order) — the twin below follows MatchIt's rules exactly.
p <- cs_causal_ps(X, t)
ps <- p$ps
converged <- p$converged
m <- cs_causal_match_nearest(p$eta, t, ratio, replace, caliper, m_order)
w <- m$w
subclass <- m$subclass
n_unmatched <- m$discarded
vcov <- if (replace) "HC1" else "cluster" # pair-clustered SEs without replacement (MatchIt's guidance)
} else {
m <- cs_causal_match_strata(df, covariates, t, coarsen = method == "cem", bins = cem_bins)
w <- m$w
subclass <- m$stratum
n_unmatched <- m$dropped
vcov <- "HC1"
}
if (sum(w[t == 1] > 0) < 2 || sum(w[t == 0] > 0) < 2) stop("Fewer than two treated units found a match; loosen the caliper or use fewer covariates for exact matching.")
res <- cs_causal_wdiff(y, t, w, conf, vcov, subclass)
n_t_matched <- sum(w > 0 & t == 1)
n_c_matched <- sum(w > 0 & t == 0)
# %% Balance and checks
bal <- cs_causal_balance(X, labels, binary, t, w, "ATT")
max_before <- max(vapply(bal, function(r) abs(r$smd_before), numeric(1)))
bc <- cs_causal_balance_check(bal)
ess_c <- cs_causal_ess(w[t == 0 & w > 0])
share_lost <- n_unmatched / n_treated
support <- if (share_lost <= 0.05) {
list(id = "support", label = "Common support", status = "pass", detail = sprintf("%d of %d treated units unmatched.", n_unmatched, n_treated))
} else {
s <- list(id = "support", label = "Common support", status = if (share_lost <= 0.3) "concern" else "fail",
detail = sprintf("%d of %d treated units (%s) found no match: the estimate describes the matched treated, not all treated.",
n_unmatched, n_treated, cs_causal_pct1(share_lost)))
if (share_lost > 0.3) s$downgrade_to <- "L1"
s
}
checks <- list()
if (!is.null(ps)) checks[[1]] <- cs_causal_overlap_check(ps, t)
checks <- c(checks, list(bc$check, support, cs_causal_no_confounding_check()))
values <- list()
for (r in bal) {
values[[sprintf("smd_before[%s]", r$covariate)]] <- r$smd_before
values[[sprintf("smd_after[%s]", r$covariate)]] <- r$smd_after
if (!is.null(r$vr_after)) values[[sprintf("vr_after[%s]", r$covariate)]] <- r$vr_after
}
values$n_vr_outside <- length(cs_causal_vr_outside(bal))
# %% Matched rows (artifact)
out <- cs_ml_out_dir("target/academy-parity/run-8142/causal.matching/nearest-lalonde/out-r")
rows <- as.integer(rownames(df)) - 1L # 0-based positions in the input file
keep <- w > 0
matched <- data.frame(row = rows[keep], treated = t[keep] == 1, weight = w[keep], subclass = as.integer(subclass[keep]))
if (!is.null(ps)) matched$propensity <- ps[keep]
nanoparquet::write_parquet(matched, file.path(out, "matched.parquet"))
# %% Result
mname <- switch(method,
nearest = sprintf("nearest-neighbor matching (%d:1%s%s)", ratio, if (replace) ", with replacement" else "",
if (!is.null(caliper)) sprintf(", caliper %s SD", sprintf("%g", caliper)) else ""),
exact = "exact matching", cem = sprintf("coarsened exact matching (%d bins)", cem_bins))
pct <- sprintf("%.0f%%", conf * 100)
effect_label <- sprintf("Average treatment effect on the treated of %s on %s", contrast_text, outcome_text)
summary <- paste0(
sprintf("After %s, %d treated units are compared with %d controls. ", mname, n_t_matched, n_c_matched),
sprintf("The ATT of %s vs %s on %s is %s (%s CI [%s, %s], %s). ", treated_level, control_level, outcome_text, cs_fmt_num(res$estimate), pct,
cs_fmt_num(res$ci_low), cs_fmt_num(res$ci_high), cs_fmt_p(res$p_value)),
sprintf("The largest standardized covariate difference fell from %.3f to %.3f.", max_before, bc$max))
values <- c(values, list(
estimate = res$estimate, se = res$se, ci_low = res$ci_low, ci_high = res$ci_high, z = res$z, p_value = res$p_value,
n = n, n_treated = n_treated, n_control = n_control, n_treated_matched = n_t_matched, n_control_matched = n_c_matched,
n_treated_unmatched = as.integer(n_unmatched), mu_treated = res$mu_treated, mu_control = res$mu_control, estimand = "ATT",
effect_label = effect_label, claim_level_max = "L2", ess_control = ess_c, max_abs_smd_before = max_before,
max_abs_smd_after = bc$max, mean_abs_smd_after = bc$mean, method = method, treated_level = treated_level, control_level = control_level))
charts <- list(cs_chart("balance", "love-plot", "Covariate balance before and after matching", list(
covariate = cs_col("Covariate", rep(vapply(bal, `[[`, "", "covariate"), 2), kind = "categorical"),
smd = cs_col("Standardized mean difference", c(vapply(bal, `[[`, 0, "smd_before"), vapply(bal, `[[`, 0, "smd_after"))),
stage = cs_col("Stage", rep(c("before", "matched"), each = length(bal)), kind = "categorical")),
controls = list(threshold = 0.1)))
if (!is.null(ps)) {
charts[[2]] <- cs_chart("overlap", "overlap-density", "Propensity scores by group (matched weights)", list(
score = cs_col("Propensity score", ps), group = cs_col(treatment, ifelse(t == 1, treated_level, control_level), kind = "categorical"),
weight = cs_col("Matching weight", w)))
}
cs_publish(list(
method = "causal.matching",
methodVersion = "2.0.1",
title = sprintf("Matching (%s)", switch(method, nearest = "nearest neighbor", exact = "exact", cem = "coarsened exact")),
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "estimate", label = "ATT (matched difference)", value = res$estimate),
list(key = "ci", label = paste(pct, "CI"), value = c(res$ci_low, res$ci_high)),
list(key = "p_value", label = "p", value = res$p_value, format = "p"),
list(key = "matched", label = "Matched treated / controls", value = c(n_t_matched, n_c_matched)),
list(key = "max_abs_smd_after", label = "Max |SMD| after", value = bc$max)),
tables = list(
list(key = "effect", title = "Matched estimate", columns = list(
list(key = "quantity", label = "Quantity", type = "string"), list(key = "value", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "ci_low", label = paste(pct, "CI low"), type = "number"),
list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = list(
list(quantity = sprintf("ATT (%s − %s)", treated_level, control_level), value = res$estimate, se = res$se, ci_low = res$ci_low, ci_high = res$ci_high),
list(quantity = sprintf("Mean, matched %s", treated_level), value = res$mu_treated, se = NULL, ci_low = NULL, ci_high = NULL),
list(quantity = sprintf("Weighted mean, matched %s", control_level), value = res$mu_control, se = NULL, ci_low = NULL, ci_high = NULL)),
note = if (vcov == "cluster") "Standard error clustered on matched sets (HC1)." else "Robust (HC1) standard error with the matching weights treated as known."),
list(key = "balance", title = "Covariate balance", columns = list(
list(key = "covariate", label = "Covariate", type = "string"), list(key = "type", label = "Type", type = "string"),
list(key = "mean_treated_before", label = paste("Mean", treated_level), type = "number"),
list(key = "mean_control_before", label = paste("Mean", control_level), type = "number"),
list(key = "smd_before", label = "SMD before", type = "number"), list(key = "smd_after", label = "SMD matched", type = "number"),
list(key = "vr_after", label = "Variance ratio matched", type = "number")),
rows = bal, note = "Standardized by the treated group's SD (ATT); binary covariates as differences in proportions.")),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
checks = checks,
artifacts = list(list(key = "matched", path = "matched.parquet", format = "parquet", title = "Matched rows with weights")),
warnings = c(warnings, if (!converged) list("The propensity model did not converge (a covariate predicts treatment perfectly).") else list()),
notes = list(sprintf("Estimand: ATT. Treated = %s; covariates: %s.", treated_level, paste(covariates, collapse = ", "))),
charts = charts,
values = values
))
After nearest-neighbor matching (1:1), 185 treated units are compared with 185 controls. The ATT of true vs false on earnings 1978 is 894.37 (95% CI [−508.50, 2297.24], p = .211). The largest standardized covariate difference fell from 0.721 to 0.216.
- ATT (matched difference)
- 894.37
- 95% CI
- [−508.50, 2297.24]
- p
- .211
- Matched treated / controls
- [185, 185]
- Max |SMD| after
- 0.2162
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Overlap (positivity) — 25.7% of rows have propensity scores below .05 or above .95; 10.6% lie outside the common support [0.025, 0.789].
- Covariate balance — Largest |SMD| after adjustment is 0.216 (race: white) > 0.1: residual imbalance can bias the estimate. Also, the variance ratio for age is 0.46, outside 0.5–2.
- Common support — 0 of 185 treated units unmatched.
- No unmeasured confounding — The estimate is causal only if the covariates include every common cause of treatment and outcome; check how strong an omitted confounder would have to be with the sensitivity analysis.
Matched estimate
| Quantity | Estimate | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| ATT (true − false) | 894.37 | 715.76 | −508.50 | 2297.24 |
| Mean, matched true | 6349.14 | — | — | — |
| Weighted mean, matched false | 5454.78 | — | — | — |
Standard error clustered on matched sets (HC1).
Covariate balance
| Covariate | Type | Mean true | Mean false | SMD before | SMD matched | Variance ratio matched |
|---|---|---|---|---|---|---|
| age | continuous | 25.816 | 28.030 | −0.3094 | 0.0718 | 0.4568 |
| educ | continuous | 10.346 | 10.235 | 0.0550 | −0.1290 | 0.5721 |
| race: hispan | binary | 0.0595 | 0.1422 | −0.0827 | −0.1568 | — |
| race: white | binary | 0.0973 | 0.6550 | −0.5577 | −0.2162 | — |
| married: true | binary | 0.1892 | 0.5128 | −0.3236 | −0.0216 | — |
| nodegree: true | binary | 0.7081 | 0.5967 | 0.1114 | 0.0703 | — |
| re74 | continuous | 2095.57 | 5619.24 | −0.7211 | −0.0505 | 1.329 |
| re75 | continuous | 1532.06 | 2466.48 | −0.2903 | −0.0257 | 1.496 |
Standardized by the treated group's SD (ATT); binary covariates as differences in proportions.
- Estimand: ATT. Treated = true; covariates: age, educ, race, married, nodegree, re74, re75.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Matching (nearest neighbor, exact, coarsened exact)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.matching 2.0.1 · spec 4b8691687a698f55
# Dataset: c2_lalonde (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.causal import matching as csm
from codesplash.causal import weighting as csw
from codesplash.ml.run import out_dir as cs_out_dir
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c2_lalonde.parquet", columns=["earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75"])
n_input = len(df)
df["treat"] = pd.Categorical(df["treat"], categories=["false", "true"]) # stored level order
df["race"] = pd.Categorical(df["race"], categories=["black", "hispan", "white"]) # stored level order
df["married"] = pd.Categorical(df["married"], categories=["false", "true"]) # stored level order
df["nodegree"] = pd.Categorical(df["nodegree"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75"]) # listwise deletion over the analysis columns
df["treat"] = df["treat"].cat.remove_unused_categories()
df["race"] = df["race"].cat.remove_unused_categories()
df["married"] = df["married"].cat.remove_unused_categories()
df["nodegree"] = df["nodegree"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["earnings 1978", "treat", "age", "educ", "race", "married", "nodegree", "re74", "re75"]) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment = "treat"
outcome = "earnings 1978"
covariates = ["age", "educ", "race", "married", "nodegree", "re74", "re75"]
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same folds and resamples
t, treated_level, control_level = csw.treatment_indicator(df, treatment, None)
y, event_level = csw.outcome_vector(df, outcome)
X, labels, binary, sources = csw.covariate_matrix(df, covariates)
if X.shape[1]:
csw.check_rank(X, labels)
n = len(t)
n_treated, n_control = int(t.sum()), int(n - t.sum())
outcome_text = f"{outcome} = {event_level}" if event_level is not None else outcome
contrast_text = f"{treatment} = {treated_level} vs {control_level}"
method = "nearest" # nearest | exact | cem
ratio = int(1)
replace = False
caliper = None # SDs of the logit propensity score; None = no caliper
order = "largest" # MatchIt's m.order: largest | smallest | data
cem_bins = int(5)
# %% Match (ATT)
ps = None
if method == "nearest":
# = MatchIt::matchit(treat ~ …, method = "nearest", distance = "glm", link = "linear.logit",
# ratio, replace, caliper, std.caliper = TRUE, m.order) in R
ps, eta, _, converged = csw.propensity(X, t)
w, subclass, n_unmatched = csm.nearest(eta, t, ratio, replace, caliper, order)
vcov = "HC1" if replace else "cluster" # pair-clustered SEs without replacement (MatchIt's guidance)
else:
converged = True
w, subclass, n_unmatched = csm.strata(df, covariates, t, coarsen=(method == "cem"), bins=cem_bins)
vcov = "HC1"
if (w[t == 1] > 0).sum() < 2 or (w[t == 0] > 0).sum() < 2:
raise ValueError("Fewer than two treated units found a match; loosen the caliper or use fewer covariates for exact matching.")
res = csw.weighted_difference(y, t, w, conf, vcov, subclass)
n_t_matched = int(((w > 0) & (t == 1)).sum())
n_c_matched = int(((w > 0) & (t == 0)).sum())
# %% Balance and checks
bal = csw.balance(X, labels, binary, t, w, "ATT")
max_before = max(abs(r["smd_before"]) for r in bal)
max_after, mean_after, bal_check = csw.balance_checks(bal)
ess_c = csw.ess(w[(t == 0) & (w > 0)])
share_lost = n_unmatched / n_treated
if share_lost <= 0.05:
support = {"id": "support", "label": "Common support", "status": "pass", "detail": f"{n_unmatched} of {n_treated} treated units unmatched."}
else:
support = {"id": "support", "label": "Common support", "status": "concern" if share_lost <= 0.3 else "fail",
"detail": f"{n_unmatched} of {n_treated} treated units ({share_lost:.1%}) found no match: the estimate describes the matched treated, not all treated."}
if share_lost > 0.3:
support["downgrade_to"] = "L1"
checks = []
if ps is not None:
checks.append(csw.overlap_check(ps, t))
checks += [bal_check, support, csw.no_confounding_check()]
values = {}
for r in bal:
values[f"smd_before[{r['covariate']}]"] = r["smd_before"]
values[f"smd_after[{r['covariate']}]"] = r["smd_after"]
if r.get("vr_after") is not None:
values[f"vr_after[{r['covariate']}]"] = r["vr_after"]
values["n_vr_outside"] = len(csw.variance_ratios_outside(bal))
# %% Matched rows (artifact)
out = cs_out_dir("target/academy-parity/run-8142/causal.matching/nearest-lalonde/out-python")
rows = df.index.to_numpy(dtype=np.int64) # 0-based positions in the input file
matched = pd.DataFrame({"row": rows, "treated": t.astype(bool), "weight": w, "subclass": subclass})
matched = matched[matched["weight"] > 0]
if ps is not None:
matched["propensity"] = ps[w > 0]
matched.to_parquet(os.path.join(out, "matched.parquet"), index=False)
# %% Result
mname = {"nearest": f"nearest-neighbor matching ({ratio}:1{', with replacement' if replace else ''}{f', caliper {caliper:g} SD' if caliper is not None else ''})",
"exact": "exact matching", "cem": f"coarsened exact matching ({cem_bins} bins)"}[method]
pct = f"{conf:.0%}"
effect_label = f"Average treatment effect on the treated of {contrast_text} on {outcome_text}"
summary = (
f"After {mname}, {n_t_matched} treated units are compared with {n_c_matched} controls. The ATT of {treated_level} vs "
f"{control_level} on {outcome_text} is {cs.fmt_num(res['estimate'])} ({pct} CI [{cs.fmt_num(res['ci_low'])}, {cs.fmt_num(res['ci_high'])}], "
f"{cs.fmt_p(res['p_value'])}). The largest standardized covariate difference fell from {max_before:.3f} to {max_after:.3f}."
)
values.update({
"estimate": res["estimate"], "se": res["se"], "ci_low": res["ci_low"], "ci_high": res["ci_high"], "z": res["z"],
"p_value": res["p_value"], "n": n, "n_treated": n_treated, "n_control": n_control, "n_treated_matched": n_t_matched,
"n_control_matched": n_c_matched, "n_treated_unmatched": int(n_unmatched), "mu_treated": res["mu_treated"],
"mu_control": res["mu_control"], "estimand": "ATT", "effect_label": effect_label, "claim_level_max": "L2",
"ess_control": ess_c, "max_abs_smd_before": max_before, "max_abs_smd_after": max_after, "mean_abs_smd_after": mean_after,
"method": method, "treated_level": treated_level, "control_level": control_level,
})
charts = [cs.chart(
"balance", "love-plot", "Covariate balance before and after matching",
{"covariate": cs.col("Covariate", [r["covariate"] for r in bal] * 2, kind="categorical"),
"smd": cs.col("Standardized mean difference", [r["smd_before"] for r in bal] + [r["smd_after"] for r in bal]),
"stage": cs.col("Stage", ["before"] * len(bal) + ["matched"] * len(bal), kind="categorical")},
{"threshold": 0.1},
)]
if ps is not None:
charts.append(cs.chart(
"overlap", "overlap-density", "Propensity scores by group (matched weights)",
{"score": cs.col("Propensity score", ps), "group": cs.col(treatment, np.where(t == 1, str(treated_level), str(control_level)), kind="categorical"),
"weight": cs.col("Matching weight", w)},
))
cs.publish({
"method": "causal.matching",
"methodVersion": "2.0.1",
"title": f"Matching ({ {'nearest': 'nearest neighbor', 'exact': 'exact', 'cem': 'coarsened exact'}[method] })",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "estimate", "label": "ATT (matched difference)", "value": res["estimate"]},
{"key": "ci", "label": f"{pct} CI", "value": [res["ci_low"], res["ci_high"]]},
{"key": "p_value", "label": "p", "value": res["p_value"], "format": "p"},
{"key": "matched", "label": "Matched treated / controls", "value": [n_t_matched, n_c_matched]},
{"key": "max_abs_smd_after", "label": "Max |SMD| after", "value": max_after},
],
"tables": [
{"key": "effect", "title": "Matched estimate", "columns": [
{"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "ci_low", "label": f"{pct} CI low", "type": "number"},
{"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": [
{"quantity": f"ATT ({treated_level} − {control_level})", "value": res["estimate"], "se": res["se"], "ci_low": res["ci_low"], "ci_high": res["ci_high"]},
{"quantity": f"Mean, matched {treated_level}", "value": res["mu_treated"], "se": None, "ci_low": None, "ci_high": None},
{"quantity": f"Weighted mean, matched {control_level}", "value": res["mu_control"], "se": None, "ci_low": None, "ci_high": None}],
"note": ("Standard error clustered on matched sets (HC1)." if vcov == "cluster" else "Robust (HC1) standard error with the matching weights treated as known.")},
{"key": "balance", "title": "Covariate balance", "columns": [
{"key": "covariate", "label": "Covariate", "type": "string"}, {"key": "type", "label": "Type", "type": "string"},
{"key": "mean_treated_before", "label": f"Mean {treated_level}", "type": "number"},
{"key": "mean_control_before", "label": f"Mean {control_level}", "type": "number"},
{"key": "smd_before", "label": "SMD before", "type": "number"}, {"key": "smd_after", "label": "SMD matched", "type": "number"},
{"key": "vr_after", "label": "Variance ratio matched", "type": "number"}],
"rows": bal, "note": "Standardized by the treated group's SD (ATT); binary covariates as differences in proportions."},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"artifacts": [{"key": "matched", "path": "matched.parquet", "format": "parquet", "title": "Matched rows with weights"}],
"warnings": warnings + ([] if converged else ["The propensity model did not converge (a covariate predicts treatment perfectly)."]),
"notes": [f"Estimand: ATT. Treated = {treated_level}; covariates: {', '.join(covariates)}."],
"charts": charts,
"values": values,
})
After matching, the largest imbalance is 0.22, much better but still above the usual 0.1 guideline. This design reaches at most claim level L2, a conditional causal claim.
Check your understanding
CheckpointCheck yourself
Why isn't the raw gap in earnings an effect of training?
Show the answer
Answer: b
That's confounding. Sample size can't fix it: more data only gives you a more precise wrong answer.
Check yourself
Put the first steps of a causal study in order.
Show the answer
The order:
- State the treatment, outcome and estimand.
- Choose the design the data allow.
- Draw your causal assumptions as a DAG.
- Run the estimator.
Decide what you're estimating and why it could be identified before you see a number.
Check yourself
What wording fits a conditional causal claim like this one?
Show the answer
Answer: b
State the assumption, give the range, and don't read a large p-value as no effect.
Do the study
In the appThis guided tour uses the same data, in the real studio, with {{treatment}} as the treatment and {{outcome}} as the outcome.
Recap
Recap- A gap between groups mixes any effect with who ended up in each group.
- The studio makes you state the question, design and assumptions before the estimate.
- Report the estimate with its interval and the claim level the design supports.
Concepts in this lesson