File size: 3,325 Bytes
6e33b3b | 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 | """Frozen TESSERA optical-feature adapter for MTLCC (13-band tiles).
TESSERA's optical branch consumes 10 S2 bands in the order
[B04,B02,B03,B08,B8A,B05,B06,B07,B11,B12] (raw digital numbers, its own mean/std)
plus acquisition day-of-year. MTLCC provides all ten bands (tile channel order
B2,B3,B4,B8,B5,B6,B7,B8A,B11,B12,B1,B9,B10) and the real day-of-year of every
acquisition, so no band is synthesised. Everything else is the PASTIS adapter.
"""
import numpy as np
import torch
import config as C
ENCODER_SHA = '92619d4ffc2936895f145fdcf710140b58c23c860e02f01873828b10c6958d95'
BAND_ORDER = [2, 0, 1, 3, 7, 4, 5, 6, 8, 9] # tile channel index for each TESSERA band
def prepare(x, pos, days):
"""x (1,T,13,H,W) reflectance*1e-4, days (1,T) real DOY -> (H*W, T', 11)."""
import tessera_student as student
assert len(x) == 1 and x.shape[2] == C.N_CHANNELS
n = x.shape[1] # all 30 acquisitions are real
raw = x[0].float() / C.REFLECTANCE_SCALE # back to digital numbers
raw = raw[:, BAND_ORDER].permute(2, 3, 0, 1).reshape(-1, n, 10)
doy = days[0, :n].to(x.device).round().long()
remain = ((n + 7) // 8) * 8 - n # pad T to a multiple of 8 (30 -> 32)
if remain:
groups = np.array_split(np.arange(n), remain)
fill = np.array([g[len(g) // 2] for g in groups]) if remain <= n else np.arange(remain) % n
indices = torch.as_tensor(np.concatenate([np.arange(n), fill]), device=x.device)
raw, doy = raw[:, indices], doy[indices]
bands = (raw - torch.as_tensor(student.S2_BAND_MEAN, device=x.device)) / (
torch.as_tensor(student.S2_BAND_STD, device=x.device) + 1e-9)
return torch.cat([bands, doy[None, :, None].expand(len(bands), -1, 1).to(bands.dtype)], -1)
@torch.inference_mode()
def optical_features(model, inputs):
chunks = []
for start in range(0, len(inputs), 512):
with torch.autocast('cuda', dtype=torch.float16, enabled=inputs.is_cuda):
features = model.s2_backbone(inputs[start:start + 512])
chunks.append(features.float().cpu().numpy())
return np.concatenate(chunks)[:, None, :]
def predict(features, params):
x = (np.asarray(features[:, 0], np.float32) - params['mean']) / params['std']
scores = x @ params['weight'] + params['bias']
p = np.zeros((len(x), C.N_CLASSES), np.float32)
p[:, 1:] = torch.from_numpy(np.asarray(scores / float(params['temperature']), np.float32)).softmax(1).numpy()
return p
def confusion(labels, prediction):
NC = C.N_CLASSES
valid = labels > 0
return np.bincount(NC * labels[valid].astype(np.int64) + prediction[valid], minlength=NC * NC).reshape(NC, NC)
def metrics(cm):
tp = cm.diagonal()[1:].astype(float); gt = cm.sum(1)[1:]; pr = cm.sum(0)[1:]
iou = tp / np.maximum(gt + pr - tp, 1); f1 = 2 * tp / np.maximum(gt + pr, 1)
present = gt > 0
total = cm.sum(); oa = cm.trace() / max(total, 1)
chance = np.dot(cm.sum(0).astype(float), cm.sum(1)) / max(total * total, 1)
return dict(miou=float(iou[present].mean()), oa=float(oa), macro_f1=float(f1[present].mean()),
kappa=float((oa - chance) / max(1 - chance, 1e-12)), valid_pixels=int(total),
per_class_iou=iou.tolist(), confusion_matrix=cm.tolist())
|