File size: 5,852 Bytes
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
from __future__ import annotations

from pathlib import Path
import re

import numpy as np

GRID_HW = (294, 518)
CONTEXT = (0, 5, 10, 15)
GT_FOLDER = 'ground_truth'
GT_DATASET = 'occluder_policy_hard'
VISIBILITY = 'gt_visibility_v2'


def safe_id(value):
    if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9_.-]+', value) or value in ('.', '..'):
        raise ValueError('unsafe source / scene / clip identity')
    return value


def source_of(clip):
    source = clip.get('source_id') or clip.get('source') or clip.get('sample_key', {}).get('source_id')
    if source is None:
        dataset = clip.get('sample_key', {}).get('dataset_id', '')
        source = {'dcgaussian_native_pinhole_v1': 'nurec', 'waymo': 'waymo', 'waymo_front_crop169_v1': 'waymo',
                  'nuscenes': 'nuscenes', 'nuscenes_cam_front_v1': 'nuscenes', 'nuscenes_front_v1': 'nuscenes'}.get(dataset)
    if source is None:
        raise ValueError('clip must carry source_id')
    return safe_id(source)


def checked_binary(array, shape):
    array = np.asarray(array)
    if array.shape != shape or not np.isin(array, (0, 1)).all():
        raise ValueError(f'expected binary scoring mask {shape}, got {array.shape}')
    return array.astype(bool)


class PolicyLabels:
    def __init__(self, data_root, folder=GT_FOLDER, dataset=GT_DATASET):
        self.root = Path(data_root) / 'masks' / folder
        self.folder, self.dataset = folder, dataset

    def read(self, source, scene, frames):
        import h5py
        source, scene = safe_id(source), safe_id(scene)
        path = self.root / source / scene / 'mask.h5'
        with h5py.File(path, 'r') as handle:
            if any(int(frame) != frame or frame < 0 for frame in frames):
                raise ValueError('mask frames must be nonnegative native frame indices')
            if handle[self.dataset].ndim == 2:
                if not handle.attrs.get('static_across_frames', False):
                    raise ValueError('2D mask requires the static_across_frames attribute')
                plane = checked_binary(handle[self.dataset][:], GRID_HW)
                masks = np.broadcast_to(plane, (len(frames), *GRID_HW)).copy()
            else:
                indices = handle['frame_indices'][:]
                if len(indices) != len(set(map(int, indices))):
                    raise ValueError('duplicate mask frames')
                lookup = {int(frame): i for i, frame in enumerate(indices)}
                masks = np.stack([handle[self.dataset][lookup[int(frame)]] for frame in frames])
        masks = checked_binary(masks, (len(frames), *GRID_HW))
        return masks, dict(folder=self.folder, dataset=self.dataset, file=f'masks/{self.folder}/{source}/{scene}/mask.h5')


class MaskProvider:
    def __init__(self, data_root, folder=GT_FOLDER):
        self.reader = PolicyLabels(data_root, folder)

    def load(self, clip):
        frames = clip['frame_indices']
        masks, identity = self.reader.read(source_of(clip), clip['scene_id'], frames)
        return checked_binary(masks, (len(frames), *GRID_HW)), identity


class VisibilityProvider:
    def __init__(self, data_root, version=VISIBILITY):
        self.version = version
        self.root = Path(data_root) / 'labels' / version
        self.policy = PolicyLabels(data_root)

    def unavailable(self, clip):
        from agt.data.store import read_unavailable
        entries = read_unavailable(self.root / source_of(clip))
        scene = safe_id(clip['scene_id'])
        if scene not in entries:
            return None
        return dict(version=self.version, status='unavailable_for_scene', reason=entries[scene].get('reason'))

    def load(self, clip):
        import h5py
        count = len(clip['frame_indices'])
        source, scene = source_of(clip), safe_id(clip['scene_id'])
        if self.unavailable(clip) is not None:
            from agt.data.store import read_unavailable, unavailable_error
            raise unavailable_error('gt_visibility', self.version, source, [scene],
                                    read_unavailable(self.root / source), self.root / source)
        path = self.root / source / (scene + '.h5')
        contexts = clip.get('context_positions', list(CONTEXT))
        if contexts != list(CONTEXT):
            raise ValueError('visibility requires the four protocol contexts')
        frames = clip['frame_indices']
        sources = [int(frames[p]) for p in contexts]
        result = np.zeros((count, *GRID_HW), bool)
        policy, _ = self.policy.read(source, scene, frames)
        with h5py.File(path, 'r') as handle:
            if not handle.attrs.get('complete', False):
                raise ValueError(f'{path}: incomplete visibility file')
            offsets = list(map(int, handle['offsets'][:]))
            if handle['strict'].shape[1:] != (len(offsets), (np.prod(GRID_HW)+7)//8) or handle['strict'].dtype != np.uint8:
                raise ValueError(f'{path}: packed shape / dtype mismatch')
            stored = {int(f): i for i, f in enumerate(handle['frame_indices'][:])}
            for i, frame in enumerate(frames):
                row = stored[int(frame)]
                for src in sources:
                    if src == frame:
                        result[i] |= ~policy[i]
                        continue
                    offset = src - int(frame)
                    if offset not in offsets:
                        raise ValueError(f'input frame offset {offset} outside the stored +-{max(offsets)} offsets')
                    bits = np.unpackbits(handle['strict'][row, offsets.index(offset)], bitorder='little',
                                         count=GRID_HW[0] * GRID_HW[1]).reshape(GRID_HW)
                    result[i] |= bits.astype(bool)
        return result, dict(version=self.version, offsets=offsets)