Three offers after discharge: g-formula and blip models#
At a glance#
A hospital’s navigators decide three times whether to offer a patient navigation: at discharge, on day 10, and on day 20. What would the average day-30 recovery score be if every patient got all three offers, against none? And how much does each single offer add?
Offering all three times raises the average score by an estimated 10.66 points (95% confidence interval 9.49 to 11.82), from 49.37 to 60.03 on a scale of 0 to 100. This answer comes from the parametric g-formula, which simulates each patient’s symptoms and score under each plan. A second method, the blip model, estimates each offer’s effect: the discharge offer adds about 13.39 points for patients who live alone against 2.00 for the others, and the later offers about 2 to 4 each.
Both answers depend on their models. With models of the symptom flags that are too simple, the g-formula reports 12.32 points and misses the true 11.22; it then disagrees with the blip model by 1.50 points, a warning that one of them is off.
Both answers are also causal only if the recorded characteristics and symptom flags capture everything that drove both the offers and the score, which the data cannot check.
The data are simulated; the main fit’s interval contains the true gain (11.22).
The question#
Navigators offer more often to patients who live alone, to patients with a high discharge risk,
and to patients whose check-in before a later decision flags symptoms. The program lead asks for
the mean day-30 score under the plan always (offer at all three decisions) against never (no
offer), and for the effect of each single offer.
In the graph, an arrow means “causes”. \(W\) is the baseline record (living alone and discharge risk), \(A_1\), \(A_2\), \(A_3\) the three offers, \(S_2\) and \(S_3\) the symptom flags on days 10 and 20, \(Y\) the day-30 score, and \(U\) an unrecorded cause.
W (lives alone, discharge risk) --> every offer and the score
W (lives alone) --> S_2, S_3 (the symptom flags)
A_1 (discharge) --> S_2 (symptoms, day 10) --> A_2 (day 10) --> S_3 (symptoms, day 20) --> A_3 (day 20)
\ \ \ \ \
+-------------------------+------------------------+-----------------------+-----------------------+--> Y (score, day 30)
U (unrecorded cause) - - -> the offers and Y (assumed absent)
A confounder is a cause of both an offer and the score. The symptom flags cause the difficulty. A flag is a reason for the next offer and lowers the score, so each later offer must be compared among patients with the same flags. But the earlier offer changed the flag: part of the discharge offer’s effect works by preventing symptoms. Adjusting for both flags in one regression of the score would remove that part of the effect. Both methods below adjust each offer for the flags recorded before it and keep the early offers’ effect through the later flags.
Details: what each arrow and missing arrow asserts
arrow or absent arrow |
what it asserts |
role |
|---|---|---|
|
living alone and discharge risk shape every offer, and both lower the score |
baseline confounder |
|
patients who live alone have symptoms more often |
baseline confounder |
|
the discharge offer lowers the chance of day-10 symptoms only for patients who live alone; the day-10 offer lowers day-20 symptoms a little for everyone and much more for them |
the treatment changes a later confounder |
|
navigators offer more often after a symptom flag |
a time-varying confounder |
|
symptoms lower the day-30 score |
the path through which early offers work |
offers to the next offer |
a patient offered once is more likely to be offered again |
part of the record the analysis adjusts for |
|
nothing unrecorded drives both an offer and the score |
the assumption the data cannot check |
Load the tools#
Every fit sets its seeds, so a rerun prints the same numbers. Another version of cleverly can
print slightly different numbers.
import dataclasses
import pandas as pd
import cleverly
pd.set_option("display.width", 130)
pd.set_option("display.max_columns", 20)
print("cleverly", cleverly.__version__)
cleverly 0.2.4
The data#
make_recovery_score draws 4,000 simulated patients and also returns the true values, which real
data never give you. The seed, 3100, was fixed before the page first ran, so the page could not
pick a flattering draw.
from cleverly.datasets import make_recovery_score
# With your own data, load a wide table here: one row per patient, with the baseline columns, then
# for each decision what the navigator saw just before it (here a symptom flag) and the offer
# (1 offered, 0 not), and the day-30 score last.
# Real data have no `truth`, so drop every line that uses it.
frame, truth = make_recovery_score(4_000, seed=3100)
OFFERS = ["offer_discharge", "offer_day10", "offer_day20"] # the offer columns, in time order
print("rows and columns:", frame.shape)
print(list(frame.columns))
print(frame.head(5).round(2).to_string())
print()
print("share of each group, by living situation:")
by_group = frame.groupby("lives_alone")
shares = by_group[["offer_discharge", "symptoms_day10", "offer_day10", "symptoms_day20"]].mean()
print(shares.round(3).to_string())
print()
print("true values of the simulated data:")
for name in ("ey_regimen[never]", "ey_regimen[always]", "ate_regimen[always vs never]"):
print(f" {name:30s} {truth[name]:.2f}")
rows and columns: (4000, 8)
['lives_alone', 'discharge_risk', 'offer_discharge', 'symptoms_day10', 'offer_day10', 'symptoms_day20', 'offer_day20', 'recovery_day30']
lives_alone discharge_risk offer_discharge symptoms_day10 offer_day10 symptoms_day20 offer_day20 recovery_day30
0 1.0 0.53 1.0 1.0 1.0 0.0 0.0 42.42
1 0.0 0.92 0.0 1.0 1.0 0.0 1.0 48.16
2 0.0 0.11 0.0 0.0 0.0 0.0 1.0 68.09
3 1.0 0.17 0.0 1.0 1.0 0.0 0.0 45.42
4 0.0 0.50 0.0 1.0 0.0 1.0 0.0 23.23
share of each group, by living situation:
offer_discharge symptoms_day10 offer_day10 symptoms_day20
lives_alone
0.0 0.132 0.299 0.498 0.170
1.0 0.624 0.426 0.672 0.128
true values of the simulated data:
ey_regimen[never] 49.24
ey_regimen[always] 60.46
ate_regimen[always vs never] 11.22
Each row is one patient: lives_alone (1 or 0), discharge_risk (0 to 1, higher is worse), then
in time order the discharge offer, the day-10 symptom flag and offer, the day-20 flag and offer, and
the day-30 score. The second table shows how unequal the offers are: 0.624 of the patients who live
alone got the discharge offer, against 0.132 of the others. A name such as ey_regimen[always]
reads: the expected (mean) score under the plan (regimen) always, and
ate_regimen[always vs never] is the average effect, the difference of the two means.
Why a simple comparison misleads#
A quick analysis would compare the patients who happened to get all three offers with those who got none.
# This cell only shows why a simple comparison misleads, so you can skip it on your own data.
groups = {
"offered all three times": frame[(frame[OFFERS] == 1).all(axis=1)],
"never offered": frame[(frame[OFFERS] == 0).all(axis=1)],
}
summary = pd.DataFrame(
{
label: {
"patients": len(rows),
"lives alone": rows["lives_alone"].mean(),
"discharge risk": rows["discharge_risk"].mean(),
"symptoms on day 10": rows["symptoms_day10"].mean(),
"mean score on day 30": rows["recovery_day30"].mean(),
}
for label, rows in groups.items()
}
)
print(summary.round(3).to_string())
scores = summary.loc["mean score on day 30"]
crude = scores["offered all three times"] - scores["never offered"]
print()
print(
f"difference in mean score: {crude:.2f} true effect of always against never: "
f"{truth['ate_regimen[always vs never]']:.2f}"
)
offered all three times never offered
patients 495.000 812.000
lives alone 0.754 0.110
discharge risk 0.638 0.389
symptoms on day 10 0.315 0.240
mean score on day 30 55.987 57.815
difference in mean score: -1.83 true effect of always against never: 11.22
The simple difference is -1.83 points: offered patients seem to do worse, while the true effect is a gain of 11.22. The offered patients are not like the others. Three in four live alone (0.754 against 0.110), their discharge risk is higher (0.638 against 0.389), and more of them had symptoms on day 10, which is part of why they were offered again. Those patients would score lower under any plan.
Write down the study design#
The study description (StudyProtocol) says who is in the study, when follow-up starts, the
plans, the outcome, and how events after the start count. It is optional, but CausalStudy stores
it with every result, so whoever reads your result later sees exactly what was estimated.
from cleverly.datasets import recovery_score_protocol
# For your own study, build cleverly.StudyProtocol(target_population=..., eligibility=(...),
# time_zero=..., treatment_strategies=(...), treatment_versions=(...), outcome=..., horizon=...,
# intercurrent_event_handling=(...), interference_unit=..., assumption_rationale=(...)).
# Each field is plain text, and a tuple holds several sentences; the printed lines below are
# this study's values, a model for your own.
protocol = recovery_score_protocol()
print("\n".join(protocol.summary_lines()))
Population: Adults discharged home from a participating hospital during the enrollment period
Eligibility: Age 18 years or older; Discharged alive; Discharged home from a participating hospital
Follow-up starts: Hospital discharge, after baseline measurement and before first assignment
Strategies: Offer navigation at discharge, on day 10 and on day 20; Offer no navigation at any of the three decisions
Versions: The declared navigation contact at each of the three decisions; Usual discharge support without navigation contacts
Outcome: Patient-reported recovery score on day 30, on a scale from 0 to 100
Horizon: 30 days after discharge
Intercurrent events: Every patient completes the day-30 score, so no patient leaves follow-up; The protocol scores death before day 30 as 0 (composite strategy); Analyze each navigation offer regardless of completed contacts
Interference unit: Individual patient
Rationale: The navigator reads only the recorded discharge risk, living situation, symptom flags and earlier offers, which supports no hidden confounding at each decision; Version records support that the navigation contact at each of the three decisions is one well-defined action, so a patient's recorded score is the score they would have had under the offers they got; Reserved navigator capacity supports no interference between patients
Follow-up starts at discharge, before the first offer, so no offer changes who is in the study. “Intercurrent events” are events after the start that could change what the score means: every patient completes the score, and a death before day 30 would count as a score of 0 (nobody dies in the simulated data). “Versions” says what one offer is, so that every patient’s offer means the same contact; the rationale gives the reason to believe three of the conditions the next section lists, and the fourth, overlap, is probed from the data.
Columns, plans, and what must hold#
LongitudinalTreatment names the columns of the wide table: one offer per decision, and the
columns recorded before each one. A plan (a “regime” or “regimen” in the output) is a tuple with
one offer per decision. study.identify with RegimeMean checks which methods can estimate the
mean score under each plan from these columns, and lists what must hold for the answer to be
causal. A “unit” in the output is a patient.
from cleverly import CausalStudy, LongitudinalTreatment, RegimeMean
# For your own data, change the column names: one offer column per decision, in time order, and
# for each decision the columns recorded just before it.
design = LongitudinalTreatment(
outcome="recovery_day30",
treatment=("offer_discharge", "offer_day10", "offer_day20"),
baseline=("lives_alone", "discharge_risk"),
time_varying=((), ("symptoms_day10",), ("symptoms_day20",)),
)
plans = {"never": (0, 0, 0), "always": (1, 1, 1)} # one offer per decision
study = CausalStudy(frame, design=design, protocol=protocol)
question = study.identify(RegimeMean(plans, reference="never"))
print(question.summary())
Causal question (ey_regime)
==============================================================================
Question: mean outcome under each Rows: 4,000
declared regime Answered by: adjusting for history
Outcome: recovery_day30
(continuous)
Treatment: offer_discharge,
offer_day10, offer_day20
Baseline: lives_alone,
discharge_risk
==============================================================================
What each treatment time adjusts for
treatment adjusted for
------------------------------------------------------------------------------
offer_discharge lives_alone, discharge_risk
offer_day10 lives_alone, discharge_risk, symptoms_day10, offer_discharge
offer_day20 lives_alone, discharge_risk, symptoms_day10, symptoms_day20,
offer_discharge, offer_day10
==============================================================================
Conditions the answer rests on
condition checkable what it says
------------------------------------------------------------------------------
well-defined treatment no Each unit's observed outcomes
are the ones it would have
had under the treatments it
actually received over time.
This needs each treatment to
be well defined: every way of
getting the same treatment
has the same effect.
no interference no One unit's treatment does not
change another unit's
outcome.
no hidden confounding at each time no At each time, among units
with the same recorded
history, which treatment a
unit got is unrelated to the
outcomes it would have had.
overlap at each time partly At each time, units with
every history that following
the compared regimens can
produce had some chance of
the treatment a regimen
assigns.
==============================================================================
Methods
method name
------------------------------------------------------------------------------
tmle targeted maximum likelihood (TMLE)
sdr sequentially doubly robust regression (SDR)
ipsi incremental propensity score intervention (IPSI)
gcomp sequential g-computation
ipw sequential inverse probability weighting
parametric_gformula parametric g-formula
==============================================================================
Notes:
[1] The data cannot confirm these conditions. Overlap (marked partly) can be
probed: after a fit, result.diagnostics.support() shows where the fitted
treatment model gives units little chance of a compared treatment. That
check reads a fitted model, so a clean result does not prove overlap.
[2] The methods table lists the methods that fit. 6 other methods cannot
estimate this question; the full summary says why.
Each offer is adjusted for the flags recorded before it. In plain words, the conditions are that an offer means the same contact for every patient, that one patient’s offers do not change another’s score, that at each decision nothing unrecorded drives both the offer and the score, and that patients with every record the plans can produce had a real chance of the plan’s offer (overlap). The first three need judgment; “Check overlap” probes the fourth.
This page fits the parametric g-formula (parametric_gformula) and the blip model, a separate tool
(snmm()) that gives each offer’s effect. Both show how the offers work, at the price that more of
their models must be right. For the plan means alone, TMLE (in the weekly outcomes
example) needs only all its offer models or all its score models right, and
no form for the effects.
The main answer: simulate each plan forward#
The parametric g-formula fits a model for each symptom flag from the record before it, and a model for the score from the whole record. Then it copies each patient, sets the offers to the plan’s values, and walks the copy forward in time: it draws the day-10 flag from its model, then the day-20 flag, then predicts the score. The mean of the predicted scores is the plan’s mean. Because the simulated flags respond to the plan’s offers, every route from an early offer to the score stays in the answer.
The price is that the symptom models and the score model must all be right. Here the symptom models include every product of two record columns, so an offer’s effect on symptoms can differ by living situation. On your own data, allow such products and compare with a second method. For fixed plans like these the simulation reads no offer model (note [2]’s “natural-treatment model”); only the overlap check does.
from cleverly import ModelSpec, ParametricGFormulaMethod, Runtime
from cleverly.learners import GLM
gformula = ParametricGFormulaMethod(
models=ModelSpec(
outcome_learner=GLM(family="gaussian"), # the day-30 score: linear regression
treatment_learner=GLM(), # each offer: logistic regression, read by the overlap check
),
# Each symptom flag: logistic regression with every product of two record columns, so the
# offer's effect on symptoms can differ by living situation.
covariate_learner=GLM(interactions=2),
n_draws=10, # simulated copies of each patient under each plan
runtime=Runtime(random_state=3100, n_jobs=1), # fix the seed of the simulation
)
result = question.estimate(method=gformula)
print(result.summary())
Longitudinal estimate (parametric g-formula)
==============================================================================
Question: recovery_day30 under Rows: 4,000
each plan; each row is Time points: 3
defined below Out-of-fold predictions: no
Outcome: recovery_day30 Outcome model: generalized linear
(continuous), at the model
end Covariate models: generalized linear
Treatment: offer_discharge, model for 2
offer_day10, covariates
offer_day20
Adjusted for: lives_alone,
discharge_risk; later:
symptoms_day10,
symptoms_day20
Method: parametric g-formula
(forward simulation)
==============================================================================
estimate std. error 95% CI p-value
------------------------------------------------------------------------------
ey_regimen[never] 49.37 0.36 [48.66, 50.06] <0.0001
ey_regimen[always] 60.03 0.48 [59.08, 60.96] <0.0001
==============================================================================
What each row estimates
meaning
------------------------------------------------------------------------------
ey_regimen[never] mean recovery_day30 if every unit followed plan never
ey_regimen[always] mean recovery_day30 if every unit followed plan always
==============================================================================
What each plan assigns and who followed it to the end
plan followed in data assigns
------------------------------------------------------------------------------
never 812 of 4,000 0 at every time point
always 495 of 4,000 1 at every time point
==============================================================================
Simultaneous 95% bands
band
------------------------------------------------------------------------------
ey_regimen[never] [48.58, 50.15]
ey_regimen[always] [58.98, 61.08]
==============================================================================
Notes:
[1] The interval of ey_regimen[never], ey_regimen[always] is widened on the
side where a skewed outcome makes misses more likely, so it need not be
centred on the estimate. Its t distribution has 250 or more degrees of
freedom, so it is close to the normal one. The p-value is the level at
which the interval would just reach the null value.
[2] The bands cover all 2 rows at once with 95% probability; use them when you
read several rows together. No validation study covers the bands for this
kind of fit, so cleverly marks them experimental.
[3] The interval holds only if every covariate model, outcome (or
event-hazard) model and natural-treatment model the simulation reads is
correctly specified. It includes the simulation error.
The two rows are the plan means. The p-values test a mean score of zero, which nobody asks, so ignore them here. “Followed in data” counts the patients whose actual offers matched each plan. The simultaneous bands are not needed, because the next cell compares the two plans directly.
LEVELS = ["ey_regimen[never]", "ey_regimen[always]"]
# contrast() takes the difference of the two plan means with their joint uncertainty.
difference = result.contrast(
lambda means: means[1] - means[0], LEVELS, name="ate_regimen[always vs never]"
)
# against_truth needs the true values, so on your own data read result.summary() instead.
def against_truth(estimates):
rows = {}
for estimate in estimates:
low, high = estimate.ci
rows[estimate.name] = {
"estimate": estimate.psi,
"ci_low": low,
"ci_high": high,
"truth": truth[estimate.name],
"covers": bool(low <= truth[estimate.name] <= high),
}
return pd.DataFrame(rows).T.astype(
{"estimate": float, "ci_low": float, "ci_high": float, "truth": float}
)
print(against_truth([result[key] for key in LEVELS] + [difference]).round(2).to_string())
print()
print("support:", sorted({result[key].support.label for key in LEVELS}))
print()
shares = result.simulation.monte_carlo_share
print("share of each variance that comes from the simulation:")
for name, share in shares.items():
print(f" {name:30s} {share:.1%}")
estimate ci_low ci_high truth covers
ey_regimen[never] 49.37 48.66 50.06 49.24 True
ey_regimen[always] 60.03 59.08 60.96 60.46 True
ate_regimen[always vs never] 10.66 9.49 11.82 11.22 True
support: ['supported']
share of each variance that comes from the simulation:
ey_regimen[never] 2.7%
ey_regimen[always] 1.2%
ate_regimen[always vs never] 0.5%
Against the truth, all three intervals hold, and the gain of always over never is 10.66 points
(9.49 to 11.82); result.contrast accounts for the two means sharing patients. The means and their difference read supported: a simulation study checks this kind of
fit (“How we know the method works” at the end).
The simulation adds noise, because each patient is copied only ten times (n_draws=10). The
interval includes it, and the last lines show its share of each variance, under 3% here and
smallest for the difference, since both plans reuse the same random draws. Above 10%, cleverly
warns; raise n_draws then.
Details: the page’s 400 repeated draws
A simulation we ran for this page (script
reviews/notebook-review/probes/model-based-over-time/sweep.py in the repository) repeats the
page’s fits on 400 draws, seeds 3100 to 3499. The g-formula intervals held the true value on 373
of 400 draws for never, 381 for always, and 377 for the difference. A correct 95% interval
gives about 380, and chance alone moves the count between about 371 and 388. The
simulation’s share of the variance was at most 3.0% for a plan mean and 0.7% for the difference.
What goes wrong when the symptom models are too simple#
The default symptom model (covariate_learner=None) is a logistic regression on the record
columns with no products. It assumes the discharge offer changes the log-odds of symptoms equally
for every patient. In these data the offer prevents symptoms mainly
among patients who live alone, who were also the ones offered, so the default model carries their
effect to everyone.
# This check needs the true values, so it runs only on simulated data. covariate_learner=None is
# the default: main-terms logistic models, with no product of two columns.
wrong = question.estimate(method=dataclasses.replace(gformula, covariate_learner=None))
wrong_difference = wrong.contrast(
lambda means: means[1] - means[0], LEVELS, name="ate_regimen[always vs never]"
)
print("main-terms symptom models:")
print(against_truth([wrong[key] for key in LEVELS] + [wrong_difference]).round(2).to_string())
print()
print("support:", sorted({wrong[key].support.label for key in LEVELS}))
main-terms symptom models:
estimate ci_low ci_high truth covers
ey_regimen[never] 50.05 49.4 50.70 49.24 False
ey_regimen[always] 62.38 61.7 63.04 60.46 False
ate_regimen[always vs never] 12.32 11.3 13.34 11.22 False
support: ['supported']
With the default symptom models, all three intervals miss: the mean under always is 62.38 (61.70
to 63.04) against a true 60.46, and the gain is 12.32 against 11.22. The fit still reads
supported, because the label describes the kind of fit, not whether your models match your data.
On real data no truth is printed, so you need a second method that rests on different models.
Details: the wrong models over 400 draws
In the page’s simulation, the interval for the mean under always missed the truth on all 400
draws, and the interval for the gain held it on only 71 of 400. The wrong models overstate the
mean under always by 2.26 points on average.
What each offer adds#
A structural nested mean model (snmm(), “the blip model” below) answers the second question. It
estimates the effect of one offer with the later offers set to no offer, called a “blip”, and lets
that effect depend on columns you name, here living alone at the first two decisions. It fits models of
the offers and of the score, but none of the symptom flags. Each row’s predictions come from models
trained without that row (n_folds=5), as in cross-validation.
Its own conditions are that the models of who is offered are right, and that the blips are linear in the named columns: an offer’s effect may differ by living situation, but not, say, by the day-10 flag.
from cleverly.datasets import RECOVERY_BOUNDS
from cleverly.longitudinal import snmm
# For your own data, change the column names, and list in FEATURES the baseline columns that you
# expect to change how much an offer helps. Here decisions 1 and 2 may depend on lives_alone, and
# decision 3 has one effect for all.
FEATURES = {1: ["lives_alone"], 2: ["lives_alone"]}
blips = snmm(
frame,
outcome="recovery_day30",
treatment=list(OFFERS),
baseline=["lives_alone", "discharge_risk"],
time_varying=[[], ["symptoms_day10"], ["symptoms_day20"]],
regimens=plans,
reference="never",
blip_features=FEATURES,
outcome_learner=GLM(family="gaussian"),
treatment_learner=GLM(family="binomial"),
n_folds=5, # out-of-fold predictions, as in cross-validation
random_state=3100,
)
# Each effect is named blip[offer column:offer value:column it depends on]; "intercept" is the
# effect for a patient with that column at 0. Offers coded 1 appear as 1.0. The loop reads the
# names from FEATURES and assumes one 0-or-1 feature, lives_alone; adapt it for others.
effect_rows = []
for node, column in enumerate(OFFERS, start=1):
names = [f"blip[{column}:1.0:{feature}]" for feature in ["intercept", *FEATURES.get(node, [])]]
for alone in (0, 1):
# The effect for a patient who lives alone adds the lives_alone term to the intercept.
effect = blips.contrast(lambda values, a=alone: values[0] + a * sum(values[1:]), names)
effect_rows.append(
{
"offer": column,
"lives_alone": alone,
"effect": effect.psi,
"ci_low": effect.ci[0],
"ci_high": effect.ci[1],
"truth": truth[names[0]] + alone * sum(truth[name] for name in names[1:]),
}
)
effects = pd.DataFrame(effect_rows).set_index(["offer", "lives_alone"])
print("effect of one offer, with the later offers set to no offer, in score points:")
print(effects.round(2).to_string())
print()
# When the effects depend only on baseline columns, the gain of always over never is the
# patients' average of the three effects. Each offer's part is its effect with the earlier offers
# given and the later ones off, weighted by the share of patients in each group.
alone_share = frame["lives_alone"].mean()
parts = effects["effect"].unstack().reindex(OFFERS) * [1 - alone_share, alone_share]
print(f"share of patients who live alone: {alone_share:.3f}")
print("part of the gain of always over never, by offer and group:")
parts["both groups"] = parts.sum(axis=1)
print(parts.round(2).to_string())
print(f"total: {parts['both groups'].sum():.2f}")
print()
print("support:", sorted({estimate.support.label for estimate in blips.estimates.values()}))
effect of one offer, with the later offers set to no offer, in score points:
effect ci_low ci_high truth
offer lives_alone
offer_discharge 0 2.00 0.60 3.36 2.0
1 13.39 12.18 14.59 14.1
offer_day10 0 2.15 1.57 2.73 2.0
1 3.84 3.00 4.68 4.8
offer_day20 0 2.10 1.79 2.40 2.0
1 2.10 1.79 2.40 2.0
share of patients who live alone: 0.350
part of the gain of always over never, by offer and group:
lives_alone 0 1 both groups
offer
offer_discharge 1.30 4.69 5.98
offer_day10 1.40 1.34 2.74
offer_day20 1.36 0.73 2.10
total: 10.82
support: ['supported']
The discharge offer adds far more for a patient who lives alone, because it prevents day-10 symptoms mainly among them. The day-20 offer has one declared effect, so its two rows repeat. Of the five distinct effects, four intervals hold their true values; the day-10 effect for patients who live alone (3.00 to 4.68) misses the true 4.8, ordinary sampling variation for one interval among several (Details).
Because these effects depend only on living alone, the gain of always over never is the
patients’ average of the three effects, each with the earlier offers given and the later ones off.
The discharge offer carries 5.98 of the 10.82 points, 4.69 of them from patients who live alone,
though they are only 0.350 of the patients.
Details: the blip model over 400 draws
In the page’s simulation, the effect intervals held their true values on 373 to 384 of 400 draws (95% would be 380), and the average error of each was within 0.05 points of zero.
Compare the two methods#
The blip model also reports the two plan means, derived from its effects, so they can sit beside
both g-formula fits. check_model() then tests the blip model against a third method.
comparison = pd.DataFrame(
{
"g-formula": [result[key].psi for key in LEVELS] + [difference.psi],
"g-formula, simple symptom models": [wrong[key].psi for key in LEVELS]
+ [wrong_difference.psi],
"blip model": [blips[key].psi for key in LEVELS]
+ [blips["ate_regimen[always vs never]"].psi],
"truth": [truth[key] for key in LEVELS] + [truth["ate_regimen[always vs never]"]],
},
index=[*LEVELS, "ate_regimen[always vs never]"],
)
print(comparison.round(2).to_string())
gain = comparison.loc["ate_regimen[always vs never]"]
for fit in ("g-formula", "g-formula, simple symptom models"):
print(f"gain of {fit} minus the blip model's: {gain[fit] - gain['blip model']:.2f}")
print()
check = blips.check_model(q_bounds=RECOVERY_BOUNDS) # your score's known range, here (0, 100)
print("always minus never, blip model:", f"{check.structural[0]:.2f}")
print(
"always minus never, method with no model of the effect (LTMLE):",
f"{check.nonparametric[0]:.2f}",
)
print(f"test of agreement: p = {check.pvalue:.2f}")
print("support:", check.support.label)
g-formula g-formula, simple symptom models blip model truth
ey_regimen[never] 49.37 50.05 49.46 49.24
ey_regimen[always] 60.03 62.38 60.29 60.46
ate_regimen[always vs never] 10.66 12.32 10.82 11.22
gain of g-formula minus the blip model's: -0.16
gain of g-formula, simple symptom models minus the blip model's: 1.50
always minus never, blip model: 10.80
always minus never, method with no model of the effect (LTMLE): 10.41
test of agreement: p = 0.29
support: experimental
The two methods lean on different models: the g-formula on the symptom and score models, the blip model on the offer models and the linear effects. With products in its symptom models, the g-formula agrees with the blip model to within 0.3 points; with simple ones its gain sits 1.50 points higher, more than half the width of the g-formula’s interval. No exact test of such a gap exists, but on these data the page’s 400 draws separate the two cases cleanly (Details). Treat a gap that large as a warning that one method is off: try richer symptom models, and run the check below. Agreement cannot catch a hidden cause that both methods miss, because both adjust for the same recorded columns. Choose the method you report before you look; this page reports the g-formula, which estimates the plan means directly.
check_model() tests the blip model against longitudinal TMLE (LTMLE). LTMLE fits models of the
offers and the score, then corrects the score model’s answer with the offer models; it assumes no
form for the effects, and it needs the score’s known range (q_bounds) because it works on a 0-to-1
scale and, fitted in folds, cannot take that scale from the observed scores. It fits
both methods on the same rows and on five random fold splits, and compares the averages. The two gains, 10.80 for the blip model (its single fit gave
10.82) and 10.41 for LTMLE, agree (p = 0.29). A small p-value would say that the linear effects are
wrong; a large one does not prove them right. The check reads experimental: no simulation study
covers it for this kind of fit.
Details: the two methods and the model check over 400 draws
In the page’s simulation, the gain of the g-formula with products differed from the blip model’s by at most 0.43 points, while the gain with simple symptom models sat at least 0.96 points above it, and more than 1.165, half the width of the page’s interval, on 380 of 400 draws. The linear effects are right in these data, and the check gave p below 0.05 on 23 of 400 draws, close to the 5% a correct check should give.
Check overlap#
Overlap still matters for the g-formula: where few patients followed a plan, its models must
extrapolate. assess() uses the g-formula fit’s offer models to count how many patients followed
each plan and how much weight each would need to stand in for all patients.
assessment = result.assess()
attention = tuple(item.name for item in assessment.attention)
print("checks that need attention:", attention or "none")
print(assessment.report("support").summary())
checks that need attention: none
Overlap over time
==============================================================================
Regimens: 2 Result: no pass or fail
Time points: 3
==============================================================================
regimen time rows max weight eff. rows capped assigned
------------------------------------------------------------------------------
never 1 2,783 3.78 2326.1 0.000 0.000
never 2 1,348 25.27 703.6 0.000 0.000
never 3 812 60.46 307.1 0.000 0.000
always 1 1,217 12.36 691.8 0.000 1.000
always 2 801 34.16 381.6 0.000 1.000
always 3 495 63.48 206.5 0.000 1.000
==============================================================================
Overlap is thinnest for always at time 3: 206.5 effective rows of 495
followed.
Notes:
[1] rows counts the units that followed the regimen and stayed observed
through the time point. max weight and eff. rows describe the cumulative
weight: one over the product of the treatment and censoring probabilities
up to that time point, times the observation weight on a weighted fit. A
product can be extreme while every time point looks fine. capped is the
share of rows whose cumulative probability the lower limit replaced.
[2] assigned is the share of the units at risk at that time point whom the
regimen treats; a regimen that names one arm assigns exactly 0 or 1.
Overlap is thinnest for always at the third decision, where the 495
followers count as about 206.5 equally weighted patients, 42% of them. On your own data, worry when that share falls to a few percent.
Try to break the result#
These checks change the data in a known way and refit the blip model’s gain of always 20 times
each. They use the blip model because it reports the gain as one estimate. The placebo swaps in
random offers, so the gain should be about zero. The random common cause adds a column of pure
noise, so the gain should barely move. The subset check refits on random 70% samples, whose gains
should spread as the standard error predicts. None can detect a hidden cause.
from cleverly.validation import refute
refutation = refute(
blips,
estimand="ate_regimen[always vs never]",
tests=("placebo", "subset", "random_common_cause"),
n_replicates=20,
)
columns = ["test", "original", "refuted_mean", "refuted_sd", "expectation", "verdict"]
print(refutation.to_frame()[columns].round(3).to_string(index=False))
print()
for test in refutation.tests:
if test.statistic_name:
print(f"{test.name}: {test.statistic_name} = {test.statistic:.3f}")
test original refuted_mean refuted_sd expectation verdict
placebo 10.824 0.128 0.537 ~ 0 descriptive
subset 10.824 10.644 0.390 scatter ~ 0.3788 descriptive
random_common_cause 10.824 10.822 0.015 ~ 10.82 descriptive
placebo: t = 1.065
subset: scatter ratio rho = 1.028
random_common_cause: paired shift in standard errors = -0.003
None of the three raises a concern. The placebo refits average about zero (t 1.065, well inside
2), the noise column leaves the gain unchanged to two decimals, and the 70% refits spread about as
predicted (rho 1.028, ideal 1). descriptive means no simulation study backs a pass or fail, so
you judge the numbers.
What if a confounder is missing?#
cleverly has no bound for how strong a hidden cause must be to change an answer over time, so the
code drops one recorded covariate at a time, refits both methods, and reports how far the gain
moves, in standard errors.
# For your own data, drop each recorded covariate in turn. lives_alone stays, because the
# blips read it.
reduced = {
"without discharge risk": {
"baseline": ("lives_alone",),
"time_varying": ((), ("symptoms_day10",), ("symptoms_day20",)),
},
"without symptom flags": {
"baseline": ("lives_alone", "discharge_risk"),
"time_varying": ((), (), ()),
},
}
move_rows = []
for label, columns in reduced.items():
smaller = dataclasses.replace(design, **columns)
fit = (
CausalStudy(frame, design=smaller)
.identify(RegimeMean(plans, reference="never"))
.estimate(method=gformula)
)
moved = fit.contrast(lambda means: means[1] - means[0], LEVELS).psi - difference.psi
structural = snmm(
frame,
outcome="recovery_day30",
treatment=list(OFFERS),
baseline=list(columns["baseline"]),
time_varying=[list(names) for names in columns["time_varying"]],
regimens=plans,
reference="never",
blip_features=FEATURES,
outcome_learner=GLM(family="gaussian"),
treatment_learner=GLM(family="binomial"),
n_folds=5,
random_state=3100,
)
full = blips["ate_regimen[always vs never]"]
move_rows.append(
{
"dropped": label,
"g-formula move": moved / difference.std_error,
"blip model move": (structural["ate_regimen[always vs never]"].psi - full.psi)
/ full.std_error,
}
)
print("move of always minus never, in standard errors of the full fit:")
print(pd.DataFrame(move_rows).set_index("dropped").round(2).to_string())
move of always minus never, in standard errors of the full fit:
g-formula move blip model move
dropped
without discharge risk -6.26 -6.57
without symptom flags -7.36 -10.83
Dropping either covariate moves the gain down by 6 to 11 standard errors, for both methods, because the navigators read them. An unrecorded cause of the offers and the score would bias the answer too: the interval spans about 2 standard errors on each side, so a cause whose omission moved the gain a third as far as the smallest move here could put the estimate outside it. Someone who knows how navigators decide must judge whether one exists; this comparison is not a bound.
What we can and can’t conclude#
Had every patient been offered navigation at discharge, day 10 and day 20, the mean day-30 recovery score would be about 10.7 points higher than with no offers (9.49 to 11.82). More than half of the gain comes from the discharge offer, most of that among patients who live alone, where one offer adds about 13 points against 2 to 4 elsewhere. That suggests where limited navigators might help most, though the page did not estimate a targeted plan.
The interval covers sampling and simulation noise only. The answer also needs the four conditions of “Columns, plans, and what must hold”, three of which the data cannot check, and each method’s models: simple symptom models moved it by 1.66 points. The model check and the agreement between methods only partly check the models.
One simulated sample says nothing about real patients or how the methods perform in general.
Go deeper#
How we know the method works#
Two simulation studies check the methods on this page, each on other simulated data with three decisions and a continuous score.
fit on this page |
simulation study |
what it covers |
|---|---|---|
the g-formula (all rows) |
other simulated data with a Gaussian and a binary covariate per decision, main-terms models that are right for those data, 2,000 to 8,000 rows. |
|
the blip model (five folds) |
other simulated data with binary covariates, 2,000 rows, ten folds. Its three-decision scenario has one effect per offer for all patients; a two-decision scenario lets the effect depend on a baseline column. EconML’s |
Neither study uses this page’s data. The g-formula study fits main-terms symptom models, while this page’s include products of two columns, and the blip-model study’s three-decision scenario names no column in its effects, while this page names living alone. The page’s own 400 draws show how often this page’s intervals hold on its own simulated data; only the studies above test the methods more widely. The technical entries list each method’s evidence and limits: parametric g-formula and structural dynamic effects.
Where to go next#
The weekly outcomes example estimates effects of offers repeated over time without modeling the covariates, and the discharge-to-readmission example follows patients after a discharge offer. The longitudinal user guide shows both methods on your own table. The examples index lists every example.