File size: 10,675 Bytes
806dfca
 
 
 
 
 
 
 
 
 
 
684a186
806dfca
 
 
 
 
684a186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
806dfca
 
684a186
806dfca
 
 
 
 
 
 
 
 
684a186
 
806dfca
 
 
 
 
 
 
 
 
684a186
 
 
 
 
 
 
 
6ec1f08
684a186
 
 
806dfca
 
684a186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ec1f08
806dfca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
684a186
806dfca
 
 
 
 
 
 
684a186
806dfca
 
 
684a186
806dfca
 
684a186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
806dfca
 
 
 
 
 
 
684a186
 
 
 
 
 
806dfca
 
 
 
 
 
 
 
 
 
 
 
684a186
 
806dfca
684a186
806dfca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
684a186
 
 
 
 
 
 
 
 
806dfca
684a186
 
 
 
 
806dfca
684a186
806dfca
684a186
 
 
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import os
import json
import shutil
import datasets
import tifffile

import pandas as pd
import numpy as np
import geopandas as gpd

from datetime import datetime
from GFMBench.datasets.base_dataset import GFMBenchDataset

S2_MEAN = [1180.2278549 , 1387.76882557, 1436.67627781, 1773.66437066, 2735.86417202, 3080.12530686, 3223.60015887, 3338.35639825, 2418.01390106, 1630.11250759]

S2_STD = [1976.91493068, 1917.02121286, 1996.45123112, 1903.34296117, 1785.08356262, 1796.4477813 , 1811.90019014, 1793.47036145, 1474.46979658, 1309.88416505]

S1A_MEAN = [-10.91848081, -17.34320436]

S1A_STD = [3.26830557, 3.19895575]

S1D_MEAN = [-11.07395082, -17.45261358]

S1D_STD = [3.33774017, 3.15584225]

S1_MEAN = [-10.996215815 -17.39790897]

S1_STD = [3.30411987, 3.177943]

s1_metadata = {
    'radar': {
        'mean': S1_MEAN,
        'std': S1_STD,
    },
    'radar_a': {
        'mean': S1A_MEAN,
        'std': S1A_STD,
    },
    'radar_d': {
        'mean': S1D_MEAN,
        'std': S1D_STD,
    },
}

s1_num_seq = {
    'radar': 142,
    'radar_a': 71,
    'radar_d': 71,
}

sats = {
    "radar": ["S2", "S1A", "S1D"],
    "radar_a": ["S2", "S1A"],
    "radar_d": ["S2", "S1D"],
}

class PASTISDataset(GFMBenchDataset):
    VERSION = datasets.Version("1.0.0")
    
    DATA_URL = "https://huggingface.co/datasets/GFM-Bench/PASTIS/resolve/main/PASTIS.tar.xz"

    metadata = {
        "s2c": {
            "bands": ["B2", "B3", "B4", "B5", "B6", "B7", "B8", "B8A", "B11", "B12"],
            "channel_wv": [492.4, 559.8, 664.6, 704.1, 740.5, 782.8, 832.8, 864.7, 1613.7, 2202.4],
            "mean": S2_MEAN,
            "std": S2_STD,
        },
        "s1": {
            "bands": ["VV", "VH"],
            "channel_wv": [5500, 5700],
        }
    }

    SIZE = HEIGHT = WIDTH = 128

    spatial_resolution = 10 

    NUM_CLASSES = 20 # 0 is background class, and 19 is the void label


    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="default"),
        *[datasets.BuilderConfig(name=name) for name in ['radar', 'radar_a', 'radar_d']]
    ] 

    DEFAULT_CONFIG_NAME = "radar"

    def __init__(self, reference_date="2018-09-10", **kwargs):
        name = kwargs.get('config_name', None)
        print(f"config_name: {name}")

        self.reference_date = datetime(*map(int, reference_date.split("-")))
        print(f"reference_date: {reference_date} -> {self.reference_date}")

        config = "radar" if name == "default" or name is None else name
        self.NUM_RADAR_SEQ = s1_num_seq[config]
        self.sats = sats[config]
        self.metadata["s1"].update(s1_metadata[config])
        self.sats_name = config

        super().__init__( **kwargs)

    def _info(self):
        metadata = self.metadata
        metadata['size'] = self.SIZE
        metadata['num_classes'] = self.NUM_CLASSES
        metadata['spatial_resolution'] = self.spatial_resolution

        return datasets.DatasetInfo(
            description=json.dumps(metadata),
            features=datasets.Features({
                "optical": datasets.Array4D(shape=(61, 10, self.HEIGHT, self.WIDTH), dtype="float32"),
                "radar": datasets.Array4D(shape=(self.NUM_RADAR_SEQ, 2, self.HEIGHT, self.WIDTH), dtype="float32"),
                "label": datasets.Array2D(shape=(self.HEIGHT, self.WIDTH), dtype="int32"),
                "optical_dates": datasets.Sequence(datasets.Value("int32")),
                "radar_dates": datasets.Sequence(datasets.Value("int32")),
                "optical_sequence_len": datasets.Value("int32"),
                "radar_sequence_len": datasets.Value("int32"),
                "optical_channel_wv": datasets.Sequence(datasets.Value("float32")),
                "radar_channel_wv": datasets.Sequence(datasets.Value("float32")),
                "spatial_resolution": datasets.Value("int32"),
            }),
        )
    
    def _split_generators(self, dl_manager):
        if isinstance(self.DATA_URL, list):
            downloaded_files = dl_manager.download(self.DATA_URL)
            combined_file = os.path.join(dl_manager.download_config.cache_dir, "combined.tar.gz")        
            with open(combined_file, 'wb') as outfile:
                for part_file in downloaded_files:
                    with open(part_file, 'rb') as infile:
                        shutil.copyfileobj(infile, outfile)
            data_dir = dl_manager.extract(combined_file)
            os.remove(combined_file)
        else:
            data_dir = dl_manager.download_and_extract(self.DATA_URL)

        return [
            datasets.SplitGenerator(
                name="train",
                gen_kwargs={
                    "split": 'train',
                    "data_dir": data_dir, 
                },
            ),
            datasets.SplitGenerator(
                name="val",
                gen_kwargs={
                    "split": 'val',
                    "data_dir": data_dir,
                },
            ),
            datasets.SplitGenerator(
                name="test",
                gen_kwargs={
                    "split": 'test',
                    "data_dir": data_dir,
                },
            )
        ]

    def _generate_examples(self, split, data_dir):
        optical_channel_wv = self.metadata["s2c"]["channel_wv"]
        radar_channel_wv = self.metadata["s1"]["channel_wv"]
        spatial_resolution = self.spatial_resolution

        data_dir = os.path.join(data_dir, "PASTIS")
        metadata = pd.read_csv(os.path.join(data_dir, "metadata.csv"))
        metadata = metadata[metadata["split"] == split].reset_index(drop=True)

        self._prepare_meta_patch(data_dir)
        self._prepare_date_tables()

        for index, row in metadata.iterrows():
            id_patch = row.optical_path.replace("DATA_S2/S2_", "").replace(".tif", "")

            optical_path = os.path.join(data_dir, row.optical_path)
            optical = self._read_image(optical_path).astype(np.float32) # TxCxHxW
            optical_sequence_len = optical.shape[0]
            optical = self._pad_sequence(optical, sat="S2") # 61xCxHxW
            optical_dates = self._get_dates(id_patch=id_patch, sat="S2")

            radar_sequence_len = 0
            if self.sats_name in ["radar", "radar_a"]:
                radar_a_path = os.path.join(data_dir, row.radar_a_path)
                radar_a = self._read_image(radar_a_path).astype(np.float32)[:, :2, :, :] # T, 2, 128, 128
                radar_a_dates = self._get_dates(id_patch=id_patch, sat="S1A")
                radar_sequence_len += radar_a.shape[0]
                if self.sats_name == "radar_a":
                    radar = self._pad_sequence(radar_a, "S1A") # 71, 2, 128, 128
                    radar_dates = radar_a_dates
            
            if self.sats_name in ["radar", "radar_d"]:
                radar_d_path = os.path.join(data_dir, row.radar_d_path)
                radar_d = self._read_image(radar_d_path).astype(np.float32)[:, :2, :, :]
                radar_d_dates = self._get_dates(id_patch=id_patch, sat="S1D")
                radar_sequence_len += radar_d.shape[0]
                if self.sats_name == "radar_d":
                    radar = self._pad_sequence(radar_d, sat="S1D") # 71, 2, 128, 128
                    radar_dates = radar_d_dates

            if self.sats_name == "radar":
                assert radar_a is not None and radar_d is not None
                radar, radar_dates = self._merge_sort_dates(radar_a_dates, radar_d_dates, radar_a, radar_d)
                radar = self._pad_sequence(radar, sat="S1_both") # 142, 2, 128, 128

            label_path = os.path.join(data_dir, row.label_path) # 3xHxW
            label = tifffile.imread(label_path)[0] # HxW

            sample = {
                "optical": optical,
                "optical_channel_wv": optical_channel_wv,
                "optical_dates": optical_dates,
                "optical_sequence_len": optical_sequence_len,
                "radar": radar,
                "radar_channel_wv": radar_channel_wv,
                "radar_dates": radar_dates,
                "radar_sequence_len": radar_sequence_len,
                "label": label,
                "spatial_resolution": spatial_resolution,
            }

            yield f"{index}", sample

    # util functions
    def _prepare_meta_patch(self, data_dir):
        self.meta_patch = gpd.read_file(os.path.join(data_dir, "metadata.geojson"))
        self.meta_patch.index = self.meta_patch["ID_PATCH"].astype(int)
        self.meta_patch.sort_index(inplace=True)

    def _prepare_date_tables(self):
        self.date_tables = {sat: None for sat in self.sats}
        self.date_range = np.array(range(-200, 600))
        for s in self.sats:
            dates = self.meta_patch["dates-{}".format(s)]
            date_table = pd.DataFrame(
                index=self.meta_patch.index, columns=self.date_range, dtype=int
            )
            for pid, date_seq in dates.items():
                if type(date_seq) == str:
                    date_seq = json.loads(date_seq)
                d = pd.DataFrame().from_dict(date_seq, orient="index")
                d = d[0].apply(
                    lambda x: (
                        datetime(int(str(x)[:4]), int(str(x)[4:6]), int(str(x)[6:]))
                        - self.reference_date
                    ).days
                )
                date_table.loc[pid, d.values] = 1
            date_table = date_table.fillna(0)
            self.date_tables[s] = {
                index: np.array(list(d.values()))
                for index, d in date_table.to_dict(orient="index").items()
            }
    
    def _get_dates(self, id_patch, sat="S2"):
        id_patch = int(id_patch)
        return self.date_range[np.where(self.date_tables[sat][id_patch] == 1)[0]]

    def _merge_sort_dates(self, radar_a_dates, radar_d_dates, radar_a, radar_d):
        merged_dates = np.concatenate((radar_a_dates, radar_d_dates))
        sorted_indices = np.argsort(merged_dates)

        sorted_images = np.concatenate((radar_a, radar_d), axis=0)[sorted_indices]
        sorted_dates = merged_dates[sorted_indices]

        return sorted_images, sorted_dates
    
    def _pad_sequence(self, image, sat="S2"):
        assert sat in ["S2", "S1A", "S1D", "S1_both"]
        sizes = {"S2": 61, "S1A": 71, "S1D": 71, "S1_both": 142}
        assert image.shape[0] <= sizes[sat]
        padding_size = sizes[sat] - image.shape[0]
        if padding_size == 0:
            return image
        
        pad = np.zeros((padding_size, *image.shape[1:]))
        padded_image = np.concatenate((image, pad), axis=0)
        return padded_image