File size: 6,265 Bytes
f877698
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
 
 
 
 
 
2ad60ce
 
 
 
 
 
f877698
2ad60ce
 
 
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from pathlib import Path

import numpy as np

Z_MAX_M = 75.0
SKY_THRESHOLD = 128
MAX_TIME_OFFSET_MS = 50.0
MIN_NATIVE_CELLS = 2000
GRID = (518, 294)
DEPTH_FILE = 'depth.h5'
SKY_FILE = 'sky.h5'


def eval_mask(gt, valid, sky=None, z_max=Z_MAX_M):
    gt = np.asarray(gt)
    mask = np.asarray(valid, bool) & np.isfinite(gt)
    with np.errstate(invalid='ignore'):
        mask &= (gt > 0) & (gt <= z_max)
    if sky is not None:
        mask &= ~np.asarray(sky, bool)
    return mask


def missing_mask(pred, alpha, eps):
    missing = ~np.isfinite(pred)
    if alpha is not None:
        alpha = np.asarray(alpha, np.float64)
        with np.errstate(invalid='ignore'):
            missing |= ~(np.isfinite(alpha) & (alpha > eps))
    return missing


def frame_drmse(pred, gt, mask, *, alpha=None, eps):
    mask = np.asarray(mask, bool)
    n = int(mask.sum())
    if n == 0:
        raise ValueError('Frame has no valid GT pixel; it must be excluded')
    g = np.asarray(gt, np.float64)[mask]
    g_mean = float(g.mean())
    sigma = float(np.sqrt(np.mean((g - g_mean) ** 2)))
    if pred is None:
        missing = np.ones(n, bool)
        p = np.zeros(n)
    else:
        p = np.asarray(pred, np.float64)[mask]
        missing = missing_mask(p, None if alpha is None else np.asarray(alpha)[mask], eps)
    fit = ~missing
    n_fit = int(fit.sum())
    a, b, rank = 0., g_mean, 0
    if n_fit == 0:
        status = 'all_missing'
        sq_fit = 0.
    else:
        pf, gf = p[fit], g[fit]
        if n_fit >= 2:
            design = np.stack([pf, np.ones_like(pf)], axis=1)
            coef, _, rank, _ = np.linalg.lstsq(design, gf, rcond=None)
            rank = int(rank)
        if n_fit >= 2 and rank == 2:
            a, b = float(coef[0]), float(coef[1])
            status = 'fit'
        else:
            a, b = 0., float(gf.mean())
            status = 'degenerate'
        sq_fit = float(np.sum((a * pf + b - gf) ** 2))
    sq_missing = float(np.sum((g[missing] - g_mean) ** 2))
    value = float(np.sqrt((sq_fit + sq_missing) / n))
    return {'value': value, 'a': a, 'b': b, 'rank': rank, 'status': status, 'n_valid': n,
            'n_missing': int(missing.sum()), 'n_fit': n_fit, 'sigma_gt': sigma, 'gt_mean': g_mean,
            'a_nonpositive': bool(status == 'fit' and a <= 0)}


def frame_metrics(pred, gt, mask, *, alpha=None, eps):
    mask = np.asarray(mask, bool)
    fit = frame_drmse(pred, gt, mask, alpha=alpha, eps=eps)
    gt = np.asarray(gt, np.float64)
    missing = np.ones(mask.shape, bool) if pred is None else missing_mask(np.asarray(pred), alpha, eps)
    prediction = np.zeros_like(gt) if pred is None else np.asarray(pred, np.float64)
    aligned = fit['a'] * np.where(missing, 0., prediction) + fit['b']
    relative = np.abs(aligned-gt) / np.where(mask, gt, 1.)
    present = mask & ~missing
    return dict(fit=fit, rmse=fit['value'], absrel=float(relative[present].mean()) if present.any() else None)


def aggregate(frames):
    selected = [frame for frame in frames if frame is not None]
    out = {}
    for metric in ('rmse', 'absrel'):
        values = [frame[metric] for frame in selected if frame[metric] is not None]
        out[metric] = sum(values)/len(values) if values else None
    return out


def upsample_index(src: int, dst: int) -> np.ndarray:
    return np.minimum(np.floor(np.arange(dst) * (src / dst)).astype(np.int64), src - 1)


def upsample_nearest(quarter: np.ndarray, width=GRID[0], height=GRID[1]) -> np.ndarray:
    iy, ix = upsample_index(quarter.shape[-2], height), upsample_index(quarter.shape[-1], width)
    return quarter[..., iy[:, None], ix[None, :]]


def native_cells_in_v(V, native_shape) -> int:
    h, w = native_shape
    iy, ix = upsample_index(h, V.shape[-2]), upsample_index(w, V.shape[-1])
    return int(len(np.unique((iy[:, None] * w + ix[None, :])[V])))


def frame_reasons(offset_us, cells) -> list:
    reasons = []
    if abs(offset_us) / 1e3 > MAX_TIME_OFFSET_MS:
        reasons.append(f'time_offset_ms={offset_us / 1e3:.2f}')
    if cells < MIN_NATIVE_CELLS:
        reasons.append(f'native_cells_in_V={cells}')
    return reasons


class DepthLabels:
    def __init__(self, root, sky_root, sources):
        self.root, self.sky_root = Path(root), Path(sky_root)
        self.sources = tuple(sources)
        self._source_of = {}

    def source_of(self, scene_id):
        if scene_id not in self._source_of:
            found = [s for s in self.sources if (self.root / s / scene_id / DEPTH_FILE).is_file()]
            if len(found) > 1:
                raise ValueError(f'scene {scene_id} labelled under several sources {found}')
            self._source_of[scene_id] = found[0] if found else None
        return self._source_of[scene_id]

    def path(self, scene_id):
        return self.root / self.source_of(scene_id) / scene_id / DEPTH_FILE

    def sky_path(self, scene_id):
        return self.sky_root / self.source_of(scene_id) / scene_id / SKY_FILE

    def has_scene(self, scene_id):
        source = self.source_of(scene_id)
        return source is not None and (self.sky_root / source / scene_id / SKY_FILE).is_file()

    @staticmethod
    def _rows(f, indices):
        stored = f['frame_indices'][:]
        lookup = {int(k): i for i, k in enumerate(stored)}
        return [lookup[int(i)] for i in indices]

    def read(self, scene_id, indices) -> dict:
        import h5py
        indices = [int(i) for i in indices]
        with h5py.File(self.path(scene_id), 'r') as f:
            rows = self._rows(f, indices)
            native = np.stack([f['depth'][r] for r in rows]).astype(np.float32)
            offset = np.asarray([f['scan_time_offset_us'][r] for r in rows], np.float64)
        with h5py.File(self.sky_path(scene_id), 'r') as f:
            rows = self._rows(f, indices)
            sky = np.stack([f['sky'][r] for r in rows]) >= SKY_THRESHOLD
        depth = upsample_nearest(native, GRID[0], GRID[1])
        valid = np.isfinite(depth) & (depth > 0)
        V = np.stack([eval_mask(depth[k], valid[k], sky[k]) for k in range(len(indices))])
        return {'native': native, 'depth_z_m': depth, 'valid': valid, 'eval_valid': V, 'sky': sky,
                'scan_time_offset_us': offset}