mark000071's picture
Add EnvShip-Voyage: long-term ship trajectory imputation dataset + full build pipeline + docs
b61a1c7 verified
Raw History Blame Contribute Delete
3.3 kB
"""Streaming environment loader for EnvShip-Voyage.
Reads the shared regional basemap (Zarr) lazily and samples per-point environmental features along
any trajectory — the streaming access pattern that replaces per-sample rasters. Also loads the
fairway distance field / network when present.
env = EnvLoader(basemap_dir)
df = env.sample_track(lat_array, lon_array) # -> DataFrame of env features per point
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
class EnvLoader:
def __init__(self, basemap_dir: str | Path):
import zarr
from pyproj import Transformer
self.dir = Path(basemap_dir)
self.meta = json.loads((self.dir / "basemap_meta.json").read_text())
a, b, c, d, e, f = self.meta["transform"]
self.transform = (a, b, c, d, e, f) # affine: x = a*col + b*row + c ; y = d*col + e*row + f
self.root = zarr.open_group(str(self.dir / "basemap.zarr"), mode="r")
self.to_metric = Transformer.from_crs("EPSG:4326", self.meta["crs"], always_xy=True)
self.H, self.W = self.meta["height"], self.meta["width"]
self._layers = {name: self.root[name] for name in self.meta["layers"]}
# fairway distance field (optional, added by S6)
fd = self.dir / "fairway_dist.zarr"
self.fairway = zarr.open_array(str(fd), mode="r") if fd.exists() else None
def _rowcol(self, lat, lon):
x, y = self.to_metric.transform(np.asarray(lon), np.asarray(lat))
a, b, c, d, e, f = self.transform
# invert affine (b,d assumed 0 for north-up metric grid)
col = np.round((x - c) / a).astype(int)
row = np.round((y - f) / e).astype(int)
inb = (col >= 0) & (col < self.W) & (row >= 0) & (row < self.H)
return row, col, inb
def sample_track(self, lat, lon):
import pandas as pd
lat = np.asarray(lat, dtype=float)
lon = np.asarray(lon, dtype=float)
ok = np.isfinite(lat) & np.isfinite(lon)
row = np.full(lat.shape, -1)
col = np.full(lat.shape, -1)
if ok.any():
r, c, inb = self._rowcol(lat[ok], lon[ok])
# points outside the basemap grid are invalid (NOT clamped -> no edge artifacts)
idx = np.where(ok)[0]
row[idx] = r
col[idx] = c
ok[idx[~inb]] = False
row[idx[~inb]] = -1
col[idx[~inb]] = -1
out = {}
for name, arr in self._layers.items():
vals = np.full(lat.shape, np.nan, dtype="float32")
if ok.any():
vals[ok] = np.asarray(arr[row[ok], col[ok]], dtype="float32")
out[name] = vals
if self.fairway is not None and ok.any():
fv = np.full(lat.shape, np.nan, dtype="float32")
fv[ok] = np.asarray(self.fairway[row[ok], col[ok]], dtype="float32")
out["dist_fairway_m"] = fv
# convenience aliases
res = pd.DataFrame(out)
res.rename(columns={"sdf_shore": "d_shore_m", "sdf_nav": "d_nav_m", "depth": "depth_m",
"landwater": "is_water"}, inplace=True)
if "dist_fairway_m" in res:
res["in_fairway"] = (res["dist_fairway_m"] <= 200).astype("int8")
return res