File size: 4,078 Bytes
1981005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from torch.utils.data import DataLoader, Dataset
import cv2
import os
import rasterio
import numpy as np
from pyproj import Transformer
from datetime import date

class S5P_EEAAirQualityDataset(Dataset):
    '''
    1973/494 train/test air quality dataset for NO2 and O3, measure from S5P, label from EEA
    annual: 1x56x56x1 annual avg
    seasonal: 4x56x56x1 seasonal avg
    s5p nodata: -inf
    label nodata: -3.4e38 # this needs to be masked out for loss and metric calculation
    '''

    def __init__(self, root_dir, modality='no2', mode='annual', split='train', meta=False):
        self.root_dir = root_dir
        self.mode = mode
        self.modality = modality

        if self.mode == 'annual':
            mode_dir = 's5p_annual'
        elif self.mode == 'seasonal':
            mode_dir = 's5p_seasonal'

        self.img_dir = os.path.join(root_dir, modality, split, mode_dir)
        self.label_dir = os.path.join(root_dir, modality, split, 'label_annual')

        self.fnames = sorted(os.listdir(self.label_dir))
   
        self.meta = meta
        if self.meta:
            self.reference_date = date(1970, 1, 1)

    def __len__(self):
        return len(self.fnames)
    
    def __getitem__(self, idx):
        fname = self.fnames[idx] # label filename
        label_path = os.path.join(self.label_dir, fname)
        img_path = os.path.join(self.img_dir, fname.replace('.tif', ''))
        img_fnames = os.listdir(img_path)
        img_paths = []
        for img_fname in img_fnames:
            img_paths.append(os.path.join(img_path, img_fname))
        
        # img
        imgs = []
        meta_infos = []
        for img_path in img_paths:
            with rasterio.open(img_path) as src:
                img = src.read(1)
                img = cv2.resize(img, (56,56), interpolation=cv2.INTER_CUBIC)
                img[np.isnan(img)] = 0
                img = torch.from_numpy(img).float()
                img = img.unsqueeze(0)

                if self.meta:
                    cx,cy = src.xy(src.height // 2, src.width // 2)
                    crs_transformer = Transformer.from_crs(src.crs, 'epsg:4326')
                    lon, lat = crs_transformer.transform(cx,cy)
                    #lon, lat = cx, cy
                    img_fname = os.path.basename(img_path)
                    date_str = img_fname.split('_')[0][:10]
                    date_obj = date(int(date_str[:4]), int(date_str[5:7]), int(date_str[8:10]))
                    delta = (date_obj - self.reference_date).days
                    meta_info = np.array([lon, lat, delta, 0]).astype(np.float32)
                else:
                    meta_info = np.array([np.nan,np.nan,np.nan,np.nan]).astype(np.float32)

            imgs.append(img)
            meta_infos.append(meta_info)
        if self.mode == 'seasonal':
            # pad to 4 images if less than 4
            while len(imgs) < 4:
                imgs.append(img)
                img_paths.append(img_path)
                meta_infos.append(meta_info)
        # label
        with rasterio.open(label_path) as src:
           label = src.read(1)
           label = cv2.resize(label, (56,56), interpolation=cv2.INTER_CUBIC) # 0-650
           label[label<-1e10] = np.nan
           label[label>1e10] = np.nan
           #label[np.isnan(label)] = -1e10
           label = torch.from_numpy(label.astype('float32'))
        #nan_mask = (label > -1e10)

        if self.mode == 'annual':
            return imgs[0], meta_infos[0], label#, nan_mask #,label_path
        elif self.mode == 'seasonal':
            return imgs[0], imgs[1], imgs[2], imgs[3], meta_infos[0], meta_infos[1], meta_infos[2], meta_infos[3], label#, nan_mask #,label_path
        
if __name__ == '__main__':
    dataset = S5P_EEAAirQualityDataset(root_dir='./airquality_s5p', modality='no2', mode='annual', split='train')
    dataloader = DataLoader(dataset, batch_size=1, shuffle=False)
    for i, data in enumerate(dataloader):
        print(data[0].shape, data[1].shape, data[2].shape, data[3].shape)
        break