PeterTor commited on
Commit
16583e6
1 Parent(s): 47c3af6

Update AGBD.py

Browse files
Files changed (1) hide show
  1. AGBD.py +166 -33
AGBD.py CHANGED
@@ -14,12 +14,10 @@
14
  # TODO: Address all TODOs and remove all explanatory comments
15
  """TODO: Add a description here."""
16
 
17
- import csv
18
- import json
19
- import os
20
  import numpy as np
21
  import datasets
22
  from datasets import Value
 
23
  # TODO: Add BibTeX citation
24
  # Find for instance the citation on arxiv or on the dataset repo/website
25
  _CITATION = """\
@@ -43,19 +41,7 @@ _HOMEPAGE = ""
43
  # TODO: Add the licence for the dataset here if you can find it
44
  _LICENSE = ""
45
 
46
- norm_values = {
47
- 'B01': {'mean': 0.12478869, 'std': 0.024433358, 'min': 1e-04, 'max': 1.8808, 'p1': 0.0787, 'p99': 0.1946},
48
- 'B02': {'mean': 0.13480005, 'std': 0.02822557, 'min': 1e-04, 'max': 2.1776, 'p1': 0.0925, 'p99': 0.2216},
49
- 'B03': {'mean': 0.16031432, 'std': 0.032037303, 'min': 1e-04, 'max': 2.12, 'p1': 0.1035, 'p99': 0.2556},
50
- 'B04': {'mean': 0.1532097, 'std': 0.038628064, 'min': 1e-04, 'max': 2.0032, 'p1': 0.1023, 'p99': 0.2816},
51
- 'B05': {'mean': 0.20312776, 'std': 0.04205057, 'min': 0.0422, 'max': 1.7502, 'p1': 0.1178, 'p99': 0.319},
52
- 'B06': {'mean': 0.32636437, 'std': 0.07139242, 'min': 0.0502, 'max': 1.7245, 'p1': 0.1633, 'p99': 0.519},
53
- 'B07': {'mean': 0.36605212, 'std': 0.08555025, 'min': 0.0616, 'max': 1.7149, 'p1': 0.1776, 'p99': 0.6076},
54
- 'B08': {'mean': 0.3811653, 'std': 0.092815965, 'min': 1e-04, 'max': 1.7488, 'p1': 0.1691, 'p99': 0.646},
55
- 'B8A': {'mean': 0.3910436, 'std': 0.0896364, 'min': 0.055, 'max': 1.688, 'p1': 0.1871, 'p99': 0.6386},
56
- 'B09': {'mean': 0.3910644, 'std': 0.0836445, 'min': 0.0012, 'max': 1.7915, 'p1': 0.2124, 'p99': 0.6241},
57
- 'B11': {'mean': 0.2917373, 'std': 0.07472579, 'min': 0.0953, 'max': 1.648, 'p1': 0.1334, 'p99': 0.4827},
58
- 'B12': {'mean': 0.21169408, 'std': 0.05880649, 'min': 0.0975, 'max': 1.6775, 'p1': 0.115, 'p99': 0.3872}}
59
 
60
  feature_dtype = {'s2_num_days': Value('int16'),
61
  'gedi_num_days': Value('uint16'),
@@ -71,6 +57,140 @@ feature_dtype = {'s2_num_days': Value('int16'),
71
  "solar_elev": Value('float32'),
72
  "urban_prop":Value('uint8')}
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  class NewDataset(datasets.GeneratorBasedBuilder):
75
  def __init__(self, *args, additional_features=[], normalize_data=True, patch_size=15, **kwargs):
76
  self.inner_dataset_kwargs = kwargs
@@ -82,6 +202,7 @@ class NewDataset(datasets.GeneratorBasedBuilder):
82
 
83
  VERSION = datasets.Version("1.1.0")
84
 
 
85
  BUILDER_CONFIGS = [
86
  datasets.BuilderConfig(name="default", version=VERSION, description="Normalized data"),
87
  datasets.BuilderConfig(name="unnormalized", version=VERSION, description="Unnormalized data"),
@@ -94,6 +215,9 @@ class NewDataset(datasets.GeneratorBasedBuilder):
94
  return super().as_streaming_dataset(split=split, base_path=base_path)
95
 
96
  def _info(self):
 
 
 
97
  all_features = {
98
  'input': datasets.Sequence(datasets.Sequence(datasets.Sequence(datasets.Value('float32')))),
99
  'label': Value('float32')
@@ -110,14 +234,7 @@ class NewDataset(datasets.GeneratorBasedBuilder):
110
  citation=_CITATION,
111
  )
112
 
113
- def denormalize_s2(self, patch):
114
- res = []
115
- for band, band_value in zip(['B04', 'B03', 'B02'], [patch[3], patch[2], patch[1]]):
116
- p1, p99 = norm_values[band]['p1'], norm_values[band]['p99']
117
- band_value = (p99 - p1) * band_value + p1
118
- res.append(band_value)
119
- patch[3], patch[2], patch[1] = res
120
- return patch
121
 
122
  def _split_generators(self, dl_manager):
123
  self.original_dataset = datasets.load_dataset("prs-eth/AGBD_raw", streaming=self._is_streaming)
@@ -129,18 +246,34 @@ class NewDataset(datasets.GeneratorBasedBuilder):
129
 
130
  def _generate_examples(self, split):
131
  for i, d in enumerate(self.original_dataset[split]):
132
- if self.config.name == "default":
133
- data = {'input': np.asarray(d["input"]), 'label': d["label"]}
134
- elif self.config.name == "unnormalized":
135
- data = {'input': np.asarray(self.denormalize_s2(np.array(d["input"]))), 'label': d["label"]}
 
 
 
 
 
 
 
 
 
 
136
 
137
- start_x = (data["input"].shape[1] - self.patch_size) // 2
138
- start_y = (data["input"].shape[2] - self.patch_size) // 2
139
- data["input"] = data["input"][:, start_x:start_x + self.patch_size, start_y:start_y + self.patch_size]
140
 
 
 
 
 
 
 
 
 
 
 
141
  for feat in self.additional_features:
142
  data[feat] = d["metadata"][feat]
143
 
144
  yield i, data
145
-
146
-
 
14
  # TODO: Address all TODOs and remove all explanatory comments
15
  """TODO: Add a description here."""
16
 
 
 
 
17
  import numpy as np
18
  import datasets
19
  from datasets import Value
20
+ import pickle
21
  # TODO: Add BibTeX citation
22
  # Find for instance the citation on arxiv or on the dataset repo/website
23
  _CITATION = """\
 
41
  # TODO: Add the licence for the dataset here if you can find it
42
  _LICENSE = ""
43
 
44
+
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  feature_dtype = {'s2_num_days': Value('int16'),
47
  'gedi_num_days': Value('uint16'),
 
57
  "solar_elev": Value('float32'),
58
  "urban_prop":Value('uint8')}
59
 
60
+
61
+ def encode_lat_lon(lat, lon):
62
+ """
63
+ Encode the latitude and longitude into sin/cosine values. We use a simple WRAP positional encoding, as
64
+ Mac Aodha et al. (2019).
65
+
66
+ Args:
67
+ - lat (float): the latitude
68
+ - lon (float): the longitude
69
+
70
+ Returns:
71
+ - (lat_cos, lat_sin, lon_cos, lon_sin) (tuple): the sin/cosine values for the latitude and longitude
72
+ """
73
+
74
+ # The latitude goes from -90 to 90
75
+ lat_cos, lat_sin = np.cos(np.pi * lat / 90), np.sin(np.pi * lat / 90)
76
+ # The longitude goes from -180 to 180
77
+ lon_cos, lon_sin = np.cos(np.pi * lon / 180), np.sin(np.pi * lon / 180)
78
+
79
+ # Now we put everything in the [0,1] range
80
+ lat_cos, lat_sin = (lat_cos + 1) / 2, (lat_sin + 1) / 2
81
+ lon_cos, lon_sin = (lon_cos + 1) / 2, (lon_sin + 1) / 2
82
+
83
+ return lat_cos, lat_sin, lon_cos, lon_sin
84
+
85
+
86
+ def encode_coords(central_lat, central_lon, patch_size, resolution=10):
87
+ """
88
+ This function computes the latitude and longitude of a patch, from the latitude and longitude of its central pixel.
89
+ It then encodes these values into sin/cosine values, and scales the results to [0,1].
90
+
91
+ Args:
92
+ - central_lat (float): the latitude of the central pixel
93
+ - central_lon (float): the longitude of the central pixel
94
+ - patch_size (tuple): the size of the patch
95
+ - resolution (int): the resolution of the patch
96
+
97
+ Returns:
98
+ - (lat_cos, lat_sin, lon_cos, lon_sin) (tuple): the sin/cosine values for the latitude and longitude
99
+ """
100
+
101
+ # Initialize arrays to store latitude and longitude coordinates
102
+
103
+ i_indices, j_indices = np.indices(patch_size)
104
+
105
+ # Calculate the distance offset in meters for each pixel
106
+ offset_lat = (i_indices - patch_size[0] // 2) * resolution
107
+ offset_lon = (j_indices - patch_size[1] // 2) * resolution
108
+
109
+ # Calculate the latitude and longitude for each pixel
110
+ latitudes = central_lat + (offset_lat / 6371000) * (180 / np.pi)
111
+ longitudes = central_lon + (offset_lon / 6371000) * (180 / np.pi) / np.cos(central_lat * np.pi / 180)
112
+
113
+ lat_cos, lat_sin, lon_cos, lon_sin = encode_lat_lon(latitudes, longitudes)
114
+
115
+ return lat_cos, lat_sin, lon_cos, lon_sin
116
+
117
+
118
+ """
119
+ Example usage:
120
+ lat_cos, lat_sin, lon_cos, lon_sin = encode_coords(lat, lon, self.patch_size)
121
+ lat_cos, lat_sin, lon_cos, lon_sin = lat_cos[..., np.newaxis], lat_sin[..., np.newaxis], lon_cos[..., np.newaxis], lon_sin[..., np.newaxis]
122
+ """
123
+
124
+
125
+ #########################################################################################################################
126
+ # Denormalizer
127
+
128
+
129
+ def denormalize_data(data, norm_values, norm_strat='pct'):
130
+ """
131
+ Normalize the data, according to various strategies:
132
+ - mean_std: subtract the mean and divide by the standard deviation
133
+ - pct: subtract the 1st percentile and divide by the 99th percentile
134
+ - min_max: subtract the minimum and divide by the maximum
135
+
136
+ Args:
137
+ - data (np.array): the data to normalize
138
+ - norm_values (dict): the normalization values
139
+ - norm_strat (str): the normalization strategy
140
+
141
+ Returns:
142
+ - normalized_data (np.array): the normalized data
143
+ """
144
+
145
+ if norm_strat == 'mean_std':
146
+ mean, std = norm_values['mean'], norm_values['std']
147
+ data = (data - mean) / std
148
+
149
+ elif norm_strat == 'pct':
150
+ p1, p99 = norm_values['p1'], norm_values['p99']
151
+ data = data * (p99 - p1) + p1
152
+
153
+ elif norm_strat == 'min_max':
154
+ min_val, max_val = norm_values['min'], norm_values['max']
155
+ data = data * (max_val - min_val) + min_val
156
+
157
+ else:
158
+ raise ValueError(f'De-normalization strategy `{norm_strat}` is not valid.')
159
+
160
+ return data
161
+
162
+
163
+ def denormalize_bands(bands_data, norm_values, order, norm_strat='pct'):
164
+ """
165
+ This function normalizes the bands data using the normalization values and strategy.
166
+
167
+ Args:
168
+ - bands_data (np.array): the bands data to normalize
169
+ - norm_values (dict): the normalization values
170
+ - order (list): the order of the bands
171
+ - norm_strat (str): the normalization strategy
172
+
173
+ Returns:
174
+ - bands_data (np.array): the normalized bands data
175
+ """
176
+
177
+ for i, band in enumerate(order):
178
+ band_norm = norm_values[band]
179
+ bands_data[:, :, i] = denormalize_data(bands_data[:, :, i], band_norm, norm_strat)
180
+
181
+ return bands_data
182
+
183
+
184
+ def decode_lc(encoded_lc, mode='cos'):
185
+ # Encode the LC classes with sin/cosine values and scale the data to [0,1]
186
+ if mode == 'cos':
187
+ lc = 100 * np.arccos(2 * encoded_lc - 1) / (2 * np.pi)
188
+ elif mode == 'sin':
189
+ lc = 100 * np.arcsin(2 * encoded_lc - 1) / (2 * np.pi)
190
+ else:
191
+ raise ValueError(f'Mode `{mode}` is not valid.')
192
+ return lc
193
+
194
  class NewDataset(datasets.GeneratorBasedBuilder):
195
  def __init__(self, *args, additional_features=[], normalize_data=True, patch_size=15, **kwargs):
196
  self.inner_dataset_kwargs = kwargs
 
202
 
203
  VERSION = datasets.Version("1.1.0")
204
 
205
+
206
  BUILDER_CONFIGS = [
207
  datasets.BuilderConfig(name="default", version=VERSION, description="Normalized data"),
208
  datasets.BuilderConfig(name="unnormalized", version=VERSION, description="Unnormalized data"),
 
215
  return super().as_streaming_dataset(split=split, base_path=base_path)
216
 
217
  def _info(self):
218
+ with open('statistics.pkl', 'rb') as f:
219
+ self.norm_values = pickle.load(f)
220
+
221
  all_features = {
222
  'input': datasets.Sequence(datasets.Sequence(datasets.Sequence(datasets.Value('float32')))),
223
  'label': Value('float32')
 
234
  citation=_CITATION,
235
  )
236
 
237
+
 
 
 
 
 
 
 
238
 
239
  def _split_generators(self, dl_manager):
240
  self.original_dataset = datasets.load_dataset("prs-eth/AGBD_raw", streaming=self._is_streaming)
 
246
 
247
  def _generate_examples(self, split):
248
  for i, d in enumerate(self.original_dataset[split]):
249
+ if self.normalize_data :
250
+ patch = np.asarray(d["input"])
251
+
252
+ else:
253
+ patch = np.asarray(d["input"])
254
+ patch[:12] = denormalize_bands(patch[:12], self.norm_values['S2_bands'],['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09','B11', 'B12'])
255
+ patch[12:14] = denormalize_bands(patch[12:14], self.norm_values['ALOS_bands'], ['HH', 'HV'])
256
+ patch[14] = denormalize_data(patch[14], self.norm_values['CH']['ch'])
257
+ patch[15] = denormalize_data(patch[15], self.norm_values['CH']['std'])
258
+ patch[16] = decode_lc(patch[16], 'cos')
259
+ patch[17] = decode_lc(patch[17], 'sin')
260
+ patch[18] = patch[18] * 100
261
+ patch[19] = denormalize_data(patch[19], self.norm_values['DEM'])
262
+
263
 
264
+ lat, lon = d["metadata"]["lat"],d["metadata"]["lon"]
 
 
265
 
266
+ latlon_patch = encode_coords(lat, lon,(self.patch_size,self.patch_size))
267
+
268
+
269
+ start_x = (patch.shape[1] - self.patch_size) // 2
270
+ start_y = (patch.shape[2] - self.patch_size) // 2
271
+ patch = patch[:, start_x:start_x + self.patch_size, start_y:start_y + self.patch_size]
272
+
273
+ patch = np.concatenate([patch[:12],latlon_patch,patch[12:]],0)
274
+
275
+ data = {'input': patch, 'label': d["label"]}
276
  for feat in self.additional_features:
277
  data[feat] = d["metadata"][feat]
278
 
279
  yield i, data