File size: 5,406 Bytes
97ab756
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Ground-truth depth, flow and tracks of the synthetic cases, from their reference worlds.

Run from the root of the 4DCodeBench code release, after its environment is set up
and `python scripts/download_data.py --kind synthetic` has unpacked the worlds:

    python /path/to/extract_synthetic.py                         # every case under data/synthetic
    python /path/to/extract_synthetic.py B_01 G_03 --out gt      # some cases, another output root

Each case gets `<out>/<case>/` with the same files, keys and timeline as the real
cases' estimates, computed from the world's meshes and camera instead of a model:

    depth.h5     `depth (F', H, W)` float32 camera-space z in metres, `inf` where no
                 surface covers the pixel; `shape [F, H, W]`, `stride`, `fps`
    flow.h5      `flow (F'-1, H, W, 2)` float16 pixels from sampled frame k to k + 1,
                 `valid (F'-1, H, W)` bool, `stride`
    tracks.npz   `tracks (Q, F', 2)` float32 pixels, `visible (Q, F')` bool, the frame-0
                 queries `queries (Q, 3)` `(0, x, y)`, `on_mask`, `shape`, `step`, `stride`

Flow and tracks follow each surface point through the world: by its face and
barycentrics where the object keeps its topology, by the nearest material columns of
`dynamics/` where it does not (a liquid, a fracture). These are the scorer's own
`scorer.analytic` paths, the ones it reads every submission with. The query grid is
the benchmark's: dense on the frame-0 dynamic pixels, sparse over the whole frame.
Files already written are skipped, so an interrupted run resumes by running again.
"""

from __future__ import annotations

import argparse
import sys
import time
from pathlib import Path

import numpy as np


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("cases", nargs="*", help="case names (default: every world under --data)")
    ap.add_argument("--code", type=Path, default=Path("."), help="code release root (default: .)")
    ap.add_argument("--data", type=Path, default=None,
                    help="directory of <case>/world (default: <code>/data/synthetic)")
    ap.add_argument("--out", type=Path, default=Path("synthetic"), help="output root")
    args = ap.parse_args()

    sys.path.insert(0, str(args.code.resolve()))
    from config.estimates import DEPTH_FILENAME, FLOW_FILENAME, TRACKS_FILENAME
    from config.sampling import sampled_indices, stride_for
    from scorer.analytic.flow import frame_flow
    from scorer.analytic.tracks import DRIFT, grid_queries, grid_step, inside, track_points
    from scorer.raster import default_device, id_frame, rasterize_frame
    from scorer.storage import write_dense
    from scorer.world import World

    data = args.data or args.code / "data/synthetic"
    cases = args.cases or sorted(p.parent.name for p in data.glob("*/world"))
    device = default_device()

    for number, case in enumerate(cases, 1):
        out = args.out / case
        out.mkdir(parents=True, exist_ok=True)
        world = World(data / case / "world")
        stride = stride_for(world.frames)
        frames = sampled_indices(world.frames, stride)
        height, width = world.shape[1:]
        started = time.time()

        if not (out / DEPTH_FILENAME).exists():
            depth = np.stack([rasterize_frame(world, int(t), device)[0] for t in frames])
            write_dense(out / DEPTH_FILENAME, depth=depth.astype(np.float32),
                        shape=np.asarray(world.shape, dtype=np.int64),
                        stride=np.int64(stride), fps=np.float64(world.fps))

        if not (out / FLOW_FILENAME).exists():
            flows, valids = [], []
            for t in frames[:-1]:
                flow, valid, _ = frame_flow(world, int(t), device, stride=stride)
                flows.append(flow.cpu().numpy().astype(np.float16))
                valids.append(valid.cpu().numpy())
            write_dense(out / FLOW_FILENAME, flow=np.stack(flows), valid=np.stack(valids),
                        stride=np.int64(stride), model="ground_truth")

        if not (out / TRACKS_FILENAME).exists():
            mask = np.isin(id_frame(world, 0, device), world.dynamic_ids)
            mask = mask if mask.any() else None
            queries = grid_queries(height, width, mask=mask)
            on_mask = (inside(queries[:, 1:], mask) if mask is not None
                       else np.zeros(len(queries), dtype=bool))
            step = (grid_step(height, width, max(len(queries) - DRIFT, 1), mask)
                    if mask is not None else grid_step(height, width))
            tracks, visible = track_points(world, queries, device, stride=stride)
            np.savez_compressed(out / TRACKS_FILENAME, tracks=tracks.astype(np.float32),
                                visible=visible, queries=queries.astype(np.float32),
                                on_mask=on_mask,
                                shape=np.asarray([len(frames), height, width], dtype=np.int64),
                                step=np.int64(step), stride=np.int64(stride),
                                model="ground_truth")

        print(f"[{number}/{len(cases)}] {case}: {len(frames)} frames, "
              f"{time.time() - started:.0f}s", flush=True)


if __name__ == "__main__":
    main()