CCausal inference · causal.weighting
Inverse-probability and entropy-balancing weights
What is the average effect of a treatment once the groups are reweighted to have the same covariates?
Estimates the average treatment effect (ATE), the effect on the treated (ATT) or on the controls (ATC), or the overlap-weighted effect (ATO) by reweighting the treated and control groups so their covariates match: inverse-probability weights from a logistic propensity model (with optional trimming) or entropy-balancing weights that match covariate means exactly. Reports the weighted difference in means with a robust or bootstrap interval, covariate balance before and after weighting (cobalt conventions), effective sample sizes, overlap and extreme-weight checks.
A real result
Example “Ate propensity”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
| Quantity | Estimate | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| ATE (true − false) | 1.736 | 0.3450 | 1.060 | 2.412 |
| Weighted mean, true | 5.788 | — | — | — |
| Weighted mean, false | 4.052 | — | — | — |
Robust (HC0) standard error with the weights treated as known; 0 row(s) trimmed.
Covariate balance
| Covariate | Type | Mean true | Mean false | SMD before | SMD after | Variance ratio after |
|---|---|---|---|---|---|---|
| x1 | continuous | 0.3150 | −0.3302 | 0.6755 | −0.0723 | 1.351 |
| x2 | continuous | 4.572 | 5.254 | −0.2328 | −0.0341 | 0.9951 |
| segment: b | binary | 0.3352 | 0.2567 | 0.0785 | 0.0205 | — |
| segment: c | binary | 0.1538 | 0.2050 | −0.0512 | −0.0017 | — |
| member: true | binary | 0.5201 | 0.3537 | 0.1665 | −0.0032 | — |
| income (k) | continuous | 23.783 | 22.246 | 0.1192 | 0.0344 | 0.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).
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
| Quantity | Estimate | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| ATE (true − false) | 1.736 | 0.3450 | 1.060 | 2.412 |
| Weighted mean, true | 5.788 | — | — | — |
| Weighted mean, false | 4.052 | — | — | — |
Robust (HC0) standard error with the weights treated as known; 0 row(s) trimmed.
Covariate balance
| Covariate | Type | Mean true | Mean false | SMD before | SMD after | Variance ratio after |
|---|---|---|---|---|---|---|
| x1 | continuous | 0.3150 | −0.3302 | 0.6755 | −0.0723 | 1.351 |
| x2 | continuous | 4.572 | 5.254 | −0.2328 | −0.0341 | 0.9951 |
| segment: b | binary | 0.3352 | 0.2567 | 0.0785 | 0.0205 | — |
| segment: c | binary | 0.1538 | 0.2050 | −0.0512 | −0.0017 | — |
| member: true | binary | 0.5201 | 0.3537 | 0.1665 | −0.0032 | — |
| income (k) | continuous | 23.783 | 22.246 | 0.1192 | 0.0344 | 0.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).
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Ate propensityc2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
- Att entropyc2_lalonde · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
- Ato binary bootstrapc2_obs · covariates: x1, segment, member · outcome: converted · treatment: treated
- Ate trimmedc2_lalonde · covariates: age, educ, race, married, re74 · outcome: earnings 1978 · treatment: treat
- Degenerate constantc2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
- Degenerate n1c2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
- Degenerate n3c2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
In the guides
Where it sits in the decision guides
- Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?
- Causal ML (uplift modeling) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric / boolean · 1 column
- Numeric, or yes/no (the effect is then a difference in proportions).
- Treatmentboolean / categorical · 1 column · 2–2 levels
- Two groups; choose the treated level below (default the second stored level, "true" for yes/no).
- Confounders (covariates)numeric / categorical / boolean · 1–40 columns · 2–30 levels
- Every pre-treatment variable that affects both treatment and outcome. Never include variables measured after treatment.
Choices you make
hypothesis
- Treated groupdefault —
The level that received the treatment; default: the second stored level (true for yes/no columns).
- Estimanddefault ATE
Whose average effect you want: everyone (ATE), the treated (ATT), the controls (ATC) or the overlap population (ATO).
- ATE — everyone(default) — The average effect if everyone were treated versus no one; pick it when a policy could reach everyone.
- ATT — the treated — The average effect on those actually treated; pick it to judge a program for the people who got it.
- ATC — the controls — The average effect on the controls if they were treated; pick it when thinking of extending a treatment.
- ATO — the overlap population — The average effect among people who could plausibly go either way; pick it when propensities reach extremes.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Weightsdefault propensity
How weights are built: inverse propensity from a logistic model, or entropy balancing (exact covariate mean balance).
- Inverse propensity (logistic model)(default) — Weights rows by inverse propensity from a logistic model; the usual choice.
- Entropy balancing (exact mean balance) — Finds weights that match covariate means exactly; pick it when propensity weights leave imbalance.
- Trim propensity scores outsidedefault 0
Rows with a propensity score below this value or above 1 minus it are dropped (0 = keep all; Crump et al. suggest 0.1).
- Intervaldefault robust
Robust sandwich errors treat the weights as known; the bootstrap re-estimates them each time (slower, more honest).
- Robust (sandwich, weights treated as known)(default) — Sandwich standard errors that treat the weights as known; fast, and usually slightly conservative.
- Bootstrap (re-estimates the weights) — Re-estimates the weights in every resample; slower, and it carries the weight model's uncertainty.
- Bootstrap resamplesdefault 499
Number of bootstrap resamples. More gives steadier intervals but takes longer; use 1,000 or more for reporting.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Overlap (positivity)
Every kind of unit must have some chance of being treated and of being a control.
Covariate balance
After weighting, standardized mean differences should be below 0.1.
No extreme weights
A few very large weights make the estimate unstable.
No unmeasured confounding
The covariates must include every common cause of treatment and outcome.
Weights converged
Entropy balancing and CBPS solve for weights; if they don't converge, balance isn't guaranteed.
What it reports
- Tests: Weighted treatment effect
- estimate
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- z
- An estimate in standard-error units, compared with the standard normal distribution.
- p_value
- How surprising your data would be if the null hypothesis were true, as a probability.
- n
- How many independent units the analysis used; it sets precision and power.
- n_treated
- How many independent units the analysis used; it sets precision and power.
- n_control
- How many independent units the analysis used; it sets precision and power.
- n_trimmed
- How many independent units the analysis used; it sets precision and power.
- mu_treated
- What a unit's outcome would be under one treatment; you only ever see one of them per unit.
- mu_control
- What a unit's outcome would be under one treatment; you only ever see one of them per unit.
- estimand
- The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
- effect_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- claim_level_max
- How strong a causal statement the design supports, from association up to a causal effect.
- ess_treated
- How many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count.
- ess_control
- How many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count.
- max_weight_share
- Biggest share of its group's total weight carried by one row, worst of treated and control. High means a few rows dominate.
- max_abs_smd_before
- Whether compared groups look alike on measured covariates after matching or weighting.
- max_abs_smd_after
- Whether compared groups look alike on measured covariates after matching or weighting.
- mean_abs_smd_after
- Whether compared groups look alike on measured covariates after matching or weighting.
- n_vr_outside
- Whether compared groups look alike on measured covariates after matching or weighting.
- converged
- Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
- ci_method
- A range of effect values compatible with your data at the chosen confidence level.
- treated_level
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- control_level
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
Per group, level or term: smd_before[<covariate>], smd_after[…], vr_after[…], ps_min, ps_max, n_boot_valid
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same twins (codesplash.causal.weighting ↔ codesplashr cs_causal_*): Newton–Raphson logistic propensity model, Newton entropy balancing, cobalt-convention balance and HC0 sandwich; WeightIt::weightit is the classic R equivalent (its ebal optimizer stops earlier).
- Bootstrap intervals resample rows with the portable Wichmann–Hill stream, so both engines use the same resamples.
The exact script CodeSplash ran for example “Ate propensity” · 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,
})
The exact script CodeSplash ran for example “Ate propensity” · 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
))
Sources
- Austin, P. C., & Stuart, E. A. (2015). Moving towards best practice when using inverse probability of treatment weighting (IPTW). Statistics in Medicine, 34, 3661–3679.
- Hainmueller, J. (2012). Entropy balancing for causal effects. Political Analysis, 20, 25–46.
- Li, F., Morgan, K. L., & Zaslavsky, A. M. (2018). Balancing covariates via propensity score weighting. JASA, 113, 390–400.
- Crump, R. K., Hotz, V. J., Imbens, G. W., & Mitnik, O. A. (2009). Dealing with limited overlap in estimation of average treatment effects. Biometrika, 96, 187–199.
From the CodeSplash method registry · causal.weighting v2.0.0.