-
Notifications
You must be signed in to change notification settings - Fork 0
/
majalicious.py
382 lines (322 loc) · 11.9 KB
/
majalicious.py
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import re
import uuid
import warnings
from collections import OrderedDict
def _find_granules(src_input, tile):
granules = list(src_input.glob(f'*.SAFE/GRANULE/*L1C*{tile}*'))
if not granules:
raise RuntimeError(
f'No granule files found in {src_input} for tile {tile}')
return granules
def _maja_date_from_safe_name(safe_name):
"""Get the date-time that MAJA uses to name its product from a .SAFE name"""
dtex = re.compile(r'\d{8}T\d{6}')
if len(safe_name) < 70:
# new format
dtstr = safe_name.split('_')[2]
else:
# old format
dtstr = safe_name.split('_')[5]
if dtex.match(dtstr) is None:
raise ValueError(f'Unable to get date from {safe_name}')
return dtstr
def _date_from_maja_output(name):
"""Get the date-time string from a MAJA L2A product filename"""
try:
return re.search(r'_(\d{8})', name).group(1)
except AttributeError:
raise ValueError(f'Unable to get date string from {name}.')
def _datetime_to_unique_date(date_mapping):
"""Turn a mapping from date-time strings into unique dates where the most recent is preserved
Parameters
----------
date_mapping : OrderedDict
mapping date-time string
of format %Y%m%dT%H%M%S
to something
Returns
-------
OrderedDict
mapping date strings
of format %Y%m%d to something
"""
data = {}
for date_and_time in sorted(list(date_mapping)):
date = date_and_time[:8]
data[date] = date_mapping[date_and_time]
return OrderedDict(sorted(list(data.items())))
def _find_inputs(src_input, tile):
"""Find Sentinel 2 L1C products in src_input for a given tile name
Parameters
----------
src_input : pathlib.Path
source directory
tile : str
tile name e.g. 32UMG
Returns
-------
OrderedDict
maps date to path
L1C .SAFE products sorted by date
"""
all_granules = _find_granules(src_input, tile=tile)
pairs = []
for granule in all_granules:
safe = granule.parents[1]
if not safe.name.endswith('.SAFE'):
raise ValueError(f'Expecting .SAFE, got {safe}')
date = _maja_date_from_safe_name(safe.name)
pairs.append((date, safe))
paths_by_date = OrderedDict(sorted(pairs))
return _datetime_to_unique_date(paths_by_date)
def _find_outputs(dst_output, tile):
"""Find MAJA's L2A products for tile in an output directory
Parameters
----------
dst_output : Path
destination directory
tile : str, format \d{2}{[A-Z]{4}}
Sentinel 2 tile name
Returns
-------
OrderedDict
maps date to path
L2A products sorted by date
"""
fnpattern = f'*SSC_L2VALD*{tile}*.DBL.DIR'
all_paths = dst_output.glob(fnpattern)
pairs = []
for path in all_paths:
date = _date_from_maja_output(path.name)
pairs.append((date, path))
paths_by_date = OrderedDict(sorted(pairs))
return paths_by_date
def _get_most_recent_output(date, outputs_by_date):
"""Finds the most recent L2A product before `date` to be used in forward mode
Parameters
----------
date : str
date in format %Y%m%d
outputs_by_date : OrderedDict
mapping date to path
Returns
-------
dict length 1
most recent item from outputs_by_date before the given date
"""
most_recent_date = None
for output_date, output_path in outputs_by_date.items():
if output_date >= date:
break
if (most_recent_date is None) or (output_date > most_recent_date):
most_recent_date = output_date
if most_recent_date is None:
return None
else:
return {most_recent_date: outputs_by_date[most_recent_date]}
def _get_inputs_backward(date, inputs_by_date, num_inputs=8):
"""Get L1C products after a reference date
Parameters
----------
date : str
reference date
inputs_by_date : OrderedDict
mapping date to path
assumed to be ordered in ascending order by date
num_inputs : int
number of inputs to find
Returns
-------
OrderedDict
selected items from inputs_by_date
"""
pairs = []
for input_date, input_path in inputs_by_date.items():
if input_date < date:
continue
if len(pairs) >= num_inputs:
break
pairs.append((input_date, input_path))
return OrderedDict(pairs)
def _symlink_dir_contents(src_dir, dst_dir):
"""Create symlinks in dst_dir for all files in src_dir"""
for src in src_dir.glob('*'):
dst = dst_dir / src.name
dst.symlink_to(src)
def _symlink_into_dir(src_file, dst_dir):
"""Create a symlink for src_file in dst_dir"""
dst_file = dst_dir / src_file.name
dst_file.symlink_to(src_file)
return dst_file
def _symlink_l2a(src_dbldir, dst_dir):
"""Create symlinks for a MAJA L2A product, including .HDR file"""
if not src_dbldir.match('*.DBL.DIR'):
raise ValueError(f'Expecting a .DBL.DIR file, got {src_dbldir}')
dbl = src_dbldir.parent / src_dbldir.stem
hdr = dbl.with_suffix('.HDR')
for path in [src_dbldir, dbl, hdr]:
if not path.exists():
raise RuntimeError(f'File not found: {path}')
_symlink_into_dir(path, dst_dir)
def be_a_symlink_guy(
src_input, src_userconf, src_dtm, src_gipp,
dst_work_root, dst_output, tile, maja,
start_date=None, end_date=None, num_backward=8):
"""Create all necessary symlinks in dst_work and yield MAJA commands to be run sequentially
Parameters
----------
src_input : pathlib.Path
directory containing L1C input products (.SAFE)
src_userconf : pathlib.Path
directory containing config files
src_dtm : pathlib.Path
directory containing DTM files
src_gipp : pathlib.Path
directory containing GIPP files
dst_work_root : pathlib.Path
root directory where to create work folders
for products
dst_output : pathlib.Path
directory where to save L2A outputs to
tile : str
tile name (e.g. 32UNG)
maja : pathlib.Path
path to MAJA executable
start_date, end_date : str, optional
process products with acquisition dates in this range
format %Y%m%dT%H%M%S
num_backward : int
number of products to process when running
in backward mode
Notes
-----
The work directory must contain images, all GIPPs files, the DTM, etc.
The work directory must contain only one L1 product for the 'L2INIT' mode,
a list of L1 products for the 'L2BACKWARD' mode,
one L1 product and one L2 product for the 'L2NOMINAL' mode
and a list of L2 products for the L3 mode.
Yields
------
str
command to execute MAJA
"""
tile = tile.upper()
inputs_by_date = _find_inputs(src_input, tile)
outputs_by_date = _find_outputs(dst_output, tile)
if outputs_by_date:
inputs_to_process = {
d: path for d, path in inputs_by_date.items() if d not in outputs_by_date}
else:
inputs_to_process = inputs_by_date
if start_date is not None or end_date is not None:
ds = start_date or '0'
de = end_date or '9'
inputs_to_process = {
d: path for d, path in inputs_to_process.items() if (ds >= d >= de)}
if not inputs_to_process:
print('No new input data to process.')
return
minusp = dict(parents=True, exist_ok=True)
dst_output.mkdir(**minusp)
dst_work_root.mkdir(**minusp)
dst_userconf = dst_work_root / 'userconf'
if dst_userconf.exists():
dst_userconf.unlink()
dst_userconf.symlink_to(src_userconf)
for date, input_path in inputs_to_process.items():
print(f'Processing date {date}')
new_uuid = str(uuid.uuid4())
dst_work = dst_work_root / f'work_{date}_{new_uuid}'
dst_work.mkdir(exist_ok=False)
_symlink_dir_contents(src_dtm, dst_work)
_symlink_dir_contents(src_gipp, dst_work)
output = _get_most_recent_output(date, outputs_by_date)
if output is None:
print(f'No recent L2A product for date {date}')
mode = 'L2BACKWARD'
inputs_backward = _get_inputs_backward(date, inputs_by_date, num_backward)
num_backward_found = len(inputs_backward)
if num_backward_found < num_backward:
warnings.warn(
f'Did not find {num_backward} input products for '
f'backward processing but only {num_backward_found}.')
for input_backward in inputs_backward.values():
_symlink_into_dir(input_backward, dst_work)
else:
output_date, output_path = next(iter(output.items()))
print(f'Most recent L2A product date is {output_date}')
mode = 'L2NOMINAL'
_symlink_l2a(output_path, dst_work)
_symlink_into_dir(input_path, dst_work)
print('Work folder contents:')
print('\n'.join([str(p.name) for p in dst_work.glob('*')]))
cmd = [
str(maja),
'-i', str(dst_work),
'-o', str(dst_output),
'-m', mode,
'-ucs', str(dst_userconf),
'--TileId', tile]
yield cmd
# update outputs
outputs_by_date = _find_outputs(dst_output, tile)
def runner(tile, **kwargs):
"""Create symlinks and run MAJA"""
import subprocess
kwargs.update(tile=tile)
for k in ['src_dtm']:
kwargs[k] = pathlib.Path(str(kwargs[k]).format(tile=tile))
for cmd in be_a_symlink_guy(**kwargs):
cmdstr = ' '.join(cmd)
print(f'Running MAJA command {cmdstr}')
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
line = True
while line:
line = proc.stdout.readline().rstrip()
print(line)
proc.communicate()
if proc.returncode != 0:
raise RuntimeError(f'MAJA command {cmdstr} failed.')
if __name__ == '__main__':
import os
import argparse
import pathlib
def to_path(value):
if value:
return pathlib.Path(value)
else:
return value
parser = argparse.ArgumentParser(description='Create symlinks and run MAJA')
parser.add_argument(
'--src-input', type=to_path, required=True, help='dir containing L1C .SAFE')
parser.add_argument(
'--dst-output', type=to_path, required=True, help='Output directory')
parser.add_argument(
'--tile', required=True, help='Tile name (e.g. 32UNG)')
parser.add_argument(
'--src-userconf', default=pathlib.Path('/maja-aux/userconf'),
type=to_path, help='userconf dir (default: /maja-aux/userconf)')
parser.add_argument(
'--src-gipp', default=pathlib.Path('/maja-aux/GIPP'),
type=to_path, help='GIPP dir (default: /maja-aux/GIPP)')
parser.add_argument(
'--src-dtm', default='/maja-aux/DTM/{tile}',
type=to_path, help='DTM dir (default: /maja-aux/DTM/{tile})')
parser.add_argument(
'--dst-work-root', default=pathlib.Path('/maja-work-root'),
type=to_path, help='Work root dir (default: /maja-work-root)')
parser.add_argument(
'--start-date', default=None,
help='Process images from this acquisition date onward (format %Y%m%dT%H%M%S)')
parser.add_argument(
'--end-date', default=None,
help='Process images until this acquisition date (format %Y%m%dT%H%M%S)')
parser.add_argument(
'--maja', type=to_path, help='Path to maja executable (default: read MAJA_BIN envvar)')
args = parser.parse_args()
kwargs = vars(args)
if kwargs['maja'] is None:
kwargs['maja'] = os.environ.get('MAJA_BIN', None)
if kwargs['maja'] is None:
raise RuntimeError('You need to either provide `--maja` or define envvar MAJA_BIN')
runner(**kwargs)