Skip to content

Overlap and balance

Check whether treated and untreated units can be compared at all, and what to do when they can't.

Applied ~9 min7 steps

What runs in CodeSplash

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

01

Can they be compared?

Read

OverlapOverlapEvery 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.

Propensity score overlapDo treated and control units share a range of propensity scores (overlap / positivity)?
View data
propensity scoregroupATT weight
0.3396control0.5143
0.4744control0.9024
0.0755control0.0816
0.7225control2.603
0.2746control0.3786
0.0869control0.0952
0.9007treated1
0.9307treated1
0.4145control0.7080
0.9280treated1
0.4889control0.9566
0.7315treated1
0.2515control0.3360
0.6990control2.323
0.7714treated1
0.2006control0.2509
0.8423treated1
0.4303treated1
0.6040treated1
0.5619treated1
0.5129treated1
0.7210control2.585
0.5944treated1
0.3544control0.5489
0.6202treated1
0.8802control7.344
0.6118control1.576
0.3643control0.5731
0.3997control0.6657
0.6967treated1
0.2202control0.2823
0.2443control0.3233
0.2313control0.3010
0.9203treated1
0.9681treated1
0.2934control0.4151
0.2944control0.4172
0.3978control0.6607
0.2799control0.3887
0.8551treated1
0.8255treated1
0.6405control1.782
0.4186control0.7199
0.0329control0.0341
0.1994control0.2490
0.4960control0.9843
0.7782treated1
0.4633control0.8632
0.8173treated1
0.9229treated1
0.2363control0.3094
0.3708treated1
0.8013treated1
0.4384control0.7807
0.8331control4.991
0.3892control0.6372
0.3799control0.6126
0.2191control0.2807
0.9112treated1
0.4456control0.8037

First 60 of 900 rows.

02

How much overlap?

Predict

Predict first

In the LaLonde job-training data, with very different groups, what range do you expect for the propensity scores?

Between 0.3 and 0.7Between 0.1 and 0.9Almost 0 to almost 1
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.

03

Balance, before and after

Read

A 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.

Covariate balance (love plot)After matching or weighting, are treated and control groups alike on every covariate?
View data
covariatestandardized mean differencestage
age−0.3100Before
age0.0110Nearest-neighbor matching
age−0.0290Entropy balancing
education0.0700Before
education0.0240Nearest-neighbor matching
education0.0330Entropy balancing
black1.670Before
black0.1160Nearest-neighbor matching
black0.0330Entropy balancing
hispanic−0.2800Before
hispanic0.0180Nearest-neighbor matching
hispanic−0.0230Entropy balancing
married−0.7200Before
married−0.1070Nearest-neighbor matching
married0.0050Entropy balancing
no degree0.2400Before
no degree0.0660Nearest-neighbor matching
no degree0.0400Entropy balancing
earnings 1974−0.7200Before
earnings 1974−0.0900Nearest-neighbor matching
earnings 1974−0.0100Entropy balancing
earnings 1975−0.2900Before
earnings 19750.0360Nearest-neighbor matching
earnings 19750.0080Entropy balancing
unemployed 19740.2500Before
unemployed 19740.0240Nearest-neighbor matching
unemployed 19740.0080Entropy balancing
unemployed 19750.2100Before
unemployed 19750.0400Nearest-neighbor matching
unemployed 19750.0240Entropy 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.

04

Two ways out

In the app

When 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.
Inverse-probability weighting (ATO)Recorded · Python and R agreeRecorded 2026-11-18 · 38 values compared
R

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

QuantityEstimateSE90% CI low90% CI high
ATO (true − false)0.30140.02520.26040.3431
Weighted mean, true0.6705———
Weighted mean, false0.3691———

Bootstrap percentile interval; 0 row(s) trimmed.

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD afterVariance ratio after
x1continuous0.3108−0.33230.6748−3.640e-171.058
segment: bbinary0.33450.25660.07800—
segment: cbinary0.15550.2040−0.0485−1.665e-16—
member: truebinary0.51720.35240.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
))
Python

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

QuantityEstimateSE90% CI low90% CI high
ATO (true − false)0.30140.02520.26040.3431
Weighted mean, true0.6705———
Weighted mean, false0.3691———

Bootstrap percentile interval; 0 row(s) trimmed.

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD afterVariance ratio after
x1continuous0.3108−0.33230.6748−5.460e-171.058
segment: bbinary0.33450.25660.07801.665e-16—
segment: cbinary0.15550.2040−0.04852.776e-17—
member: truebinary0.51720.35240.16485.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.

05

Check your understanding

Checkpoint

Check 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.

06

Check yours

In the app

In 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?
07

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