File size: 8,487 Bytes
7bab2df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""End-to-end codec demo on the WORLD corpus: one exemplar track per concept.

For each exemplar: build the codec track from its shard (polygon from the
teacher mask, 7-channel spectral fill from the raw multispec, exact-date
clock), hide a third of its observations with CLOUD mask tokens, let codec v3
impute them, and render ground truth vs decode side by side.

Writes renders/world_codec_<tag>.png + world_codec_report.json and the
Space asset spaces/hrm-space/assets/worldtour/*.png.

Usage: python world_codec.py   (needs shards in experiments/recall/)
"""
import json, os, pathlib, sys
import numpy as np
import cv2
import torch

HERE = pathlib.Path(__file__).parent
sys.path.insert(0, str(HERE))
os.environ["PLAYBACK_ONLY"] = "1"
import codec_v3 as C3                      # loads codec_v3.pt, no training
from codec_mlm import encode_shape, decode_shape, iou_poly
from codec_time import timefeat, F_MU, F_SD, L_MU, L_SD, NV, CC

SH = HERE.parent / "experiments/recall"
from huggingface_hub import hf_hub_download

EXEMPLARS = [  # (shard tag, concept substring, display name)
    ("kansas",      "center pivot",        "center-pivot field · Kansas"),
    ("guayas",      "aquaculture pond",    "shrimp pond · Guayas"),
    ("parkfire_ev", "burned",              "burn scar · Park Fire 2024"),
    ("indus_ev",    "flood",               "flooded farmland · Indus 2010/22"),
    ("atacama",     "mine",                "open-pit mine · Atacama"),
    ("oregon",      "clearcut",            "clearcut · Oregon"),
    ("aralsea",     "lake",                "shrinking lake · Aral Sea"),
]

def months_since(datestr):
    y, mo = int(str(datestr)[:4]), int(str(datestr)[5:7])
    return (y - 2023) * 12 + (mo - 1)

def fill7(px):                              # px: (N,4) r,g,b,nir reflectance
    r, g, b, nir = px[:, 0].mean(), px[:, 1].mean(), px[:, 2].mean(), px[:, 3].mean()
    s = r + g + b + 1e-6
    return np.array([r, g, b, (nir - r) / (nir + r + 1e-6),
                     (2 * g - r - b) / s, 1 - np.clip(s / 3 / 0.12, 0, 1), s / 3],
                    np.float32)

def build_track(tag, concept_sub):
    sh = np.load(SH / f"shard_{tag}.npz")
    lf = hf_hub_download("cp500/hyperkd-rs", f"labels/labels_{tag}.npz", repo_type="dataset")
    lb = np.load(lf)
    names = lb["concepts"]; sl = lb["sample_labels"]
    samples, masks, images = sh["samples"], sh["masks"], sh["images"]
    dates = [str(d) for d in sh["dates"]]
    ms = sh["multispec"].astype(np.float32)
    want = {int(r[0]) for r in sl if concept_sub in str(names[int(r[1])])}
    # longest track containing a wanted sample
    by_track = {}
    for i, r in enumerate(samples):
        by_track.setdefault(int(r[7]), []).append(i)
    cands = [(len(v), t) for t, v in by_track.items() if any(i in want for i in v)]
    if not cands: return None
    cands.sort(reverse=True)
    _, tid = cands[0]
    steps = []
    for i in sorted(by_track[tid], key=lambda i: int(samples[i][0])):
        r = samples[i]; si = int(r[0]); mi = int(r[3 + int(r[6])])
        if mi < 0: continue
        m8 = (masks[mi] > 0).astype(np.uint8)
        cs, _ = cv2.findContours(m8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        if not cs: continue
        cnt = max(cs, key=cv2.contourArea)
        if cv2.contourArea(cnt) < 20 or len(cnt) < 8: continue
        P = cnt[:, 0, :].astype(float) * (800 / 256)
        try: vec, pose = encode_shape(P)
        except Exception: continue
        m160 = cv2.resize(m8, (160, 160), interpolation=cv2.INTER_NEAREST) > 0
        px = ms[si][m160]
        if len(px) < 4: continue
        steps.append(dict(vec=vec, pose=pose, logs=pose[1], fill=fill7(px),
                          tm=months_since(dates[si]), period=dates[si][:7],
                          si=si, m8=m8))
    if len(steps) < 5: return None
    s = dict(tag=tag, steps=steps)
    s["X"] = np.stack([np.concatenate([st["vec"], [(st["logs"] - L_MU) / L_SD],
                                       (st["fill"] - F_MU) / F_SD]).astype(np.float32)
                       for st in steps])
    s["T"] = np.stack([timefeat(st["tm"]) for st in steps])
    return s

def stretch_rgb(fill):
    return tuple(int(np.clip((max(float(v), 0) / 0.35) ** (1 / 2.2), 0, 1) * 255)
                 for v in fill[:3][::-1])   # BGR for cv2

OUTD = HERE / "renders"; OUTD.mkdir(exist_ok=True)
SPACED = HERE.parent / "spaces/hrm-space/assets/worldtour"; SPACED.mkdir(parents=True, exist_ok=True)
report = []
TILE = 128
for tag, sub, title in EXEMPLARS:
    s = build_track(tag, sub)
    if s is None:
        print(f"{tag}: no track for '{sub}'"); continue
    T = len(s["steps"])
    hide = list(range(1, T, 3))             # hide every 3rd obs (CLOUD)
    pred = C3.impute(s, hide)               # rows for hidden idxs
    # metrics vs persistence
    ious, pious, fmae, pfmae = [], [], [], []
    sh_img = np.load(SH / f"shard_{tag}.npz")["images"]
    for k, t in enumerate(hide):
        st, ref = s["steps"][t], s["steps"][t - 1]
        e = pred[k]
        vec = e[:NV]; logs = e[NV] * L_SD + L_MU; fill = e[NV + 1:] * F_SD + F_MU
        pose = (st["pose"][0], logs, ref["pose"][2], ref["pose"][3])
        ious.append(iou_poly(decode_shape(vec, pose), decode_shape(st["vec"], st["pose"])))
        pious.append(iou_poly(decode_shape(ref["vec"], ref["pose"]),
                              decode_shape(st["vec"], st["pose"])))
        fmae.append(np.abs(fill - st["fill"]).mean())
        pfmae.append(np.abs(ref["fill"] - st["fill"]).mean())
        s["steps"][t]["dec"] = (vec, pose, fill)
    # render strip: up to 10 columns, GT on top, decode below
    cols = [t for t in range(T)][:: max(1, T // 10)][:10]
    tiles_top, tiles_bot = [], []
    # common crop around the track's union bbox (256 grid)
    u = np.zeros((256, 256), np.uint8)
    for st in s["steps"]: u |= st["m8"]
    ys, xs = np.where(u > 0)
    cx, cy = int(xs.mean()), int(ys.mean())
    r = max(int(max(xs.max()-xs.min(), ys.max()-ys.min()) * 0.8), 40)
    x0, y0 = np.clip(cx - r, 0, 255), np.clip(cy - r, 0, 255)
    x1, y1 = np.clip(cx + r, 1, 256), np.clip(cy + r, 1, 256)
    for t in cols:
        st = s["steps"][t]
        img = sh_img[st["si"]][y0:y1, x0:x1].copy()
        cs, _ = cv2.findContours(st["m8"][y0:y1, x0:x1], cv2.RETR_EXTERNAL,
                                 cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(img, cs, -1, (90, 220, 90), 1)
        gt = cv2.resize(img, (TILE, TILE), interpolation=cv2.INTER_NEAREST)
        gt = cv2.copyMakeBorder(gt, 16, 0, 0, 0, cv2.BORDER_CONSTANT, value=(15, 15, 15))
        cv2.putText(gt, st["period"], (3, 12), cv2.FONT_HERSHEY_SIMPLEX, 0.33,
                    (230, 230, 230), 1)
        tiles_top.append(gt[..., ::-1])     # to BGR
        bot = np.full((TILE, TILE, 3), 24, np.uint8)
        if t in hide and "dec" in st:
            vec, pose, fill = st["dec"]
            poly = decode_shape(vec, pose) * (256 / 800)
            poly = (poly - [x0, y0]) * (TILE / max(x1 - x0, 1))
            cv2.fillPoly(bot, [poly.astype(np.int32)], stretch_rgb(fill))
            cv2.polylines(bot, [poly.astype(np.int32)], True, (80, 160, 255), 1)
            tagtxt, col = "IMPUTED", (80, 160, 255)
        else:
            poly = st["m8"][y0:y1, x0:x1]
            cs, _ = cv2.findContours(poly, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            scale = TILE / max(x1 - x0, 1)
            for c in cs:
                cv2.fillPoly(bot, [(c[:, 0, :] * scale).astype(np.int32)],
                             stretch_rgb(st["fill"]))
            tagtxt, col = "OBSERVED", (120, 200, 120)
        bot = cv2.copyMakeBorder(bot, 16, 0, 0, 0, cv2.BORDER_CONSTANT, value=(15, 15, 15))
        cv2.putText(bot, tagtxt, (3, 12), cv2.FONT_HERSHEY_SIMPLEX, 0.33, col, 1)
        tiles_bot.append(bot)
    strip = np.vstack([np.hstack(tiles_top), np.hstack(tiles_bot)])
    fn = f"world_codec_{tag}.png"
    cv2.imwrite(str(OUTD / fn), strip)
    cv2.imwrite(str(SPACED / fn), strip)
    rec = dict(tag=tag, title=title, obs=T, hidden=len(hide),
               iou=round(float(np.mean(ious)), 3),
               pers_iou=round(float(np.mean(pious)), 3),
               fmae=round(float(np.mean(fmae)), 4),
               pers_fmae=round(float(np.mean(pfmae)), 4))
    report.append(rec); print(rec)
json.dump(report, open(HERE / "world_codec_report.json", "w"), indent=1)
json.dump(report, open(SPACED / "report.json", "w"), indent=1)
print(f"-> {len(report)} concept tracks rendered")