File size: 3,920 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Dashboard physical-distance metrics and per-clip non-metric scale fitting."""

from __future__ import annotations

import numpy as np

from evaluation.ucpe_inputs import ClipLabels

THRESHOLDS_M = (0.05, 0.10, 0.20, 0.40)


def score_tracks(
    labels: ClipLabels,
    tracks: np.ndarray,
    visibility: np.ndarray,
    *,
    evaluation_mask: np.ndarray | None = None,
) -> dict:
    gt = labels.tracks_target_camera
    visible = labels.visibility.astype(bool)
    known = (
        np.ones_like(visible)
        if labels.visibility_known is None
        else labels.visibility_known.astype(bool)
    )
    if (
        gt.shape != tracks.shape
        or visible.shape != visibility.shape
        or known.shape != visible.shape
    ):
        raise ValueError("Prediction, label and visibility shapes differ")
    if bool((visible & ~known).any()):
        raise ValueError("Every visible observation must have known visibility")
    if evaluation_mask is not None:
        if evaluation_mask.shape != visible.shape:
            raise ValueError("Evaluation mask and visibility shapes differ")
        known = known & evaluation_mask.astype(bool)
        visible = visible & evaluation_mask.astype(bool)
    predicted_visible = np.isfinite(visibility) & (visibility > 0.5)
    oa = (
        100.0 * float((predicted_visible == visible)[known].mean())
        if known.any()
        else None
    )
    joint = visible & predicted_visible
    scale = None
    if joint.any():
        gt_norm = np.sqrt(np.maximum(1e-12, np.sum(np.square(gt), axis=-1)))
        pred_norm = np.sqrt(np.maximum(1e-12, np.sum(np.square(tracks), axis=-1)))
        numerator, denominator = (
            float(np.median(gt_norm[joint])),
            float(np.median(pred_norm[joint])),
        )
        if np.isfinite(numerator) and np.isfinite(denominator):
            scale = numerator / denominator
    result = {"non_metric_scale": scale}
    for mode, predicted in (
        ("metric", tracks),
        ("non_metric", None if scale is None else tracks * scale),
    ):
        scores = {"aj": None, "apd": None, "oa": oa, "epe": None}
        if predicted is not None and visible.any():
            distance = np.linalg.norm(predicted - gt, axis=-1)
            finite = distance[visible]
            finite = finite[np.isfinite(finite)]
            scores["epe"] = 100.0 * float(finite.mean()) if len(finite) else None
            aj, apd = [], []
            for threshold in THRESHOLDS_M:
                within = distance < threshold
                correct = within & visible
                apd.append(100.0 * float(correct.sum()) / int(visible.sum()))
                tp = correct & predicted_visible
                fp = predicted_visible & (~visible | ~within) & known
                aj.append(
                    100.0 * float(tp.sum()) / (int(visible.sum()) + int(fp.sum()))
                )
            scores.update(aj=float(np.mean(aj)), apd=float(np.mean(apd)))
        result[mode] = scores
    return result


def aggregate_cells(cells: list[dict]) -> list[dict]:
    groups = {}
    for cell in cells:
        for source, scores in cell["scores"].items():
            for scale_mode in ("metric", "non_metric"):
                key = cell["dataset"], cell["views"], cell["camera"], source, scale_mode
                groups.setdefault(key, []).append(scores[scale_mode])
    return [
        dict(
            dataset=key[0],
            views=key[1],
            camera=key[2],
            position_source=key[3],
            scale_mode=key[4],
            clips=len(values),
            **{
                metric: float(np.mean([value[metric] for value in values]))
                if all(value[metric] is not None for value in values)
                else None
                for metric in ("aj", "apd", "oa", "epe")
            },
        )
        for key, values in sorted(groups.items())
    ]