File size: 2,272 Bytes
7bc4c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
r"""dataset.py — windows the prepped tensors for training. Full-graph, one target

day per sample. SSL masking for pretraining. Loss is restricted to fold nodes by

the caller (spatial split -> supervise on train nodes only)."""
from __future__ import annotations
import json, pathlib, numpy as np, torch

class AtmosIQData:
    def __init__(self, tdir, window=7, device="cpu"):
        t = pathlib.Path(tdir); self.w = window; self.dev = device
        self.X   = torch.tensor(np.load(t/"features.npy"), dtype=torch.float32)      # [D,N,F]
        self.PH  = torch.tensor(np.load(t/"physics.npy"),  dtype=torch.float32)      # [D,N,3]
        self.Y   = torch.tensor(np.load(t/"targets.npy"),  dtype=torch.float32)      # [D,N,7]
        self.M   = torch.tensor(np.load(t/"target_mask.npy"), dtype=torch.float32)   # [D,N,7]
        ed = np.load(t/"edges.npz")
        self.ei    = torch.tensor(ed["ei"], dtype=torch.long)
        self.e_hat = torch.tensor(ed["e_hat"], dtype=torch.float32)
        self.n_hat = torch.tensor(ed["n_hat"], dtype=torch.float32)
        self.split = torch.tensor(np.load(t/"node_split.npy"), dtype=torch.long)     # [N]
        self.D, self.N, self.F = self.X.shape
        self.feat_cols = json.load(open(t/"feat_cols.json"))

    def target_days(self, fold=0):
        """days t (>= window-1) that have >=1 labeled cell in `fold`."""
        fold_nodes = (self.split == fold)
        has = ((self.M.sum(-1) > 0) & fold_nodes.unsqueeze(0)).sum(-1)   # [D]
        return [t for t in range(self.w-1, self.D) if has[t] > 0]

    def window(self, t):
        sl = slice(t-self.w+1, t+1)
        return dict(X=self.X[sl].to(self.dev), wu=self.PH[sl,:,0].to(self.dev),
                    wv=self.PH[sl,:,1].to(self.dev), blh=self.PH[sl,:,2].to(self.dev),
                    y=self.Y[t].to(self.dev), m=self.M[t].to(self.dev))

    def edges(self):
        return (self.ei.to(self.dev), self.e_hat.to(self.dev), self.n_hat.to(self.dev))

def ssl_corrupt(X, ratio=0.15):
    """mask a fraction of (node,feature) entries to 0; return corrupted X + mask."""
    fmask = (torch.rand_like(X[-1]) < ratio).float()      # [N,F] on target day
    Xc = X.clone(); Xc[-1] = X[-1] * (1 - fmask)
    return Xc, fmask