File size: 10,688 Bytes
cfaa196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfee986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaa196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfee986
cfaa196
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import os
import sys
import lmdb
import gzip
import torch
import logging
import numpy as np
from enum import Enum
import safetensors.torch
from torch.utils.data import Dataset

"""
tensors = {
        "center": torch.tensor(center),
        "wcmap": map_data,
        "B4": rgbnir_data[0, :, :],
        "B3": rgbnir_data[1, :, :],
        "B2": rgbnir_data[2, :, :],
        "B8": rgbnir_data[3, :, :],
        "B11": swir_data[0, :, :],
        "B12": swir_data[1, :, :],
        "S1VV": s1_data[0, :, :],
        "S1VH": s1_data[1, :, :],
        "classprops": torch.tensor(count_classes(map_data)),
    }
"""


class Bands(Enum):
    B2 = "B2"  # blue
    B3 = "B3"  # green
    B4 = "B4"  # red
    B8 = "B8"  # VNIR
    B11 = "B11"  # SWIR
    B12 = "B12"  # SWIR
    S1VV = "S1VV"
    S1VH = "S1VH"
    RGBNIR = "RGBNIR"
    SWIR = "SWIR"
    S1 = "S1"
    ALL = "ALL"


class WCv1LMDBReader(Dataset):
    def __init__(self,
                 map_lmdb_file: os.PathLike,
                 split: str,
                 return_key=False,
                 readonly=True,
                 lmdb_size_limit=8*1024**3,
                 key_type=str,
                 max_len=-1,
                 return_type=tuple,
                 output_bands: list = [Bands.RGBNIR],
                 transforms=None
                 ):
        super().__init__()
        self.map_lmdb_file = map_lmdb_file
        self.env: lmdb.Environment | None = None
        self.db = None
        self.return_key = return_key
        self.logger = logging.getLogger(__name__)
        self.readonly = readonly
        self._keys = None
        self.lmdb_size_limit = lmdb_size_limit
        self.key_type = key_type
        self.max_len = max_len
        self.return_type = return_type
        # self.configure_output(output_bands)
        self. transforms = transforms
        self.split = split
        
        if split is not None:
            assert split in ['train', 'val', 'test'], f"unrecignized split type. Expected one of ['train', 'val', 'test'] but got {split}"
        
        # self.keys()
        self.configure_output(output_bands)

        
    def configure_output(self, output_bands):
        output = []
        for band in output_bands:
            if band == Bands.RGBNIR:
                output += [Bands.B2, Bands.B3, Bands.B4, Bands.B8]
            elif band == Bands.SWIR:
                output += [Bands.B11, Bands.B12]
            elif band == Bands.S1:
                output += [Bands.S1VV, Bands.S1VH]
            elif band == Bands.ALL:
                output = [Bands.B2, Bands.B3, Bands.B4, Bands.B8,
                          Bands.B11, Bands.B12, Bands.S1VV, Bands.S1VH]
            else:
                if band not in output:
                    output.append(band)
        self.output_bands = output

    def set_transforms(self, transfomrs):
        self.transforms = transfomrs

    def set_max_len(self, max_len):
        self.max_len = max_len
        self.keys()

    def open_env(self):
        try:
            if self.env is None:
                self.logger.info(
                    f"Opening LMDB environment at {self.map_lmdb_file} ...")
                self.env = lmdb.open(
                    self.map_lmdb_file,
                    readonly=self.readonly,
                    lock=not self.readonly,
                    meminit=False,
                    readahead=True,
                    map_size=self.lmdb_size_limit,
                    max_spare_txns=18,
                    max_dbs=3
                )
                if self.split is not None:
                    self.db = self.env.open_db(self.split.encode())
                else:
                    self.db = None
        except Exception as err:
            raise err

    def keys(self, update: bool = False):
        self.open_env()

        if self._keys is None or update:
            logging.info("(Re-)Reading keys")
            with self.env.begin(db=self.db) as txn:
                self._keys = list(txn.cursor().iternext(values=False))
            if self.key_type == str:
                self._keys = [x.decode() for x in self._keys]
            elif self.key_type == int:
                self._keys = [int.from_bytes(x, 'big') for x in self._keys]
        if self.max_len > 0:
            idxs = np.random.choice(np.arange(len(self._keys)), self.max_len)
            self._keys = np.asarray(self._keys)[idxs]
        return self._keys

    def _encode_key(self, key):
        if self.key_type == str:
            return key.encode()
        if self.key_type == int:
            return key.to_bytes(sys.getsizeof(key), 'big')
        return None

    def close_env(self):
        if self.env is not None:
            self.env.close()
            self.env = None

    def update_key(self, key: str, updateData: dict, compress=False) -> bool:
        try:
            if self.env is None:
                self.logger.info("LMDB not yet opened")
                self.logger.info("Open LMDB")
                self.open_env()
            with self.env.begin(write=True, db=self.db) as txn:
                byte_data = safetensors.torch.save(updateData)
                if compress:
                    byte_data = gzip.compress(byte_data)
                status = txn.put(self._encode_key(key), byte_data)
            return status
        except Exception as ex:
            print(ex)
            self.logger.error(ex)
            raise ex
        
    def delete_key(self, index:str|int):
        if type(index) == int and self.key_type != int:
            key = self._keys[index]
        else:
            key = index
        with self.env.begin(write=True, buffers=True, db=self.db) as txn:
            status = txn.delete(self._encode_key(key))
            self.keys()
            return status

    def count_classes(self, map: np.ndarray | torch.Tensor,output_type=None) -> np.ndarray | torch.Tensor:
        """function to count the class proportions of an segmentation map.
    
        Args:
            map (np.ndarray | torch.Tensor): input map on which the class proportions needs to be counted. Input can be a single map (np.ndarray) or batched tensor of multiple maps (torch.Tensor)
    
        Returns:
            np.ndarray | torch.Tensor: the class proportions of the input map. 
        """
        if len(map.shape) == 3:
            map = map.squeeze()
        
        if type(map) == np.ndarray:
            map = torch.tensor(map, dtype=torch.float32)
        
        output = []
        num_pixel = map.shape[0] * map.shape[1]
        
        for i in range(10, 110, 10):
            if len(map.shape) == 4:
                percentage = torch.sum(torch.where(map == i, 1, 0), dim=(1,2,3)) / num_pixel
            else:
                percentage = torch.sum(torch.where(map == i, 1, 0)) / num_pixel
            output.append(percentage)
            
            if i == 90:
                if len(map.shape) == 4:
                    percentage = torch.sum(torch.where(map == i, 1, 0), dim=(1,2,3)) / num_pixel
                else:
                    percentage = torch.sum(torch.where(map == i, 1, 0)) / num_pixel
                output.append(percentage)
        
        if len(map.shape) == 4:
            class_props = torch.stack(output, dim=1)
            class_props.requires_grad = True
        else:
            class_props = torch.tensor(output)
        
        if type(map) == np.ndarray:
            return class_props.cpu().detach().numpy()
        if type(map) == torch.Tensor:
            if output_type is not None:
                return class_props.type(dtype=output_type)
            else:
                return class_props

    def __len__(self):
        if self._keys is None:
            self.logger.info("keys are not loaded yet")
            self.logger.info("Loading keys")
            self.keys()
        if self.max_len > 0:
            return self.max_len
        else:
            return len(self._keys)

    def __getitem__(self, index: int | str):
        assert type(index) == int or type(
            index) == str, f"index can only be of type int or str. Got {type(index)}"

        if self.env is None:
            self.logger.info("LMDB not yet opened")
            self.logger.info("Open LMDB")
            try:
                self.open_env()
            except Exception as err:
                raise err
            
        key = None
        with self.env.begin(write=False, buffers=True) as txn:
            if type(index) == int and self.key_type != int:
                byte_data = txn.get(self._encode_key(self._keys[index]), db=self.db)
                key = self._keys[index]
            else:
                byte_data = txn.get(self._encode_key(index), db=self.db)
                key = index
            magic_number = b'\x1f\x8b'

            try:
                # check if byte_data is gzip-compressed
                if (bytes([byte_data[0], byte_data[1]]) == magic_number):
                    tensor_dict = safetensors.torch.load(
                        gzip.decompress(byte_data))
                else:
                    tensor_dict = safetensors.torch.load(bytes(byte_data))
            except KeyError as e:
                print(e)

            # print(tensor_dict.keys())
            # print(self.output_bands)

            if "wcmap" in tensor_dict.keys():
                num_no_data = torch.where(tensor_dict['wcmap'] == 0, 1, 0)
                # if (torch.sum(num_no_data) > 0):
                #     print(f"{key} contains nodata")
                class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100]
                label = tensor_dict['wcmap'].clone()
                for i, val in enumerate(class_values):
                    label = torch.where(
                        label == val, i, label)
                label = torch.nn.functional.one_hot(
                    label.squeeze().type(torch.LongTensor), 11).permute(2, 0, 1)

            if self.return_key:
                tensor_dict['key'] = key
        if self.return_type == dict:
            return tensor_dict
        else:
            bands = []
            for band in self.output_bands:
                bands.append(tensor_dict[band.value])
            rs_image = torch.stack(bands, 0).type(torch.float32)
            
            if self.transforms is not None:
                image = self.transforms(rs_image)
            else:
                image = rs_image

            if "classprops" in tensor_dict.keys():
                class_props = tensor_dict['classprops']
            else:
                class_props = self.count_classes(tensor_dict['wcmap'])
            return (image, label, class_props)