File size: 10,305 Bytes
e6eb7ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import List
from pathlib import Path
import logging
import numpy as np
import pandas as pd
import xarray as xr
import datasets
from datasets import Array2D, Array3D, Value

logger = logging.getLogger(__name__)


_DESCRIPTION = 'Initial Release of eo4wildfires for Huggingface library.'
_CITATION = '''
    @Article{fire7110374,
        AUTHOR = {Sykas, Dimitris and Zografakis, Dimitrios and Demestichas, Konstantinos},
        TITLE = {Deep Learning Approaches for Wildfire Severity Prediction: A Comparative Study of Image Segmentation Networks and Visual Transformers on the EO4WildFires Dataset},
        JOURNAL = {Fire},
        VOLUME = {7},
        YEAR = {2024},
        NUMBER = {11},
        ARTICLE-NUMBER = {374},
        URL = {https://www.mdpi.com/2571-6255/7/11/374},
        ISSN = {2571-6255},
        ABSTRACT = {This paper investigates the applicability of deep learning models for predicting the severity of forest wildfires, utilizing an innovative benchmark dataset called EO4WildFires. EO4WildFires integrates multispectral imagery from Sentinel-2, SAR data from Sentinel-1, and meteorological data from NASA Power annotated with EFFIS data for forest fire detection and size estimation. These data cover 45 countries with a total of 31,730 wildfire events from 2018 to 2022. All of these various sources of data are archived into data cubes, with the intention of assessing wildfire severity by considering both current and historical forest conditions, utilizing a broad range of data including temperature, precipitation, and soil moisture. The experimental setup has been arranged to test the effectiveness of different deep learning architectures in predicting the size and shape of wildfire-burned areas. This study incorporates both image segmentation networks and visual transformers, employing a consistent experimental design across various models to ensure the comparability of the results. Adjustments were made to the training data, such as the exclusion of empty labels and very small events, to refine the focus on more significant wildfire events and potentially improve prediction accuracy. The models’ performance was evaluated using metrics like F1 score, IoU score, and Average Percentage Difference (aPD). These metrics offer a multi-faceted view of model performance, assessing aspects such as precision, sensitivity, and the accuracy of the burned area estimation. Through extensive testing the final model utilizing LinkNet and ResNet-34 as backbones, we obtained the following metric results on the test set: 0.86 F1 score, 0.75 IoU, and 70% aPD. These results were obtained when all of the available samples were used. When the empty labels were absent during the training and testing, the model increased its performance significantly: 0.87 F1 score, 0.77 IoU, and 44.8% aPD. This indicates that the number of samples, as well as their respectively size (area), tend to have an impact on the model’s robustness. This restriction is well known in the remote sensing domain, as accessible, accurately labeled data may be limited. Visual transformers like TeleViT showed potential but underperformed compared to segmentation networks in terms of F1 and IoU scores.},
        DOI = {10.3390/fire7110374}}
    '''

DEFAULT_CONFIG_NAME = 'base'
VERSION = datasets.Version('0.0.1')

_URL = 'https://huggingface.co/datasets/AUA-Informatics-Lab/eo4wildfires/resolve/main/'
_URLS = {
    'dataset': _URL + 'eo4wildfires.tar.gz',
    'train': _URL + 'files_train.csv.gz',
    'validation': _URL + 'files_val.csv.gz',
    'test': _URL + 'files_test.csv.gz',
}

nasa_cols = [
    'RH2M', 'T2M', 'PRECTOTCORR', 'WS2M',
    'FRSNO', 'GWETROOT', 'SNODP', 'PRECSNOLAND',
    'GWETTOP'
]

# (y, x)
patch_size = (224, 224)


def make_patches(
        arr: np.ndarray
) -> np.ndarray:

    if arr.ndim == 2:
        num_patches_h = int(arr.shape[0] // patch_size[0])
        num_patches_w = int(arr.shape[1] // patch_size[1])

        _ = np.reshape(arr, (num_patches_h, patch_size[0], num_patches_w, patch_size[1]))
        _ = np.transpose(_, (0, 2, 1, 3))
        _ = np.reshape(_, (-1, patch_size[0], patch_size[1]))
    elif arr.ndim == 3:
        num_patches_h = int(arr.shape[1] // patch_size[0])
        num_patches_w = int(arr.shape[2] // patch_size[1])

        _ = np.reshape(arr, (arr.shape[0], num_patches_h, patch_size[0], num_patches_w, patch_size[1]))
        _ = np.transpose(_, (1, 3, 0, 2, 4))
        _ = np.reshape(_, (-1, arr.shape[0], patch_size[0], patch_size[1]))
    else:
        raise NotImplemented(f'Patches not implemented for array with dimensions: {arr.ndim}')

    return _


class EO4Wildfires(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name='base', version=VERSION, description=_DESCRIPTION),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    'id': Value('string'),
                    'S1_GRD_A': Array3D(shape=(3, patch_size[0], patch_size[1]), dtype='float32'),
                    'S1_GRD_D': Array3D(shape=(3, patch_size[0], patch_size[1]), dtype='float32'),
                    'S2A': Array3D(shape=(6, patch_size[0], patch_size[1]), dtype='float32'),
                    'NASA': Array2D(shape=(9, 31), dtype='float32'),
                    'x': Array2D(shape=(patch_size[0], patch_size[1]), dtype='float64'),
                    'y': Array2D(shape=(patch_size[0], patch_size[1]), dtype='float64'),
                    'total_burned_area': Value('float64'),
                    'burned_mask': Array2D(shape=(patch_size[0], patch_size[1]), dtype='float32'),
                }
            ),
            supervised_keys=None,
            homepage='https://huggingface.co/AUA-Informatics-Lab',
            citation=_CITATION,
            version=VERSION
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
        logger.info(f'Downloading and Extracting files from {_URL}. This might take a while.')

        # Download files from repo locally
        downloaded_files = dl_manager.download_and_extract(_URLS)

        logger.info(f'Creating data split generators')
        # List train files
        df = pd.read_csv(downloaded_files['train'], names=['file'], dtype={'file': 'str'})
        filepaths_train = sorted(
            [Path(downloaded_files['dataset']) / 'eo4wildfires' / row.file for row in df.itertuples()]
        )

        # List val files
        df = pd.read_csv(downloaded_files['validation'], names=['file'], dtype={'file': 'str'})
        filepaths_val = sorted(
            [Path(downloaded_files['dataset']) / 'eo4wildfires' / row.file for row in df.itertuples()]
        )

        # List test files
        df = pd.read_csv(downloaded_files['test'], names=['file'], dtype={'file': 'str'})
        filepaths_test = sorted(
            [Path(downloaded_files['dataset']) / 'eo4wildfires' / row.file for row in df.itertuples()]
        )

        # Create generators
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN, gen_kwargs={
                    'filepaths': filepaths_train,
                }
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION, gen_kwargs={
                    'filepaths': filepaths_val,
                }
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST, gen_kwargs={
                    'filepaths': filepaths_test,
                }
            ),
        ]


    def _generate_examples(self, filepaths):
        logger.info(f'Generating Samples.')

        # Loop over files
        for filepath in filepaths:
            event_id = int(Path(filepath).stem)

            # Open netcdf dataset
            _data = xr.open_dataset(filepath, decode_coords='all')

            # Convert xarray data to numpy arrays
            s1a = _data['S1_GRD_A'].to_numpy()
            s1d = _data['S1_GRD_D'].to_numpy()
            s2a = _data['S2A'].to_numpy()
            burned_area = _data['BURNED_AREA'].to_numpy()
            nasa = np.array([_data[col].to_numpy() for col in nasa_cols])

            # Load mask, fill nan with 0s
            burned_mask = _data['burned_mask'].to_numpy()
            burned_mask[np.isnan(burned_mask)] = 0

            # Tile coordinates
            x = np.expand_dims(_data.x.values, axis=0)
            y = np.expand_dims(_data.y, axis=1)
            x = np.tile(x, (y.shape[0], 1))
            y = np.tile(y, (1, x.shape[1]))

            # How much to pad in each dim
            pad_1d = (0, 0)
            pad_2d = (0, patch_size[0] - (s1a.shape[1] % patch_size[0]))
            pad_3d = (0, patch_size[1] - (s1a.shape[2] % patch_size[1]))

            # Do the padding
            s1a = np.pad(s1a, (pad_1d, pad_2d, pad_3d), 'constant')
            s1d = np.pad(s1d, (pad_1d, pad_2d, pad_3d), 'constant')
            s2a = np.pad(s2a, (pad_1d, pad_2d, pad_3d), 'constant')
            burned_mask = np.pad(burned_mask, (pad_2d, pad_3d), 'constant')
            x = np.pad(x, (pad_2d, pad_3d), 'constant')
            y = np.pad(y, (pad_2d, pad_3d), 'constant')

            # Resize everything to (N, self.patch_size[0], self.patch_size[1])
            s1a = make_patches(s1a)
            s1d = make_patches(s1d)
            s2a = make_patches(s2a)
            burned_mask = make_patches(burned_mask)
            x = make_patches(x)
            y = make_patches(y)

            # Loop over patches
            num_patches = s1a.shape[0]

            for patch_id in range(num_patches):
                _id = f'{event_id}-{patch_id:03d}'
                yield _id, {
                    '_id': _id,
                    'event_id': event_id,
                    'patch_id': patch_id,
                    'S1_GRD_A': s1a[patch_id],
                    'S1_GRD_D': s1d[patch_id],
                    'S2A': s2a[patch_id],
                    'NASA': nasa,
                    'x': x[patch_id],
                    'y': y[patch_id],
                    'total_burned_area': burned_area,
                    'burned_mask': burned_mask[patch_id],
                }