-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbatch_scenes2strips.py
More file actions
2181 lines (1895 loc) · 94.9 KB
/
batch_scenes2strips.py
File metadata and controls
2181 lines (1895 loc) · 94.9 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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Erik Husby, Claire Porter; Polar Geospatial Center, University of Minnesota; 2019
from __future__ import division
from lib import script_utils
PYTHON_VERSION_ACCEPTED_MIN = "3.11" # supports multiple dot notation
if script_utils.PYTHON_VERSION < script_utils.VersionString(PYTHON_VERSION_ACCEPTED_MIN):
raise script_utils.VersionError("Python version ({}) is below accepted minimum ({})".format(
script_utils.PYTHON_VERSION, PYTHON_VERSION_ACCEPTED_MIN))
import argparse
import copy
import filecmp
import gc
import glob
import os
import re
import shutil
import subprocess
import sys
import traceback
import warnings
from collections import OrderedDict
from time import sleep
from datetime import datetime
try:
from packaging.version import Version as SortVersion
except ImportError or ModuleNotFoundError:
from distutils.version import StrictVersion as SortVersion
from lib import script_utils
from lib.script_utils import ScriptArgumentError, ExternalError, InvalidArgumentError
##############################
## Core globals
SCRIPT_VERSION_NUM = script_utils.VersionString('4.2')
# Script paths and execution
SCRIPT_FILE = os.path.abspath(os.path.realpath(__file__))
SCRIPT_FNAME = os.path.basename(SCRIPT_FILE)
SCRIPT_NAME, SCRIPT_EXT = os.path.splitext(SCRIPT_FNAME)
SCRIPT_DIR = os.path.dirname(SCRIPT_FILE)
SCRIPT_RUNCMD = ' '.join(sys.argv)+'\n'
PYTHON_EXE = 'python3 -u'
##############################
## Argument globals
# Argument strings
ARGSTR_SRC = 'src'
ARGSTR_RES = 'res'
ARGSTR_DST = '--dst'
ARGSTR_SINGLE_SCENE_STRIPS = '--single-scene-strips'
ARGSTR_META_ONLY = '--meta-only'
ARGSTR_META_TRANS_DIR = '--meta-trans-dir'
ARGSTR_NO_BROWSE = '--no-browse'
ARGSTR_BUILD_AUX = '--build-aux'
ARGSTR_REBUILD_AUX = '--rebuild-aux'
ARGSTR_DEM_TYPE = '--dem-type'
ARGSTR_MASK_VER = '--mask-ver'
ARGSTR_NOENTROPY = '--noentropy'
ARGSTR_NOWATER = '--nowater'
ARGSTR_NOCLOUD = '--nocloud'
ARGSTR_UNFILTERED = '--unf'
ARGSTR_NOFILTER_COREG = '--nofilter-coreg'
ARGSTR_SAVE_COREG_STEP = '--save-coreg-step'
ARGSTR_RMSE_CUTOFF = '--rmse-cutoff'
ARGSTR_REMERGE_STRIPS = '--remerge-strips'
ARGSTR_SCHEDULER = '--scheduler'
ARGSTR_JOBSCRIPT = '--jobscript'
ARGSTR_LOGDIR = '--logdir'
ARGSTR_EMAIL = '--email'
ARGSTR_LICENSES = '--licenses'
ARGSTR_RESTART = '--restart'
ARGSTR_REMOVE_INCOMPLETE = '--remove-incomplete'
ARGSTR_USE_OLD_MASKS = '--use-old-masks'
ARGSTR_CLEANUP_ON_FAILURE = '--cleanup-on-failure'
ARGSTR_OLD_ORG = '--old-org'
ARGSTR_DRYRUN = '--dryrun'
ARGSTR_STRIPID = '--stripid'
ARGSTR_SCENEDIRNAME = '--scenedirname'
ARGSTR_SKIP_ORTHO2_ERROR = '--skip-xtrack-missing-ortho2-error'
ARGSTR_SCENE_MASKS_ONLY = '--build-scene-masks-only'
ARGSTR_USE_PIL_IMRESIZE = '--use-pil-imresize'
# Argument choices
ARGCHO_DEM_TYPE_LSF = 'lsf'
ARGCHO_DEM_TYPE_NON_LSF = 'non-lsf'
ARGCHO_DEM_TYPE = [
ARGCHO_DEM_TYPE_NON_LSF
]
ARGCHO_MASK_VER_MASKV1 = 'maskv1'
ARGCHO_MASK_VER_MASKV2 = 'maskv2'
ARGCHO_MASK_VER_REMA2A = 'rema2a'
ARGCHO_MASK_VER_MASK8M = 'mask8m'
ARGCHO_MASK_VER_BITMASK = 'bitmask'
ARGCHO_MASK_VER = [
ARGCHO_MASK_VER_MASKV1,
ARGCHO_MASK_VER_MASKV2,
ARGCHO_MASK_VER_REMA2A,
ARGCHO_MASK_VER_MASK8M,
ARGCHO_MASK_VER_BITMASK
]
ARGCHO_SAVE_COREG_STEP_OFF = 'off'
ARGCHO_SAVE_COREG_STEP_META = 'meta'
ARGCHO_SAVE_COREG_STEP_ALL = 'all'
ARGCHO_SAVE_COREG_STEP = [
ARGCHO_SAVE_COREG_STEP_OFF,
ARGCHO_SAVE_COREG_STEP_META,
ARGCHO_SAVE_COREG_STEP_ALL
]
ARGCHO_CLEANUP_ON_FAILURE_MASKS = 'masks'
ARGCHO_CLEANUP_ON_FAILURE_STRIP = 'strip'
ARGCHO_CLEANUP_ON_FAILURE_OUTPUT = 'output'
ARGCHO_CLEANUP_ON_FAILURE_NONE = 'none'
ARGCHO_CLEANUP_ON_FAILURE = [
ARGCHO_CLEANUP_ON_FAILURE_MASKS,
ARGCHO_CLEANUP_ON_FAILURE_STRIP,
ARGCHO_CLEANUP_ON_FAILURE_OUTPUT,
ARGCHO_CLEANUP_ON_FAILURE_NONE
]
# Segregation of argument choices
MASK_VER_8M = [
ARGCHO_MASK_VER_MASKV1,
ARGCHO_MASK_VER_REMA2A,
ARGCHO_MASK_VER_MASK8M,
ARGCHO_MASK_VER_BITMASK
]
MASK_VER_2M = [
ARGCHO_MASK_VER_MASKV1,
ARGCHO_MASK_VER_MASKV2,
ARGCHO_MASK_VER_BITMASK
]
MASK_VER_XM = [
ARGCHO_MASK_VER_BITMASK
]
# Argument groups
ARGGRP_OUTDIR = [ARGSTR_DST, ARGSTR_LOGDIR]
ARGGRP_BATCH = [ARGSTR_SCHEDULER, ARGSTR_JOBSCRIPT, ARGSTR_LOGDIR, ARGSTR_EMAIL, ARGSTR_LICENSES]
ARGGRP_UNFILTERED = [ARGSTR_NOWATER, ARGSTR_NOCLOUD]
ARGGRP_META_ONLY = [ARGSTR_SINGLE_SCENE_STRIPS, ARGSTR_USE_OLD_MASKS, ARGSTR_NOFILTER_COREG, (ARGSTR_CLEANUP_ON_FAILURE, ARGCHO_CLEANUP_ON_FAILURE_NONE)]
ARGGRP_SINGLE_SCENE_STRIPS = [ARGSTR_USE_OLD_MASKS, ARGSTR_NOFILTER_COREG, (ARGSTR_CLEANUP_ON_FAILURE, ARGCHO_CLEANUP_ON_FAILURE_STRIP)]
##############################
## Batch settings
JOBSCRIPT_DIR = os.path.join(SCRIPT_DIR, 'jobscripts')
JOBSCRIPT_INIT = os.path.join(JOBSCRIPT_DIR, 'init.sh')
JOB_ABBREV = 's2s'
JOB_WALLTIME_HR = 3
JOB_MEMORY_GB = 80
JOB_NCORES = 12
JOB_NODE = None
##############################
## Custom globals
SUFFIX_PRIORITY_DEM = ['dem.tif', 'dem_smooth.tif']
SUFFIX_PRIORITY_MATCHTAG = ['matchtag_mt.tif', 'matchtag.tif']
SUFFIX_PRIORITY_ORTHO1 = ['ortho_image1.tif', 'ortho_image_1.tif', 'ortho1.tif', 'ortho_1.tif', 'ortho.tif']
SUFFIX_PRIORITY_ORTHO2 = ['ortho_image2.tif', 'ortho_image_2.tif', 'ortho2.tif', 'ortho_2.tif']
DEM_TYPE_SUFFIX_DICT = {
ARGCHO_DEM_TYPE_LSF: 'dem_smooth.tif',
ARGCHO_DEM_TYPE_NON_LSF: 'dem.tif'
}
RE_STRIPID_STR = r"^(?:SETSM_s2s[0-9]{3}_)?([A-Z0-9]{4}_.*?_?[0-9A-F]{16}_.*?_?[0-9A-F]{16}).*$"
RE_STRIPID = re.compile(RE_STRIPID_STR)
RE_STRIPFNAME_SEGNUM = re.compile(r"_seg(\d+)_", re.I)
RE_SCENEMETA_SETSM_VERSION_STR = r"^setsm[ _]version=.*$"
RE_SCENEMETA_SETSM_VERSION = re.compile(RE_SCENEMETA_SETSM_VERSION_STR, re.I|re.MULTILINE)
RE_SCENEMETA_GROUP_VERSION = re.compile(r"^group[ _]version=.*$", re.I|re.MULTILINE)
RE_STRIPMETA_SCENE_NAME_KEY = re.compile(r"^scene \d+ name=", re.I)
META_ONLY_META_SUFFIX = 's2s_meta.txt'
##############################
class MetaReadError(Exception):
def __init__(self, msg=""):
super(Exception, self).__init__(msg)
def argparser_init():
parser = argparse.ArgumentParser(
formatter_class=script_utils.RawTextArgumentDefaultsHelpFormatter,
description=' '.join([
"Filters scene DEMs in a source directory,",
"then mosaics them into strips and saves the results.",
"\nBatch work is done in units of strip-pair IDs, as parsed from scene dem filenames",
"(see {} argument for how this is parsed).".format(ARGSTR_STRIPID)
])
)
# Positional arguments
parser.add_argument(
ARGSTR_SRC,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_SRC,
existcheck_fn=os.path.isdir,
existcheck_reqval=True),
help=' '.join([
"Path to source directory containing scene DEMs to process.",
"Scene DEMs should be organized in folders named like '<stripid>_<resolution>' (e.g. WV02_20201204_10300100B061A200_10300100B19D1900_2m)",
"placed directly within the source directory, unless {} option is provided, in which case".format(ARGSTR_OLD_ORG),
"all scene DEM result files must be stored flat within the source directory.",
"If {} is not specified, this path should contain the folder 'tif_results'".format(ARGSTR_DST),
"so that the destination directory can be automatically derived.".format(ARGSTR_DST),
"The range of source scenes worked on may be limited with the {} argument.".format(ARGSTR_STRIPID)
])
)
parser.add_argument(
ARGSTR_RES,
type=float,
help="Resolution of target DEMs in meters."
)
# Optional arguments
parser.add_argument(
ARGSTR_DST,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_DST,
existcheck_fn=os.path.isfile,
existcheck_reqval=False),
help=' '.join([
"Path to destination directory for output mosaicked strip data.",
"(default is {}.(reverse)replace('tif_results', 'strips'))".format(ARGSTR_SRC)
])
)
parser.add_argument(
ARGSTR_OLD_ORG,
action='store_true',
help=' '.join([
"For source and destination directories, use old scene and strip results organization",
"(*flat directory structure*, used prior to reorganization into strip pairname folders)."
])
)
parser.add_argument(
ARGSTR_DEM_TYPE,
type=str,
choices=ARGCHO_DEM_TYPE,
default=ARGCHO_DEM_TYPE_NON_LSF,
help=' '.join([
"Which version of all scene DEMs to work with.",
#"\n'{}': Use the LSF DEM with '{}' file suffix.".format(ARGCHO_DEM_TYPE_LSF, DEM_TYPE_SUFFIX_DICT[ARGCHO_DEM_TYPE_LSF]),
"\n'{}': Use the non-LSF DEM with '{}' file suffix.".format(ARGCHO_DEM_TYPE_NON_LSF, DEM_TYPE_SUFFIX_DICT[ARGCHO_DEM_TYPE_NON_LSF]),
"\n"
])
)
parser.add_argument(
ARGSTR_META_ONLY,
action='store_true',
help=' '.join([
"Build scene masks if they don't already exist,",
"then run scenes2strips process only to gather information",
"to build metadata as if scenes are single-scene strips.",
"\nOutput s2s-style metadata textfiles are created next to",
"source scene DEMs with '{}' file suffix.".format(META_ONLY_META_SUFFIX),
"\nThe following argument flags are set automatically: {}".format(ARGGRP_META_ONLY)
])
)
parser.add_argument(
ARGSTR_SINGLE_SCENE_STRIPS,
action='store_true',
help=' '.join([
"Force creation of strip results to break into a new output strip segment,"
"for each non-masked/non-redundant input scene DEM.",
"\nThe following argument flags are set automatically: {}".format(ARGGRP_SINGLE_SCENE_STRIPS)
])
)
parser.add_argument(
ARGSTR_UNFILTERED,
action='store_true',
help=' '.join([
"Shortcut for setting {} options to create \"unfiltered\" strips.".format(ARGGRP_UNFILTERED),
"\nDefault for {} argument becomes "
"({}.(reverse)replace('tif_results', 'strips_unf')).".format(ARGSTR_DST, ARGSTR_SRC),
"\nCan only be used when {}={}.".format(ARGSTR_MASK_VER, ARGCHO_MASK_VER_BITMASK)
])
)
parser.add_argument(
ARGSTR_USE_OLD_MASKS,
action='store_true',
help="Use existing scene masks instead of deleting and re-filtering."
)
parser.add_argument(
ARGSTR_SCENE_MASKS_ONLY,
action='store_true',
help="Build scene masks and then exit before proceeding to strip-building steps."
)
parser.add_argument(
ARGSTR_REMERGE_STRIPS,
action='store_true',
help=' '.join([
"Source are strip segment results to be treated as input scenes for",
"rerunning through the coregistration and mosaicking steps to produce",
"a new set of 're-merged' strip results."
])
)
parser.add_argument(
ARGSTR_RMSE_CUTOFF,
type=float,
choices=None,
default=3.5,
help=' '.join([
"Maximum RMSE from coregistration step tolerated for scene merging.",
"A value greater than this causes a new strip segment to be created."
])
)
parser.add_argument(
ARGSTR_MASK_VER,
type=str,
choices=ARGCHO_MASK_VER,
default=ARGCHO_MASK_VER_BITMASK,
help=' '.join([
"Filtering scheme to use when generating mask raster images,",
"to classify bad data in scene DEMs.",
"\n'{}': Two-component (edge, data density) filter to create".format(ARGCHO_MASK_VER_MASKV1),
"separate edgemask and datamask files for each scene.",
"\n'{}': Three-component (edge, water, cloud) filter to create".format(ARGCHO_MASK_VER_MASKV2),
"classical 'flat' binary masks for 2m DEMs.",
"\n'{}': Same filter as '{}', but distinguish between".format(ARGCHO_MASK_VER_BITMASK, ARGCHO_MASK_VER_MASKV2),
"the different filter components by creating a bitmask.",
"\n'{}': Filter designed specifically for 8m Antarctic DEMs.".format(ARGCHO_MASK_VER_REMA2A),
"\n'{}': General-purpose filter for 8m DEMs.".format(ARGCHO_MASK_VER_MASK8M),
"\n"
])
)
parser.add_argument(
ARGSTR_NOENTROPY,
action='store_true',
help=' '.join([
"Use filter without entropy protection.",
"Can only be used when {}={}.".format(ARGSTR_MASK_VER, ARGCHO_MASK_VER_MASKV1)
])
)
parser.add_argument(
ARGSTR_NOWATER,
action='store_true',
help=' '.join([
"Use filter without water masking.",
"Can only be used when {}={}.".format(ARGSTR_MASK_VER, ARGCHO_MASK_VER_BITMASK)
])
)
parser.add_argument(
ARGSTR_NOCLOUD,
action='store_true',
help=' '.join([
"Use filter without cloud masking.",
"Can only be used when {}={}.".format(ARGSTR_MASK_VER, ARGCHO_MASK_VER_BITMASK)
])
)
parser.add_argument(
ARGSTR_NOFILTER_COREG,
action='store_true',
help=' '.join([
"If {}/{}, turn off the respective filter(s) during".format(ARGSTR_NOWATER, ARGSTR_NOCLOUD),
"coregistration step in addition to mosaicking step.",
"Can only be used when {}={}.".format(ARGSTR_MASK_VER, ARGCHO_MASK_VER_BITMASK)
])
)
parser.add_argument(
ARGSTR_SAVE_COREG_STEP,
type=str,
choices=ARGCHO_SAVE_COREG_STEP,
default=ARGCHO_SAVE_COREG_STEP_OFF,
help=' '.join([
"If {}/{}, save output from coregistration step in directory".format(ARGSTR_NOWATER, ARGSTR_NOCLOUD),
"'`dstdir`_coreg_filtXXX' where [XXX] is the bit-code corresponding to filter components",
"([cloud, water, edge], respectively) applied during the coregistration step.",
"By default, all three filter components are applied so this code is 111.",
"\nIf '{}', do not save output from coregistration step.".format(ARGCHO_SAVE_COREG_STEP_OFF),
"\nIf '{}', save only the *_meta.txt component of output strip segments.".format(ARGCHO_SAVE_COREG_STEP_META),
"(useful for subsequent runs with {} argument)".format(ARGSTR_META_TRANS_DIR),
"\nIf '{}', save all output from coregistration step, including both".format(ARGCHO_SAVE_COREG_STEP_ALL),
"metadata and raster components.",
"\nCan only be used when {}={}, and has no affect if neither".format(ARGSTR_MASK_VER, ARGCHO_MASK_VER_BITMASK),
"{} nor {} arguments are provided, or either".format(ARGSTR_NOWATER, ARGSTR_NOCLOUD),
"{} or {} arguments are provided since then the".format(ARGSTR_META_TRANS_DIR, ARGSTR_NOFILTER_COREG),
"coregistration and mosaicking steps are effectively rolled into one step.",
"\n"
])
)
parser.add_argument(
ARGSTR_META_TRANS_DIR,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_META_TRANS_DIR,
existcheck_fn=os.path.isdir,
existcheck_reqval=True),
help=' '.join([
"Path to directory of old strip metadata from which translation values",
"will be parsed to skip scene coregistration step."
])
)
parser.add_argument(
ARGSTR_NO_BROWSE,
action='store_true',
help=' '.join([
"Do not build 10m hillshade '*_dem_10m_shade.tif' images alongside output DEM strip segments.",
])
)
parser.add_argument(
ARGSTR_BUILD_AUX,
action='store_true',
help=' '.join([
"Build a suite of downsampled browse images alongside output DEM strip segments.",
"These images are primarily useful to PGC in tile mosaicking efforts."
])
)
parser.add_argument(
ARGSTR_REBUILD_AUX,
action='store_true',
help=' '.join([
"Rebuild browse images along existing output DEM strip segments."
])
)
parser.add_argument(
ARGSTR_CLEANUP_ON_FAILURE,
type=str,
choices=ARGCHO_CLEANUP_ON_FAILURE,
default=ARGCHO_CLEANUP_ON_FAILURE_OUTPUT,
help=' '.join([
"Which type of output files should be automatically removed upon encountering an error.",
"\nIf '{}', remove all scene masks for the strip-pair ID if any scene masks are created".format(ARGCHO_CLEANUP_ON_FAILURE_MASKS),
"during this run (meaning {} option was not used, or if it was used but additional".format(ARGSTR_USE_OLD_MASKS),
"scene masks were created).",
"\nIf '{}', remove all output strip results for the strip-pair ID from the destination.".format(ARGCHO_CLEANUP_ON_FAILURE_STRIP),
"\nIf '{}', remove both scene masks and output strip results for the strip-pair ID.".format(ARGCHO_CLEANUP_ON_FAILURE_OUTPUT),
"\nIf '{}', remove nothing on error.".format(ARGCHO_CLEANUP_ON_FAILURE_NONE),
"\n"
])
)
parser.add_argument(
ARGSTR_REMOVE_INCOMPLETE,
action='store_true',
help="Only remove unfinished (no .fin file) output, do not build strips."
)
parser.add_argument(
ARGSTR_RESTART,
action='store_true',
help="Remove any unfinished (no .fin file) output before submitting all unfinished strips."
)
parser.add_argument(
ARGSTR_SCHEDULER,
type=str,
choices=script_utils.SCHED_SUPPORTED,
default=None,
help="Submit tasks to job scheduler."
)
parser.add_argument(
ARGSTR_JOBSCRIPT,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_JOBSCRIPT,
existcheck_fn=os.path.isfile,
existcheck_reqval=True),
default=None,
help=' '.join([
"Script to run in job submission to scheduler.",
"(default scripts are found in {})".format(JOBSCRIPT_DIR)
])
)
parser.add_argument(
ARGSTR_LOGDIR,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_LOGDIR,
existcheck_fn=os.path.isfile,
existcheck_reqval=False),
default=None,
help=' '.join([
"Directory to which standard output/error log files will be written for batch job runs.",
"\nIf not provided, default scheduler (or jobscript #CONDOPT_) options will be used.",
"\n**Note:** Due to implementation difficulties, this directory will also become the",
"working directory for the job process. Since relative path inputs are always changed",
"to absolute paths in this script, this should not be an issue."
])
)
parser.add_argument(
ARGSTR_EMAIL,
type=script_utils.ARGTYPE_BOOL_PLUS(
parse_fn=str),
nargs='?',
help="Send email to user upon end or abort of the LAST SUBMITTED task."
)
parser.add_argument(
ARGSTR_LICENSES,
type=script_utils.ARGTYPE_BOOL_PLUS(
parse_fn=str),
nargs='?',
help="Licenses argument to pass to slurm."
)
parser.add_argument(
ARGSTR_DRYRUN,
action='store_true',
help="Print actions without executing."
)
parser.add_argument(
ARGSTR_STRIPID,
help=' '.join([
"Run filtering and mosaicking for a single strip with strip-pair ID",
"as parsed from scene DEM filenames using the following regex: '{}'".format(RE_STRIPID_STR),
"\nA text file containing a list of strip-pair IDs, each on a separate line,"
"may instead be provided for batch processing of select strips."
])
)
parser.add_argument(
ARGSTR_SCENEDIRNAME,
help=' '.join([
"Name of folder containing the scene DEM files for a single strip-pair ID",
"designated by the {} argument".format(ARGSTR_STRIPID)
])
)
parser.add_argument(
ARGSTR_SKIP_ORTHO2_ERROR,
action='store_true',
help=' '.join([
"If at least one scene in a cross-track strip is missing the second ortho component raster,",
"do not throw an error but instead build the strip as if it were in-track with only one ortho."
])
)
parser.add_argument(
ARGSTR_USE_PIL_IMRESIZE,
action='store_true',
help=' '.join([
"Use PIL imresize method over usual fast OpenCV resize method for final resize from",
"8m processing resolution back to native scene raster resolution when generating",
"output scene mask rasters. This is to avoid an OpenCV error with unknown cause that",
"can occur when using OpenCV resize on some 50cm scenes at Blue Waters."
])
)
return parser
def main():
# Invoke argparse argument parsing.
arg_parser = argparser_init()
try:
args = script_utils.ArgumentPasser(PYTHON_EXE, SCRIPT_FILE, arg_parser, sys.argv)
except ScriptArgumentError as e:
arg_parser.error(e)
## Further parse/adjust argument values.
res_m = args.get(ARGSTR_RES)
if int(res_m) == res_m:
res_m = int(res_m)
res_str = '{}m'.format(res_m)
args.set(ARGSTR_RES, int(res_m))
else:
res_cm = res_m * 100
if int(res_cm) == res_cm:
res_cm = int(res_cm)
res_str = '{}cm'.format(res_cm)
else:
raise ScriptArgumentError("Resolution is not in whole meters or whole centimeters")
if not (args.get(ARGSTR_META_ONLY) or args.get(ARGSTR_SCENE_MASKS_ONLY)):
if args.get(ARGSTR_DST) is not None:
if ( args.get(ARGSTR_SRC) == args.get(ARGSTR_DST)
or ( os.path.isdir(args.get(ARGSTR_DST))
and filecmp.cmp(args.get(ARGSTR_SRC), args.get(ARGSTR_DST)))):
arg_parser.error("argument {} directory is the same as "
"argument {} directory".format(ARGSTR_SRC, ARGSTR_DST))
else:
# Set default dst dir.
split_ind = args.get(ARGSTR_SRC).rfind('tif_results')
if split_ind == -1:
arg_parser.error("argument {} path does not contain 'tif_results', "
"so default argument {} cannot be set".format(ARGSTR_SRC, ARGSTR_DST))
args.set(ARGSTR_DST, ( args.get(ARGSTR_SRC)[:split_ind]
+ args.get(ARGSTR_SRC)[split_ind:].replace(
'tif_results', 'strips' if not args.get(ARGSTR_UNFILTERED) else 'strips_unf')))
print("argument {} set automatically to: {}".format(ARGSTR_DST, args.get(ARGSTR_DST)))
argcho_dem_type_opp = ARGCHO_DEM_TYPE_NON_LSF if args.get(ARGSTR_DEM_TYPE) == ARGCHO_DEM_TYPE_LSF else ARGCHO_DEM_TYPE_LSF
if args.get(ARGSTR_SCENE_MASKS_ONLY):
args.set(ARGSTR_DST, args.get(ARGSTR_SRC))
print("via provided argument {}, set argument {}={}".format(ARGSTR_SCENE_MASKS_ONLY, ARGSTR_DST, args.get(ARGSTR_DST)))
if not args.provided(ARGSTR_CLEANUP_ON_FAILURE):
args.set(ARGSTR_CLEANUP_ON_FAILURE, ARGCHO_CLEANUP_ON_FAILURE_MASKS)
print("via provided argument {}, set argument {}={}".format(ARGSTR_SCENE_MASKS_ONLY, ARGSTR_CLEANUP_ON_FAILURE, args.get(ARGSTR_CLEANUP_ON_FAILURE)))
elif args.get(ARGSTR_META_ONLY):
args.set(ARGSTR_DST, args.get(ARGSTR_SRC))
print("via provided argument {}, set argument {}={}".format(ARGSTR_META_ONLY, ARGSTR_DST, args.get(ARGSTR_DST)))
args.set(ARGGRP_META_ONLY)
print("via provided argument {}, arguments {} set automatically".format(ARGSTR_META_ONLY, ARGGRP_META_ONLY))
elif args.get(ARGSTR_SINGLE_SCENE_STRIPS):
args.set(ARGGRP_SINGLE_SCENE_STRIPS)
print("via provided argument {}, arguments {} set automatically".format(ARGSTR_SINGLE_SCENE_STRIPS, ARGGRP_SINGLE_SCENE_STRIPS))
if args.get(ARGSTR_UNFILTERED):
args.set(ARGGRP_UNFILTERED)
print("via provided argument {}, arguments {} set automatically".format(ARGSTR_UNFILTERED, ARGGRP_UNFILTERED))
if args.get(ARGSTR_REBUILD_AUX):
args.set(ARGSTR_USE_OLD_MASKS)
print("via provided argument {}, argument {} set automatically".format(ARGSTR_REBUILD_AUX, ARGSTR_USE_OLD_MASKS))
if args.get(ARGSTR_SCHEDULER) is not None:
if args.get(ARGSTR_JOBSCRIPT) is None:
jobscript_default = os.path.join(JOBSCRIPT_DIR, 'head_{}.sh'.format(args.get(ARGSTR_SCHEDULER)))
if not os.path.isfile(jobscript_default):
arg_parser.error(
"Default jobscript ({}) does not exist, ".format(jobscript_default)
+ "please specify one with {} argument".format(ARGSTR_JOBSCRIPT))
else:
args.set(ARGSTR_JOBSCRIPT, jobscript_default)
print("argument {} set automatically to: {}".format(ARGSTR_JOBSCRIPT, args.get(ARGSTR_JOBSCRIPT)))
if args.get(ARGSTR_REMERGE_STRIPS):
demSuffix = 'dem.tif'
else:
demSuffix = DEM_TYPE_SUFFIX_DICT[args.get(ARGSTR_DEM_TYPE)]
if args.get(ARGSTR_REMERGE_STRIPS) and not args.provided(ARGSTR_CLEANUP_ON_FAILURE):
args.set(ARGSTR_CLEANUP_ON_FAILURE, ARGCHO_CLEANUP_ON_FAILURE_STRIP)
## Validate argument values.
if args.get(ARGSTR_RES) == 8:
res_req_mask_ver = MASK_VER_8M
elif args.get(ARGSTR_RES) == 2:
res_req_mask_ver = MASK_VER_2M
else:
res_req_mask_ver = MASK_VER_XM
if args.get(ARGSTR_MASK_VER) not in res_req_mask_ver:
arg_parser.error("argument {} must be one of {} for {}-meter argument {}".format(
ARGSTR_MASK_VER, res_req_mask_ver, args.get(ARGSTR_RES), ARGSTR_RES
))
if args.get(ARGSTR_NOENTROPY) and args.get(ARGSTR_MASK_VER) != ARGCHO_MASK_VER_MASKV1:
arg_parser.error("{} option is compatible only with {} option".format(
ARGSTR_NOENTROPY, ARGCHO_MASK_VER_MASKV1
))
if ( (args.get(ARGSTR_NOWATER) or args.get(ARGSTR_NOCLOUD))
and args.get(ARGSTR_MASK_VER) != ARGCHO_MASK_VER_BITMASK):
arg_parser.error("{}/{} option(s) can only be used when {}='{}'".format(
ARGSTR_NOWATER, ARGSTR_NOCLOUD, ARGSTR_MASK_VER, ARGCHO_MASK_VER_BITMASK
))
if not args.get(ARGSTR_SINGLE_SCENE_STRIPS):
if args.get(ARGSTR_NOFILTER_COREG) and [args.get(ARGSTR_NOWATER), args.get(ARGSTR_NOCLOUD)].count(True) == 0:
arg_parser.error("{} option must be used in conjunction with {}/{} option(s)".format(
ARGSTR_NOFILTER_COREG, ARGSTR_NOWATER, ARGSTR_NOCLOUD
))
if args.get(ARGSTR_NOFILTER_COREG) and args.get(ARGSTR_META_TRANS_DIR) is not None:
arg_parser.error("{} option cannot be used in conjunction with {} argument".format(
ARGSTR_NOFILTER_COREG, ARGSTR_META_TRANS_DIR
))
if ( args.get(ARGSTR_SAVE_COREG_STEP) != ARGCHO_SAVE_COREG_STEP_OFF
and ( (not (args.get(ARGSTR_NOWATER) or args.get(ARGSTR_NOCLOUD)))
or (args.get(ARGSTR_META_TRANS_DIR) is not None or args.get(ARGSTR_NOFILTER_COREG)))):
arg_parser.error("Non-'{}' {} option must be used in conjunction with ({}/{}) arguments "
"and cannot be used in conjunction with ({}/{}) arguments".format(
ARGCHO_SAVE_COREG_STEP_OFF, ARGSTR_SAVE_COREG_STEP,
ARGSTR_NOWATER, ARGSTR_NOCLOUD,
ARGSTR_META_TRANS_DIR, ARGSTR_NOFILTER_COREG
))
if args.get(ARGSTR_RMSE_CUTOFF) <= 0:
arg_parser.error("argument {} must be greater than zero".format(ARGSTR_RMSE_CUTOFF))
## Create output directories if they don't already exist.
if not args.get(ARGSTR_META_ONLY) and not args.get(ARGSTR_DRYRUN):
for dir_argstr, dir_path in list(zip(ARGGRP_OUTDIR, args.get_as_list(ARGGRP_OUTDIR))):
if dir_path is not None and not os.path.isdir(dir_path):
print("Creating argument {} directory: {}".format(dir_argstr, dir_path))
os.makedirs(dir_path)
if args.get(ARGSTR_STRIPID) is None or os.path.isfile(args.get(ARGSTR_STRIPID)) or args.get(ARGSTR_SCHEDULER) is not None:
## Batch processing
# Gather strip-pair IDs to process.
if args.get(ARGSTR_STRIPID) is None:
# Find all scene DEMs to be merged into strips.
src_scenedem_ffile_pattern = os.path.join(
args.get(ARGSTR_SRC),
'*'*(not args.get(ARGSTR_OLD_ORG)),
'*_{}'.format(demSuffix)
)
src_scenedem_ffile_glob = glob.glob(src_scenedem_ffile_pattern)
if not src_scenedem_ffile_glob:
print("No scene DEMs found to process with pattern: '{}'".format(src_scenedem_ffile_pattern))
print("Check --help to see if {} or {} options should be provided".format(
ARGSTR_OLD_ORG, ARGSTR_DEM_TYPE
))
sys.exit(0)
# Find all unique strip IDs.
stripids = set()
stripid_cannot_be_parsed_flag = False
old_org = args.get(ARGSTR_OLD_ORG)
for scenedem_ffile in src_scenedem_ffile_glob:
sID_match = re.match(RE_STRIPID, os.path.basename(scenedem_ffile))
if sID_match is None:
stripid_cannot_be_parsed_flag = True
print("Could not parse strip ID from the following scene DEM file name: {}".format(scenedem_ffile))
warnings.warn("There are source scene DEMs for which a strip ID cannot be parsed. "
"Please fix source raster filenames so that a strip ID can be parsed "
"using the following regular expression: '{}'".format(RE_STRIPID_STR))
continue
sID = sID_match.group(1)
scenedirname = None
if not old_org:
scenedirname_test = os.path.basename(os.path.dirname(scenedem_ffile))
scenedirname_match = re.match(RE_STRIPID, scenedirname_test)
if scenedirname_match is not None:
scenedirname = scenedirname_test
stripids.add((sID, scenedirname))
if stripid_cannot_be_parsed_flag:
print("One or more scene DEMs could not have their strip ID parsed, exiting")
sys.exit(1)
del src_scenedem_ffile_glob
elif os.path.isfile(args.get(ARGSTR_STRIPID)):
# Assume file is a list of strip-pair IDs, one per line.
stripids = set(script_utils.read_task_bundle(args.get(ARGSTR_STRIPID)))
# Check that source scenes exist for each strip-pair ID, else exclude and notify user.
stripids_to_process = [
sID for sID in stripids if glob.glob(os.path.join(
args.get(ARGSTR_SRC),
'{}_{}*'.format(sID, res_str)*(not args.get(ARGSTR_OLD_ORG)),
'{}_*_{}'.format(sID, demSuffix)
))
]
stripids_missing = stripids.difference(set(stripids_to_process))
if stripids_missing:
print('')
print("Missing scene data for {} of the listed strip-pair IDs:".format(len(stripids_missing)))
for stripid in sorted(list(stripids_missing)):
print(stripid)
print('')
stripids = stripids_to_process
demSuffix = None
else:
stripids = {args.get(ARGSTR_STRIPID)}
stripids = sorted(list(stripids))
if len(stripids) == 0:
print("No strip-pair IDs found")
sys.exit(0)
## Create processing list.
## Existence check. Filter out strips with existing .fin output file.
stripids_to_process = list()
dstdir = args.get(ARGSTR_DST)
stripdirname_s2sidentifier = '{}{}'.format(
res_str, '_lsf' if (args.get(ARGSTR_DEM_TYPE) == ARGCHO_DEM_TYPE_LSF and not args.get(ARGSTR_META_ONLY)) else ''
)
use_scenedirname = (len(stripids[0]) == 2)
scenedirname = None
stripdirname = None
for stripid_tuple in stripids:
if use_scenedirname:
sID, scenedirname = stripid_tuple
else:
sID = stripid_tuple
if scenedirname is not None:
if stripdirname_s2sidentifier in scenedirname:
stripdirname = scenedirname
else:
stripdirname = scenedirname.replace(res_str, stripdirname_s2sidentifier)
elif args.get(ARGSTR_OLD_ORG):
stripdirname = ''
else:
stripdirname = '{}_{}*'.format(sID, stripdirname_s2sidentifier)
dst_sID_ffile_glob = glob.glob(os.path.join(dstdir, stripdirname, '{}_{}*.fin'.format(sID, res_str)))
if len(dst_sID_ffile_glob) == 0:
stripids_to_process.append((sID, scenedirname, stripdirname))
print("Found {}{} strip-pair IDs, {} unfinished".format(
len(stripids), ' *'+demSuffix if demSuffix is not None else '', len(stripids_to_process)))
if len(stripids) == 0:
print("(Did you mean to pass `{} {}` or `{}` arguments?)".format(
ARGSTR_DEM_TYPE, argcho_dem_type_opp, ARGSTR_OLD_ORG
))
if args.get(ARGSTR_REBUILD_AUX):
stripids_to_process = stripids
stripids_to_process.sort()
if len(stripids_to_process) == 0:
print("No unfinished strip DEMs found to process, exiting")
sys.exit(0)
elif args.get(ARGSTR_DRYRUN) and args.get(ARGSTR_SCHEDULER) is not None:
print("Exiting dryrun")
sys.exit(0)
# Pause for user review.
if not args.get(ARGSTR_REMOVE_INCOMPLETE):
wait_seconds = 5
print("Sleeping {} seconds before task submission".format(wait_seconds))
sleep(wait_seconds)
## Batch process each strip-pair ID.
jobnum_fmt = script_utils.get_jobnum_fmtstr(stripids)
last_job_email = args.get(ARGSTR_EMAIL)
args_batch = args
args_single = copy.deepcopy(args)
args_single.unset(*ARGGRP_BATCH)
gen_job_node = script_utils.yield_loop(JOB_NODE) if type(JOB_NODE) is list else None
job_num = 0
num_jobs = len(stripids_to_process)
for sID, scenedirname, stripdirname in stripids_to_process:
job_num += 1
if args.get(ARGSTR_OLD_ORG):
strip_dname_pattern = args_batch.get(ARGSTR_DST)
else:
if stripdirname is None:
stripdirname = '{}_{}*/'.format(sID, stripdirname_s2sidentifier)
strip_dname_pattern = os.path.join(args_batch.get(ARGSTR_DST), stripdirname)
strip_dfull_glob = glob.glob(strip_dname_pattern)
if len(strip_dfull_glob) > 1:
raise InvalidArgumentError("Found more than one match for output strip folder in"
" destination directory with pattern: {}".format(strip_dname_pattern))
elif len(strip_dfull_glob) == 1:
strip_dfull = strip_dfull_glob[0]
# If output does not already exist, add to task list.
stripid_fin_ffile = glob.glob(os.path.join(
strip_dfull,
'{}_{}*.fin'.format(sID, res_str)
))
dst_sID_ffile_glob = glob.glob(os.path.join(
strip_dfull,
'*{}_{}{}_*{}'.format(
sID,
res_str,
'_lsf' if (args.get(ARGSTR_DEM_TYPE) == ARGCHO_DEM_TYPE_LSF and not args.get(ARGSTR_META_ONLY)) else '',
META_ONLY_META_SUFFIX if args.get(ARGSTR_META_ONLY) else ''
)
))
if len(stripid_fin_ffile) > 0 and not args.get(ARGSTR_REBUILD_AUX):
print("{}, {} {} :: ({}) .fin file exists, skipping".format(
job_num, ARGSTR_STRIPID, sID, res_str))
continue
elif len(dst_sID_ffile_glob) > 0:
if args.get(ARGSTR_REMOVE_INCOMPLETE) or args.get(ARGSTR_RESTART):
print("{}, {} {} :: {} ({}) output files exist ".format(
job_num, ARGSTR_STRIPID, sID, len(dst_sID_ffile_glob), res_str)
+ "(potentially unfinished since no *.fin file), REMOVING"+" (dryrun)"*args.get(ARGSTR_DRYRUN))
for f in dst_sID_ffile_glob:
cmd = "rm {}".format(f)
print(cmd)
if not args.get(ARGSTR_DRYRUN):
os.remove(f)
if not args.get(ARGSTR_OLD_ORG):
if not args.get(ARGSTR_DRYRUN):
os.rmdir(strip_dfull)
elif not args.get(ARGSTR_REBUILD_AUX):
print("{}, {} {} :: {} ({}) output files exist ".format(
job_num, ARGSTR_STRIPID, sID, len(dst_sID_ffile_glob), res_str)
+ "(potentially unfinished since no *.fin file), skipping")
continue
if args.get(ARGSTR_REMOVE_INCOMPLETE):
continue
args_single.set(ARGSTR_STRIPID, sID)
args_single.set(ARGSTR_SCENEDIRNAME, scenedirname)
if last_job_email and job_num == num_jobs:
args_single.set(ARGSTR_EMAIL, last_job_email)
cmd_single = args_single.get_cmd()
if args_batch.get(ARGSTR_SCHEDULER) is not None:
job_name = JOB_ABBREV+jobnum_fmt.format(job_num)
job_node_single = next(gen_job_node) if gen_job_node is not None else JOB_NODE
cmd = args_single.get_jobsubmit_cmd(
args_batch.get(ARGSTR_SCHEDULER),
jobscript=args_batch.get(ARGSTR_JOBSCRIPT), jobname=job_name,
time_hr=JOB_WALLTIME_HR, memory_gb=JOB_MEMORY_GB,
node=job_node_single, ncores=JOB_NCORES,
email=args.get(ARGSTR_EMAIL), licenses=args.get(ARGSTR_LICENSES),
envvars=[args_batch.get(ARGSTR_JOBSCRIPT), JOB_ABBREV, cmd_single, PYTHON_VERSION_ACCEPTED_MIN],
)
else:
cmd = cmd_single
print("{}, {}".format(job_num, cmd))
if not args_batch.get(ARGSTR_DRYRUN):
# For most cases, set `shell=True`.
# For attaching process to PyCharm debugger,
# set `shell=False`.
subprocess.call(cmd, shell=True, cwd=args_batch.get(ARGSTR_LOGDIR))
else:
run_s2s(args, res_str, argcho_dem_type_opp, demSuffix)
def run_s2s(args, res_str, argcho_dem_type_opp, demSuffix):
error_trace = None
sceneMaskSuffix = None
dstdir_coreg = None
scene_dname = None
strip_dname = None
scene_dfull = None
strip_dfull = None
strip_dfull_coreg = None
cleanup_on_failure_backup = args.get(ARGSTR_CLEANUP_ON_FAILURE)
args.set(ARGSTR_CLEANUP_ON_FAILURE, ARGCHO_CLEANUP_ON_FAILURE_NONE)
try:
import numpy as np # necessary check for later requirement
from lib.filter_scene import generateMasks
from lib.filter_scene import MASK_FLAT, MASK_SEPARATE, MASK_BIT
from lib.filter_scene import DEBUG_NONE, DEBUG_ALL, DEBUG_MASKS, DEBUG_ITHRESH
from lib.scenes2strips import scenes2strips
from lib.scenes2strips import HOLD_GUESS_OFF, HOLD_GUESS_ALL, HOLD_GUESS_UPDATE_RMSE
from batch_mask import get_mask_bitstring
## Process a single strip.
print('')
# Parse arguments in context of strip.
stripid_is_xtrack = args.get(ARGSTR_STRIPID)[1].isdigit()
bypass_ortho2 = False
use_old_trans = True if args.get(ARGSTR_META_TRANS_DIR) is not None else False
mask_name = 'mask' if args.get(ARGSTR_MASK_VER) == ARGCHO_MASK_VER_MASKV2 else args.get(ARGSTR_MASK_VER)
if args.get(ARGSTR_REMERGE_STRIPS):
scene_mask_name = mask_name
else:
scene_mask_name = demSuffix.replace('.tif', '_'+mask_name)
strip_mask_name = mask_name