ConsDrive / scripts /analysis /recorder_extract.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
4.77 kB
"""Extract compact kinematics from CARLA recorder logs.
Usage: python recorder_extract.py --port 2000 --out-dir DIR log1.log [log2.log ...]
For each log writes DIR/<log stem>.npz with
hero: (T, 5) t, x, y, yaw_deg, speed
hero_ctrl: (T, 4) t, steer, throttle, brake
collisions: (K, 2) t, other_id (only collisions involving the hero)
actors: JSON string {id: type_id}
others: (N, 5) t, id, x, y, yaw_deg (vehicles/walkers within 80 m of the hero, 10 Hz)
Positions are in metres (the recorder stores centimetres).
"""
import argparse
import json
import math
import re
from pathlib import Path
import carla
import numpy as np
FRAME_RE = re.compile(r"^Frame \d+ at ([\d.]+) seconds")
CREATE_RE = re.compile(r"^ Create (\d+): (\S+) \(\d+\) at")
ATTR_RE = re.compile(r"^\s+role_name = (\S+)")
POS_RE = re.compile(r"^ Id: (\d+) Location: \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\) Rotation: \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\)")
CTRL_RE = re.compile(r"^ Id: (\d+) Steering: ([-+\d.e]+) Throttle: ([-+\d.e]+) Brake: ([-+\d.e]+)")
COLL_RE = re.compile(r"^ Collision id \d+ between (\d+)(?: \((\w+)\))?\s+with (\d+)(?: \((\w+)\))?")
KEEP_PREFIX = ("vehicle.", "walker.")
def extract(text):
types, roles = {}, {}
hero = None
frames = []
cur_create = None
t = None
pos, ctrl, colls = {}, {}, []
for line in text.splitlines():
m = FRAME_RE.match(line)
if m:
if t is not None:
frames.append((t, pos, ctrl))
t, pos, ctrl, cur_create = float(m.group(1)), {}, {}, None
continue
if line.startswith(" Id: "):
m = POS_RE.match(line)
if m:
pos[int(m.group(1))] = (float(m.group(2)) / 100, float(m.group(3)) / 100, float(m.group(7)))
continue
m = CTRL_RE.match(line)
if m:
ctrl[int(m.group(1))] = (float(m.group(2)), float(m.group(3)), float(m.group(4)))
continue
m = CREATE_RE.match(line)
if m:
cur_create = int(m.group(1))
types[cur_create] = m.group(2)
continue
m = ATTR_RE.match(line)
if m and cur_create is not None:
roles[cur_create] = m.group(1)
if m.group(1) == "hero" and types.get(cur_create, "").startswith("vehicle."):
hero = cur_create
continue
m = COLL_RE.match(line)
if m and t is not None:
a, b = int(m.group(1)), int(m.group(3))
colls.append((t, a, b))
if t is not None:
frames.append((t, pos, ctrl))
hero_rows, ctrl_rows, other_rows = [], [], []
last = None
next_other_t = -1.0
for t, pos, ctrl in frames:
if hero not in pos:
continue
x, y, yaw = pos[hero]
v = 0.0 if last is None or t <= last[0] else math.hypot(x - last[1], y - last[2]) / (t - last[0])
hero_rows.append((t, x, y, yaw, v))
last = (t, x, y)
if hero in ctrl:
ctrl_rows.append((t,) + ctrl[hero])
if t >= next_other_t:
next_other_t = t + 0.1 - 1e-6
for aid, (ax, ay, ayaw) in pos.items():
if aid == hero or not types.get(aid, "").startswith(KEEP_PREFIX):
continue
if math.hypot(ax - x, ay - y) < 80.0:
other_rows.append((t, aid, ax, ay, ayaw))
hero_colls = [(t, b if a == hero else a) for t, a, b in colls if hero in (a, b)]
return {
"hero": np.array(hero_rows, dtype=np.float64),
"hero_ctrl": np.array(ctrl_rows, dtype=np.float64).reshape(-1, 4),
"collisions": np.array(hero_colls, dtype=np.float64).reshape(-1, 2),
"others": np.array(other_rows, dtype=np.float64).reshape(-1, 5),
"actors": json.dumps({str(k): v for k, v in types.items()}),
"hero_id": hero,
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=2000)
ap.add_argument("--out-dir", required=True)
ap.add_argument("logs", nargs="+")
args = ap.parse_args()
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
client = carla.Client("localhost", args.port)
client.set_timeout(600.0)
for log in args.logs:
log = Path(log).resolve()
out = out_dir / (log.stem + ".npz")
if out.exists():
continue
data = extract(client.show_recorder_file_info(str(log), True))
np.savez_compressed(out, **data)
print(f"{log.stem}: hero={data['hero_id']} frames={len(data['hero'])} "
f"collisions={len(data['collisions'])} others={len(data['others'])}", flush=True)
if __name__ == "__main__":
main()