"""QC the canal labels against the tooth labels, per (case, tooth-instance). WHY: in the held-out metrics, canal failures were NOT spread across the model -- they were concentrated in a couple of cases. When a tooth reconstructs fine but its canal lands several mm away, the most likely cause is a DATA problem: the canal voxels carrying instance id `iid` (cinst == iid) are not actually inside tooth `iid` (inst == iid). This script tests exactly that, with no model and no inference. For every tooth instance it reports: tooth_vox, canal_vox voxel counts of (inst==id) and (cinst==id) canal_tooth_vol_ratio canal volume / tooth volume centroid_offset_mm distance between tooth and canal(id) centroids (mm) canal_in_tooth_bbox_frac fraction of canal(id) voxels inside the tooth bbox best_match_canal_id the canal id whose voxels are MOST inside this tooth (if != id -> instance-id misassignment) flag OK / MISSING / OUTSIDE / FAR / ID_MISMATCH A healthy tooth has: canal_in_tooth_bbox_frac ~ 1.0, small centroid_offset_mm, best_match_canal_id == id. Anything else is a label/preprocessing bug to fix or exclude BEFORE you read the reconstruction metrics. Usage: python -m toothcanal.qc_canal_labels --config configs/default.yaml # test cases python -m toothcanal.qc_canal_labels --config configs/default.yaml --cases all """ import os, csv, argparse import numpy as np from scipy import ndimage as ndi from .utils import load_config, ensure_dir from .splits import make_split, list_processed # thresholds for flagging (tune via CLI if needed) FAR_MM = 4.0 # tooth<->canal centroid offset above this is suspicious OUTSIDE_FRAC = 0.50 # less than this fraction of canal inside the tooth bbox is suspicious BBOX_MARGIN_VOX = 2 # allow a small margin around the tooth bbox def _centroid_mm(mask, sp): if not mask.any(): return None c = np.array(ndi.center_of_mass(mask)) return c * np.asarray(sp, np.float32) def _bbox(mask, margin, shape): pts = np.argwhere(mask) lo = np.clip(pts.min(0) - margin, 0, np.array(shape) - 1) hi = np.clip(pts.max(0) + margin, 0, np.array(shape) - 1) return lo, hi def _in_bbox_frac(canal_mask, lo, hi): if not canal_mask.any(): return float("nan") pts = np.argwhere(canal_mask) inside = np.all((pts >= lo) & (pts <= hi), axis=1) return float(inside.mean()) def qc_case(cid, proc_dir): d = dict(np.load(os.path.join(proc_dir, f"{cid}.npz"))) inst, cinst = d["inst"], d["cinst"] sp = np.asarray(d["spacing"], np.float32) shape = inst.shape tooth_ids = [int(v) for v in np.unique(inst) if v > 0] canal_ids = [int(v) for v in np.unique(cinst) if v > 0] rows = [] for tid in tooth_ids: tmask = (inst == tid) cmask = (cinst == tid) tvox = int(tmask.sum()) cvox = int(cmask.sum()) lo, hi = _bbox(tmask, BBOX_MARGIN_VOX, shape) t_c = _centroid_mm(tmask, sp) c_c = _centroid_mm(cmask, sp) if cvox else None offset = float(np.linalg.norm(t_c - c_c)) if (c_c is not None) else float("nan") in_frac = _in_bbox_frac(cmask, lo, hi) # which canal id actually lives inside this tooth's bbox the most? best_id, best_count = -1, 0 for cid_k in canal_ids: ck = (cinst == cid_k) pts = np.argwhere(ck) if not len(pts): continue n_in = int(np.all((pts >= lo) & (pts <= hi), axis=1).sum()) if n_in > best_count: best_count, best_id = n_in, cid_k # flag. Primary signal is the canal<->tooth centroid offset (robust). The # best-match id is kept as secondary info only: a tooth's (margin-expanded) # bbox can clip a larger NEIGHBOUR canal, so best_match!=tid alone is NOT # reliable evidence of a mislabel (it caused false positives on adjacent teeth). if cvox == 0: flag = "MISSING" elif not np.isnan(offset) and offset > 8.0: flag = "BROKEN" # canal centroid >8mm from its tooth elif not np.isnan(offset) and offset > 4.0: flag = "SUSPECT" # 4-8mm: inspect visually elif not np.isnan(in_frac) and in_frac < OUTSIDE_FRAC: flag = "OUTSIDE" else: flag = "OK" rows.append(dict( case=cid, tooth_id=tid, tooth_vox=tvox, canal_vox=cvox, canal_tooth_vol_ratio=round(cvox / (tvox + 1e-9), 4), centroid_offset_mm=round(offset, 3) if not np.isnan(offset) else "", canal_in_tooth_bbox_frac=round(in_frac, 3) if not np.isnan(in_frac) else "", best_match_canal_id=best_id, id_mismatch=bool(best_id != tid and best_id > 0), flag=flag, )) return rows def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", default="configs/default.yaml") ap.add_argument("--cases", default="test", choices=["test", "all"]) args = ap.parse_args() cfg = load_config(args.config) proc_dir = cfg["paths"]["proc_dir"] if args.cases == "all": cases = list_processed(proc_dir) else: _, cases = make_split(proc_dir, cfg) cases = sorted(cases) all_rows = [] for cid in cases: rows = qc_case(cid, proc_dir) all_rows.extend(rows) bad = [r for r in rows if r["flag"] != "OK"] print(f"[qc] {cid}: {len(rows)} teeth | " f"{len(rows) - len(bad)} OK | {len(bad)} suspect") for r in bad: print(f" t{r['tooth_id']:>2} flag={r['flag']:<11} " f"offset={r['centroid_offset_mm']}mm in_bbox={r['canal_in_tooth_bbox_frac']} " f"best_canal_id={r['best_match_canal_id']} canal_vox={r['canal_vox']}") out = ensure_dir(cfg["paths"]["out_dir"]) csv_path = os.path.join(out, "qc_canal_labels.csv") keys = ["case", "tooth_id", "tooth_vox", "canal_vox", "canal_tooth_vol_ratio", "centroid_offset_mm", "canal_in_tooth_bbox_frac", "best_match_canal_id", "id_mismatch", "flag"] with open(csv_path, "w", newline="") as f: w = csv.DictWriter(f, fieldnames=keys); w.writeheader(); w.writerows(all_rows) # case-level summary print("\n===== per-case suspect summary =====") for cid in cases: rows = [r for r in all_rows if r["case"] == cid] from collections import Counter cnt = Counter(r["flag"] for r in rows) susp = sum(v for k, v in cnt.items() if k != "OK") detail = ", ".join(f"{k}={v}" for k, v in cnt.items() if k != "OK") print(f" {cid}: {susp}/{len(rows)} suspect" + (f" ({detail})" if detail else "")) print(f"\nwritten to {csv_path}") if __name__ == "__main__": main()