File size: 7,421 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
 
 
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
from __future__ import annotations

from dataclasses import dataclass, field, fields
import hashlib
import json
from pathlib import Path

SCHEMA = 'clip_protocol_v1'
PROTOCOL_DIR = Path(__file__).resolve().parent / 'protocols'

GRID_518x294 = {
    'width': 518,
    'height': 294,
    'geometry': 'direct_anisotropic_full_frame',
    'resampler': 'torch_interpolate_bilinear_antialias_align_corners_false_cpu_float32',
    'rgb_quantization': 'u8_div255_float32_resize_then_floor_clip01_times255_plus0.5',
    'mask_threshold': 0.5,
}

WINDOW_MODES = ('full', 'partial', 'list')
ROLE_CONTEXT, ROLE_INTERP, ROLE_EXTRAP, ROLE_PRE = 'context', 'interp', 'extrap', 'pre'
FRAME_SETS = ('heldout', 'interp', 'extrap', 'recon')
US = 1_000_000


def _us(seconds) -> int:
    value = round(float(seconds) * US)
    if abs(value - float(seconds) * US) > 1e-3:
        raise ValueError(f'{seconds} s is not a whole number of microseconds')
    return int(value)


@dataclass(frozen=True)
class ClipProtocol:
    name: str = 'clips'
    version: str = '1'
    schema: str = SCHEMA
    window_s: float = 2.0
    sample_hz: float = 10.0
    context_s: tuple = (0.0, 0.5, 1.0, 1.5)
    window_mode: str = 'full'
    window_starts_s: tuple | None = None
    full_first_s: float = 0.0
    partial_starts_s: tuple = (0.0, 9.0)
    partial_last_s: float = 17.97
    duration_rule: str = 'T = frame_count * mean_frame_period; window fits if start + window_s <= T + period/2'
    frame_selection: str = 'nearest_exposure_midpoint_within_half_mean_frame_period'
    frame_time: str = 'exposure_midpoint'
    pose_time: str = 'exposure_midpoint'
    pose_reference: str = 'first_context_frame'
    t_norm: str = '(t - t_context_first) / (t_context_last - t_context_first)'
    grid: dict = field(default_factory=lambda: dict(GRID_518x294))

    def __post_init__(self):
        if self.schema != SCHEMA:
            raise ValueError('Unknown protocol schema: ' + str(self.schema))
        context = tuple(float(c) for c in self.context_s)
        object.__setattr__(self, 'context_s', context)
        object.__setattr__(self, 'partial_starts_s', tuple(float(s) for s in self.partial_starts_s))
        if self.window_starts_s is not None:
            object.__setattr__(self, 'window_starts_s', tuple(float(s) for s in self.window_starts_s))
        if self.window_s <= 0 or self.sample_hz <= 0:
            raise ValueError('window_s and sample_hz must be positive')
        n = self.window_s * self.sample_hz
        if abs(n - round(n)) > 1e-9:
            raise ValueError('window_s * sample_hz must be an integer number of samples')
        offsets = self.offsets_us()
        ctx = [_us(c) for c in context]
        if len(ctx) < 2 or ctx != sorted(set(ctx)):
            raise ValueError('context_s must hold >= 2 distinct increasing times')
        if any(c not in offsets for c in ctx):
            raise ValueError('context times must lie on the sampling lattice inside the window')
        if self.window_mode not in WINDOW_MODES:
            raise ValueError(f'window_mode must be one of {WINDOW_MODES}')
        if self.window_mode == 'list':
            starts = [_us(s) for s in self.window_starts_s or ()]
            if not starts or starts != sorted(set(starts)) or starts[0] < 0:
                raise ValueError('window_mode=list needs distinct, increasing, nonnegative window_starts_s')
        elif self.window_starts_s is not None:
            raise ValueError('window_starts_s is only used with window_mode=list')
        for key in ('width', 'height', 'geometry', 'resampler', 'rgb_quantization', 'mask_threshold'):
            if key not in self.grid:
                raise ValueError('grid needs ' + key)

    def n_samples(self) -> int:
        return int(round(self.window_s * self.sample_hz))

    def offsets_us(self) -> tuple:
        return tuple(int(round(j * US / self.sample_hz)) for j in range(self.n_samples()))

    def context_us(self) -> tuple:
        return tuple(_us(c) for c in self.context_s)

    def roles(self) -> tuple:
        ctx = self.context_us()
        first, last = ctx[0], ctx[-1]
        out = []
        for o in self.offsets_us():
            if o in ctx:
                out.append(ROLE_CONTEXT)
            elif o < first:
                out.append(ROLE_PRE)
            elif o < last:
                out.append(ROLE_INTERP)
            else:
                out.append(ROLE_EXTRAP)
        return tuple(out)

    def frame_set_positions(self, which: str) -> list:
        roles = self.roles()
        wanted = {'heldout': (ROLE_INTERP, ROLE_EXTRAP), 'interp': (ROLE_INTERP,),
                  'extrap': (ROLE_EXTRAP,), 'recon': (ROLE_CONTEXT,)}[which]
        return [i for i, r in enumerate(roles) if r in wanted]

    def window_starts_us(self, duration_us: float, period_us: float) -> list:
        W = _us(self.window_s)
        tol = period_us / 2

        def fits(start):
            return start >= 0 and start + W <= duration_us + tol

        if self.window_mode == 'full':
            starts, s = [], _us(self.full_first_s)
            while fits(s):
                starts.append(s)
                s += W
        elif self.window_mode == 'partial':
            last = min(_us(self.partial_last_s), int(round(duration_us - W)))
            starts = [_us(s) for s in self.partial_starts_s] + [last]
            if starts != sorted(set(starts)):
                raise ValueError('partial windows collapse or reorder for this duration')
        else:
            starts = [_us(s) for s in self.window_starts_s]
        bad = [s for s in starts if not fits(s)]
        if bad or not starts:
            raise ValueError(f'windows {bad or "none"} do not fit a {duration_us/US:.4f} s scene')
        return starts

    def to_dict(self) -> dict:
        d = {f.name: getattr(self, f.name) for f in fields(self)}
        for key in ('context_s', 'partial_starts_s', 'window_starts_s'):
            if d[key] is not None:
                d[key] = list(d[key])
        d['grid'] = dict(self.grid)
        return d

    def canonical_json(self) -> str:
        return json.dumps(self.to_dict(), sort_keys=True, separators=(',', ':'), ensure_ascii=False)

    @property
    def protocol_id(self) -> str:
        return hashlib.sha256(self.canonical_json().encode('utf-8')).hexdigest()

    @property
    def short_id(self) -> str:
        return self.protocol_id[:12]

    @classmethod
    def from_dict(cls, value: dict) -> 'ClipProtocol':
        known = {f.name for f in fields(cls)}
        unknown = set(value) - known
        if unknown:
            raise ValueError(f'Unknown protocol fields: {sorted(unknown)}')
        value = dict(value)
        for key in ('context_s', 'partial_starts_s', 'window_starts_s'):
            if value.get(key) is not None:
                value[key] = tuple(value[key])
        return cls(**value)

    @classmethod
    def load(cls, name_or_path='partial') -> 'ClipProtocol':
        path = Path(name_or_path)
        if not str(name_or_path).endswith('.json'):
            path = PROTOCOL_DIR / f'{name_or_path}.json'
        return cls.from_dict(json.loads(path.read_text()))

    def with_window_mode(self, mode: str, starts_s=None) -> 'ClipProtocol':
        d = self.to_dict()
        d['window_mode'] = mode
        d['window_starts_s'] = None if starts_s is None else list(starts_s)
        return ClipProtocol.from_dict(d)