File size: 8,681 Bytes
3799002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Mesh quality metrics: Chamfer, HD95, normal consistency, watertight, containment."""
import numpy as np


def _sample(mesh, n):
    import trimesh
    pts, fid = trimesh.sample.sample_surface(mesh, n)
    nrm = mesh.face_normals[fid]
    return np.asarray(pts), np.asarray(nrm)


def chamfer_hd95_nc(pred, gt, n=30000):
    """Returns dict with chamfer (mm), hd95 (mm), normal_consistency in [0,1]."""
    from scipy.spatial import cKDTree
    pp, pn = _sample(pred, n)
    gp, gn = _sample(gt, n)
    tp = cKDTree(pp); tg = cKDTree(gp)
    d_pg, i_pg = tg.query(pp)        # pred -> gt
    d_gp, i_gp = tp.query(gp)        # gt -> pred
    chamfer = 0.5 * (d_pg.mean() + d_gp.mean())
    hd95 = max(np.percentile(d_pg, 95), np.percentile(d_gp, 95))
    nc = 0.5 * (np.abs((pn * gn[i_pg]).sum(1)).mean() +
                np.abs((gn * pn[i_gp]).sum(1)).mean())
    return dict(chamfer_mm=float(chamfer), hd95_mm=float(hd95),
                normal_consistency=float(nc))


def dice_asd_rvd(pred, gt, pitch=0.1):
    """Volumetric metrics comparable to Duan 2021 baseline:
        Dice (volume overlap), ASD (avg symmetric surface distance, mm),
        RVD (relative volume difference). Both meshes are voxelized onto a SHARED
        grid (pitch mm) spanning their combined bounds, then compared as solids.
    Returns dict(dice, asd_mm, rvd)."""
    import trimesh
    if pred is None or gt is None:
        return dict(dice=float("nan"), asd_mm=float("nan"), rvd=float("nan"), signed_rvd=float("nan"))
    try:
        lo = np.minimum(pred.bounds[0], gt.bounds[0]) - 2 * pitch
        hi = np.maximum(pred.bounds[1], gt.bounds[1]) + 2 * pitch
        dims = np.maximum(np.ceil((hi - lo) / pitch).astype(int), 1)

        def solid(mesh):
            try:
                v = mesh.voxelized(pitch).fill()
                idx = np.round((v.points - lo) / pitch).astype(int)
                vol = np.zeros(dims, bool)
                ok = np.all((idx >= 0) & (idx < dims), axis=1)
                idx = idx[ok]
                vol[idx[:, 0], idx[:, 1], idx[:, 2]] = True
                return vol
            except Exception:
                return None

        pv, gv = solid(pred), solid(gt)
        if pv is None or gv is None:
            return dict(dice=float("nan"), asd_mm=float("nan"), rvd=float("nan"), signed_rvd=float("nan"))
        inter = np.logical_and(pv, gv).sum()
        dice = 2.0 * inter / (pv.sum() + gv.sum() + 1e-9)
        rvd = (pv.sum() - gv.sum()) / (gv.sum() + 1e-9)
        # ASD from surface samples (reuse chamfer-style nearest distances)
        from scipy.spatial import cKDTree
        pp, _ = _sample(pred, 20000); gp, _ = _sample(gt, 20000)
        d_pg, _ = cKDTree(gp).query(pp)
        d_gp, _ = cKDTree(pp).query(gp)
        asd = 0.5 * (d_pg.mean() + d_gp.mean())
        return dict(dice=float(dice), asd_mm=float(asd),
                    rvd=float(abs(rvd)), signed_rvd=float(rvd))
    except Exception:
        return dict(dice=float("nan"), asd_mm=float("nan"), rvd=float("nan"), signed_rvd=float("nan"))


def watertight(mesh):
    try:
        return bool(mesh.is_watertight)
    except Exception:
        return False


def containment_rate(canal_mesh, tooth_mesh, n=20000):
    """Fraction of canal surface points lying inside the tooth mesh.
    Tries trimesh.contains (ray), then signed_distance, then a voxelized
    point-in-volume test, so it returns a real number on headless servers."""
    if canal_mesh is None or tooth_mesh is None:
        return float("nan")
    import numpy as np
    import trimesh
    try:
        pts, _ = trimesh.sample.sample_surface(canal_mesh, n)
    except Exception:
        pts = canal_mesh.vertices
    pts = np.asarray(pts)

    # 1) ray-based contains (needs a backend; may raise/warn on headless)
    try:
        inside = tooth_mesh.contains(pts)
        if inside is not None and len(inside) == len(pts):
            return float(np.mean(inside))
    except Exception:
        pass
    # 2) signed distance (positive inside in trimesh convention)
    try:
        from trimesh.proximity import signed_distance
        sd = signed_distance(tooth_mesh, pts)
        return float(np.mean(sd > 0))
    except Exception:
        pass
    # 3) voxelize the tooth solid and test point membership
    try:
        pitch = max(tooth_mesh.extents.max() / 64.0, 1e-3)
        vox = tooth_mesh.voxelized(pitch).fill()
        inside = vox.is_filled(pts)
        return float(np.mean(inside))
    except Exception:
        return float("nan")


def _apex_point_from_gt(gt, apex_mm, n=20000):
    """Orientation-free apex localization on the GT canal.
    The canal runs crown(pulp chamber, WIDE) -> apex(root tip, NARROW). We take the
    two extremes along the canal's principal axis and pick the NARROWER one (fewer GT
    surface points within apex_mm) as the apex. Returns (apex_pt[3], gt_pts[n,3]) or
    (None, None) if the canal is too small to localize an apex."""
    gp, _ = _sample(gt, n)
    if len(gp) < 50:
        return None, None
    c = gp.mean(0)
    X = gp - c
    # first principal direction via SVD
    try:
        u = np.linalg.svd(X, full_matrices=False)[2][0]
    except Exception:
        return None, None
    t = X @ u
    lo_end = gp[int(t.argmin())]
    hi_end = gp[int(t.argmax())]
    n_lo = int((np.linalg.norm(gp - lo_end, axis=1) <= apex_mm).sum())
    n_hi = int((np.linalg.norm(gp - hi_end, axis=1) <= apex_mm).sum())
    apex_pt = lo_end if n_lo <= n_hi else hi_end
    return apex_pt, gp


def apex_metrics(pred, gt, apex_mm=3.0, pitch=0.1):
    """Apex-restricted canal metrics (the clinically important root-tip region).
    All quantities are computed ONLY within `apex_mm` of the GT apex point.
    Returns apex_dice, apex_asd_mm, apex_hd95_mm, apex_signed_rvd (signed: + = pred
    too thick / over-extended at the apex, - = pred too thin / missing apex)."""
    nan = float("nan")
    blank = dict(apex_dice=nan, apex_asd_mm=nan, apex_hd95_mm=nan, apex_signed_rvd=nan)
    if pred is None or gt is None:
        return blank
    try:
        from scipy.spatial import cKDTree
        apex_pt, gp = _apex_point_from_gt(gt, apex_mm)
        if apex_pt is None:
            return blank
        pp, _ = _sample(pred, 20000)

        gm = np.linalg.norm(gp - apex_pt, axis=1) <= apex_mm     # GT apex surface
        pm = np.linalg.norm(pp - apex_pt, axis=1) <= apex_mm     # pred apex surface
        gp_a = gp[gm]
        pp_a = pp[pm]
        if len(gp_a) < 10:
            return blank

        # --- apex ASD / HD95 ---
        # gt-apex -> nearest pred surface (full): "is the true apex reconstructed?"
        d_g = cKDTree(pp).query(gp_a)[0]
        if len(pp_a) >= 10:
            d_p = cKDTree(gp).query(pp_a)[0]           # pred-apex -> nearest GT
            apex_asd = 0.5 * (d_g.mean() + d_p.mean())
            apex_hd95 = max(np.percentile(d_g, 95), np.percentile(d_p, 95))
        else:
            # pred has (almost) nothing at the apex -> missed apex
            apex_asd = float(d_g.mean())
            apex_hd95 = float(np.percentile(d_g, 95))

        # --- apex Dice / signed-RVD on a shared voxel grid in an apex box ---
        import trimesh
        lo = apex_pt - apex_mm
        hi = apex_pt + apex_mm

        def solid_box(mesh):
            try:
                v = mesh.voxelized(pitch).fill()
                pts = v.points
                keep = np.all((pts >= lo) & (pts <= hi), axis=1)
                pts = pts[keep]
                if len(pts) == 0:
                    return np.zeros((0, 3))
                return np.round((pts - lo) / pitch).astype(int)
            except Exception:
                return None

        dims = np.maximum(np.ceil((hi - lo) / pitch).astype(int) + 1, 1)
        pi = solid_box(pred)
        gi = solid_box(gt)
        if pi is None or gi is None:
            return dict(apex_asd_mm=float(apex_asd), apex_hd95_mm=float(apex_hd95),
                        apex_dice=nan, apex_signed_rvd=nan)

        def to_vol(idx):
            vol = np.zeros(dims, bool)
            if len(idx):
                ok = np.all((idx >= 0) & (idx < dims), axis=1)
                idx = idx[ok]
                vol[idx[:, 0], idx[:, 1], idx[:, 2]] = True
            return vol

        pv, gv = to_vol(pi), to_vol(gi)
        inter = np.logical_and(pv, gv).sum()
        apex_dice = 2.0 * inter / (pv.sum() + gv.sum() + 1e-9)
        apex_srvd = (pv.sum() - gv.sum()) / (gv.sum() + 1e-9)
        return dict(apex_dice=float(apex_dice), apex_asd_mm=float(apex_asd),
                    apex_hd95_mm=float(apex_hd95), apex_signed_rvd=float(apex_srvd))
    except Exception:
        return blank