File size: 10,016 Bytes
cda81ff | 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 | import numpy as np
import torch
from torch.utils.data import Dataset
import os
import glob
from config import bands_list_order, time_before, window_size
import re
from accelerate import Accelerator
from torch.utils.data import DataLoader
class RasterTensorDataset1Mil(Dataset):
def __init__(self, base_path):
self.folder_path = base_path
self.id_to_file = self._create_id_mapping()
self.data_cache = {id_num: np.load(filepath) for id_num, filepath in self.id_to_file.items()}
def _create_id_mapping(self):
id_to_file = {}
for file_path in glob.glob(os.path.join(self.folder_path, "*.npy")):
match = re.search(r'ID(\d+)N', file_path)
if match:
id_num = int(match.group(1))
id_to_file[id_num] = file_path
return id_to_file
def get_tensor_by_location(self, id_num, x, y, window_size=window_size):
if id_num not in self.id_to_file:
raise ValueError(f"ID {id_num} not found in dataset")
# CRITICAL: previous code was
# data = self.data_cache.get(id_num, np.load(self.id_to_file[id_num]))
# — which evaluated the np.load default eagerly on EVERY call, even
# on cache hits, loading the entire ~1.9 MB tile from disk every
# time. At ~30 raster lookups per sample × 256 samples × ~50
# batches that's ~370 GB of pointless I/O. Using `if` avoids it.
data = self.data_cache.get(id_num)
if data is None:
data = np.load(self.id_to_file[id_num])
self.data_cache[id_num] = data
# Cast x, y to int up front. coordinates.npy stores them as
# numpy.float64, which trickled into the padded-window branch as
# float slice indices and crashed ~0.4% of grid points (edge
# pixels). One cast covers both branches.
x = int(x); y = int(y)
half_window = window_size // 2
x_start, x_end = max(0, x - half_window), min(data.shape[0], x + half_window + 1)
y_start, y_end = max(0, y - half_window), min(data.shape[1], y + half_window + 1)
window = data[x_start:x_end, y_start:y_end]
if window.shape != (window_size, window_size):
padded_window = np.zeros((window_size, window_size))
x_offset = half_window - (x - x_start)
y_offset = half_window - (y - y_start)
padded_window[x_offset:x_offset + window.shape[0], y_offset:y_offset + window.shape[1]] = window
window = padded_window
return torch.from_numpy(window).float()
def __len__(self):
return len(self.id_to_file)
def __getitem__(self, idx):
id_num = list(self.id_to_file.keys())[idx]
return self.data_cache[id_num]
class MultiRasterDataset1MilMultiYears(Dataset):
def __init__(self, samples_coordinates_array_subfolders, data_array_subfolders, dataframe, time_before=time_before):
def flatten_list(lst):
return [item for sublist in lst for item in (flatten_list(sublist) if isinstance(sublist, list) else [sublist])]
self.data_array_subfolders = flatten_list(data_array_subfolders)
self.seasonalityBased = self.check_seasonality(self.data_array_subfolders)
self.time_before = time_before
self.samples_coordinates_array_subfolders = flatten_list(samples_coordinates_array_subfolders)
self.dataframe = dataframe
self.datasets = {
self.get_last_three_folders(subfolder): RasterTensorDataset1Mil(subfolder)
for subfolder in self.data_array_subfolders
}
self.coordinates = {
self.get_last_three_folders(subfolder): np.load(f"{subfolder}/coordinates.npy")
for subfolder in self.samples_coordinates_array_subfolders
}
# Build (lat, lon) -> (id_num, x, y) hashmap per subfolder so that
# find_coordinates_index() is O(1) instead of an O(N) np.where scan
# over the 1.3 M-row coordinates.npy. Cuts 80k-sample dataset
# materialisation from ~tens-of-minutes to seconds. Keys are
# quantised to 9 decimal digits (≈ sub-mm at the equator) to be
# robust against float-equality flakiness.
self._coord_index = {
subfolder: {
(round(float(row[0]), 9), round(float(row[1]), 9)):
(row[2], row[3], row[4])
for row in coords
}
for subfolder, coords in self.coordinates.items()
}
def check_seasonality(self, data_array_subfolders):
seasons = ['winter', 'spring', 'summer', 'autumn']
return any(any(season in subfolder.lower() for season in seasons) for subfolder in data_array_subfolders)
def get_last_three_folders(self, path):
parts = path.rstrip('/').split('/')
return '/'.join(parts[-2:])
def find_coordinates_index(self, subfolder, longitude, latitude):
key = (round(float(latitude), 9), round(float(longitude), 9))
idx = self._coord_index[subfolder].get(key)
if idx is None:
# Fallback to legacy linear scan (handles any edge-case keys
# that don't survive the round-trip — should never fire in
# practice but kept as a safety net).
coords = self.coordinates[subfolder]
match = np.where((coords[:, 1] == longitude) & (coords[:, 0] == latitude))[0]
if match.size == 0:
raise ValueError(f"Coordinates ({longitude}, {latitude}) not found in {subfolder}")
return coords[match[0], 2], coords[match[0], 3], coords[match[0], 4]
return idx
def filter_by_season_or_year(self, season, year, seasonality_based):
if seasonality_based:
filtered_array = [
path for path in self.samples_coordinates_array_subfolders
if ('Elevation' in path) or
('MODIS_NPP' in path and path.endswith(str(year))) or
(not 'Elevation' in path and not 'MODIS_NPP' in path and path.endswith(season))
]
else:
filtered_array = [
path for path in self.samples_coordinates_array_subfolders
if ('Elevation' in path) or
(not 'Elevation' in path and path.endswith(str(year)))
]
return filtered_array
def __getitem__(self, index):
row = self.dataframe.iloc[index]
longitude, latitude = row["longitude"], row["latitude"]
filtered_array = self.filter_by_season_or_year(row.get('season', ''), row.get('year', ''), self.seasonalityBased)
band_tensors = {band: [] for band in bands_list_order}
for subfolder in filtered_array:
subfolder_key = self.get_last_three_folders(subfolder)
if subfolder_key.split(os.path.sep)[-1] == 'Elevation':
id_num, x, y = self.find_coordinates_index(subfolder_key, longitude, latitude)
elevation_tensor = self.datasets[subfolder_key].get_tensor_by_location(id_num, x, y)
if elevation_tensor is not None:
for _ in range(self.time_before):
band_tensors['Elevation'].append(elevation_tensor)
else:
year = int(subfolder_key.split(os.path.sep)[-1])
for decrement in range(self.time_before):
current_year = year - decrement
decremented_subfolder = os.path.sep.join(subfolder_key.split(os.path.sep)[:-1] + [str(current_year)])
if decremented_subfolder in self.datasets:
id_num, x, y = self.find_coordinates_index(decremented_subfolder, longitude, latitude)
tensor = self.datasets[decremented_subfolder].get_tensor_by_location(id_num, x, y)
if tensor is not None:
band = subfolder_key.split(os.path.sep)[-2]
if band in band_tensors:
band_tensors[band].append(tensor)
stacked_tensors = []
for band in bands_list_order:
if not band_tensors[band]:
band_tensors[band] = [torch.zeros(window_size, window_size) for _ in range(self.time_before)]
elif len(band_tensors[band]) < self.time_before:
while len(band_tensors[band]) < self.time_before:
band_tensors[band].append(torch.zeros(window_size, window_size))
elif len(band_tensors[band]) > self.time_before:
band_tensors[band] = band_tensors[band][:self.time_before]
stacked_tensor = torch.stack(band_tensors[band])
stacked_tensors.append(stacked_tensor)
if len(stacked_tensors) != len(bands_list_order):
raise ValueError(f"Expected {len(bands_list_order)} bands, but got {len(stacked_tensors)}")
final_tensor = torch.stack(stacked_tensors)
final_tensor = final_tensor.permute(0, 2, 3, 1)
return longitude, latitude, final_tensor
def __len__(self):
return len(self.dataframe)
def get_tensor_by_location(self, subfolder, id_num, x, y):
return self.datasets[subfolder].get_tensor_by_location(id_num, x, y)
class NormalizedMultiRasterDataset1MilMultiYears(MultiRasterDataset1MilMultiYears):
"""Wrapper around MultiRasterDatasetMultiYears that adds feature normalization"""
def __init__(self, samples_coordinates_array_path, data_array_path, df,feature_means,feature_stds,time_before):
super().__init__(samples_coordinates_array_path, data_array_path, df,time_before)
self.feature_means=feature_means
self.feature_stds=feature_stds
time_before=time_before
def __getitem__(self, idx):
longitude, latitude, features = super().__getitem__(idx)
features = (features - self.feature_means[:, None, None]) / self.feature_stds[:, None, None]
return longitude, latitude, features
|