File size: 10,325 Bytes
47abdb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import csv
import json
import math
import os

import numpy as np

STRUCT_TYPES = {"trajectory", "polyline", "mask", "timeseries", "edges"}


def s_of_e(e):
    if e is None or (isinstance(e, float) and math.isnan(e)):
        return 0.0
    if e <= 1:
        return 1.0
    if os.environ.get("SCI_SCORE_MODE", "binary") == "binary":
        return 0.0
    return max(0.0, 1 - (e - 1) / 2)


def is_file_ref(x):
    return isinstance(x, dict) and set(x) == {"file"} and isinstance(x["file"], str)


def resolve(x, base):
    if not is_file_ref(x):
        return x
    if base is None:
        raise FileNotFoundError("no directory to resolve " + x["file"])
    p = os.path.realpath(os.path.join(base, x["file"]))
    if not p.startswith(os.path.realpath(base) + os.sep):
        raise FileNotFoundError("file reference escapes its directory")
    return load_file(p)


def load_file(p):
    ext = os.path.splitext(p)[1].lower()
    if ext == ".json":
        return json.load(open(p))
    if ext == ".npy":
        return np.load(p, allow_pickle=False)
    if ext in (".png", ".tif", ".tiff", ".bmp"):
        from PIL import Image
        Image.MAX_IMAGE_PIXELS = None
        if ext in (".tif", ".tiff"):
            import tifffile
            return tifffile.imread(p)
        return np.array(Image.open(p))
    if ext in (".csv", ".tsv", ".txt"):
        rows = list(csv.reader(open(p), delimiter="\t" if ext == ".tsv" else ","))
        rows = [r for r in rows if r and any(c.strip() for c in r)]
        head = [c.strip().lower() for c in rows[0]]
        try:
            [float(c) for c in rows[0]]
            head = None
        except ValueError:
            rows = rows[1:]
        return {"header": head, "rows": [[c.strip() for c in r] for r in rows]}
    raise ValueError("unsupported answer file type " + ext)


def table_cols(tab, want):
    head = tab["header"]
    rows = tab["rows"]
    if head is None:
        return None
    idx = {w: head.index(w) for w in want if w in head}
    return idx, rows


def to_tracks(x):
    if isinstance(x, dict) and "rows" in x:
        cols = table_cols(x, ["id", "t", "frame", "x", "y", "z"])
        if cols is None:
            arr = [[float(c) for c in r] for r in x["rows"]]
            return {"0": arr}
        idx, rows = cols
        tk = "t" if "t" in idx else "frame"
        dims = [d for d in ("x", "y", "z") if d in idx]
        out = {}
        for r in rows:
            k = r[idx["id"]] if "id" in idx else "0"
            out.setdefault(str(k), []).append([float(r[idx[tk]])] + [float(r[idx[d]]) for d in dims])
        return out
    if isinstance(x, dict):
        return {str(k): to_points(v) for k, v in x.items()}
    if isinstance(x, (list, np.ndarray)):
        return {"0": to_points(x)}
    return {}


def to_points(v):
    out = []
    for p in v if v is not None else []:
        if isinstance(p, dict):
            keys = [k for k in ("t", "frame", "x", "y", "z") if k in p]
            out.append([float(p[k]) for k in keys])
        else:
            out.append([float(c) for c in p])
    return out


def track_score(gt, pr, tau):
    if not gt:
        return 0.0
    if not pr:
        return 0.0
    pr = sorted(pr, key=lambda r: r[0])
    pt = np.array([r[0] for r in pr])
    pv = np.array([r[1:] for r in pr])
    tot = 0.0
    for r in gt:
        t, g = r[0], np.array(r[1:])
        if t < pt[0] - 1e-9 or t > pt[-1] + 1e-9:
            continue
        p = np.array([np.interp(t, pt, pv[:, j]) for j in range(pv.shape[1])])
        if len(p) < len(g):
            continue
        tot += s_of_e(float(np.linalg.norm(p[:len(g)] - g)) / tau)
    return tot / len(gt)


def score_trajectory(pred, gt, tol):
    from scipy.optimize import linear_sum_assignment
    tau = float(tol["value"])
    G, P = to_tracks(gt), to_tracks(pred)
    if not G:
        return 0.0, {}
    gk, pk = list(G), list(P)
    if not pk:
        return 0.0, {"matched": 0}
    if len(gk) == 1 and len(pk) == 1:
        s = track_score(G[gk[0]], P[pk[0]], tau)
        return s, {"track": round(s, 3)}
    S = np.array([[track_score(G[g], P[p], tau) for p in pk] for g in gk])
    r, c = linear_sum_assignment(-S)
    matched = float(S[r, c].sum())
    denom = max(len(gk), len(pk)) if tol.get("penalize_extra", True) else len(gk)
    return matched / denom, {"per_track": {gk[i]: round(float(S[i, j]), 3) for i, j in zip(r, c)}, "n_gt": len(gk), "n_pred": len(pk)}


def to_lines(x):
    if isinstance(x, dict) and "rows" in x:
        cols = table_cols(x, ["id", "x", "y", "z"])
        if cols is None:
            return [[[float(c) for c in r] for r in x["rows"]]]
        idx, rows = cols
        dims = [d for d in ("x", "y", "z") if d in idx]
        out = {}
        for r in rows:
            out.setdefault(r[idx["id"]] if "id" in idx else "0", []).append([float(r[idx[d]]) for d in dims])
        return list(out.values())
    if isinstance(x, dict):
        return [to_points(v) for v in x.values()]
    if isinstance(x, np.ndarray):
        x = x.tolist()
    if isinstance(x, list) and x and isinstance(x[0], (list, tuple)) and x[0] and isinstance(x[0][0], (list, tuple, dict)):
        return [to_points(v) for v in x]
    return [to_points(x)]


def densify(lines, step):
    pts = []
    for L in lines:
        L = np.array(L, float)
        if len(L) == 1:
            pts.append(L)
            continue
        for a, b in zip(L[:-1], L[1:]):
            n = max(1, int(math.ceil(np.linalg.norm(b - a) / step)))
            pts.append(a + (b - a) * np.linspace(0, 1, n, endpoint=False)[:, None])
        pts.append(L[-1:])
    return np.vstack(pts) if pts else np.zeros((0, 2))


def score_polyline(pred, gt, tol):
    from scipy.spatial import cKDTree
    tau = float(tol["value"])
    G, P = to_lines(gt), to_lines(pred)
    G, P = [L for L in G if L], [L for L in P if L]
    if not G or not P:
        return 0.0, {}
    dim = min(len(G[0][0]), len(P[0][0]))
    g = densify([[p[:dim] for p in L] for L in G], tau / 4)
    p = densify([[q[:dim] for q in L] for L in P], tau / 4)
    dg, _ = cKDTree(p).query(g)
    dp, _ = cKDTree(g).query(p)
    recall = float(np.mean([s_of_e(d / tau) for d in dg]))
    precision = float(np.mean([s_of_e(d / tau) for d in dp]))
    f = 0.0 if recall + precision == 0 else 2 * recall * precision / (recall + precision)
    return f, {"recall": round(recall, 3), "precision": round(precision, 3),
                                      "mean_dist_gt_to_pred": round(float(dg.mean()), 2)}


def as_mask(x):
    if isinstance(x, dict) and "rows" in x:
        x = [[float(c) for c in r] for r in x["rows"]]
    a = np.asarray(x)
    if a.ndim == 3 and a.shape[-1] in (3, 4):
        a = a[..., 0]
    return a


def score_mask(pred, gt, tol):
    thr = float(tol.get("value", 0.5))
    metric = tol.get("metric", "iou")
    G, P = as_mask(gt), as_mask(pred)
    if G.shape != P.shape:
        return 0.0, {"error": f"shape {P.shape} != {G.shape}"}
    classes = tol.get("classes")
    if classes is None:
        classes = [None]
    vals = {}
    for c in classes:
        g = (G > 0) if c is None else (G == c)
        p = (P > 0) if c is None else (P == c)
        inter, union, tot = np.logical_and(g, p).sum(), np.logical_or(g, p).sum(), g.sum() + p.sum()
        if union == 0:
            m = 1.0
        elif metric == "dice":
            m = 2 * inter / tot
        else:
            m = inter / union
        vals["all" if c is None else str(c)] = float(m)
    s = float(np.mean([min(1.0, v / thr) for v in vals.values()]))
    return s, {metric: {k: round(v, 3) for k, v in vals.items()}}


def to_series(x):
    if isinstance(x, dict) and "rows" in x:
        cols = table_cols(x, ["t", "y", "value"])
        if cols is None:
            arr = [[float(c) for c in r] for r in x["rows"]]
        else:
            idx, rows = cols
            yk = "y" if "y" in idx else "value"
            arr = [[float(r[idx["t"]]), float(r[idx[yk]])] for r in rows]
    elif isinstance(x, dict) and "t" in x:
        arr = list(zip(map(float, x["t"]), map(float, x.get("y", x.get("value")))))
    else:
        arr = [[float(a), float(b)] for a, b in x]
    arr = sorted(arr)
    return np.array([a for a, _ in arr]), np.array([b for _, b in arr])


def score_timeseries(pred, gt, tol):
    gt_t, gt_y = to_series(gt)
    try:
        pt, py = to_series(pred)
    except Exception:
        return 0.0, {}
    if len(pt) == 0:
        return 0.0, {}
    v, mode = float(tol["value"]), tol.get("mode", "abs")
    floor = float(tol.get("floor", 0.0))
    tot = 0.0
    for t, y in zip(gt_t, gt_y):
        if t < pt[0] - 1e-9 or t > pt[-1] + 1e-9:
            continue
        p = float(np.interp(t, pt, py))
        tau = v if mode == "abs" else max(abs(y) * v, floor, 1e-12)
        tot += s_of_e(abs(p - y) / tau)
    return tot / len(gt_t), {}


def score_edges(pred, gt, tol):
    directed = bool(tol.get("directed", False))

    def norm(es):
        out = set()
        for e in es or []:
            if not isinstance(e, (list, tuple)) or len(e) != 2:
                continue
            a, b = str(e[0]).strip().lower(), str(e[1]).strip().lower()
            out.add((a, b) if directed else tuple(sorted((a, b))))
        return out
    if isinstance(pred, dict) and "rows" in pred:
        pred = [r[:2] for r in pred["rows"]]
    G, P = norm(gt), norm(pred)
    if not G and not P:
        return 1.0, {}
    tp = len(G & P)
    if tp == 0:
        return 0.0, {"tp": 0, "n_gt": len(G), "n_pred": len(P)}
    pr, rc = tp / len(P), tp / len(G)
    return 2 * pr * rc / (pr + rc), {"tp": tp, "n_gt": len(G), "n_pred": len(P)}


def score_struct(pred, gt, tol, pred_dir=None, gt_dir=None):
    try:
        gt = resolve(gt, gt_dir)
    except Exception as e:
        return 0.0, {"error": "gt: " + str(e)[:200]}
    try:
        pred = resolve(pred, pred_dir)
    except Exception as e:
        return 0.0, {"error": "pred: " + str(e)[:200]}
    if pred is None:
        return 0.0, {}
    f = {"trajectory": score_trajectory, "polyline": score_polyline, "mask": score_mask,
         "timeseries": score_timeseries, "edges": score_edges}[tol["type"]]
    try:
        return f(pred, gt, tol)
    except Exception as e:
        return 0.0, {"error": type(e).__name__ + ": " + str(e)[:200]}