File size: 11,767 Bytes
5f4c454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
"""Table 2 / Section 5.1 reproduction analysis for arXiv 2604.26070 (ObsNODE).

Reads the author-pipeline metric pickles produced by the patched
Pred_{ObsNODE,NODE}_CF_cancer_*.py scripts, aggregates over seeds 1-5,
computes the paper's Table 2 quantities on the first-6-prediction-point
window (paper: "averaged over six prediction time points") and the full
19-point horizon, and independently recomputes CB/ATE from the raw
prediction and CF pickles with independently computed train mean/std.

Variable order in x tensors: 0 = tumor volume, 1 = body weight (toxicity).
Shapes: per-series tensors are (time_points, 2); per-variable (2,).
Raw x_pred pickles: (time_points, patients, 2), unstandardized.
"""

import os
import pickle

import numpy as np
import torch

OBS = "/work/eval_out/obsNODE"
NOD = "/work/eval_out/NODE"
CFDIR = "/work/ObsNODE/Code/Counterfactual/CF_data_cancer/dataset_cancer_cf"
TRAINPKL = "/work/data/data_train_cancer_DoseAI.pkl"

OUT = "/work/eval_out/analysis"
os.makedirs(OUT, exist_ok=True)

# Paper Table 2 reference numbers.
PAPER = {
    "obsNODE": {
        "cb_tumor": [0.1738, 0.1739, 0.1724, 0.1708, 0.1708],
        "cb_weight": [0.0952, 0.0941, 0.0924, 0.0924, 0.0926],
        "ate_tumor": [0.1633, 0.1770, 0.1831, 0.1771, 0.1771],
        "ate_weight": [0.0937, 0.0968, 0.0992, 0.0995, 0.0995],
    },
    "NODE": {
        "cb_tumor": [-0.5152, -0.5288, -0.5364, -0.5321, -0.5321],
        "cb_weight": [-2.0229, -2.0272, -2.0313, -2.0315, -2.0315],
        "ate_tumor": [-0.5257] * 5,
        "ate_weight": [-2.0245] * 5,
    },
    "true_ate_tumor": [-0.0105, 0.0031, 0.0107, 0.0063, 0.0063],
    "true_ate_weight": [-0.0016, 0.0227, 0.0068, 0.0070, 0.0070],
}
PAPER_MAE = {"obsNODE": {"tumor": 0.1723, "weight": 0.0933},
             "NODE": {"tumor": 0.5289, "weight": 2.0289}}


def load_metric_pickles(model_dir, tag):
    """Per-seed per-CF metric tensors from the author pipeline."""
    per_seed = {}  # (cf, seed) -> dict of tensors
    for cf in range(1, 7):
        for seed in range(1, 6):
            p = os.path.join(
                model_dir,
                f"data_pred_cb_ate_cancer_CF_{cf}_seed_{seed}_{tag}.pkl")
            (cb_ps, cb_pv, ate_ps, ate_pv,
             ate_ps_def, ate_pv_def) = pickle.load(open(p, "rb"))
            per_seed[(cf, seed)] = {
                "cb_ps": cb_ps, "cb_pv": cb_pv,
                "ate_ps": ate_ps, "ate_pv": ate_pv,
                "ate_ps_def": ate_ps_def, "ate_pv_def": ate_pv_def,
            }
    return per_seed


def stack_mean(ds, key):
    return torch.stack([d[key] for d in ds]).mean(dim=0)


def stack_std(ds, key):
    return torch.stack([d[key] for d in ds]).std(dim=0)


def table2_rows(per_seed):
    """CB / predATE / trueATE / |predATE-trueATE| per variable per CF,
    averaged over seeds, on the 6-point window and full horizon."""
    rows = {}
    for cf in range(1, 6):
        ds = [per_seed[(cf, s)] for s in range(1, 6)]
        # Six-point window (paper Table 2): first 6 prediction points after tc.
        cb_ps6 = torch.stack([d["cb_ps"][:6] for d in ds]).mean(0)  # (6, 2)
        ate_ps6 = torch.stack([d["ate_ps"][:6] for d in ds]).mean(0)
        ate_ps_def6 = torch.stack([d["ate_ps_def"][:6] for d in ds]).mean(0)
        # Full 19-point horizon for reference.
        cb_full = torch.stack([d["cb_pv"] for d in ds]).mean(0)     # (2,)
        ate_full = torch.stack([d["ate_pv"] for d in ds]).mean(0)
        ate_def_full = torch.stack([d["ate_pv_def"] for d in ds]).mean(0)
        rows[cf] = {
            "cb6": cb_ps6.mean(0), "ate6": ate_ps6.mean(0),
            "true_ate6": ate_ps_def6.mean(0),
            "abs_ate_err6": (ate_ps6.mean(0) - ate_ps_def6.mean(0)).abs(),
            "cb_full": cb_full, "ate_full": ate_full,
            "true_ate_full": ate_def_full,
            "abs_ate_err_full": (ate_full - ate_def_full).abs(),
            "seed_std_cb6": torch.stack(
                [d["cb_ps"][:6].mean(0) for d in ds]).std(0),
        }
    return rows


def independent_check(model_dir, tag, cf):
    """Recompute CB over the 6-point window directly from the raw
    unstandardized prediction pickle and the raw CF pickles, using train
    mean/std recomputed here from the raw training data."""
    data_train = pickle.load(open(TRAINPKL, "rb"))
    t_train, x_train, _ = data_train
    mean = x_train.mean(dim=(0, 1), keepdim=True)
    std = x_train.std(dim=(0, 1), keepdim=True)

    x_pred = pickle.load(open(os.path.join(
        model_dir, f"data_pred_cancer_CF_{cf}_seed_1_{tag}.pkl"), "rb"))
    data_cf = pickle.load(open(os.path.join(
        CFDIR, f"data_test_cancer_gamma_4_CF_{cf}.pkl"), "rb"))
    data_cf6 = pickle.load(open(os.path.join(
        CFDIR, f"data_test_cancer_gamma_4_CF_6.pkl"), "rb"))
    t_cf, x_cf, _ = data_cf
    t_cf6, x_cf6, _ = data_cf6
    num_time = 24
    x_cf, x_cf6 = x_cf[:num_time], x_cf6[:num_time]
    idx = 5
    x_true_cf = x_cf[idx:]
    x_true_cf6 = x_cf6[idx:]
    assert x_pred.shape == x_true_cf.shape, (x_pred.shape, x_true_cf.shape)

    cb = ((x_pred - mean) / std - (x_true_cf - mean) / std)
    ate = ((x_pred - mean) / std - (x_true_cf6 - mean) / std)
    true_ate = ((x_true_cf - mean) / std - (x_true_cf6 - mean) / std)
    return {
        "cb6": cb[:6].mean(dim=(0, 1)),
        "cb_full": cb.mean(dim=(0, 1)),
        "ate6": ate[:6].mean(dim=(0, 1)),
        "true_ate6": true_ate[:6].mean(dim=(0, 1)),
    }


def treatment_path_check(model_dir, tag):
    """Does the prediction actually depend on the future treatment path?
    Compare x_pred across regimes and against CF6's own prediction."""
    preds = {}
    for cf in range(1, 7):
        vals = []
        for seed in range(1, 6):
            p = pickle.load(open(os.path.join(
                model_dir,
                f"data_pred_cancer_CF_{cf}_seed_{seed}_{tag}.pkl"), "rb"))
            vals.append(p[:6].mean(dim=1))  # (6, 2) mean over patients
        preds[cf] = torch.stack(vals).mean(0)
    sens = {}
    for cf in range(1, 6):
        d = (preds[cf] - preds[6]).abs().mean().item()
        sens[cf] = d
    spread = max(
        (preds[a] - preds[b]).abs().mean().item()
        for a in range(1, 6) for b in range(1, 6) if a < b)
    return sens, spread


def fmt(vals, n=4):
    return "/".join(f"{v:.{n}f}" for v in vals.tolist())


def main():
    report = []
    rep = report.append

    summary = {}
    for model_dir, tag, label in [(OBS, "obsNODE", "ObsNODE"),
                                  (NOD, "NODE", "NODE")]:
        per_seed = load_metric_pickles(model_dir, tag)
        rows = table2_rows(per_seed)
        summary[label] = rows

        rep(f"## {label}")
        rep(f"{'CF':>3} | {'CB6 tumor':>10} {'CB6 weight':>10} | "
            f"{'predATE6 t':>10} {'predATE6 w':>10} | "
            f"{'trueATE6 t':>10} {'trueATE6 w':>10} | "
            f"{'|ATEerr|6 t':>11} {'|ATEerr|6 w':>11} | "
            f"{'seedstd CB t':>12}")
        mae = {"tumor": [], "weight": []}
        for cf in range(1, 6):
            r = rows[cf]
            rep(f"{cf:>3} | {fmt(r['cb6'])[:10+5]} | "
                f"{r['ate6'][0]:.4f} {r['ate6'][1]:.4f} | "
                f"{r['true_ate6'][0]:.4f} {r['true_ate6'][1]:.4f} | "
                f"{r['abs_ate_err6'][0]:.4f} {r['abs_ate_err6'][1]:.4f} | "
                f"{r['seed_std_cb6'][0]:.4f}")
            mae["tumor"].append(r["abs_ate_err6"][0].item())
            mae["weight"].append(r["abs_ate_err6"][1].item())
        rep(f"mean |ATE err| tumor = {np.mean(mae['tumor']):.4f} "
            f"(paper {PAPER_MAE[tag]['tumor']}), "
            f"weight = {np.mean(mae['weight']):.4f} "
            f"(paper {PAPER_MAE[tag]['weight']})")
        rep("full-horizon CB tumor: " +
            fmt(torch.stack([rows[c]["cb_full"][0] for c in range(1, 6)])))
        rep("full-horizon CB weight: " +
            fmt(torch.stack([rows[c]["cb_full"][1] for c in range(1, 6)])))
        rep("full-horizon predATE tumor: " +
            fmt(torch.stack([rows[c]["ate_full"][0] for c in range(1, 6)])))
        rep("full-horizon trueATE tumor: " +
            fmt(torch.stack([rows[c]["true_ate_full"][0] for c in range(1, 6)])))
        rep("full-horizon predATE weight: " +
            fmt(torch.stack([rows[c]["ate_full"][1] for c in range(1, 6)])))
        rep("full-horizon trueATE weight: " +
            fmt(torch.stack([rows[c]["true_ate_full"][1] for c in range(1, 6)])))
        rep("")

    # Paper reference table alongside.
    rep("## Paper Table 2 reference")
    rep(f"ObsNODE CB tumor   : {PAPER['obsNODE']['cb_tumor']}")
    rep(f"ours    CB tumor   : " + fmt(torch.stack(
        [summary['ObsNODE'][c]['cb6'][0] for c in range(1, 6)])))
    rep(f"ObsNODE CB weight  : {PAPER['obsNODE']['cb_weight']}")
    rep(f"ours    CB weight  : " + fmt(torch.stack(
        [summary['ObsNODE'][c]['cb6'][1] for c in range(1, 6)])))
    rep(f"NODE CB tumor      : {PAPER['NODE']['cb_tumor']}")
    rep(f"ours    CB tumor   : " + fmt(torch.stack(
        [summary['NODE'][c]['cb6'][0] for c in range(1, 6)])))
    rep(f"NODE CB weight     : {PAPER['NODE']['cb_weight']}")
    rep(f"ours    CB weight  : " + fmt(torch.stack(
        [summary['NODE'][c]['cb6'][1] for c in range(1, 6)])))
    rep(f"true ATE tumor     : {PAPER['true_ate_tumor']}")
    rep(f"ours    true tumor : " + fmt(torch.stack(
        [summary['ObsNODE'][c]['true_ate6'][0] for c in range(1, 6)])))
    rep(f"true ATE weight    : {PAPER['true_ate_weight']}")
    rep(f"ours    true weight: " + fmt(torch.stack(
        [summary['ObsNODE'][c]['true_ate6'][1] for c in range(1, 6)])))
    rep(f"ObsNODE ATE tumor  : {PAPER['obsNODE']['ate_tumor']}")
    rep(f"ours    ATE tumor  : " + fmt(torch.stack(
        [summary['ObsNODE'][c]['ate6'][0] for c in range(1, 6)])))
    rep(f"ObsNODE ATE weight : {PAPER['obsNODE']['ate_weight']}")
    rep(f"ours    ATE weight : " + fmt(torch.stack(
        [summary['ObsNODE'][c]['ate6'][1] for c in range(1, 6)])))
    rep(f"NODE ATE tumor     : {PAPER['NODE']['ate_tumor']}")
    rep(f"ours    ATE tumor  : " + fmt(torch.stack(
        [summary['NODE'][c]['ate6'][0] for c in range(1, 6)])))
    rep(f"NODE ATE weight    : {PAPER['NODE']['ate_weight']}")
    rep(f"ours    ATE weight : " + fmt(torch.stack(
        [summary['NODE'][c]['ate6'][1] for c in range(1, 6)])))
    rep("")

    # Independent recomputation (seed 1) vs author pipeline.
    rep("## Independent recomputation from raw pickles (seed 1)")
    for model_dir, tag, label in [(OBS, "obsNODE", "ObsNODE"),
                                  (NOD, "NODE", "NODE")]:
        per_seed = load_metric_pickles(model_dir, tag)
        for cf in [1, 5]:
            ind = independent_check(model_dir, tag, cf)
            pipe = per_seed[(cf, 1)]
            dcb = (ind["cb6"] - pipe["cb_ps"][:6].mean(0)).abs().max().item()
            date = (ind["ate6"] - pipe["ate_ps"][:6].mean(0)).abs().max().item()
            rep(f"{label} CF{cf}: max|independent-pipeline| "
                f"CB={dcb:.2e} predATE={date:.2e} "
                f"(indep CB6 t/w = {ind['cb6'][0]:.4f}/{ind['cb6'][1]:.4f})")
    rep("")

    # Treatment-path sensitivity.
    rep("## Treatment-path sensitivity (mean |x_pred_CFk - x_pred_CF6|, 6 pts)")
    for model_dir, tag, label in [(OBS, "obsNODE", "ObsNODE"),
                                  (NOD, "NODE", "NODE")]:
        sens, spread = treatment_path_check(model_dir, tag)
        rep(f"{label}: CF1..CF5 vs CF6 = " +
            "/".join(f"{sens[c]:.4f}" for c in range(1, 6)) +
            f" | max pairwise spread = {spread:.4f}")

    text = "\n".join(report)
    print(text)
    with open(os.path.join(OUT, "table2_report.txt"), "w") as f:
        f.write(text)


if __name__ == "__main__":
    main()