wangyi111 commited on
Commit
d2cbecc
·
verified ·
1 Parent(s): 4f8a14c

Upload senbench_airqualitys5p_wrapper.py

Browse files
airquality_s5p/senbench_airqualitys5p_wrapper.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import kornia as K
2
+ import torch
3
+ from torchgeo.datasets.geo import NonGeoDataset
4
+ import os
5
+ from collections.abc import Callable, Sequence
6
+ from torch import Tensor
7
+ import numpy as np
8
+ import rasterio
9
+ import cv2
10
+ from pyproj import Transformer
11
+ from datetime import date
12
+ from typing import TypeAlias, ClassVar
13
+ import pathlib
14
+
15
+ import logging
16
+ import pdb
17
+
18
+ logging.getLogger("rasterio").setLevel(logging.ERROR)
19
+ Path: TypeAlias = str | os.PathLike[str]
20
+
21
+ class SenBenchAirQualityS5P(NonGeoDataset):
22
+ url = None
23
+ splits = ('train', 'val', 'test')
24
+ split_fnames = {
25
+ 'train': 'train.csv',
26
+ 'val': 'val.csv',
27
+ 'test': 'test.csv',
28
+ }
29
+
30
+ def __init__(
31
+ self,
32
+ root: Path = 'data',
33
+ split: str = 'train',
34
+ modality = 'no2', # or 'o3'
35
+ mode = 'annual', # or 'seasonal'
36
+ transforms: Callable[[dict[str, Tensor]], dict[str, Tensor]] | None = None,
37
+ download: bool = False,
38
+ ) -> None:
39
+
40
+ self.root = root
41
+ self.transforms = transforms
42
+ self.download = download
43
+ #self.checksum = checksum
44
+
45
+ assert split in ['train', 'val', 'test']
46
+
47
+ self.modality = modality
48
+ self.mode = mode
49
+
50
+ if self.mode == 'annual':
51
+ mode_dir = 's5p_annual'
52
+ elif self.mode == 'seasonal':
53
+ mode_dir = 's5p_seasonal'
54
+
55
+ self.img_dir = os.path.join(root, modality, mode_dir)
56
+ self.label_dir = os.path.join(root, modality, 'label_annual')
57
+
58
+ self.split_csv = os.path.join(self.root, modality, self.split_fnames[split])
59
+ with open(self.split_csv, 'r') as f:
60
+ lines = f.readlines()
61
+ self.pids = []
62
+ for line in lines:
63
+ self.pids.append(line.strip())
64
+
65
+ self.reference_date = date(1970, 1, 1)
66
+ self.patch_area = (16*10/1000)**2 # patchsize 16 pix, gsd 10m
67
+
68
+ def __len__(self):
69
+ return len(self.pids)
70
+
71
+ def __getitem__(self, index):
72
+
73
+ images, meta_infos = self._load_image(index)
74
+ #meta_info = np.array([coord[0], coord[1], np.nan, self.patch_area]).astype(np.float32)
75
+ label = self._load_target(index)
76
+ if self.mode == 'annual':
77
+ sample = {'image': images[0], 'groudtruth': label, 'meta': meta_infos[0]}
78
+ elif self.mode == 'seasonal':
79
+ sample = {'image': images, 'groudtruth': label, 'meta': meta_infos}
80
+
81
+ #pdb.set_trace()
82
+
83
+ if self.transforms is not None:
84
+ sample = self.transforms(sample)
85
+
86
+ return sample
87
+
88
+
89
+ def _load_image(self, index):
90
+
91
+ pid = self.pids[index]
92
+ s5p_path = os.path.join(self.img_dir, pid)
93
+
94
+ img_fnames = os.listdir(s5p_path)
95
+ s5p_paths = []
96
+ for img_fname in img_fnames:
97
+ s5p_paths.append(os.path.join(s5p_path, img_fname))
98
+
99
+ imgs = []
100
+ meta_infos = []
101
+ for img_path in s5p_paths:
102
+ with rasterio.open(img_path) as src:
103
+ img = src.read(1)
104
+ img[np.isnan(img)] = 0
105
+ img = cv2.resize(img, (56,56), interpolation=cv2.INTER_CUBIC)
106
+ img = torch.from_numpy(img).float()
107
+ img = img.unsqueeze(0)
108
+
109
+ # get lon, lat
110
+ cx,cy = src.xy(src.height // 2, src.width // 2)
111
+ if src.crs.to_string() != 'EPSG:4326':
112
+ # convert to lon, lat
113
+ crs_transformer = Transformer.from_crs(src.crs, 'epsg:4326', always_xy=True)
114
+ lon, lat = crs_transformer.transform(cx,cy)
115
+ else:
116
+ lon, lat = cx, cy
117
+ # get time
118
+ img_fname = os.path.basename(img_path)
119
+ date_str = img_fname.split('_')[0][:10]
120
+ date_obj = date(int(date_str[:4]), int(date_str[5:7]), int(date_str[8:10]))
121
+ delta = (date_obj - self.reference_date).days
122
+ meta_info = np.array([lon, lat, delta, self.patch_area]).astype(np.float32)
123
+ meta_info = torch.from_numpy(meta_info)
124
+
125
+ imgs.append(img)
126
+ meta_infos.append(meta_info)
127
+
128
+ if self.mode == 'seasonal':
129
+ # pad to 4 images if less than 4
130
+ while len(imgs) < 4:
131
+ imgs.append(img)
132
+ meta_infos.append(meta_info)
133
+
134
+ return imgs, meta_infos
135
+
136
+ def _load_target(self, index):
137
+
138
+ pid = self.pids[index]
139
+ label_path = os.path.join(self.label_dir, pid+'.tif')
140
+
141
+ with rasterio.open(label_path) as src:
142
+ label = src.read(1)
143
+ label = cv2.resize(label, (56,56), interpolation=cv2.INTER_NEAREST) # 0-650
144
+ # label contains -inf
145
+ #pdb.set_trace()
146
+ label[label<-1e10] = np.nan
147
+ label[label>1e10] = np.nan
148
+ label = torch.from_numpy(label.astype('float32'))
149
+
150
+ return label
151
+
152
+
153
+
154
+ class RegDataAugmentation(torch.nn.Module):
155
+ def __init__(self, split, size):
156
+ super().__init__()
157
+
158
+ mean = torch.Tensor([0.0])
159
+ std = torch.Tensor([1.0])
160
+
161
+ self.norm = K.augmentation.Normalize(mean=mean, std=std)
162
+
163
+ if split == "train":
164
+ self.transform = K.augmentation.AugmentationSequential(
165
+ K.augmentation.Resize(size=size, align_corners=True),
166
+ K.augmentation.RandomRotation(degrees=90, p=0.5, align_corners=True),
167
+ K.augmentation.RandomHorizontalFlip(p=0.5),
168
+ K.augmentation.RandomVerticalFlip(p=0.5),
169
+ data_keys=["input", "input"],
170
+ )
171
+ else:
172
+ self.transform = K.augmentation.AugmentationSequential(
173
+ K.augmentation.Resize(size=size, align_corners=True),
174
+ data_keys=["input", "input"],
175
+ )
176
+
177
+ @torch.no_grad()
178
+ def forward(self, batch: dict[str,]):
179
+ """Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple"""
180
+ x,mask = batch["image"], batch["groudtruth"]
181
+ x = self.norm(x)
182
+ x_out, mask_out = self.transform(x, mask.unsqueeze(0))
183
+ return x_out.squeeze(0), mask_out.squeeze(0), batch["meta"]
184
+
185
+
186
+ class SenBenchAirQualityS5PDataset:
187
+ def __init__(self, config):
188
+ self.dataset_config = config
189
+ self.img_size = (config.image_resolution, config.image_resolution)
190
+ self.root_dir = config.data_path
191
+ self.modality = config.modality
192
+ self.mode = config.mode
193
+
194
+ def create_dataset(self):
195
+ train_transform = RegDataAugmentation(split="train", size=self.img_size)
196
+ eval_transform = RegDataAugmentation(split="test", size=self.img_size)
197
+
198
+ dataset_train = SenBenchAirQualityS5P(
199
+ root=self.root_dir, split="train", modality=self.modality, mode=self.mode, transforms=train_transform
200
+ )
201
+ dataset_val = SenBenchAirQualityS5P(
202
+ root=self.root_dir, split="val", modality=self.modality, mode=self.mode, transforms=eval_transform
203
+ )
204
+ dataset_test = SenBenchAirQualityS5P(
205
+ root=self.root_dir, split="test", modality=self.modality, mode=self.mode, transforms=eval_transform
206
+ )
207
+
208
+ return dataset_train, dataset_val, dataset_test