| """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 = {} |
| 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) |
| extra = n_pred - tp |
| 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_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 = [] |
|
|
| 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 |
| 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 |
| |
| |
| |
| 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() |
| |
| cut = z_lo + int((z_hi - z_lo) * 0.33) |
| apical[:, :, cut:] = False |
| _, ncomp = _ndi.label(apical, structure=np.ones((3, 3, 3))) |
| |
| 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() |
|
|