yuxuanw8 commited on
Commit
684a186
·
verified ·
1 Parent(s): 6ec1f08

Update PASTIS.py

Browse files
Files changed (1) hide show
  1. PASTIS.py +142 -58
PASTIS.py CHANGED
@@ -9,15 +9,55 @@ import numpy as np
9
  import geopandas as gpd
10
 
11
  from datetime import datetime
 
12
 
13
  S2_MEAN = [1180.2278549 , 1387.76882557, 1436.67627781, 1773.66437066, 2735.86417202, 3080.12530686, 3223.60015887, 3338.35639825, 2418.01390106, 1630.11250759]
14
 
15
  S2_STD = [1976.91493068, 1917.02121286, 1996.45123112, 1903.34296117, 1785.08356262, 1796.4477813 , 1811.90019014, 1793.47036145, 1474.46979658, 1309.88416505]
16
 
17
- class PASTISDataset(datasets.GeneratorBasedBuilder):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  VERSION = datasets.Version("1.0.0")
19
 
20
- DATA_URL = "https://huggingface.co/datasets/GFM-Bench/PASTIS/resolve/main/PASTIS.zip" # TODO
21
 
22
  metadata = {
23
  "s2c": {
@@ -27,10 +67,8 @@ class PASTISDataset(datasets.GeneratorBasedBuilder):
27
  "std": S2_STD,
28
  },
29
  "s1": {
30
- "bands": None,
31
- "channel_wv": None,
32
- "mean": None,
33
- "std": None
34
  }
35
  }
36
 
@@ -40,10 +78,50 @@ class PASTISDataset(datasets.GeneratorBasedBuilder):
40
 
41
  NUM_CLASSES = 20 # 0 is background class, and 19 is the void label
42
 
 
 
 
 
 
 
 
 
43
  def __init__(self, reference_date="2018-09-10", **kwargs):
44
- super().__init__(**kwargs)
 
 
45
  self.reference_date = datetime(*map(int, reference_date.split("-")))
46
  print(f"reference_date: {reference_date} -> {self.reference_date}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  def _split_generators(self, dl_manager):
49
  if isinstance(self.DATA_URL, list):
@@ -82,25 +160,9 @@ class PASTISDataset(datasets.GeneratorBasedBuilder):
82
  )
83
  ]
84
 
85
- def _info(self):
86
- metadata = self.metadata
87
- metadata['size'] = self.SIZE
88
- metadata['num_classes'] = self.NUM_CLASSES
89
- metadata['spatial_resolution'] = self.spatial_resolution
90
- return datasets.DatasetInfo(
91
- description=json.dumps(metadata),
92
- features=datasets.Features({
93
- "optical": datasets.Array4D(shape=(61, 10, self.HEIGHT, self.WIDTH), dtype="float32"),
94
- "label": datasets.Array2D(shape=(self.HEIGHT, self.WIDTH), dtype="int32"),
95
- "dates": datasets.Sequence(datasets.Value("int32")),
96
- "sequence_len": datasets.Value("int32"),
97
- "optical_channel_wv": datasets.Sequence(datasets.Value("float32")),
98
- "spatial_resolution": datasets.Value("int32"),
99
- }),
100
- )
101
-
102
  def _generate_examples(self, split, data_dir):
103
  optical_channel_wv = self.metadata["s2c"]["channel_wv"]
 
104
  spatial_resolution = self.spatial_resolution
105
 
106
  data_dir = os.path.join(data_dir, "PASTIS")
@@ -108,26 +170,53 @@ class PASTISDataset(datasets.GeneratorBasedBuilder):
108
  metadata = metadata[metadata["split"] == split].reset_index(drop=True)
109
 
110
  self._prepare_meta_patch(data_dir)
111
- self._prepare_date_tables(data_dir)
112
 
113
  for index, row in metadata.iterrows():
114
  id_patch = row.optical_path.replace("DATA_S2/S2_", "").replace(".tif", "")
 
115
  optical_path = os.path.join(data_dir, row.optical_path)
116
  optical = self._read_image(optical_path).astype(np.float32) # TxCxHxW
117
- sequence_len = optical.shape[0]
118
- optical = self._pad_sequence(optical) # 61xCxHxW
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  label_path = os.path.join(data_dir, row.label_path) # 3xHxW
121
  label = tifffile.imread(label_path)[0] # HxW
122
 
123
- # Retrieve date sequences
124
- dates = self._get_dates(id_patch=id_patch, sat="S2")
125
-
126
  sample = {
127
  "optical": optical,
128
  "optical_channel_wv": optical_channel_wv,
129
- "dates": dates,
130
- "sequence_len": sequence_len,
 
 
 
 
131
  "label": label,
132
  "spatial_resolution": spatial_resolution,
133
  }
@@ -135,16 +224,15 @@ class PASTISDataset(datasets.GeneratorBasedBuilder):
135
  yield f"{index}", sample
136
 
137
  # util functions
138
-
139
  def _prepare_meta_patch(self, data_dir):
140
  self.meta_patch = gpd.read_file(os.path.join(data_dir, "metadata.geojson"))
141
  self.meta_patch.index = self.meta_patch["ID_PATCH"].astype(int)
142
  self.meta_patch.sort_index(inplace=True)
143
 
144
- def _prepare_date_tables(self, data_dir):
145
- self.date_tables = {"S2": None}
146
  self.date_range = np.array(range(-200, 600))
147
- for s in ["S2"]:
148
  dates = self.meta_patch["dates-{}".format(s)]
149
  date_table = pd.DataFrame(
150
  index=self.meta_patch.index, columns=self.date_range, dtype=int
@@ -169,28 +257,24 @@ class PASTISDataset(datasets.GeneratorBasedBuilder):
169
  def _get_dates(self, id_patch, sat="S2"):
170
  id_patch = int(id_patch)
171
  return self.date_range[np.where(self.date_tables[sat][id_patch] == 1)[0]]
 
 
 
 
 
 
 
 
 
172
 
173
- def _pad_sequence(self, optical):
174
- padding_size = 61 - optical.shape[0]
 
 
 
175
  if padding_size == 0:
176
- return optical
177
 
178
- pad = np.zeros((padding_size, *optical.shape[1:]))
179
- padded_optical = np.concatenate((optical, pad), axis=0)
180
- return padded_optical
181
-
182
- def _read_image(self, image_path):
183
- """Read tiff image from image_path
184
- Args:
185
- image_path:
186
- Image path to read from
187
-
188
- Return:
189
- image:
190
- C, H, W numpy array image
191
- """
192
- image = tifffile.imread(image_path)
193
- if len(image.shape) == 3:
194
- image = np.transpose(image, (2, 0, 1))
195
-
196
- return image
 
9
  import geopandas as gpd
10
 
11
  from datetime import datetime
12
+ from GFMBench.datasets.base_dataset import GFMBenchDataset
13
 
14
  S2_MEAN = [1180.2278549 , 1387.76882557, 1436.67627781, 1773.66437066, 2735.86417202, 3080.12530686, 3223.60015887, 3338.35639825, 2418.01390106, 1630.11250759]
15
 
16
  S2_STD = [1976.91493068, 1917.02121286, 1996.45123112, 1903.34296117, 1785.08356262, 1796.4477813 , 1811.90019014, 1793.47036145, 1474.46979658, 1309.88416505]
17
 
18
+ S1A_MEAN = [-10.91848081, -17.34320436]
19
+
20
+ S1A_STD = [3.26830557, 3.19895575]
21
+
22
+ S1D_MEAN = [-11.07395082, -17.45261358]
23
+
24
+ S1D_STD = [3.33774017, 3.15584225]
25
+
26
+ S1_MEAN = [-10.996215815 -17.39790897]
27
+
28
+ S1_STD = [3.30411987, 3.177943]
29
+
30
+ s1_metadata = {
31
+ 'radar': {
32
+ 'mean': S1_MEAN,
33
+ 'std': S1_STD,
34
+ },
35
+ 'radar_a': {
36
+ 'mean': S1A_MEAN,
37
+ 'std': S1A_STD,
38
+ },
39
+ 'radar_d': {
40
+ 'mean': S1D_MEAN,
41
+ 'std': S1D_STD,
42
+ },
43
+ }
44
+
45
+ s1_num_seq = {
46
+ 'radar': 142,
47
+ 'radar_a': 71,
48
+ 'radar_d': 71,
49
+ }
50
+
51
+ sats = {
52
+ "radar": ["S2", "S1A", "S1D"],
53
+ "radar_a": ["S2", "S1A"],
54
+ "radar_d": ["S2", "S1D"],
55
+ }
56
+
57
+ class PASTISDataset(GFMBenchDataset):
58
  VERSION = datasets.Version("1.0.0")
59
 
60
+ DATA_URL = "https://huggingface.co/datasets/GFM-Bench/PASTIS/resolve/main/PASTIS.tar.xz"
61
 
62
  metadata = {
63
  "s2c": {
 
67
  "std": S2_STD,
68
  },
69
  "s1": {
70
+ "bands": ["VV", "VH"],
71
+ "channel_wv": [5500, 5700],
 
 
72
  }
73
  }
74
 
 
78
 
79
  NUM_CLASSES = 20 # 0 is background class, and 19 is the void label
80
 
81
+
82
+ BUILDER_CONFIGS = [
83
+ datasets.BuilderConfig(name="default"),
84
+ *[datasets.BuilderConfig(name=name) for name in ['radar', 'radar_a', 'radar_d']]
85
+ ]
86
+
87
+ DEFAULT_CONFIG_NAME = "radar"
88
+
89
  def __init__(self, reference_date="2018-09-10", **kwargs):
90
+ name = kwargs.get('config_name', None)
91
+ print(f"config_name: {name}")
92
+
93
  self.reference_date = datetime(*map(int, reference_date.split("-")))
94
  print(f"reference_date: {reference_date} -> {self.reference_date}")
95
+
96
+ config = "radar" if name == "default" or name is None else name
97
+ self.NUM_RADAR_SEQ = s1_num_seq[config]
98
+ self.sats = sats[config]
99
+ self.metadata["s1"].update(s1_metadata[config])
100
+ self.sats_name = config
101
+
102
+ super().__init__( **kwargs)
103
+
104
+ def _info(self):
105
+ metadata = self.metadata
106
+ metadata['size'] = self.SIZE
107
+ metadata['num_classes'] = self.NUM_CLASSES
108
+ metadata['spatial_resolution'] = self.spatial_resolution
109
+
110
+ return datasets.DatasetInfo(
111
+ description=json.dumps(metadata),
112
+ features=datasets.Features({
113
+ "optical": datasets.Array4D(shape=(61, 10, self.HEIGHT, self.WIDTH), dtype="float32"),
114
+ "radar": datasets.Array4D(shape=(self.NUM_RADAR_SEQ, 2, self.HEIGHT, self.WIDTH), dtype="float32"),
115
+ "label": datasets.Array2D(shape=(self.HEIGHT, self.WIDTH), dtype="int32"),
116
+ "optical_dates": datasets.Sequence(datasets.Value("int32")),
117
+ "radar_dates": datasets.Sequence(datasets.Value("int32")),
118
+ "optical_sequence_len": datasets.Value("int32"),
119
+ "radar_sequence_len": datasets.Value("int32"),
120
+ "optical_channel_wv": datasets.Sequence(datasets.Value("float32")),
121
+ "radar_channel_wv": datasets.Sequence(datasets.Value("float32")),
122
+ "spatial_resolution": datasets.Value("int32"),
123
+ }),
124
+ )
125
 
126
  def _split_generators(self, dl_manager):
127
  if isinstance(self.DATA_URL, list):
 
160
  )
161
  ]
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  def _generate_examples(self, split, data_dir):
164
  optical_channel_wv = self.metadata["s2c"]["channel_wv"]
165
+ radar_channel_wv = self.metadata["s1"]["channel_wv"]
166
  spatial_resolution = self.spatial_resolution
167
 
168
  data_dir = os.path.join(data_dir, "PASTIS")
 
170
  metadata = metadata[metadata["split"] == split].reset_index(drop=True)
171
 
172
  self._prepare_meta_patch(data_dir)
173
+ self._prepare_date_tables()
174
 
175
  for index, row in metadata.iterrows():
176
  id_patch = row.optical_path.replace("DATA_S2/S2_", "").replace(".tif", "")
177
+
178
  optical_path = os.path.join(data_dir, row.optical_path)
179
  optical = self._read_image(optical_path).astype(np.float32) # TxCxHxW
180
+ optical_sequence_len = optical.shape[0]
181
+ optical = self._pad_sequence(optical, sat="S2") # 61xCxHxW
182
+ optical_dates = self._get_dates(id_patch=id_patch, sat="S2")
183
+
184
+ radar_sequence_len = 0
185
+ if self.sats_name in ["radar", "radar_a"]:
186
+ radar_a_path = os.path.join(data_dir, row.radar_a_path)
187
+ radar_a = self._read_image(radar_a_path).astype(np.float32)[:, :2, :, :] # T, 2, 128, 128
188
+ radar_a_dates = self._get_dates(id_patch=id_patch, sat="S1A")
189
+ radar_sequence_len += radar_a.shape[0]
190
+ if self.sats_name == "radar_a":
191
+ radar = self._pad_sequence(radar_a, "S1A") # 71, 2, 128, 128
192
+ radar_dates = radar_a_dates
193
+
194
+ if self.sats_name in ["radar", "radar_d"]:
195
+ radar_d_path = os.path.join(data_dir, row.radar_d_path)
196
+ radar_d = self._read_image(radar_d_path).astype(np.float32)[:, :2, :, :]
197
+ radar_d_dates = self._get_dates(id_patch=id_patch, sat="S1D")
198
+ radar_sequence_len += radar_d.shape[0]
199
+ if self.sats_name == "radar_d":
200
+ radar = self._pad_sequence(radar_d, sat="S1D") # 71, 2, 128, 128
201
+ radar_dates = radar_d_dates
202
+
203
+ if self.sats_name == "radar":
204
+ assert radar_a is not None and radar_d is not None
205
+ radar, radar_dates = self._merge_sort_dates(radar_a_dates, radar_d_dates, radar_a, radar_d)
206
+ radar = self._pad_sequence(radar, sat="S1_both") # 142, 2, 128, 128
207
 
208
  label_path = os.path.join(data_dir, row.label_path) # 3xHxW
209
  label = tifffile.imread(label_path)[0] # HxW
210
 
 
 
 
211
  sample = {
212
  "optical": optical,
213
  "optical_channel_wv": optical_channel_wv,
214
+ "optical_dates": optical_dates,
215
+ "optical_sequence_len": optical_sequence_len,
216
+ "radar": radar,
217
+ "radar_channel_wv": radar_channel_wv,
218
+ "radar_dates": radar_dates,
219
+ "radar_sequence_len": radar_sequence_len,
220
  "label": label,
221
  "spatial_resolution": spatial_resolution,
222
  }
 
224
  yield f"{index}", sample
225
 
226
  # util functions
 
227
  def _prepare_meta_patch(self, data_dir):
228
  self.meta_patch = gpd.read_file(os.path.join(data_dir, "metadata.geojson"))
229
  self.meta_patch.index = self.meta_patch["ID_PATCH"].astype(int)
230
  self.meta_patch.sort_index(inplace=True)
231
 
232
+ def _prepare_date_tables(self):
233
+ self.date_tables = {sat: None for sat in self.sats}
234
  self.date_range = np.array(range(-200, 600))
235
+ for s in self.sats:
236
  dates = self.meta_patch["dates-{}".format(s)]
237
  date_table = pd.DataFrame(
238
  index=self.meta_patch.index, columns=self.date_range, dtype=int
 
257
  def _get_dates(self, id_patch, sat="S2"):
258
  id_patch = int(id_patch)
259
  return self.date_range[np.where(self.date_tables[sat][id_patch] == 1)[0]]
260
+
261
+ def _merge_sort_dates(self, radar_a_dates, radar_d_dates, radar_a, radar_d):
262
+ merged_dates = np.concatenate((radar_a_dates, radar_d_dates))
263
+ sorted_indices = np.argsort(merged_dates)
264
+
265
+ sorted_images = np.concatenate((radar_a, radar_d), axis=0)[sorted_indices]
266
+ sorted_dates = merged_dates[sorted_indices]
267
+
268
+ return sorted_images, sorted_dates
269
 
270
+ def _pad_sequence(self, image, sat="S2"):
271
+ assert sat in ["S2", "S1A", "S1D", "S1_both"]
272
+ sizes = {"S2": 61, "S1A": 71, "S1D": 71, "S1_both": 142}
273
+ assert image.shape[0] <= sizes[sat]
274
+ padding_size = sizes[sat] - image.shape[0]
275
  if padding_size == 0:
276
+ return image
277
 
278
+ pad = np.zeros((padding_size, *image.shape[1:]))
279
+ padded_image = np.concatenate((image, pad), axis=0)
280
+ return padded_image