File size: 3,298 Bytes
b61a1c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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