Datasets:

ArXiv:
License:
ghjuliasialelli commited on
Commit
820eb00
·
verified ·
1 Parent(s): d7fa10b

Upload 2 files

Browse files
Files changed (2) hide show
  1. helper.py +318 -0
  2. statistics.pkl +3 -0
helper.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ This script contains helper functions to process the AGBD Dataset hosted on HuggingFace at: https://huggingface.co/datasets/prs-eth/AGBD.
4
+
5
+ """
6
+
7
+
8
+ ############################################################################################################################
9
+ # Imports
10
+
11
+ import numpy as np
12
+ from datasets import Value
13
+ import pickle
14
+ import pandas as pd
15
+
16
+ ############################################################################################################################
17
+ # Global variables
18
+
19
+ # Metadata features
20
+ feature_dtype = {'s2_num_days': Value('int16'),
21
+ 'gedi_num_days': Value('uint16'),
22
+ 'lat': Value('float32'),
23
+ 'lon': Value('float32'),
24
+ "agbd_se": Value('float32'),
25
+ "elev_lowes": Value('float32'),
26
+ "leaf_off_f": Value('uint8'),
27
+ "pft_class": Value('uint8'),
28
+ "region_cla": Value('uint8'),
29
+ "rh98": Value('float32'),
30
+ "sensitivity": Value('float32'),
31
+ "solar_elev": Value('float32'),
32
+ "urban_prop":Value('uint8')}
33
+
34
+ # Mapping from Sentinel-2 band to index in the data
35
+ s2_bands_idx = {'B01': 0, 'B02': 1, 'B03': 2, 'B04': 3, 'B05': 4, 'B06': 5, 'B07': 6, 'B08': 7, 'B8A': 8, 'B09': 9, 'B11': 10, 'B12': 11}
36
+
37
+ # Normalization values
38
+ with open('statistics.pkl', 'rb') as f: norm_values = pickle.load(f)
39
+
40
+ # Define the nodata values for each data source
41
+ NODATAVALS = {'S2_bands' : 0, 'CH': 255, 'ALOS_bands': -9999.0, 'DEM': -9999, 'LC': 255}
42
+
43
+ # Reference biomes, and derived metrics
44
+ REF_BIOMES = {20: 'Shrubs', 30: 'Herbaceous vegetation', 40: 'Cultivated', 90: 'Herbaceous wetland', 111: 'Closed-ENL', 112: 'Closed-EBL', 114: 'Closed-DBL', 115: 'Closed-mixed', 116: 'Closed-other', 121: 'Open-ENL', 122: 'Open-EBL', 124: 'Open-DBL', 125: 'Open-mixed', 126: 'Open-other'}
45
+ _biome_values_mapping = {v: i for i, v in enumerate(REF_BIOMES.keys())}
46
+
47
+ ############################################################################################################################
48
+ # Helper functions
49
+
50
+ def normalize_data(data, norm_values, norm_strat, nodata_value = None) :
51
+ """
52
+ Normalize the data, according to various strategies:
53
+ - mean_std: subtract the mean and divide by the standard deviation
54
+ - pct: subtract the 1st percentile and divide by the 99th percentile
55
+ - min_max: subtract the minimum and divide by the maximum
56
+
57
+ Args:
58
+ - data (np.array): the data to normalize
59
+ - norm_values (dict): the normalization values
60
+ - norm_strat (str): the normalization strategy
61
+
62
+ Returns:
63
+ - normalized_data (np.array): the normalized data
64
+ """
65
+
66
+ if norm_strat == 'mean_std' :
67
+ mean, std = norm_values['mean'], norm_values['std']
68
+ if nodata_value is not None :
69
+ data = np.where(data == nodata_value, 0, (data - mean) / std)
70
+ else : data = (data - mean) / std
71
+
72
+ elif norm_strat == 'pct' :
73
+ p1, p99 = norm_values['p1'], norm_values['p99']
74
+ if nodata_value is not None :
75
+ data = np.where(data == nodata_value, 0, (data - p1) / (p99 - p1))
76
+ else :
77
+ data = (data - p1) / (p99 - p1)
78
+ data = np.clip(data, 0, 1)
79
+
80
+ elif norm_strat == 'min_max' :
81
+ min_val, max_val = norm_values['min'], norm_values['max']
82
+ if nodata_value is not None :
83
+ data = np.where(data == nodata_value, 0, (data - min_val) / (max_val - min_val))
84
+ else:
85
+ data = (data - min_val) / (max_val - min_val)
86
+
87
+ else:
88
+ raise ValueError(f'Normalization strategy `{norm_strat}` is not valid.')
89
+
90
+ return data
91
+
92
+
93
+ def normalize_bands(bands_data, norm_values, order, norm_strat, nodata_value = None) :
94
+ """
95
+ This function normalizes the bands data using the normalization values and strategy.
96
+
97
+ Args:
98
+ - bands_data (np.array): the bands data to normalize
99
+ - norm_values (dict): the normalization values
100
+ - order (list): the order of the bands
101
+ - norm_strat (str): the normalization strategy
102
+ - nodata_value (int/float): the nodata value
103
+
104
+ Returns:
105
+ - bands_data (np.array): the normalized bands data
106
+ """
107
+
108
+ for i, band in enumerate(order) :
109
+ band_norm = norm_values[band]
110
+ bands_data[:, :, i] = normalize_data(bands_data[:, :, i], band_norm, norm_strat, nodata_value)
111
+
112
+ return bands_data
113
+
114
+
115
+ def one_hot(x) :
116
+ one_hot = np.zeros(len(_biome_values_mapping))
117
+ one_hot[_biome_values_mapping.get(x, 0)] = 1
118
+ return one_hot
119
+
120
+ def encode_biome(lc, encode_strat, embeddings = None) :
121
+ """
122
+ This function encodes the land cover data using different strategies: 1) sin/cosine encoding,
123
+ 2) cat2vec embeddings, 3) one-hot encoding.
124
+
125
+ Args:
126
+ - lc (np.array): the land cover data
127
+ - encode_strat (str): the encoding strategy
128
+ - embeddings (dict): the cat2vec embeddings
129
+
130
+ Returns:
131
+ - encoded_lc (np.array): the encoded land cover data
132
+ """
133
+
134
+ if encode_strat == 'sin_cos' :
135
+ # Encode the LC classes with sin/cosine values and scale the data to [0,1]
136
+ lc_cos = np.where(lc == NODATAVALS['LC'], 0, (np.cos(2 * np.pi * lc / 201) + 1) / 2)
137
+ lc_sin = np.where(lc == NODATAVALS['LC'], 0, (np.sin(2 * np.pi * lc / 201) + 1) / 2)
138
+ return np.stack([lc_cos, lc_sin], axis = -1).astype(np.float32)
139
+
140
+ elif encode_strat == 'cat2vec' :
141
+ # Embed the LC classes using the cat2vec embeddings
142
+ lc_cat2vec = np.vectorize(lambda x: embeddings.get(x, embeddings.get(0)), signature = '()->(n)')(lc)
143
+ return lc_cat2vec.astype(np.float32)
144
+
145
+ elif encode_strat == 'onehot' :
146
+ lc_onehot = np.vectorize(one_hot, signature = '() -> (n)')(lc).astype(np.float32)
147
+ return lc_onehot
148
+
149
+ else: raise ValueError(f'Encoding strategy `{encode_strat}` is not valid.')
150
+
151
+
152
+ def compute_num_features(input_features, encode_strat) :
153
+ """
154
+ This function computes the number of features that will be used in the model.
155
+
156
+ Args:
157
+ - input_features (dict): the input features configuration
158
+ - encode_strat (str): the encoding strategy
159
+
160
+ Returns:
161
+ - num_features (int): the number of features
162
+ """
163
+
164
+ num_features = len(input_features['S2_bands'])
165
+ if input_features['S2_dates'] : num_features += 3
166
+ if input_features['lat_lon'] : num_features += 4
167
+ if input_features['GEDI_dates'] : num_features += 3
168
+ if input_features['ALOS'] : num_features += 2
169
+ if input_features['CH'] : num_features += 2
170
+ if input_features['LC'] :
171
+ num_features += 1
172
+ if encode_strat == 'sin_cos' : num_features += 2
173
+ elif encode_strat == 'cat2vec' : num_features += 5
174
+ elif encode_strat == 'onehot' : num_features += len(REF_BIOMES)
175
+ if input_features['DEM'] : num_features += 1
176
+ if input_features['topo'] : num_features += 3
177
+
178
+ return num_features
179
+
180
+
181
+ def load_embeddings(user_config) :
182
+
183
+ if user_config['encode_strat'] == 'cat2vec' :
184
+ embeddings = pd.read_csv("embeddings_train.csv")
185
+ embeddings = dict([(v,np.array([a,b,c,d,e])) for v, a,b,c,d,e in zip(embeddings.mapping, embeddings.dim0, embeddings.dim1, embeddings.dim2, embeddings.dim3, embeddings.dim4)])
186
+ user_config['embeddings'] = embeddings
187
+ else: user_config['embeddings'] = None
188
+
189
+ return user_config
190
+
191
+
192
+ ############################################################################################################################
193
+ # Main function to process a batch
194
+
195
+ def process_batch(batch, norm_strat, encode_strat, input_features, metadata, patch_size, embeddings):
196
+ """
197
+ This function processes a batch of data from the HuggingFace AGBD dataset according to the user-defined configuration.
198
+
199
+ Args:
200
+ - batch (dict): the batch of data from the dataset
201
+ - norm_strat (str): the normalization strategy
202
+ - encode_strat (str): the encoding strategy for land cover data
203
+ - input_features (dict): the input features configuration
204
+ - metadata (list): the metadata variables to return
205
+ - patch_size (int): the size of the patches
206
+ - embeddings (dict): the cat2vec embeddings for land cover data
207
+
208
+ Returns:
209
+ - processed_batch (dict): the processed batch of data with normalized and concatenated features
210
+ """
211
+
212
+ ################################################################################
213
+ # Structure of the "input" data:
214
+ # - 12 x Sentinel-2 bands
215
+ # - 3 x S2 dates bands (s2_num_days, s2_doy_cos, s2_doy_sin)
216
+ # - 4 x lat/lon (lat_cos, lat_sin, lon_cos, lon_sin)
217
+ # - 3 x GEDI dates bands (gedi_num_days, gedi_doy_cos, gedi_doy_sin)
218
+ # - 2 x ALOS bands (HH, HV)
219
+ # - 2 x CH bands (ch, std)
220
+ # - 2 x LC bands (lc encoding, lc_prob)
221
+ # - 4 x DEM bands (slope, aspect_cos, aspect_sin, dem)
222
+ ################################################################################
223
+
224
+ # Normalize the inputs
225
+ patches = np.asarray(batch["input"])
226
+ batch_size = patches.shape[0]
227
+ og_patch_size = patches.shape[-1]
228
+
229
+ # Select the features according to input_features
230
+ num_features = compute_num_features(input_features, encode_strat)
231
+ out_patch = np.zeros((batch_size, num_features, og_patch_size, og_patch_size), dtype = np.float32)
232
+ current_idx = 0
233
+
234
+ # Sentinel-2 bands
235
+ s2_indices = [s2_bands_idx[band] for band in input_features['S2_bands']]
236
+ out_patch[:, current_idx : current_idx + len(s2_indices)] = patches[:, s2_indices] if norm_strat == 'none' else normalize_bands(patches[:, s2_indices], norm_values['S2_bands'], ['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09','B11', 'B12'], norm_strat, NODATAVALS['S2_bands'])
237
+ current_idx += len(s2_indices)
238
+
239
+ # S2 dates
240
+ if input_features['S2_dates'] :
241
+ out_patch[:, current_idx : current_idx + 3] = patches[:, 12:15] if norm_strat == 'none' else np.stack([
242
+ normalize_data(patches[:, 12], norm_values['Sentinel_metadata']['S2_date'], 'min_max' if norm_strat == 'pct' else norm_strat),
243
+ patches[:, 13],
244
+ patches[:, 14]
245
+ ], axis = 1)
246
+ current_idx += 3
247
+
248
+ # Lat/Lon
249
+ if input_features['lat_lon'] :
250
+ out_patch[:, current_idx : current_idx + 4] = patches[:, 15:19]
251
+ current_idx += 4
252
+
253
+ # GEDI dates
254
+ if input_features['GEDI_dates'] :
255
+ out_patch[:, current_idx : current_idx + 3] = patches[:, 19:22] if norm_strat == 'none' else np.stack([
256
+ normalize_data(patches[:, 19], norm_values['GEDI']['date'], 'min_max' if norm_strat == 'pct' else norm_strat),
257
+ patches[:, 20],
258
+ patches[:, 21]
259
+ ], axis = 1)
260
+ current_idx += 3
261
+
262
+ # ALOS bands
263
+ if input_features['ALOS'] :
264
+ out_patch[:, current_idx : current_idx + 2] = patches[:, 22:24] if norm_strat == 'none' else normalize_bands(patches[:, 22:24], norm_values['ALOS_bands'], ['HH', 'HV'], norm_strat, NODATAVALS['ALOS_bands'])
265
+ current_idx += 2
266
+
267
+ # CH bands
268
+ if input_features['CH'] :
269
+ out_patch[:, current_idx] = patches[:, 24] if norm_strat == 'none' else normalize_data(patches[:, 24], norm_values['CH']['ch'], norm_strat, NODATAVALS['CH'])
270
+ out_patch[:, current_idx + 1] = patches[:, 25] if norm_strat == 'none' else normalize_data(patches[:, 25], norm_values['CH']['std'], norm_strat, NODATAVALS['CH'])
271
+ current_idx += 2
272
+
273
+ # LC data
274
+ if input_features['LC'] :
275
+
276
+ # LC encoding
277
+ if encode_strat != 'none' :
278
+ lc_patch = np.vectorize(lambda x: encode_biome(x, encode_strat, embeddings), signature = '()->(n)')(patches[:, 26])
279
+ out_patch[:, current_idx : current_idx + lc_patch.shape[-1]] = lc_patch.swapaxes(-1,1)
280
+ current_idx += lc_patch.shape[-1]
281
+ else:
282
+ out_patch[:, current_idx] = patches[:, 26]
283
+ current_idx += 1
284
+
285
+ # LC probability
286
+ out_patch[:, current_idx] = patches[:, 27] / 100 # Put lc_prob in [0,1] range
287
+ current_idx += 1
288
+
289
+ # DEM topo bands
290
+ if input_features['topo'] :
291
+
292
+ out_patch[:, current_idx : current_idx + 3] = patches[:, 28:31]
293
+ current_idx += 3
294
+
295
+ # DEM band
296
+ if input_features['DEM'] :
297
+ out_patch[:, current_idx] = patches[:, 31] if norm_strat == 'none' else normalize_data(patches[:, 31], norm_values['DEM'], norm_strat, NODATAVALS['DEM'])
298
+ current_idx += 1
299
+
300
+ # ------------------------------------------------------------------------------------------------
301
+
302
+ # Crop to the patch size
303
+ start = (patches.shape[-1] - patch_size) // 2
304
+ out_patch = out_patch[:, start : start + patch_size, start : start + patch_size]
305
+
306
+ # ------------------------------------------------------------------------------------------------
307
+
308
+ # Select the metadata
309
+ if metadata == [] : out_metadata = [{} for _ in range(batch_size)]
310
+ else:
311
+ out_metadata = [
312
+ {key: d[key] for key in metadata}
313
+ for d in batch["metadata"]
314
+ ]
315
+
316
+ # ------------------------------------------------------------------------------------------------
317
+
318
+ return {'input': out_patch, 'label': batch["label"], 'metadata': out_metadata}
statistics.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b1e646dc6255806de50416f4d8d9bf79ebf8060d569f454fe513b3521883636
3
+ size 2797