envship_v2_datasets / examples /baseline_constant_velocity.py
mark000071's picture
v2.1 super-squash
6cbe918
Raw
History Blame Contribute Delete
3.41 kB
#!/usr/bin/env python3
"""Constant-velocity baseline for EnvShip-Bench v2 (Track A).
Reads the paper-default filtered subset of one jurisdiction and reports
average and final displacement error in metres. This is the simplest
sanity-check predictor: assume each vessel keeps the velocity it had
at the last history point.
The same loader works for Track B — change the path and the trajectory
will be 90 + 180 points instead of 30 + 30.
Usage
-----
python examples/baseline_constant_velocity.py \\
--csv data/envship_v2/track_a_short-term_Cross-domain_Datasets/dma_track_v1/test/part-000.csv.gz
Expected output (DMA Track A test split, filtered):
samples: 14878
ADE: 87.4 m FDE: 184.2 m
"""
from __future__ import annotations
import argparse
import gzip
import json
import csv
import numpy as np
def load_split(csv_path: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Return (hist_xy, fut_xy, keep_mask).
Each row of the gzipped CSV holds:
- hist_x_json, hist_y_json (30 history points for Track A,
90 for Track B)
- fut_x_json, fut_y_json (30 / 180 future points)
Positions are metres relative to the trajectory anchor.
"""
hist_x, hist_y, fut_x, fut_y, keep = [], [], [], [], []
with gzip.open(csv_path, "rt", encoding="utf-8") as fh:
reader = csv.DictReader(fh)
has_flag = "osm_temporal_consistent" in (reader.fieldnames or [])
for row in reader:
hist_x.append(json.loads(row["hist_x_json"]))
hist_y.append(json.loads(row["hist_y_json"]))
fut_x.append(json.loads(row["fut_x_json"]))
fut_y.append(json.loads(row["fut_y_json"]))
keep.append(row.get("osm_temporal_consistent") == "true" if has_flag else True)
hist = np.stack([np.asarray(hist_x), np.asarray(hist_y)], axis=-1) # (N, T_hist, 2)
fut = np.stack([np.asarray(fut_x), np.asarray(fut_y)], axis=-1) # (N, T_fut, 2)
return hist, fut, np.asarray(keep, dtype=bool)
def constant_velocity_predict(hist: np.ndarray, n_fut: int) -> np.ndarray:
"""Extrapolate from the last two history points (last-step velocity)."""
v = hist[:, -1] - hist[:, -2] # (N, 2)
steps = np.arange(1, n_fut + 1) # (T_fut,)
return hist[:, -1:] + steps[None, :, None] * v[:, None, :]
def displacement_errors(pred: np.ndarray, target: np.ndarray) -> tuple[float, float]:
"""Per-step euclidean error, then ADE (mean across time) and FDE (last step)."""
d = np.linalg.norm(pred - target, axis=-1) # (N, T_fut)
return float(d.mean()), float(d[:, -1].mean())
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--csv", required=True,
help="path to <subset>/{split}/part-000.csv.gz")
ap.add_argument("--apply-default-filter", action="store_true", default=True,
help="drop rows where osm_temporal_consistent != 'true' (paper default)")
args = ap.parse_args()
hist, fut, keep = load_split(args.csv)
if args.apply_default_filter:
hist, fut = hist[keep], fut[keep]
n_fut = fut.shape[1]
pred = constant_velocity_predict(hist, n_fut)
ade, fde = displacement_errors(pred, fut)
print(f"samples: {len(fut)}")
print(f"ADE: {ade:.1f} m FDE: {fde:.1f} m")
if __name__ == "__main__":
main()