Skip to content

Reweight instead of match

Use propensity and entropy-balancing weights to make the groups comparable, and watch for weights that cost you precision.

Applied ~11 min8 steps

What runs in CodeSplash

You will be able to

  • Derive inverse-probability weights from the propensity score
  • Compare propensity weights with entropy balancing
  • Read effective sample size as the cost of weighting

Read first

01

Upweight the surprising cases

Read

A treated person who looked very unlikely to be treated stands in for many similar people who weren't. Inverse-probability weighting gives such people more weight:

wi=Tie(xi)+1−Ti1−e(xi)w_i = \frac{T_i}{e(x_i)} + \frac{1 - T_i}{1 - e(x_i)}

where e(x)e(x) is the propensity scorePropensity scoreEach unit's probability of treatment given its covariates; used to match or weight comparable groups., the estimated chance of treatment given the covariates. In the weighted sample, covariates no longer predict treatment if the model is right.

02

See the weights in action

Explore

DExplorable · Propensity scores and overlap

What happens to a weighted estimate when treated and untreated people barely resemble each other?

After weighting, what share of these people's information is left (effective sample ÷ n)?

0.50
How sure?
1.2
1.0
1000

Trimming changes who the estimate is about.

TreatedUntreated2.01Raw difference1.12Weighted estimate1.00True effect

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Widen the gap between the groups. Watch the largest weights grow as scores near 0 or 1, and see how much of the sample really counts.

03

What does weighting cost?

Predict

Predict first

This study has 546 treated people. After weighting, how many do they count for?

All of themAbout two-thirdsFewer than a tenth
Reveal

An effective sample sizeEffective sample sizeHow many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count. of 355. Unequal weights lose information, because a few people carry most of the weight.

04

Read the result

In the app
Inverse-probability weighting (ATE)Recorded · Python and R agreeRecorded 2026-11-18 · 43 values compared
R

With inverse-probability weights the ATE of true vs false on outcome is 1.74 (95% CI [1.06, 2.41], p < .001). Weighted means: 5.79 treated, 4.05 control. The largest standardized covariate difference fell from 0.675 to 0.072.

ATE (weighted difference)
1.736
95% CI
[1.060, 2.412]
p
< .001
Max |SMD| after
0.0723
Effective n (treated / control)
[355.24, 502.48]

Assumptions

  • Overlap (positivity) — 0.3% of rows have propensity scores below .05 or above .95; 0.3% lie outside the common support [0.034, 0.931].
  • Covariate balance — Every |SMD| ≤ 0.1 and every variance ratio within 0.5–2 after adjustment (largest |SMD| 0.072).
  • Extreme weights — Effective sample sizes 355 treated of 546 and 502 controls of 639; the largest weight carries 2.5% 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

QuantityEstimateSE95% CI low95% CI high
ATE (true − false)1.7360.34501.0602.412
Weighted mean, true5.788———
Weighted mean, false4.052———

Robust (HC0) standard error with the weights treated as known; 0 row(s) trimmed.

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD afterVariance ratio after
x1continuous0.3150−0.33020.6755−0.07231.351
x2continuous4.5725.254−0.2328−0.03410.9951
segment: bbinary0.33520.25670.07850.0205—
segment: cbinary0.15380.2050−0.0512−0.0017—
member: truebinary0.52010.35370.1665−0.0032—
income (k)continuous23.78322.2460.11920.03440.8955

Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions).

  • 15 of 1200 rows were left out because a value was missing.
  • Estimand: average treatment effect. Treated = true; covariates: x1, x2, segment, member, income (k).
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 4e899792cd3ee7ca
# 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("outcome", "treated", "x1", "x2", "segment", "member", "income (k)")))
n_input <- nrow(df)
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("outcome", "treated", "x1", "x2", "segment", "member", "income (k)")]), , 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("outcome", "treated", "x1", "x2", "segment", "member", "income (k)"))  # infinite values stop the run (registry/errors.yaml)

# %% Treatment, outcome and covariates
treatment <- "treated"
outcome <- "outcome"
covariates <- c("x1", "x2", "segment", "member", "income (k)")
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)
estimand <- "ATE"  # 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 <- "robust"  # robust | bootstrap
B <- as.integer(499)
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 ATE of true vs false on outcome is 1.74 (95% CI [1.06, 2.41], p < .001). Weighted means: 5.79 treated, 4.05 control. The largest standardized covariate difference fell from 0.675 to 0.072.

ATE (weighted difference)
1.736
95% CI
[1.060, 2.412]
p
< .001
Max |SMD| after
0.0723
Effective n (treated / control)
[355.24, 502.48]

Assumptions

  • Overlap (positivity) — 0.3% of rows have propensity scores below .05 or above .95; 0.3% lie outside the common support [0.034, 0.931].
  • Covariate balance — Every |SMD| ≤ 0.1 and every variance ratio within 0.5–2 after adjustment (largest |SMD| 0.072).
  • Extreme weights — Effective sample sizes 355 treated of 546 and 502 controls of 639; the largest weight carries 2.5% 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

QuantityEstimateSE95% CI low95% CI high
ATE (true − false)1.7360.34501.0602.412
Weighted mean, true5.788———
Weighted mean, false4.052———

Robust (HC0) standard error with the weights treated as known; 0 row(s) trimmed.

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD afterVariance ratio after
x1continuous0.3150−0.33020.6755−0.07231.351
x2continuous4.5725.254−0.2328−0.03410.9951
segment: bbinary0.33520.25670.07850.0205—
segment: cbinary0.15380.2050−0.0512−0.0017—
member: truebinary0.52010.35370.1665−0.0032—
income (k)continuous23.78322.2460.11920.03440.8955

Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions).

  • 15 of 1200 rows were left out because a value was missing.
  • Estimand: average treatment effect. Treated = true; covariates: x1, x2, segment, member, income (k).
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 4e899792cd3ee7ca
# 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=["outcome", "treated", "x1", "x2", "segment", "member", "income (k)"])
n_input = len(df)
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=["outcome", "treated", "x1", "x2", "segment", "member", "income (k)"])  # listwise deletion over the analysis columns
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, ["outcome", "treated", "x1", "x2", "segment", "member", "income (k)"])  # infinite values stop the run (registry/errors.yaml)

# %% Treatment, outcome and covariates
treatment = "treated"
outcome = "outcome"
covariates = ["x1", "x2", "segment", "member", "income (k)"]
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}"
estimand = "ATE"  # 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 = "robust"  # robust | bootstrap
B = int(499)
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.

The largest imbalance fell from 0.68 to 0.07. The estimate is 1.74, with robust standard errors of 0.345.

05

Balance directly

Read

Entropy balancingEntropy balancingFinds weights that make the comparison group match the treated group's covariate means exactly. skips the propensity model. It looks for the weights closest to uniform that make the covariate means match exactly.

Entropy balancing (ATT)Recorded · Python and R agreeRecorded 2026-11-18 · 46 values compared
R

With entropy-balancing weights the ATT of true vs false on earnings 1978 is 1273.26 (95% CI [−342.51, 2889.03], p = .122). Weighted means: 6349.14 treated, 5075.88 control. The largest standardized covariate difference fell from 0.721 to 0.000.

ATT (weighted difference)
1273.26
95% CI
[−342.51, 2889.03]
p
.122
Max |SMD| after
7.951e-15
Effective n (treated / control)
[185, 98.458]

Plots

Covariate balance before and after weightingAfter matching or weighting, are treated and control groups alike on every covariate?
View data
CovariateStandardized mean differenceStage
age−0.3094before
educ0.0550before
race: hispan−0.0827before
race: white−0.5577before
married: true−0.3236before
nodegree: true0.1114before
re74−0.7211before
re75−0.2903before
age−1.986e-15weighted
educ−7.951e-15weighted
race: hispan2.914e-16weighted
race: white1.499e-15weighted
married: true−1.082e-15weighted
nodegree: true4.441e-16weighted
re74−5.584e-16weighted
re752.119e-16weighted

Assumptions

  • Covariate balance — Every |SMD| ≤ 0.1 after adjustment (largest 0.000), but the variance ratio for age is 0.41, outside 0.5–2: the groups' spreads still differ.
  • Extreme weights — Effective sample sizes 185 treated of 185 and 98 controls of 429; the largest weight carries 2.2% 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

QuantityEstimateSE95% CI low95% CI high
ATT (true − false)1273.26824.39−342.512889.03
Weighted mean, true6349.14———
Weighted mean, false5075.88———

Robust (HC0) standard error with the weights treated as known; 0 row(s) trimmed.

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD afterVariance ratio after
agecontinuous25.81628.030−0.3094−1.986e-150.4096
educcontinuous10.34610.2350.0550−7.951e-150.6635
race: hispanbinary0.05950.1422−0.08272.914e-16—
race: whitebinary0.09730.6550−0.55771.499e-15—
married: truebinary0.18920.5128−0.3236−1.082e-15—
nodegree: truebinary0.70810.59670.11144.441e-16—
re74continuous2095.575619.24−0.7211−5.584e-161.326
re75continuous1532.062466.48−0.29032.119e-161.335

Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions).

  • Estimand: average treatment effect on the treated. Treated = true; covariates: age, educ, race, married, nodegree, re74, re75.
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 abf1da6acf3e51e0
# 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)
estimand <- "ATT"  # ATE | ATT | ATC | ATO
method <- "entropy"  # propensity | entropy
trim <- if (method == "propensity") 0 else 0  # drop rows with e(x) outside [trim, 1 - trim]
ci_method <- "robust"  # robust | bootstrap
B <- as.integer(499)
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 entropy-balancing weights the ATT of true vs false on earnings 1978 is 1273.26 (95% CI [−342.51, 2889.03], p = .122). Weighted means: 6349.14 treated, 5075.88 control. The largest standardized covariate difference fell from 0.721 to 0.000.

ATT (weighted difference)
1273.26
95% CI
[−342.51, 2889.03]
p
.122
Max |SMD| after
1.638e-15
Effective n (treated / control)
[185, 98.458]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Covariate balance — Every |SMD| ≤ 0.1 after adjustment (largest 0.000), but the variance ratio for age is 0.41, outside 0.5–2: the groups' spreads still differ.
  • Extreme weights — Effective sample sizes 185 treated of 185 and 98 controls of 429; the largest weight carries 2.2% 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

QuantityEstimateSE95% CI low95% CI high
ATT (true − false)1273.26824.39−342.512889.03
Weighted mean, true6349.14———
Weighted mean, false5075.88———

Robust (HC0) standard error with the weights treated as known; 0 row(s) trimmed.

Covariate balance

CovariateTypeMean trueMean falseSMD beforeSMD afterVariance ratio after
agecontinuous25.81628.030−0.30944.965e-160.4096
educcontinuous10.34610.2350.05508.835e-160.6635
race: hispanbinary0.05950.1422−0.08272.776e-16—
race: whitebinary0.09730.6550−0.55771.638e-15—
married: truebinary0.18920.5128−0.3236−1.055e-15—
nodegree: truebinary0.70810.59670.11142.220e-16—
re74continuous2095.575619.24−0.7211−6.514e-161.326
re75continuous1532.062466.48−0.29037.063e-171.335

Binary covariates: difference in proportions; continuous: standardized mean difference (cobalt conventions).

  • Estimand: average treatment effect on the treated. 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
# Inverse-probability and entropy-balancing weights
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.weighting 2.0.0 · spec abf1da6acf3e51e0
# 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 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_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}"
estimand = "ATT"  # ATE | ATT | ATC | ATO
method = "entropy"  # propensity | entropy
trim = 0 if method == "propensity" else 0.0  # drop rows with e(x) outside [trim, 1 − trim]
ci_method = "robust"  # robust | bootstrap
B = int(499)
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,
})

The imbalance after weighting is 0.000, by construction. That guarantees balance only on the means you asked for, not on variables you left out.

06

Check your understanding

Checkpoint

Check yourself

A treated person has a propensity score of 0.25. What's their inverse-probability weight for the ATE?

Show the answer

Answer: 4

1/0.25=41 / 0.25 = 4: they stand in for four people like them.

Check yourself

You trim people with extreme propensity scores. Here that removed 151 of them. What changes besides the variance?

Show the answer

Answer: b

Trimming trades generality for stability. Say whom your estimate now describes.

Check yourself

What makes a propensity model good for weighting?

Show the answer

Answer: b

A model that predicts treatment too well leaves no overlap. Its job is balance, not prediction.

07

Try it

In the app

In the Causal studio, choose weighting on the Estimate step. Check the love plot, then see how much the estimate moves when the Robustness step offers an alternate estimator.

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?
08

Recap

Recap
  • Weights make covariates unrelated to treatment, if the propensity model holds.
  • Entropy balancing matches chosen means exactly, with no propensity model.
  • Extreme weights shrink the effective sample size; trimming changes who the estimate describes.

Concepts in this lesson