File size: 5,531 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
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
"""MTLCC tile dataset for T-SRDA - mirrors STCLN's `ijgiDataset` (seqlength=30).

One item = ONE whole 48x48 tile (the STCLN-MTLCC protocol never crops):
    ((x, pos, days), y)
      x    (30, 13, 48, 48) float32  = reflectance * 1e-4 (no normalisation)
           band order = x10 [B2,B3,B4,B8] | x20 [B5,B6,B7,B8A,B11,B12] | x60 [B1,B9,B10]
           (20 m / 60 m bands upsampled 'nearest' to 48x48, like F.interpolate default)
      pos  (30,) float32 = arange(30)   (index positions, as STCLN feeds range(T))
      days (30,) float32 = day-of-year of each selected acquisition
      y    (48, 48) int64 = index of the raw label id in classes.txt  (0 = background)
Date choice: 30 of the ~36 valid dates, random.sample then sorted ascending
(STCLN get_dates(n=30)).  train=True -> fresh random draw per access (python
`random`, seeded by the training script); train=False -> deterministic per
tile (seed 3407 + tile id) so validation/test numbers are reproducible.
"""
import json
import random
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import Dataset

import config as C
from tfrecord_io import load_tile

BAND_NAMES = ["B2", "B3", "B4", "B8", "B5", "B6", "B7", "B8A", "B11", "B12", "B1", "B9", "B10"]
_LUT = None


def _label_lut():
    global _LUT
    if _LUT is None:
        ids = C.CLASS_IDS or list(range(C.N_CLASSES))
        lut = np.zeros(max(ids) + 2, np.int64)          # unknown raw ids -> 0
        for idx, cid in enumerate(ids):
            lut[cid] = idx
        _LUT = lut
    return _LUT


def read_tileids(name):
    return [l.strip() for l in (C.TILEID_DIR / name).read_text().splitlines() if l.strip()]


def tile_path(tid, year_dir=None):
    return (C.DATA_ROOT / (year_dir or C.TRAIN_YEAR_DIR)) / f"{tid}.tfrecord.gz"


def _cache_file(split_name, year_dir):
    return C.EXP_ROOT / "cache" / f"valid_{year_dir}_{split_name}.json"


def valid_tile_ids(split_name, year_dir=None, seqlength=None):
    """Tile ids of a tileids file that exist on disk and have >= seqlength dates
    (STCLN ijgiDataset rejects shorter sequences).  Result is cached."""
    year_dir = year_dir or C.TRAIN_YEAR_DIR
    seqlength = seqlength or C.SEQLEN
    cache = _cache_file(split_name, year_dir)
    if cache.is_file():
        return json.loads(cache.read_text())["ids"]
    ids, stats = [], dict(rejected_nopath=0, rejected_length=0)
    for tid in read_tileids(split_name):
        p = tile_path(tid, year_dir)
        if not p.is_file():
            stats["rejected_nopath"] += 1; continue
        if int((load_tile(p)["doy"] >= 0).sum()) < seqlength:
            stats["rejected_length"] += 1; continue
        ids.append(tid)
    cache.parent.mkdir(parents=True, exist_ok=True)
    cache.write_text(json.dumps({"ids": ids, "stats": stats}))
    return ids


def pretrain_patch_ids():
    return valid_tile_ids(C.PRETRAIN_TILEIDS)


def train_patch_ids():
    return [str(t) for t in C.TRAIN_TILE_IDS]


def val_patch_ids():
    return [str(t) for t in C.VAL_TILE_IDS]


def test_patch_ids():
    return valid_tile_ids(C.TEST_TILEIDS)


class MTLCCTileDataset(Dataset):
    def __init__(self, tile_ids, load_target=True, train=False, year_dir=None, seqlength=None):
        self.ids = [str(t) for t in tile_ids]          # duplicates preserved
        self.load_target = load_target
        self.train = train
        self.year_dir = year_dir or C.TRAIN_YEAR_DIR
        self.seqlength = seqlength or C.SEQLEN

    def __len__(self):
        return len(self.ids)

    def __getitem__(self, idx):
        tid = self.ids[idx]
        t = load_tile(tile_path(tid, self.year_dir))
        valid = np.flatnonzero(t["doy"] >= 0)
        if self.train:
            pick = sorted(random.sample(list(valid), self.seqlength))
        else:
            rng = random.Random(C.SEED + int(tid))
            pick = sorted(rng.sample(list(valid), self.seqlength))
        x10 = t["x10"][pick].transpose(0, 3, 1, 2).astype(np.float32)   # (T,4,48,48)
        x20 = t["x20"][pick].transpose(0, 3, 1, 2).astype(np.float32)   # (T,6,24,24)
        x60 = t["x60"][pick].transpose(0, 3, 1, 2).astype(np.float32)   # (T,3,8,8)
        x20 = x20.repeat(2, axis=2).repeat(2, axis=3)                   # nearest 24->48
        x60 = x60.repeat(6, axis=2).repeat(6, axis=3)                   # nearest 8->48
        x = np.concatenate([x10, x20, x60], axis=1) * C.REFLECTANCE_SCALE
        days = t["doy"][pick].astype(np.float32)
        pos = np.arange(len(pick), dtype=np.float32)
        if self.load_target:
            raw = t["labels"][pick[0]]
            y = torch.from_numpy(_label_lut()[np.clip(raw, 0, None)])
        else:
            y = torch.zeros(C.PATCH_SIZE, C.PATCH_SIZE, dtype=torch.long)
        return (torch.from_numpy(x.astype(np.float32)), torch.from_numpy(pos),
                torch.from_numpy(days)), y


# --- names kept so the PASTIS-derived training scripts import unchanged -------
PASTISPatchDataset = MTLCCTileDataset


def pad_collate(batch, pad_value=0.0):
    return torch.utils.data.default_collate([((x, p, d), y) for (x, p, d), y in batch])


collate_fn = pad_collate


def crop_ij(x, y, i, j, grid=None):
    """grid==1 (the only MTLCC setting) returns the whole tile; the general
    form is kept so a sub-tile experiment remains possible."""
    grid = 1 if grid is None else grid
    s = x.shape[-1] // grid
    xc = x[:, :, :, i * s:(i + 1) * s, j * s:(j + 1) * s]
    yc = None if y is None else y[:, i * s:(i + 1) * s, j * s:(j + 1) * s]
    return xc, yc