# LATE in a medical trial: vitamin A supplements and child mortality (Aceh, Indonesia)
# Dr Nicky Grant, drnickygrant.com. Needs: pandas, statsmodels, linearmodels
import pandas as pd
import statsmodels.formula.api as smf
from linearmodels.iv import IV2SLS

# The six published cell counts (Sommer and Zeger 1991): z = 1 if the child's
# village was offered vitamin A, w = 1 if the child received it,
# died = 1 if the child died during follow-up
cells = pd.DataFrame({"z":    [0, 0, 1, 1, 1, 1],
                      "w":    [0, 0, 0, 0, 1, 1],
                      "died": [1, 0, 1, 0, 1, 0],
                      "n":    [74, 11514, 34, 2385, 12, 9663]})
df = cells.loc[cells.index.repeat(cells["n"])].drop(columns="n")
df["deaths"] = 1000 * df["died"]          # deaths per 1,000 children

# Means by assignment, then by assignment and receipt
print(df.groupby("z")[["w", "deaths"]].mean().round(4))
print(df.groupby(["z", "w"])["deaths"].agg(["count", "mean"]).round(4))

# First stage and outcome ITT, with robust standard errors
first = smf.ols("w ~ z", data=df).fit(cov_type="HC1")
itt = smf.ols("deaths ~ z", data=df).fit(cov_type="HC1")
print(f"first stage {first.params['z']:.4f}  outcome ITT {itt.params['z']:.4f}"
      f" (se {itt.bse['z']:.4f})  Wald {itt.params['z'] / first.params['z']:.4f}")

# Two-stage least squares gives the Wald ratio with its standard error
iv = IV2SLS.from_formula("deaths ~ 1 + [w ~ z]", data=df).fit(cov_type="robust")
print(iv.summary.tables[1])

# The as-treated comparison, for contrast
asis = smf.ols("deaths ~ w", data=df).fit(cov_type="HC1")
print(f"as-treated difference {asis.params['w']:.4f}")
