File size: 4,738 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
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
"""EnvShip-Voyage data loader.

Loads Track-I / Track-P samples and, for imputation, applies a named mask from the frozen mask bank.
Sequences are returned in time order as float arrays with NaN at held-out / missing steps.

Typical use:
    dl = VoyageLoader(build_dir)
    for s in dl.iter_track_i(split="test", mask_name="cont_6h"):
        # s.obs (input, NaN where held out), s.target (ground truth), s.eval_mask (where to score)
        ...
"""
from __future__ import annotations

import glob
from dataclasses import dataclass
from pathlib import Path

import numpy as np
import pandas as pd

SEQ_COLS = ["lat", "lon", "x_m", "y_m", "sog_kn", "cog_sin", "cog_cos",
            "head_sin", "head_cos", "observed_mask", "position_available", "interp_provenance"]


@dataclass
class ImputationSample:
    sample_id: str
    lat: np.ndarray
    lon: np.ndarray
    observed_mask: np.ndarray      # 1 = real observation present
    mask: np.ndarray               # 1 = held out for imputation
    eval_mask: np.ndarray          # 1 = scored (held out AND ground-truth exists)
    feats: dict                    # remaining per-step features (NaN where held out)
    meta: dict


def _to_arr(x):
    return np.array([np.nan if v is None else v for v in x], dtype=float)


class VoyageLoader:
    def __init__(self, build_dir: str | Path):
        self.build = Path(build_dir)
        self.index = pd.read_parquet(self.build / "s11" / "sample_index_split.parquet") \
            if (self.build / "s11" / "sample_index_split.parquet").exists() \
            else pd.read_parquet(self.build / "s9" / "sample_index.parquet")
        self._mask_cache: dict[str, dict] = {}

    # ---- mask bank access ----
    def _load_mask_partition(self, pidx: str) -> dict:
        if pidx not in self._mask_cache:
            npz = np.load(self.build / "s10" / "masks" / f"part-{pidx}.npz")
            self._mask_cache[pidx] = {k: npz[k] for k in npz.files if "|" in k}
        return self._mask_cache[pidx]

    def get_mask(self, sample_id: str, mask_name: str, n_steps: int, pidx: str | None = None) -> np.ndarray:
        # Mask npz partitions correspond 1:1 to the S9 track_i parquet partitions, so when the caller
        # already knows the partition (iter_track_i does) we look it up directly — no scan. Only a
        # stand-alone get_mask() with no pidx pays the one-time full scan to build sid->partition.
        if pidx is None:
            if not hasattr(self, "_sid2part"):
                self._sid2part = {}
                for f in glob.glob(str(self.build / "s10" / "masks" / "part-*.npz")):
                    p = Path(f).stem.split("-")[1]
                    npz = np.load(f)
                    for k in npz.files:
                        if "|" in k:
                            self._sid2part[k.split("|")[0]] = p
            pidx = self._sid2part.get(sample_id)
        if pidx is None:
            return np.zeros(n_steps, dtype=np.uint8)
        arr = self._load_mask_partition(pidx).get(f"{sample_id}|{mask_name}")
        if arr is None:
            return np.zeros(n_steps, dtype=np.uint8)
        return np.unpackbits(arr)[:n_steps]

    # ---- iteration ----
    def iter_track_i(self, split: str | None = None, mask_name: str = "cont_6h",
                     window_len_h: int | None = None):
        keep = self.index
        if "kept" in keep.columns:
            keep = keep[keep["kept"]]
        if split:
            keep = keep[keep["split"] == split]
        if window_len_h:
            keep = keep[keep["window_len_h"] == window_len_h]
        wanted = set(keep["sample_id"])
        for f in sorted(glob.glob(str(self.build / "s9" / "samples" / "track_i" / "part-*.parquet"))):
            pidx = Path(f).stem.split("-")[1]           # this partition's mask npz is part-<pidx>.npz
            df = pd.read_parquet(f)
            df = df[df["sample_id"].isin(wanted)]
            for _, row in df.iterrows():
                yield self._make_imputation_sample(row, mask_name, pidx)

    def _make_imputation_sample(self, row, mask_name: str, pidx: str | None = None) -> ImputationSample:
        n = int(row["n_steps"])
        observed = np.asarray(row["observed_mask"], dtype=np.uint8)
        mask = self.get_mask(row["sample_id"], mask_name, n, pidx=pidx)
        eval_mask = ((mask == 1) & (observed == 1)).astype(np.uint8)
        feats = {c: _to_arr(row[c]) for c in SEQ_COLS if c in row}
        return ImputationSample(
            sample_id=row["sample_id"], lat=_to_arr(row["lat"]), lon=_to_arr(row["lon"]),
            observed_mask=observed, mask=mask, eval_mask=eval_mask, feats=feats,
            meta={"window_len_h": int(row["window_len_h"]), "view_min": int(row["view_min"])},
        )