File size: 6,094 Bytes
3863348
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31b74e0
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
r"""dataset_v2.py — 4-group loader, GPU-RESIDENT. Big arrays live on GPU as float16
(indexing is GPU-native -> no CPU-index / per-window transfer stall). If they don't fit
in VRAM, auto-fallback to CPU (RAM). Subgraph on the pruned training graph (structural
holdout §5); 3-mode SSL masking (§1). Physics = raw wind_1330 + BLH."""
from __future__ import annotations
import json, pathlib, numpy as np, torch

class AtmosData:
    def __init__(self, tdir, window=7, device="cuda", gpu_resident=True):
        t=pathlib.Path(tdir); self.w=window; self.dev=device
        # try to place big arrays on GPU (f16); fallback to CPU on OOM
        store=device if (gpu_resident and device=="cuda" and torch.cuda.is_available()) else "cpu"
        def L(f, keepf16=True):
            a=torch.tensor(np.load(t/f))
            if a.dtype==torch.float64: a=a.float()
            if keepf16 and a.dtype==torch.float32: a=a.half()   # store f16 to save VRAM
            return a
        try:
            self.A=L("groupA.npy").to(store); self.B=L("groupB.npy").to(store)
            self.Cstat=L("groupC_static.npy").to(store); self.Cyear=L("groupC_yearly.npy").to(store)
            self.LUyear=torch.tensor(np.load(t/"groupC_landuse.npy")).long().to(store)
            self.yod=torch.tensor(np.load(t/"year_of_day.npy")).long().to(store)
            self.cal=L("calendar_num.npy").to(store); self.grap=torch.tensor(np.load(t/"grap.npy")).long().to(store)
            self.PH=L("physics.npy").to(store)
            self.comp=L("completeness.npy").to(store)
            self.Y=L("targets.npy").to(store); self.M=torch.tensor(np.load(t/"target_mask.npy")).float().to(store)
            ed=np.load(t/"edges.npz")
            self.ei=torch.tensor(ed["ei"]).long().to(store)
            self.e_hat=torch.tensor(ed["e_hat"]).float().to(store); self.n_hat=torch.tensor(ed["n_hat"]).float().to(store)
            self.split=torch.tensor(np.load(t/"node_split.npy")).long().to(store)
            self.store=store
        except torch.cuda.OutOfMemoryError:
            print("!! GPU too small for resident data -> falling back to CPU (RAM). Slower.")
            torch.cuda.empty_cache()
            return AtmosData.__init__(self, tdir, window, device, gpu_resident=False)
        self.D,self.N,_=self.A.shape
        print(f"data resident on: {store}  (A{tuple(self.A.shape)} f16)")

    def target_days(self, fold=0):
        fn=(self.split==fold)
        has=((self.M.sum(-1)>0)&fn.unsqueeze(0)).sum(-1)
        return [t for t in range(self.w-1,self.D) if has[t]>0]

    def _groups(self, day, nodes):
        yi=int(self.yod[day])
        static_num=torch.cat([self.Cstat[nodes], self.Cyear[yi][nodes]], -1).float()
        return {"satellite":self.A[day,nodes].float(), "meteorology":self.B[day,nodes].float(),
                "static_num":static_num, "landuse":self.LUyear[yi][nodes],
                "calendar_num":self.cal[day].unsqueeze(0).expand(len(nodes),-1).float(),
                "grap":self.grap[day].expand(len(nodes))}

    def subgraph(self, size=512, fold=0):
        cand=torch.where(self.split==fold)[0]
        nodes=cand[torch.randperm(len(cand),device=cand.device)[:size]]
        nset=torch.full((self.N,),-1,dtype=torch.long,device=self.store); nset[nodes]=torch.arange(len(nodes),device=self.store)
        src,dst=self.ei; keep=(nset[src]>=0)&(nset[dst]>=0)
        ei=torch.stack([nset[src[keep]],nset[dst[keep]]]).to(self.dev)
        return nodes, ei, self.e_hat[keep].to(self.dev), self.n_hat[keep].to(self.dev)

    A_FLAGMAP=[0,2,1,3,4,7,8]
    RECON_GROUP=["satellite"]*9+["meteorology"]*12+["static"]*9
    def recon_from_groups(self, groups_t):
        """target+observed from already-loaded window groups (no re-index)."""
        T=len(groups_t)
        A=torch.stack([groups_t[t]["satellite"][:,:9] for t in range(T)],1)
        Bv=torch.stack([groups_t[t]["meteorology"] for t in range(T)],1)
        C=torch.stack([groups_t[t]["static_num"] for t in range(T)],1)
        target=torch.cat([A,Bv,C],-1)
        Aobs=torch.ones_like(A)
        for k,fl in enumerate(self.A_FLAGMAP):
            Aobs[:,:,k]=torch.stack([groups_t[t]["satellite"][:,9+fl] for t in range(T)],1)
        obs=torch.cat([Aobs,torch.ones_like(Bv),torch.ones_like(C)],-1)
        return target, obs

    def window(self, t, nodes, ei, e_hat, n_hat, horizons=4):
        days=range(t-self.w+1,t+1)
        groups_t=[{k:v.to(self.dev) for k,v in self._groups(d,nodes).items()} for d in days]
        wu=torch.stack([self.PH[d,nodes,0] for d in days]).float().to(self.dev)
        wv=torch.stack([self.PH[d,nodes,1] for d in days]).float().to(self.dev)
        blh=torch.stack([self.PH[d,nodes,2] for d in days]).float().to(self.dev)
        ys=[]; ms=[]
        for h in range(horizons):
            d2=t+h; valid=d2<self.D; d2=min(d2,self.D-1)
            ys.append(self.Y[d2,nodes].float()); ms.append(self.M[d2,nodes]*(1.0 if valid else 0.0))
        y=torch.stack(ys,1).to(self.dev); m=torch.stack(ms,1).to(self.dev)
        return dict(groups_t=groups_t, ei=ei.to(self.dev), e_hat=e_hat.to(self.dev), n_hat=n_hat.to(self.dev),
                    wu=wu, wv=wv, blh=blh, comp=self.comp[t,nodes].float().to(self.dev), y=y, m=m)

def ssl_mask(groups_t, p_group=0.15, p_blackout=0.10, p_node=0.05):
    dev=groups_t[-1]["satellite"].device
    N=groups_t[-1]["satellite"].shape[0]; T=len(groups_t)
    black=(torch.rand(N,device=dev)<p_blackout); node_m=(torch.rand(N,device=dev)<p_node)
    gm_t=[]
    for _ in range(T):
        pick=torch.randint(0,3,(N,),device=dev); fg=(torch.rand(N,device=dev)<p_group)
        gm_t.append({"satellite":((fg&(pick==0))|black|node_m).float(),
                     "meteorology":((fg&(pick==1))|node_m).float(),
                     "static":((fg&(pick==2))|node_m).float()})
    return gm_t

def recon_masked(gm_t, recon_group):
    T=len(gm_t); N=gm_t[0]["satellite"].shape[0]
    out=torch.zeros(N,T,len(recon_group),device=gm_t[0]["satellite"].device)
    for t in range(T):
        for c,g in enumerate(recon_group): out[:,t,c]=gm_t[t][g]
    return out