Overlap and balance
Check whether treated and untreated units can be compared at all, and what to do when they can't.
What runs in CodeSplash
- Inverse-probability and entropy-balancing weights Verified in Python and R
You will be able to
- Read an overlap plot and a love plot
- Explain why poor overlap makes any adjustment rely on extrapolation
- Choose between trimming and an overlap estimand
Read first
Can they be compared?
ReadOverlapOverlapEvery kind of unit has some chance of being in each group; without it comparisons extrapolate. means units with the same covariates could have gone either way. If everyone over 60 was treated, the data say nothing about untreated people over 60, and any estimate there comes from the model's assumptions.
Check it before you estimate. Plot the propensity scores by group, and look for scores piled up at 0 or 1.
View data
| propensity score | group | ATT weight |
|---|---|---|
| 0.3396 | control | 0.5143 |
| 0.4744 | control | 0.9024 |
| 0.0755 | control | 0.0816 |
| 0.7225 | control | 2.603 |
| 0.2746 | control | 0.3786 |
| 0.0869 | control | 0.0952 |
| 0.9007 | treated | 1 |
| 0.9307 | treated | 1 |
| 0.4145 | control | 0.7080 |
| 0.9280 | treated | 1 |
| 0.4889 | control | 0.9566 |
| 0.7315 | treated | 1 |
| 0.2515 | control | 0.3360 |
| 0.6990 | control | 2.323 |
| 0.7714 | treated | 1 |
| 0.2006 | control | 0.2509 |
| 0.8423 | treated | 1 |
| 0.4303 | treated | 1 |
| 0.6040 | treated | 1 |
| 0.5619 | treated | 1 |
| 0.5129 | treated | 1 |
| 0.7210 | control | 2.585 |
| 0.5944 | treated | 1 |
| 0.3544 | control | 0.5489 |
| 0.6202 | treated | 1 |
| 0.8802 | control | 7.344 |
| 0.6118 | control | 1.576 |
| 0.3643 | control | 0.5731 |
| 0.3997 | control | 0.6657 |
| 0.6967 | treated | 1 |
| 0.2202 | control | 0.2823 |
| 0.2443 | control | 0.3233 |
| 0.2313 | control | 0.3010 |
| 0.9203 | treated | 1 |
| 0.9681 | treated | 1 |
| 0.2934 | control | 0.4151 |
| 0.2944 | control | 0.4172 |
| 0.3978 | control | 0.6607 |
| 0.2799 | control | 0.3887 |
| 0.8551 | treated | 1 |
| 0.8255 | treated | 1 |
| 0.6405 | control | 1.782 |
| 0.4186 | control | 0.7199 |
| 0.0329 | control | 0.0341 |
| 0.1994 | control | 0.2490 |
| 0.4960 | control | 0.9843 |
| 0.7782 | treated | 1 |
| 0.4633 | control | 0.8632 |
| 0.8173 | treated | 1 |
| 0.9229 | treated | 1 |
| 0.2363 | control | 0.3094 |
| 0.3708 | treated | 1 |
| 0.8013 | treated | 1 |
| 0.4384 | control | 0.7807 |
| 0.8331 | control | 4.991 |
| 0.3892 | control | 0.6372 |
| 0.3799 | control | 0.6126 |
| 0.2191 | control | 0.2807 |
| 0.9112 | treated | 1 |
| 0.4456 | control | 0.8037 |
First 60 of 900 rows.
How much overlap?
PredictPredict first
In the LaLonde job-training data, with very different groups, what range do you expect for the propensity scores?
Reveal
From 0.01 to 0.79. Some untreated people look nothing like anyone treated. At scores close to 0 or 1, weights grow very large.
Balance, before and after
ReadA love plot shows each covariate's SMDStandardized mean differenceA covariate's group difference in standard deviation units; below about 0.1 usually counts as balanced. before and after adjustment. You want the dots inside about 0.1 after.
View data
| covariate | standardized mean difference | stage |
|---|---|---|
| age | −0.3100 | Before |
| age | 0.0110 | Nearest-neighbor matching |
| age | −0.0290 | Entropy balancing |
| education | 0.0700 | Before |
| education | 0.0240 | Nearest-neighbor matching |
| education | 0.0330 | Entropy balancing |
| black | 1.670 | Before |
| black | 0.1160 | Nearest-neighbor matching |
| black | 0.0330 | Entropy balancing |
| hispanic | −0.2800 | Before |
| hispanic | 0.0180 | Nearest-neighbor matching |
| hispanic | −0.0230 | Entropy balancing |
| married | −0.7200 | Before |
| married | −0.1070 | Nearest-neighbor matching |
| married | 0.0050 | Entropy balancing |
| no degree | 0.2400 | Before |
| no degree | 0.0660 | Nearest-neighbor matching |
| no degree | 0.0400 | Entropy balancing |
| earnings 1974 | −0.7200 | Before |
| earnings 1974 | −0.0900 | Nearest-neighbor matching |
| earnings 1974 | −0.0100 | Entropy balancing |
| earnings 1975 | −0.2900 | Before |
| earnings 1975 | 0.0360 | Nearest-neighbor matching |
| earnings 1975 | 0.0080 | Entropy balancing |
| unemployed 1974 | 0.2500 | Before |
| unemployed 1974 | 0.0240 | Nearest-neighbor matching |
| unemployed 1974 | 0.0080 | Entropy balancing |
| unemployed 1975 | 0.2100 | Before |
| unemployed 1975 | 0.0400 | Nearest-neighbor matching |
| unemployed 1975 | 0.0240 | Entropy balancing |
Balance is a property of your sample, so it needs no hypothesis test. Check higher moments too, since means can match while spreads don't.
Two ways out
In the appWhen overlap is poor:
- Trim: drop people with extreme scores. Simple, but the population changes.
- ATO: weight toward those who could plausibly go either way. This is the overlap estimand, and it needs no cut-off.
With inverse-probability weights the ATO of true vs false on converted = true is 0.30 (90% CI [0.26, 0.34], p < .001). Weighted means: 0.67 treated, 0.37 control. The largest standardized covariate difference fell from 0.675 to 0.000.
- ATO (weighted difference)
- 0.3014
- 90% CI
- [0.2604, 0.3431]
- p
- < .001
- Max |SMD| after
- 2.220e-16
- Effective n (treated / control)
- [482.29, 543.01]
Assumptions
- Overlap (positivity) — 0.2% of rows have propensity scores below .05 or above .95; 0.4% lie outside the common support [0.033, 0.916].
- Covariate balance — Every |SMD| ≤ 0.1 and every variance ratio within 0.5–2 after adjustment (largest |SMD| 0.000).
- Extreme weights — Effective sample sizes 482 treated of 553 and 543 controls of 647; the largest weight carries 0.4% of its group.
- 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.
Weighted estimate
| Quantity | Estimate | SE | 90% CI low | 90% CI high |
|---|---|---|---|---|
| ATO (true − false) | 0.3014 | 0.0252 | 0.2604 | 0.3431 |
| Weighted mean, true | 0.6705 | — | — | — |
| Weighted mean, false | 0.3691 | — | — | — |
Bootstrap percentile interval; 0 row(s) trimmed.
Covariate balance
| Covariate | Type | Mean true | Mean false | SMD before | SMD after | Variance ratio after |
|---|---|---|---|---|---|---|
| x1 | continuous | 0.3108 | −0.3323 | 0.6748 | −3.640e-17 | 1.058 |
| segment: b | binary | 0.3345 | 0.2566 | 0.0780 | 0 | — |
| segment: c | binary | 0.1555 | 0.2040 | −0.0485 | −1.665e-16 | — |
| member: true | binary | 0.5172 | 0.3524 | 0.1648 | −2.220e-16 | — |
Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions).
- Estimand: average treatment effect in the overlap population. Treated = true; covariates: x1, segment, member.
The exact R script · R R version 4.5.1 (2025-06-13)
# Inverse-probability and entropy-balancing weights
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.weighting 2.0.0 · spec ac741ba5df01da62
# Dataset: c2_obs (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_obs.parquet", col_select = c("converted", "treated", "x1", "segment", "member")))
n_input <- nrow(df)
df[["converted"]] <- factor(df[["converted"]], levels = c("false", "true")) # stored level order
df[["treated"]] <- factor(df[["treated"]], levels = c("false", "true")) # stored level order
df[["segment"]] <- factor(df[["segment"]], levels = c("a", "b", "c")) # stored level order
df[["member"]] <- factor(df[["member"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("converted", "treated", "x1", "segment", "member")]), , 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("converted", "treated", "x1", "segment", "member")) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment <- "treated"
outcome <- "converted"
covariates <- c("x1", "segment", "member")
conf <- 0.9
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)
estimand <- "ATO" # ATE | ATT | ATC | ATO
method <- "propensity" # propensity | entropy
trim <- if (method == "propensity") 0 else 0 # drop rows with e(x) outside [trim, 1 - trim]
ci_method <- "bootstrap" # robust | bootstrap
B <- as.integer(199)
if (method == "entropy" && estimand == "ATO") stop("Entropy balancing estimates the ATE, ATT or ATC; use propensity weights for the overlap population (ATO).")
# Same weights as WeightIt::weightit(method = "glm" or "ebal", estimand = ...).
fit_weights <- function(Xs, ts) {
if (method == "entropy") {
e <- cs_causal_ebal(Xs, ts, estimand)
return(list(w = e$w, ps = NULL, keep = rep(TRUE, length(ts)), converged = e$converged))
}
p <- cs_causal_ps(Xs, ts)
keep <- if (trim > 0) p$ps >= trim & p$ps <= 1 - trim else rep(TRUE, length(ts))
list(w = cs_causal_ps_weights(p$ps, ts, estimand), ps = p$ps, keep = keep, converged = p$converged)
}
# %% Weights and the weighted difference in means
fw <- fit_weights(X, t)
ps <- fw$ps
converged <- fw$converged
n_trimmed <- sum(!fw$keep)
w <- ifelse(fw$keep, fw$w, 0)
if (sum(w[t == 1] > 0) < 2 || sum(w[t == 0] > 0) < 2) stop("Fewer than two treated or control rows are left after trimming; lower the trimming threshold.")
res <- cs_causal_wdiff(y, t, w, conf, "HC0")
values <- list()
if (ci_method == "bootstrap") {
idx <- cs_boot_indices(n, B, seed)
est_b <- rep(NA_real_, B)
for (r in seq_len(B)) {
ii <- idx[r, ]
tb <- t[ii]
if (sum(tb) < 2 || sum(1 - tb) < 2) next
fb <- tryCatch(fit_weights(X[ii, , drop = FALSE], tb), error = function(e) NULL)
if (is.null(fb)) next
wb <- ifelse(fb$keep, fb$w, 0)
if (sum(wb[tb == 1] > 0) < 2 || sum(wb[tb == 0] > 0) < 2) next
yb <- y[ii]
est_b[r] <- cs_causal_wmean(yb[tb == 1], wb[tb == 1]) - cs_causal_wmean(yb[tb == 0], wb[tb == 0])
}
valid <- est_b[!is.na(est_b)]
se <- stats::sd(valid)
q <- stats::quantile(valid, c((1 - conf) / 2, 1 - (1 - conf) / 2), type = 7, names = FALSE)
z <- res$estimate / se
res$se <- se
res$ci_low <- q[1]
res$ci_high <- q[2]
res$z <- z
res$p_value <- 2 * stats::pnorm(abs(z), lower.tail = FALSE)
values[["n_boot_valid"]] <- length(valid)
}
# %% Balance and checks
bal <- cs_causal_balance(X, labels, binary, t, w, estimand)
max_before <- max(vapply(bal, function(r) abs(r$smd_before), numeric(1)))
bc <- cs_causal_balance_check(bal)
wc <- cs_causal_weights_check(w[w > 0], t[w > 0])
checks <- list()
if (!is.null(ps)) {
checks[[length(checks) + 1]] <- cs_causal_overlap_check(ps, t)
values[["ps_min"]] <- min(ps)
values[["ps_max"]] <- max(ps)
}
checks <- c(checks, list(bc$check, wc$check, cs_causal_no_confounding_check()))
if (!converged) {
checks[[length(checks) + 1]] <- list(id = "convergence", label = "Weights converged", status = "fail", downgrade_to = "L1",
detail = "The propensity model or the balancing did not converge (perfect prediction or impossible balance).")
}
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))
# %% Result
est_text <- switch(estimand, ATE = "average treatment effect", ATT = "average treatment effect on the treated",
ATC = "average treatment effect on the controls", ATO = "average treatment effect in the overlap population")
effect_label <- sprintf("%s%s of %s on %s", toupper(substr(est_text, 1, 1)), substr(est_text, 2, nchar(est_text)), contrast_text, outcome_text)
pct <- sprintf("%.0f%%", conf * 100)
wname <- if (method == "entropy") "entropy-balancing" else "inverse-probability"
summary <- paste0(
sprintf("With %s weights the %s of %s vs %s on %s is %s (%s CI [%s, %s], %s). ", wname, estimand, 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("Weighted means: %s treated, %s control. ", cs_fmt_num(res$mu_treated), cs_fmt_num(res$mu_control)),
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_trimmed = n_trimmed, mu_treated = res$mu_treated, mu_control = res$mu_control,
estimand = estimand, effect_label = effect_label, claim_level_max = "L2", ess_treated = wc$ess_treated, ess_control = wc$ess_control,
max_weight_share = wc$max_share, max_abs_smd_before = max_before, max_abs_smd_after = bc$max, mean_abs_smd_after = bc$mean,
converged = isTRUE(converged), ci_method = ci_method, treated_level = treated_level, control_level = control_level
))
group <- ifelse(t == 1, treated_level, control_level)
charts <- list(cs_chart("balance", "love-plot", "Covariate balance before and after weighting", 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", "weighted"), 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", list(
score = cs_col("Propensity score", ps), group = cs_col(treatment, group, kind = "categorical"), weight = cs_col("Weight", w)))
}
cs_publish(list(
method = "causal.weighting",
methodVersion = "2.0.0",
title = sprintf("%s (%s)", if (method == "entropy") "Entropy balancing" else "Inverse-probability weighting", estimand),
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "estimate", label = sprintf("%s (weighted difference)", estimand), 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 = "max_abs_smd_after", label = "Max |SMD| after", value = bc$max),
list(key = "ess", label = "Effective n (treated / control)", value = c(wc$ess_treated, wc$ess_control))),
tables = list(
list(key = "effect", title = "Weighted 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("%s (%s − %s)", estimand, treated_level, control_level), value = res$estimate, se = res$se, ci_low = res$ci_low, ci_high = res$ci_high),
list(quantity = sprintf("Weighted mean, %s", treated_level), value = res$mu_treated, se = NULL, ci_low = NULL, ci_high = NULL),
list(quantity = sprintf("Weighted mean, %s", control_level), value = res$mu_control, se = NULL, ci_low = NULL, ci_high = NULL)),
note = paste0(if (ci_method == "bootstrap") "Bootstrap percentile interval; " else "Robust (HC0) standard error with the weights treated as known; ",
sprintf("%d row(s) trimmed.", n_trimmed))),
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 after", type = "number"),
list(key = "vr_after", label = "Variance ratio after", type = "number")),
rows = bal,
note = "Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions).")),
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,
warnings = warnings,
notes = list(sprintf("Estimand: %s. Treated = %s; covariates: %s.", est_text, treated_level, paste(covariates, collapse = ", "))),
charts = charts,
values = values
))
With inverse-probability weights the ATO of true vs false on converted = true is 0.30 (90% CI [0.26, 0.34], p < .001). Weighted means: 0.67 treated, 0.37 control. The largest standardized covariate difference fell from 0.675 to 0.000.
- ATO (weighted difference)
- 0.3014
- 90% CI
- [0.2604, 0.3431]
- p
- < .001
- Max |SMD| after
- 1.665e-16
- Effective n (treated / control)
- [482.29, 543.01]
Assumptions
- Overlap (positivity) — 0.2% of rows have propensity scores below .05 or above .95; 0.4% lie outside the common support [0.033, 0.916].
- Covariate balance — Every |SMD| ≤ 0.1 and every variance ratio within 0.5–2 after adjustment (largest |SMD| 0.000).
- Extreme weights — Effective sample sizes 482 treated of 553 and 543 controls of 647; the largest weight carries 0.4% of its group.
- 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.
Weighted estimate
| Quantity | Estimate | SE | 90% CI low | 90% CI high |
|---|---|---|---|---|
| ATO (true − false) | 0.3014 | 0.0252 | 0.2604 | 0.3431 |
| Weighted mean, true | 0.6705 | — | — | — |
| Weighted mean, false | 0.3691 | — | — | — |
Bootstrap percentile interval; 0 row(s) trimmed.
Covariate balance
| Covariate | Type | Mean true | Mean false | SMD before | SMD after | Variance ratio after |
|---|---|---|---|---|---|---|
| x1 | continuous | 0.3108 | −0.3323 | 0.6748 | −5.460e-17 | 1.058 |
| segment: b | binary | 0.3345 | 0.2566 | 0.0780 | 1.665e-16 | — |
| segment: c | binary | 0.1555 | 0.2040 | −0.0485 | 2.776e-17 | — |
| member: true | binary | 0.5172 | 0.3524 | 0.1648 | 5.551e-17 | — |
Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions).
- Estimand: average treatment effect in the overlap population. Treated = true; covariates: x1, segment, member.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Inverse-probability and entropy-balancing weights
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.weighting 2.0.0 · spec ac741ba5df01da62
# Dataset: c2_obs (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.causal import weighting as csw
from codesplash.stats.rng import boot_indices
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c2_obs.parquet", columns=["converted", "treated", "x1", "segment", "member"])
n_input = len(df)
df["converted"] = pd.Categorical(df["converted"], categories=["false", "true"]) # stored level order
df["treated"] = pd.Categorical(df["treated"], categories=["false", "true"]) # stored level order
df["segment"] = pd.Categorical(df["segment"], categories=["a", "b", "c"]) # stored level order
df["member"] = pd.Categorical(df["member"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["converted", "treated", "x1", "segment", "member"]) # listwise deletion over the analysis columns
df["converted"] = df["converted"].cat.remove_unused_categories()
df["treated"] = df["treated"].cat.remove_unused_categories()
df["segment"] = df["segment"].cat.remove_unused_categories()
df["member"] = df["member"].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, ["converted", "treated", "x1", "segment", "member"]) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment = "treated"
outcome = "converted"
covariates = ["x1", "segment", "member"]
conf = 0.9
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}"
estimand = "ATO" # ATE | ATT | ATC | ATO
method = "propensity" # propensity | entropy
trim = 0 if method == "propensity" else 0.0 # drop rows with e(x) outside [trim, 1 − trim]
ci_method = "bootstrap" # robust | bootstrap
B = int(199)
if method == "entropy" and estimand == "ATO":
raise ValueError("Entropy balancing estimates the ATE, ATT or ATC; use propensity weights for the overlap population (ATO).")
def fit_weights(Xs, ts):
"""Weights, propensity scores (None for entropy balancing), rows kept, convergence.
Same as WeightIt::weightit(method = "glm" or "ebal", estimand = …) in R."""
if method == "entropy":
w, ok = csw.entropy_balance(Xs, ts, estimand)
return w, None, np.ones(len(ts), dtype=bool), ok
ps, _, _, ok = csw.propensity(Xs, ts)
keep = (ps >= trim) & (ps <= 1 - trim) if trim > 0 else np.ones(len(ts), dtype=bool)
return csw.ps_weights(ps, ts, estimand), ps, keep, ok
# %% Weights and the weighted difference in means
w, ps, keep, converged = fit_weights(X, t)
n_trimmed = int((~keep).sum())
w = np.where(keep, w, 0.0)
if (w[t == 1] > 0).sum() < 2 or (w[t == 0] > 0).sum() < 2:
raise ValueError("Fewer than two treated or control rows are left after trimming; lower the trimming threshold.")
res = csw.weighted_difference(y, t, w, conf, "HC0")
values = {}
if ci_method == "bootstrap":
idx = boot_indices(n, B, seed)
est_b = np.full(B, np.nan)
for r in range(B):
ii = idx[r]
tb = t[ii]
if tb.sum() < 2 or (1 - tb).sum() < 2:
continue
try:
wb, _, kb, _ = fit_weights(X[ii], tb)
except np.linalg.LinAlgError:
continue
wb = np.where(kb, wb, 0.0)
if (wb[tb == 1] > 0).sum() < 2 or (wb[tb == 0] > 0).sum() < 2:
continue
yb = y[ii]
est_b[r] = csw.wmean(yb[tb == 1], wb[tb == 1]) - csw.wmean(yb[tb == 0], wb[tb == 0])
valid = est_b[~np.isnan(est_b)]
se = float(np.std(valid, ddof=1))
lo, hi = np.quantile(valid, [(1 - conf) / 2, 1 - (1 - conf) / 2])
z = res["estimate"] / se
from scipy import stats as _st
res.update({"se": se, "ci_low": float(lo), "ci_high": float(hi), "z": z, "p_value": float(2 * _st.norm.sf(abs(z)))})
values["n_boot_valid"] = int(valid.size)
# %% Balance and checks
bal = csw.balance(X, labels, binary, t, w, estimand)
max_before = max(abs(r["smd_before"]) for r in bal)
max_after, mean_after, bal_check = csw.balance_checks(bal)
w_check, ess1, ess0, share = csw.weights_check(w[w > 0], t[w > 0])
checks = []
if ps is not None:
checks.append(csw.overlap_check(ps, t))
values["ps_min"] = float(ps.min())
values["ps_max"] = float(ps.max())
checks += [bal_check, w_check, csw.no_confounding_check()]
if not converged:
checks.append({"id": "convergence", "label": "Weights converged", "status": "fail", "downgrade_to": "L1",
"detail": "The propensity model or the balancing did not converge (perfect prediction or impossible balance)."})
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))
# %% Result
est_text = csw.ESTIMAND_TEXT[estimand]
effect_label = f"{est_text[0].upper()}{est_text[1:]} of {contrast_text} on {outcome_text}"
pct = f"{conf:.0%}"
wname = "entropy-balancing" if method == "entropy" else "inverse-probability"
summary = (
f"With {wname} weights the {estimand} of {treated_level} vs {control_level} on {outcome_text} is {cs.fmt_num(res['estimate'])} "
f"({pct} CI [{cs.fmt_num(res['ci_low'])}, {cs.fmt_num(res['ci_high'])}], {cs.fmt_p(res['p_value'])}). "
f"Weighted means: {cs.fmt_num(res['mu_treated'])} treated, {cs.fmt_num(res['mu_control'])} control. "
f"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_trimmed": n_trimmed,
"mu_treated": res["mu_treated"], "mu_control": res["mu_control"], "estimand": estimand, "effect_label": effect_label,
"claim_level_max": "L2", "ess_treated": ess1, "ess_control": ess0, "max_weight_share": share,
"max_abs_smd_before": max_before, "max_abs_smd_after": max_after, "mean_abs_smd_after": mean_after,
"converged": bool(converged), "ci_method": ci_method, "treated_level": treated_level, "control_level": control_level,
})
group = np.where(t == 1, str(treated_level), str(control_level))
charts = [cs.chart(
"balance", "love-plot", "Covariate balance before and after weighting",
{"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) + ["weighted"] * len(bal), kind="categorical")},
{"threshold": 0.1},
)]
if ps is not None:
charts.append(cs.chart(
"overlap", "overlap-density", "Propensity scores by group",
{"score": cs.col("Propensity score", ps), "group": cs.col(treatment, group, kind="categorical"), "weight": cs.col("Weight", w)},
))
cs.publish({
"method": "causal.weighting",
"methodVersion": "2.0.0",
"title": f"{'Entropy balancing' if method == 'entropy' else 'Inverse-probability weighting'} ({estimand})",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "estimate", "label": f"{estimand} (weighted 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": "max_abs_smd_after", "label": "Max |SMD| after", "value": max_after},
{"key": "ess", "label": "Effective n (treated / control)", "value": [ess1, ess0]},
],
"tables": [
{"key": "effect", "title": "Weighted 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"{estimand} ({treated_level} − {control_level})", "value": res["estimate"], "se": res["se"], "ci_low": res["ci_low"], "ci_high": res["ci_high"]},
{"quantity": f"Weighted mean, {treated_level}", "value": res["mu_treated"], "se": None, "ci_low": None, "ci_high": None},
{"quantity": f"Weighted mean, {control_level}", "value": res["mu_control"], "se": None, "ci_low": None, "ci_high": None}],
"note": ("Bootstrap percentile interval; " if ci_method == "bootstrap" else "Robust (HC0) standard error with the weights treated as known; ") + f"{n_trimmed} row(s) trimmed."},
{"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 after", "type": "number"},
{"key": "vr_after", "label": "Variance ratio after", "type": "number"}],
"rows": bal,
"note": "Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions)."},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings,
"notes": [f"Estimand: {est_text}. Treated = {treated_level}; covariates: {', '.join(covariates)}."],
"charts": charts,
"values": values,
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Overlap weights balance the covariates in the propensity model exactly: the largest imbalance is 0.000, with an estimate of 0.301.
Check your understanding
CheckpointCheck yourself
Why does poor overlap matter even with a flexible model?
Show the answer
Answer: b
No method can create comparisons the data don't contain. It can only hide that they're missing.
Check yourself
You switch from ATE to ATO because of poor overlap. What must you report?
Show the answer
Answer: b
The ATO answers a narrower question. Often it's the only one the data can answer well, but it's still a different question.
Check yours
In the appIn the Causal studio, the Assumptions step checks balance and positivity with what you've run. A failing check there lowers the claim level the Interpret step will allow.
Method guide · causal.weightingInverse-probability and entropy-balancing weightsWhat is the average effect of a treatment once the groups are reweighted to have the same covariates?Recap
Recap- Without overlap, your estimate rests on the model rather than on data.
- Judge balance with standardized differences, not p-values.
- Trimming and the ATO both change whom the estimate describes, so say so.
Concepts in this lesson