File size: 5,090 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build the FOV-limited object bank for every SimLingo route (stage-3 object tokens + relation labels).

For each route the bank is replayed frame by frame over boxes/*.json.gz (4 Hz) and written to
<data_root>/object_bank/simlingo/<...>/<route>/objects.npz with
  raw      [F, N, RAW_DIM] float16   object rows in the ego frame of that frame (see dataloader.object_bank)
  ids      [F, N] int32              CARLA actor id (negative: id-less static matched by position), 0 = padding
  relation [F, N] int8               0 ignore / 1 follow / 2 yield, -100 padding
  count    [F] int16

Usage: python scripts/build_object_bank.py [--data-root simlingo_data] [--workers 192] [--limit N]
"""
import argparse
import glob
import gzip
import json
import os
import sys
import time
from multiprocessing import Pool
from pathlib import Path

import numpy as np
import ujson

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from dataloader.object_bank import (  # noqa: E402
    DEFAULT_BANK, RAW_DIM, ObjectBank, observations_from_simlingo_boxes, relation_labels,
)

FRAME_DT = 0.25  # SimLingo logs are stored at 4 Hz


def output_path(route_dir, data_root):
    rel = Path(route_dir).relative_to(Path(data_root) / "data")
    return Path(data_root) / "object_bank" / rel / "objects.npz"


def build_route(args):
    route_dir, data_root, bank_kwargs = args
    out = output_path(route_dir, data_root)
    if out.exists():
        return route_dir, "skipped", None
    box_files = sorted(glob.glob(f"{route_dir}/boxes/*.json.gz"))
    if not box_files:
        return route_dir, "no_boxes", None
    bank = ObjectBank(**bank_kwargs)
    n = bank.max_objects
    raw_all = np.zeros((len(box_files), n, RAW_DIM), dtype=np.float16)
    ids_all = np.zeros((len(box_files), n), dtype=np.int32)
    rel_all = np.full((len(box_files), n), -100, dtype=np.int8)
    count_all = np.zeros(len(box_files), dtype=np.int16)
    stats = np.zeros(4, dtype=np.int64)  # frames, objects, follow, yield
    try:
        for f, box_file in enumerate(box_files):
            frame = int(Path(box_file).name.split(".")[0])
            with gzip.open(box_file, "rt") as fh:
                boxes = ujson.load(fh)
            with gzip.open(f"{route_dir}/measurements/{frame:04d}.json.gz", "rt") as fh:
                measurement = ujson.load(fh)
            ego_matrix = np.asarray(measurement["ego_matrix"], dtype=np.float64)
            observations = observations_from_simlingo_boxes(boxes, ego_matrix)
            raw, ids, count = bank.step(frame * FRAME_DT, ego_matrix, observations)
            labels = relation_labels(ids, count, measurement)
            raw_all[f] = raw
            ids_all[f] = ids
            rel_all[f] = labels
            count_all[f] = count
            stats += (1, count, int((labels == 1).sum()), int((labels == 2).sum()))
    except Exception as exc:  # keep the pool alive; report the route
        return route_dir, f"error: {type(exc).__name__}: {exc}", None
    out.parent.mkdir(parents=True, exist_ok=True)
    tmp = out.with_suffix(".tmp.npz")
    np.savez(tmp, raw=raw_all, ids=ids_all, relation=rel_all, count=count_all,
             frame_dt=np.float32(FRAME_DT), bank=np.array(json.dumps(bank_kwargs)))
    os.replace(tmp, out)
    return route_dir, "built", stats


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data-root", default="simlingo_data")
    ap.add_argument("--workers", type=int, default=max(1, min(192, (os.cpu_count() or 2) - 8)))
    ap.add_argument("--limit", type=int, default=0, help="only the first N routes (smoke test)")
    for key, value in DEFAULT_BANK.items():
        ap.add_argument(f"--{key.replace('_', '-')}", type=type(value), default=value)
    args = ap.parse_args()
    bank_kwargs = {key: getattr(args, key) for key in DEFAULT_BANK}
    data_root = str(Path(args.data_root).resolve())
    routes = sorted(glob.glob(f"{data_root}/data/simlingo/*/*/*/Town*"))
    if args.limit:
        routes = routes[: args.limit]
    print(f"{len(routes)} routes, {args.workers} workers, bank={bank_kwargs}", flush=True)
    t0 = time.time()
    totals = np.zeros(4, dtype=np.int64)
    status = {}
    errors = []
    with Pool(args.workers) as pool:
        for i, (route, state, stats) in enumerate(pool.imap_unordered(
                build_route, [(r, data_root, bank_kwargs) for r in routes], chunksize=2), 1):
            key = state.split(":")[0]
            status[key] = status.get(key, 0) + 1
            if stats is not None:
                totals += stats
            if key == "error":
                errors.append((route, state))
            if i % 500 == 0 or i == len(routes):
                print(f"[{i}/{len(routes)}] {time.time() - t0:.0f}s {status}", flush=True)
    frames, objects, follow, yield_ = (int(v) for v in totals)
    print(f"frames {frames}, objects/frame {objects / max(frames, 1):.2f}, "
          f"follow labels {follow}, yield labels {yield_}", flush=True)
    for route, state in errors[:20]:
        print("ERROR", route, state)


if __name__ == "__main__":
    main()