File size: 12,090 Bytes
c4c5273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate reconstruction quality on the held-out test cases.

Builds GT meshes from the (cleaned) GT masks with the SAME marching-cubes rule,
reconstructs predictions, and reports Chamfer / HD95 / Normal-Consistency /
watertight rate / canal-in-tooth containment.

    python -m toothcanal.evaluate --config configs/default.yaml
"""
import os, csv, argparse
import numpy as np
import torch
from .utils import load_config, ensure_dir, set_seed
from .splits import make_split
from .roi import crop_roi
from .geometry import sdf_from_mask, marching_cubes_to_mesh
from .models import ImplicitNet
from .infer import reconstruct_instance
from .metrics import chamfer_hd95_nc, watertight, containment_rate, dice_asd_rvd, apex_metrics


def _gt_wise_primary(inst_pred, match, gt_inst, ids):
    """Stage-1 over-splitting fix (evaluation-side, no retrain).
    Keep ONE predicted instance per GT tooth -- the one with the largest voxel
    overlap. The remaining predictions for that tooth are over-splits and must NOT
    each be scored against the same GT (that double-penalises reconstruction).
    Returns (primary_ids, detection_stats)."""
    best = {}                                   # gt_id -> (pred_id, overlap)
    for pid in ids:
        gid = match.get(pid)
        if not gid or gid <= 0:
            continue
        ov = int(((inst_pred == pid) & (gt_inst == gid)).sum())
        if ov <= 0:
            continue
        if gid not in best or ov > best[gid][1]:
            best[gid] = (pid, ov)
    primary = sorted({pid for pid, _ in best.values()})
    n_gt = len([v for v in np.unique(gt_inst) if v > 0])
    n_pred = len(ids)
    tp = len(best)                              # GT teeth matched by >=1 prediction
    extra = n_pred - tp                         # over-splits + phantom detections
    prec = tp / n_pred if n_pred else 0.0
    rec = tp / n_gt if n_gt else 0.0
    f1 = 2 * prec * rec / (prec + rec) if (prec + rec) else 0.0
    return primary, dict(n_gt=n_gt, n_pred=n_pred, matched=tp, extra=extra,
                         precision=prec, recall=rec, f1=f1)


def gt_meshes(d, iid, cfg):
    s2 = cfg["stage2"]
    ev = cfg.get("eval", {})
    # GT resolution is decoupled from the model's roi_vox so BOTH a 96-voxel model and
    # a 144-voxel model are scored against the SAME ground-truth mesh (fair Dice).
    gt_vox = int(ev.get("gt_roi_vox", s2["roi_vox"]))
    g = int(ev.get("gt_grid", cfg["infer"]["grid"]))
    roi = crop_roi(d, iid, s2["roi_mm"], gt_vox, center_mode=s2.get("roi_center", "com"))
    if roi is None:
        return None, None
    import scipy.ndimage as ndi
    zt = ndi.zoom(roi["solid"].astype(np.float32), np.array([g] * 3) / gt_vox, order=0) > 0.5
    zc = ndi.zoom(roi["canal"].astype(np.float32), np.array([g] * 3) / gt_vox, order=0) > 0.5
    spg = np.array([s2["roi_mm"] / g] * 3)
    tooth = marching_cubes_to_mesh(sdf_from_mask(zt, spg), 0.0, spg, pad=True)
    canal = marching_cubes_to_mesh(sdf_from_mask(zc, spg), 0.0, spg, pad=True)
    return tooth, canal


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", default="configs/default.yaml")
    ap.add_argument("--roi_source", default=None, choices=[None, "oracle", "predicted"])
    ap.add_argument("--tag", default="")
    args = ap.parse_args()
    cfg = load_config(args.config)
    set_seed(cfg["split"]["seed"])
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    roi_source = args.roi_source or cfg["infer"].get("roi_source", "oracle")
    cfg["infer"]["roi_source"] = roi_source
    apex_mm = float(cfg.get("eval", {}).get("apex_mm", 3.0))
    gt_wise = bool(cfg.get("eval", {}).get("gt_wise_predicted", True))
    det_stats = []                               # per-case Stage-1 detection metrics

    ckpt = torch.load(os.path.join(cfg["paths"]["out_dir"], cfg["stage2"].get("ckpt_name", "stage2.pt")),
                      map_location=dev)
    n_lat = ckpt["model"]["latents.weight"].shape[0]

    class _N(ImplicitNet):
        def __init__(s):
            super().__init__(n_lat, cfg)
    net = _N().to(dev)
    net.load_state_dict(ckpt["model"]); net.eval()

    stage1_ckpt = os.path.join(cfg["paths"]["out_dir"], "stage1.pt")
    _, test = make_split(cfg["paths"]["proc_dir"], cfg)
    rows = []
    for cid in test:
        d = dict(np.load(os.path.join(cfg["paths"]["proc_dir"], f"{cid}.npz")))
        if roi_source == "predicted":
            if not os.path.exists(stage1_ckpt):
                raise SystemExit("[eval] predicted ROI needs stage1.pt")
            from .roi import predicted_instances
            inst_pred, match = predicted_instances(d, cfg, dev, stage1_ckpt)
            d_full = d                                # keep GT for building GT meshes
            d = dict(d); d["inst"] = inst_pred; d["cinst"] = np.zeros_like(inst_pred)
            ids = [int(v) for v in np.unique(inst_pred) if v > 0]
            if gt_wise:
                ids, dstat = _gt_wise_primary(inst_pred, match, d_full["inst"], ids)
                dstat["case"] = cid
                det_stats.append(dstat)
                print(f"[eval:predicted] {cid}: {dstat['n_pred']} predicted -> "
                      f"{dstat['matched']}/{dstat['n_gt']} GT matched, "
                      f"{dstat['extra']} over-detections dropped (GT-wise)")
        else:
            match = {iid: iid for iid in np.unique(d["inst"]) if iid > 0}
            d_full = d
            ids = [int(v) for v in np.unique(d["inst"]) if v > 0]
        for iid in ids:
            pred = reconstruct_instance(net, d, iid, cfg, dev, do_tto=False)
            gt_id = match.get(iid, iid)
            gt_t, gt_c = gt_meshes(d_full, gt_id, cfg)
            if pred is None or gt_t is None or pred["tooth"] is None:
                continue
            # classify single-rooted (ST) vs multi-rooted (MT). Canal components merge
            # near the pulp chamber, so we count components in the APICAL THIRD (root
            # tips), where separate roots/canals are actually distinct.
            from scipy import ndimage as _ndi
            cmask = (d_full["cinst"] == gt_id)
            ttype = "ST"
            if cmask.any():
                zs = np.argwhere(cmask)[:, 2]
                z_lo, z_hi = zs.min(), zs.max()
                apical = cmask.copy()
                # keep only the apical third along the long (z) axis
                cut = z_lo + int((z_hi - z_lo) * 0.33)
                apical[:, :, cut:] = False
                _, ncomp = _ndi.label(apical, structure=np.ones((3, 3, 3)))
                # also try the other end in case orientation is flipped
                apical2 = cmask.copy(); cut2 = z_hi - int((z_hi - z_lo) * 0.33)
                apical2[:, :, :cut2] = False
                _, ncomp2 = _ndi.label(apical2, structure=np.ones((3, 3, 3)))
                ttype = "MT" if max(ncomp, ncomp2) >= 2 else "ST"
            m = chamfer_hd95_nc(pred["tooth"], gt_t, cfg["eval"]["n_surface_samples"])
            extra = dice_asd_rvd(pred["tooth"], gt_t)
            row = dict(case=cid, inst=iid, structure="tooth", tooth_type=ttype, **m, **extra,
                       watertight=watertight(pred["tooth"]),
                       boundary_touch=float(pred.get("roi", {}).get("boundary_touch", float("nan"))))
            rows.append(row)
            if pred["canal"] is not None and gt_c is not None:
                mc = chamfer_hd95_nc(pred["canal"], gt_c, cfg["eval"]["n_surface_samples"])
                ec = dice_asd_rvd(pred["canal"], gt_c)
                ax = apex_metrics(pred["canal"], gt_c, apex_mm)
                rows.append(dict(case=cid, inst=iid, structure="canal", tooth_type=ttype,
                                 **mc, **ec, **ax,
                                 watertight=watertight(pred["canal"]),
                                 n_components=pred.get("n_canal_components", 1),
                                 containment=containment_rate(pred["canal"], pred["tooth"])))
            print(f"[eval:{roi_source}] {cid} t{iid:02d} ({ttype}) tooth chamfer={m['chamfer_mm']:.3f}mm "
                  f"hd95={m['hd95_mm']:.3f}mm")

    out = ensure_dir(cfg["paths"]["out_dir"])
    suffix = f"_{args.tag}" if args.tag else f"_{roi_source}"
    csv_path = os.path.join(out, f"eval_metrics{suffix}.csv")
    keys = sorted({k for r in rows for k in r})
    with open(csv_path, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=keys); w.writeheader(); w.writerows(rows)

    def agg(structure, key, ttype=None):
        vals = [r[key] for r in rows if r["structure"] == structure
                and (ttype is None or r.get("tooth_type") == ttype)
                and isinstance(r.get(key), (int, float)) and not np.isnan(r[key])]
        return float(np.mean(vals)) if vals else float("nan")
    print(f"\n===== [{roi_source}] held-out test summary =====")
    def agg_med(structure, key, ttype=None):
        vals = [r[key] for r in rows if r["structure"] == structure
                and (ttype is None or r.get("tooth_type") == ttype)
                and isinstance(r.get(key), (int, float)) and not np.isnan(r[key])]
        return float(np.median(vals)) if vals else float("nan")
    for s in ["tooth", "canal"]:
        print(f"{s:6s} | chamfer={agg(s,'chamfer_mm'):.3f}mm  hd95={agg(s,'hd95_mm'):.3f}mm  "
              f"NC={agg(s,'normal_consistency'):.3f}")
        print(f"       | Dice={agg(s,'dice'):.3f}  ASD={agg(s,'asd_mm'):.3f}mm  RVD={agg(s,'rvd'):.3f}  "
              f"(<-- comparable to Duan 2021 baseline)")
        sr = agg_med(s, "signed_rvd")
        verdict = "thicker than GT" if sr > 0.05 else ("thinner/under than GT" if sr < -0.05 else "~balanced")
        print(f"       | signed_RVD (median) = {sr:+.3f}  ->  predicted {s} is {verdict}")
    bt = [r.get("boundary_touch") for r in rows if r["structure"] == "tooth"
          and isinstance(r.get("boundary_touch"), (int, float)) and not np.isnan(r.get("boundary_touch"))]
    if bt:
        clipped = sum(1 for x in bt if x > 0.01)
        print(f"tooth ROI clipping: {clipped}/{len(bt)} teeth touch an ROI face "
              f"(>1% of solid on boundary)  median touch={np.median(bt):.4f}")
    print(f"canal containment (in-tooth) = {agg('canal','containment'):.3f}")
    ad = agg_med("canal", "apex_dice"); asr = agg_med("canal", "apex_signed_rvd")
    ahd = agg_med("canal", "apex_hd95_mm")
    av = "thicker/over-extended" if asr > 0.05 else ("thinner/missing" if asr < -0.05 else "~balanced")
    print(f"canal APEX (root tip, {apex_mm:.0f}mm): Dice={ad:.3f}  HD95={ahd:.3f}mm  "
          f"signed_RVD={asr:+.3f} -> apex is {av}")
    print(f"--- by tooth type (ST=single-rooted, MT=multi-rooted) ---")
    for tt in ["ST", "MT"]:
        n = len({r['inst'] for r in rows if r.get('tooth_type') == tt})
        ncomp = [r.get('n_components') for r in rows if r.get('tooth_type') == tt
                 and r['structure'] == 'canal' and isinstance(r.get('n_components'), (int, float))]
        mean_comp = float(np.mean(ncomp)) if ncomp else float('nan')
        print(f"  {tt} (n={n}): tooth chamfer={agg('tooth','chamfer_mm',tt):.3f}mm  "
              f"canal chamfer={agg('canal','chamfer_mm',tt):.3f}mm  "
              f"canal Dice={agg('canal','dice',tt):.3f}  "
              f"mean canal components={mean_comp:.2f}")
    if det_stats:
        N_gt = sum(s["n_gt"] for s in det_stats); N_pred = sum(s["n_pred"] for s in det_stats)
        N_match = sum(s["matched"] for s in det_stats); N_extra = sum(s["extra"] for s in det_stats)
        P = N_match / N_pred if N_pred else 0.0
        R = N_match / N_gt if N_gt else 0.0
        F = 2 * P * R / (P + R) if (P + R) else 0.0
        print(f"--- Stage-1 detection (GT-wise eval) ---")
        print(f"  GT teeth={N_gt}  predicted={N_pred}  matched={N_match}  over-detections={N_extra}")
        print(f"  precision={P:.3f}  recall={R:.3f}  F1={F:.3f}")
        print(f"  (reconstruction metrics above use 1 best-overlap prediction per GT tooth)")
    print(f"metrics written to {csv_path}")


if __name__ == "__main__":
    main()