forked from DHI-GRAS/efast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_efast.py
More file actions
284 lines (247 loc) · 8.11 KB
/
run_efast.py
File metadata and controls
284 lines (247 loc) · 8.11 KB
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
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2024 DHI A/S & contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@author: rmgu, pase
"""
import argparse
import os
import zipfile
from datetime import datetime, timedelta
from pathlib import Path
from creodias_finder import query
from creodias_finder.download import _get_token, download
from dateutil import rrule
from tqdm import tqdm
import efast.efast as efast
import efast.s2_processing as s2
import efast.s3_processing as s3
# CDSE credentials to download Sentinel-2 and Sentinel-3 imagery
def get_credentials_from_env():
"""
Read CDSE credentials from the environment variables CDSE_USER and CDSE_PASSWORD.
Returns
-------
Dictionary containing "username" and "password" keys mapped to the values of the CDSE_USER and CDSE_PASSWORD
environment variables.
"""
username = os.getenv("CDSE_USER")
password = os.getenv("CDSE_PASSWORD")
return {
"username": username,
"password": password
}
CREDENTIALS = get_credentials_from_env()
# Test parameters
path = Path("./test_data").absolute()
s3_download_dir = path / "S3/raw"
s3_binning_dir = path / "S3/binning"
s3_composites_dir = path / "S3/composites"
s3_blured_dir = path / "S3/blurred"
s3_calibrated_dir = path / "S3/calibrated"
s3_reprojected_dir = path / "S3/reprojected"
s2_download_dir = path / "S2/raw"
s2_processed_dir = path / "S2/processed"
fusion_dir = path / "fusion_results"
def main(
start_date: str,
end_date: str,
aoi_geometry: str,
s3_sensor: str,
s3_bands: list,
s2_bands: list,
mosaic_days: int,
step: int,
cdse_credentials: dict,
ratio: int,
snap_gpt_path: str = "gpt",
):
# Transform parameters
start_date = datetime.strptime(start_date, "%Y-%m-%d")
end_date = datetime.strptime(end_date, "%Y-%m-%d")
if s3_sensor == "SYN":
instrument = "SYNERGY"
else:
instrument = s3_sensor
# Create directories if necessary
for folder in [
s3_download_dir,
s3_binning_dir,
s3_composites_dir,
s3_blured_dir,
s3_calibrated_dir,
s3_reprojected_dir,
s2_processed_dir,
s2_download_dir,
fusion_dir,
]:
folder.mkdir(parents=True, exist_ok=True)
# Download the data from CDSE
download_from_cdse(
start_date,
end_date,
aoi_geometry,
s2_download_dir,
s3_download_dir,
cdse_credentials)
# Sentinel-2 pre-processing
s2.extract_mask_s2_bands(
s2_download_dir,
s2_processed_dir,
bands=s2_bands,
)
s2.distance_to_clouds(
s2_processed_dir,
ratio=ratio,
)
footprint = s2.get_wkt_footprint(
s2_processed_dir,
)
# Sentinel-3 pre-processing
s3.binning_s3(
s3_download_dir,
s3_binning_dir,
footprint=footprint,
s3_bands=s3_bands,
instrument=instrument,
aggregator="mean",
snap_gpt_path=snap_gpt_path,
snap_memory="24G",
snap_parallelization=1,
)
s3.produce_median_composite(
s3_binning_dir,
s3_composites_dir,
mosaic_days=mosaic_days,
step=step,
s3_bands=None,
)
s3.smoothing(
s3_composites_dir,
s3_blured_dir,
std=1,
preserve_nan=False,
)
s3.reformat_s3(
s3_blured_dir,
s3_calibrated_dir,
)
s3.reproject_and_crop_s3(
s3_calibrated_dir,
s2_processed_dir,
s3_reprojected_dir,
)
# Perform EFAST fusion
for date in rrule.rrule(
rrule.DAILY,
dtstart=start_date + timedelta(step),
until=end_date - timedelta(step),
interval=step,
):
efast.fusion(
date,
s3_reprojected_dir,
s2_processed_dir,
fusion_dir,
product="REFL",
ratio=ratio,
max_days=100,
minimum_acquisition_importance=0,
)
def download_from_cdse(
start_date,
end_date,
aoi_geometry,
s2_download_dir,
s3_download_dir,
credentials):
# First download Sentinel-3 SYN data
results = query.query('Sentinel3',
start_date=start_date,
end_date=end_date,
geometry=aoi_geometry,
instrument="SYNERGY",
productType="SY_2_SYN___",
timeliness="NT")
download_list_safe([result['id'] for result in results.values()],
outdir=s3_download_dir,
threads=3,
**credentials)
for zip_file in s3_download_dir.glob("*.zip"):
with zipfile.ZipFile(zip_file, "r") as zip_ref:
zip_ref.extractall(s3_download_dir)
# Then download Sentinel-2 L2A data
results = query.query(
'Sentinel2',
start_date=start_date,
end_date=end_date,
geometry=aoi_geometry,
productType="L2A",
)
download_list_safe(
[result['id'] for result in results.values()],
outdir=s2_download_dir,
threads=3,
**credentials,
)
for zip_file in s2_download_dir.glob("*.zip"):
with zipfile.ZipFile(zip_file, "r") as zip_ref:
zip_ref.extractall(s2_download_dir)
def download_list_safe(uids, username, password, outdir, threads=1, show_progress=True):
if show_progress:
pbar = tqdm(total=len(uids), unit="files")
def _download(uid):
token = _get_token(username, password)
outfile = Path(outdir) / f"{uid}.zip"
download(
uid, username, password, outfile=outfile, show_progress=False, token=token
)
if show_progress:
pbar.update(1)
return uid, outfile
paths = [_download(u) for u in uids]
return paths
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--start-date", default="2023-09-11")
parser.add_argument("--end-date", default="2023-09-21")
parser.add_argument("--aoi-geometry", default="POINT (-15.432283 15.402828)") # Dahra EC tower
parser.add_argument("--s3-sensor", default="SYN")
parser.add_argument(
"--s3-bands", nargs="+", default=["SDR_Oa04", "SDR_Oa06", "SDR_Oa08", "SDR_Oa17"]
)
parser.add_argument("--s2-bands", nargs="+", default=["B02", "B03", "B04", "B8A"])
parser.add_argument("--mosaic-days", type=int, default=100)
parser.add_argument("--step", type=int, required=False, default=2)
parser.add_argument("--cdse-credentials", default=CREDENTIALS)
parser.add_argument("--snap-gpt-path", required=False, default="gpt")
parser.add_argument("--ratio", required=False, type=int, default=30)
args = parser.parse_args()
main(
start_date=args.start_date,
end_date=args.end_date,
aoi_geometry=args.aoi_geometry,
s3_sensor=args.s3_sensor,
s3_bands=args.s3_bands,
s2_bands=args.s2_bands,
step=args.step,
mosaic_days=args.mosaic_days,
cdse_credentials=args.cdse_credentials,
ratio=args.ratio,
snap_gpt_path=args.snap_gpt_path
)