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

import numpy as np

from .protocol import ClipProtocol, ROLE_CONTEXT, ROLE_EXTRAP, ROLE_INTERP, US

RULE_NO_FRAME = 'no_frame_within_tolerance'
RULE_SAME_FRAME = 'same_frame_picked_twice'


class FrameSelectionError(ValueError):
    def __init__(self, message, *, rules=(), max_error_us=float('nan'), tolerance_us=float('nan')):
        super().__init__(message)
        self.rules, self.max_error_us, self.tolerance_us = tuple(rules), float(max_error_us), float(tolerance_us)


def frame_times(frames_meta) -> dict:
    start = np.asarray([row['timestamp_start_us'] for row in frames_meta], dtype=np.int64)
    end = np.asarray([row['timestamp_end_us'] for row in frames_meta], dtype=np.int64)
    if len(start) < 2 or not np.all(np.diff(start) > 0) or np.any(end < start):
        raise ValueError('Frame timestamps must be strictly increasing with end >= start')
    mid = (start.astype(np.float64) + end) / 2
    elapsed = mid - mid[0]
    period = float(elapsed[-1] / (len(elapsed) - 1))
    return {'start_us': start, 'end_us': end, 'mid_us': mid, 'elapsed_us': elapsed, 'period_us': period,
            'duration_us': period * len(elapsed)}


def nearest_frames(elapsed_us: np.ndarray, targets_us) -> tuple:
    targets = np.asarray(targets_us, dtype=np.float64)
    right = np.clip(np.searchsorted(elapsed_us, targets), 1, len(elapsed_us) - 1)
    left = right - 1
    pick = np.where(np.abs(elapsed_us[left] - targets) <= np.abs(elapsed_us[right] - targets), left, right)
    return pick.astype(np.int64), np.abs(elapsed_us[pick] - targets)


def selection_tolerance_us(period_us: float, tolerance_us: float | None = None) -> float:
    return float(period_us) / 2 if tolerance_us is None else float(tolerance_us)


def select_frames(elapsed_us: np.ndarray, targets_us, period_us: float, tolerance_us: float | None = None) -> tuple:
    tol = selection_tolerance_us(period_us, tolerance_us)
    targets = np.asarray(targets_us, dtype=np.float64)
    pick, error = nearest_frames(elapsed_us, targets)
    far = error > tol
    rules = ([RULE_NO_FRAME] if np.any(far) else []) + ([RULE_SAME_FRAME] if np.any(np.diff(pick) <= 0) else [])
    if rules:
        if far.any():
            where = 'half a period' if tolerance_us is None else f'the declared tolerance {tol / 1e3:g} ms'
            message = f'No frame within {where} of {targets[far] / US} s'
            if RULE_SAME_FRAME in rules:
                message += '; two samples map to one frame'
        else:
            message = 'Sampling rate exceeds the frame rate: two samples map to one frame'
        raise FrameSelectionError(message, rules=rules, max_error_us=float(error.max()), tolerance_us=tol)
    return pick, float(error.max())


def build_clips(protocol: ClipProtocol, record, frames_meta, *, sample_id: str | None = None,
                skipped: list | None = None, tolerance_us: float | None = None) -> list:
    T = int(record.frame_count)
    if len(frames_meta) != T:
        raise ValueError(f'{record.scene_id}: frames.jsonl has {len(frames_meta)} rows, record says {T}')
    times = frame_times(frames_meta)
    sample_id = sample_id or record.scene_id
    offsets, roles = np.asarray(protocol.offsets_us()), list(protocol.roles())
    ctx_pos = [i for i, r in enumerate(roles) if r == ROLE_CONTEXT]
    clips = []
    for start_us in protocol.window_starts_us(times['duration_us'], times['period_us']):
        try:
            idx, error = select_frames(times['elapsed_us'], start_us + offsets, times['period_us'], tolerance_us)
        except FrameSelectionError as exc:
            if skipped is None:
                raise
            skipped.append({'sample_id': sample_id, 'scene_id': record.scene_id,
                            'source_id': getattr(record, 'source_id', None), 'window_start_s': start_us / US,
                            'reason': str(exc), 'rules': list(exc.rules), 'max_error_us': exc.max_error_us,
                            'tolerance_us': exc.tolerance_us})
            continue
        mid = times['mid_us'][idx]
        t0, t1 = mid[ctx_pos[0]], mid[ctx_pos[-1]]
        if t1 <= t0:
            raise ValueError('Context span must be positive')
        idx_list = idx.tolist()
        clips.append({
            'clip_id': f'{sample_id}__w{idx_list[0]}',
            'sample_id': sample_id,
            'sample_key': dict(zip(('dataset_id', 'scene_id', 'camera_id', 'variant_id'), record.sample_key)),
            'scene_id': record.scene_id,
            'protocol_id': protocol.protocol_id,
            'protocol_name': protocol.name,
            'window_mode': protocol.window_mode,
            'group': record.group, 'time_of_day': record.time_of_day, 'template_id': record.template_id,
            'source_id': record.source_id, 'map_version': record.map_version,
            'window_start_s': start_us / US,
            'window_start_frame': idx_list[0],
            'frame_indices': idx_list,
            'roles': roles,
            'is_keyframe': [r == ROLE_CONTEXT for r in roles],
            'context_frames': [i for i, r in zip(idx_list, roles) if r == ROLE_CONTEXT],
            'interp_frames': [i for i, r in zip(idx_list, roles) if r == ROLE_INTERP],
            'extrap_frames': [i for i, r in zip(idx_list, roles) if r == ROLE_EXTRAP],
            'heldout_frames': [i for i, r in zip(idx_list, roles) if r in (ROLE_INTERP, ROLE_EXTRAP)],
            'timestamps_us': mid.tolist(),
            'timestamps_start_us': times['start_us'][idx].tolist(),
            't_norm': ((mid - t0) / (t1 - t0)).tolist(),
            'selection_max_error_us': error,
        })
    if len({c['clip_id'] for c in clips}) != len(clips):
        raise ValueError('Duplicate clip ids')
    return clips