-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch_check_setsm.py
2381 lines (2116 loc) · 114 KB
/
batch_check_setsm.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
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 python
# Erik Husby; Polar Geospatial Center, University of Minnesota; 2019
from __future__ import division
from lib import script_utils
PYTHON_VERSION_ACCEPTED_MIN = "2.7" # 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 glob
import logging
import os
import re
import shutil
import subprocess
import sys
import traceback
import warnings
from time import sleep
if script_utils.PYTHON_VERSION < script_utils.VersionString(3):
from StringIO import StringIO
else:
from io import StringIO
from lib import walk
from lib.script_utils import LOGGER, eprint
from lib.script_utils import ScriptArgumentError, DeveloperError
##############################
## Core globals
SCRIPT_VERSION_NUM = 1.0
# Paths
SCRIPT_FILE = 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 = 'python -u'
HOSTNAME = os.getenv('HOSTNAME')
if HOSTNAME is not None:
HOSTNAME = HOSTNAME.lower()
RUNNING_AT_PGC = True if True in [s in HOSTNAME for s in ['rookery', 'nunatak']] else False
else:
RUNNING_AT_PGC = False
LOGGER.setLevel(logging.INFO)
##############################
## Argument globals
# Argument strings
ARGSTR_SRC = 'src'
ARGSTR_DEPTH = '--depth'
ARGSTR_SRC_SUFFIX = '--src-suffix'
ARGSTR_CHECK_METHOD = '--check-method'
ARGSTR_CHECK_SETSM_VALIDRANGE = '--check-setsm-validrange'
ARGSTR_CHECK_SETSM_ALLOW_INVALID = '--check-setsm-allow-invalid'
ARGSTR_CHECKFILE_WRITE_AT_END = '--checkfile-write-at-end'
ARGSTR_CHECKFILE_OFF = '--checkfile-off'
ARGSTR_CHECKFILE = '--checkfile'
ARGSTR_CHECKFILE_ROOT = '--checkfile-root'
ARGSTR_CHECKFILE_ROOT_REGEX = '--checkfile-root-regex'
ARGSTR_CHECK_SPECIAL = '--check-special'
ARGSTR_CHECK_SPECIAL_DEMTYPE = '--check-special-demtype'
ARGSTR_VERIFY_BY_PAIRNAME_DIR = '--verify-by-pairname-dir'
ARGSTR_VERIFY_BY_PAIRNAME_DIR_DEPTH = '--verify-by-pairname-dir-depth'
ARGSTR_INDEX_PAIRNAMES_TO_JSON = '--index-pairnames-to-json'
ARGSTR_VERIFY_QUICK_CHECK = '--verify-quick-check'
ARGSTR_CHECKFILE_EXT = '--checkfile-ext'
ARGSTR_ERRFILE_EXT = '--errfile-ext'
ARGSTR_ALLOW_MISSING_SUFFIX = '--allow-missing-suffix'
ARGSTR_ALLOW_MISSING_ORTHO2 = '--allow-missing-ortho2'
ARGSTR_RETRY_ERRORS = '--retry-errors'
ARGSTR_KEEP_CHECKFILE_WITH_ERRORS = '--keep-checkfile-with-errors'
ARGSTR_SUPPRESS_ERRFILE_EXISTS = '--suppress-errfile-exists'
ARGSTR_SUPPRESS_MISSING_SUFFIX = '--suppress-missing-suffix'
ARGSTR_SUPPRESS_MISSING_CHECKED = '--suppress-missing-checked'
ARGSTR_SUPPRESS_NEW_SOURCE = '--suppress-new-source'
ARGSTR_REMOVE_TYPE = '--remove-type'
ARGSTR_RMWHERE_ERRFILE_EXISTS = '--rmwhere-errfile-exists'
ARGSTR_RMWHERE_MISSING_SUFFIX = '--rmwhere-missing-suffix'
ARGSTR_RMWHERE_MISSING_CHECKED = '--rmwhere-missing-checked'
ARGSTR_RMWHERE_NEW_SOURCE = '--rmwhere-new-source'
ARGSTR_REMOVE_ONLY = '--remove-only'
ARGSTR_STATS_ONLY = '--stats-only'
ARGSTR_SCHEDULER = '--scheduler'
ARGSTR_JOBSCRIPT = '--jobscript'
ARGSTR_JOBNAME = '--jobname'
ARGSTR_TASKS_PER_JOB = '--tasks-per-job'
ARGSTR_SCRATCH = '--scratch'
ARGSTR_WD = '--wd'
ARGSTR_LOGDIR = '--logdir'
ARGSTR_EMAIL = '--email'
ARGSTR_DO_DELETE = '--do-delete'
ARGSTR_DRYRUN = '--dryrun'
ARGSTR_DEBUG = '--debug'
# Argument groups
ARGGRP_OUTDIR = [ARGSTR_LOGDIR, ARGSTR_SCRATCH]
ARGGRP_BATCH = [ARGSTR_SCHEDULER, ARGSTR_JOBSCRIPT, ARGSTR_TASKS_PER_JOB, ARGSTR_EMAIL]
ARGGRP_CHECK_REGULAR = [ARGSTR_CHECKFILE, ARGSTR_CHECKFILE_ROOT, ARGSTR_CHECKFILE_ROOT_REGEX]
ARGGRP_CHECK_OTHER = [ARGSTR_CHECK_SPECIAL]
ARGGRP_CHECK_ALL = ARGGRP_CHECK_REGULAR + ARGGRP_CHECK_OTHER
ARGGRP_RMWHERE = [
ARGSTR_RMWHERE_ERRFILE_EXISTS,
ARGSTR_RMWHERE_MISSING_SUFFIX,
ARGSTR_RMWHERE_MISSING_CHECKED,
ARGSTR_RMWHERE_NEW_SOURCE
]
ARGGRP_REQUIRES_RMWHERE = [ARGSTR_DO_DELETE, ARGSTR_REMOVE_ONLY]
# Argument choices
ARGCHO_CHECK_METHOD_READ = 'read'
ARGCHO_CHECK_METHOD_CHECKSUM = 'checksum'
ARGCHO_CHECK_METHOD = [
ARGCHO_CHECK_METHOD_READ,
ARGCHO_CHECK_METHOD_CHECKSUM
]
ARGCHO_CHECK_SPECIAL_ALL_TOGETHER = 'altogether'
ARGCHO_CHECK_SPECIAL_ALL_SEPARATE = 'separate'
ARGCHO_CHECK_SPECIAL_SCENEPAIRS = 'scenes'
ARGCHO_CHECK_SPECIAL_PAIRNAMES = 'pairnames'
ARGCHO_CHECK_SPECIAL_STRIPSEGMENTS = 'strip-segments'
ARGCHO_CHECK_SPECIAL_STRIPS = 'strips'
ARGCHO_CHECK_SPECIAL_SCENEMETA = 'scene-meta'
ARGCHO_CHECK_SPECIAL_STRIPMETA = 'strip-meta'
ARGCHO_CHECK_SPECIAL_DSP = '2m_dsp_scenes'
ARGCHO_CHECK_SPECIAL = [
ARGCHO_CHECK_SPECIAL_ALL_TOGETHER,
ARGCHO_CHECK_SPECIAL_ALL_SEPARATE,
ARGCHO_CHECK_SPECIAL_SCENEPAIRS,
ARGCHO_CHECK_SPECIAL_PAIRNAMES,
ARGCHO_CHECK_SPECIAL_STRIPSEGMENTS,
ARGCHO_CHECK_SPECIAL_STRIPS,
ARGCHO_CHECK_SPECIAL_SCENEMETA,
ARGCHO_CHECK_SPECIAL_STRIPMETA,
ARGCHO_CHECK_SPECIAL_DSP
]
ARGCHO_CHECK_SPECIAL_DEMTYPE_REGULAR = 'non-lsf'
ARGCHO_CHECK_SPECIAL_DEMTYPE_SMOOTH = 'lsf'
ARGCHO_CHECK_SPECIAL_DEMTYPE_BOTH = 'both'
ARGCHO_CHECK_SPECIAL_DEMTYPE = [
ARGCHO_CHECK_SPECIAL_DEMTYPE_REGULAR,
ARGCHO_CHECK_SPECIAL_DEMTYPE_SMOOTH,
ARGCHO_CHECK_SPECIAL_DEMTYPE_BOTH
]
ARGCHO_REMOVE_TYPE_CHECKFILES = 'checkfiles'
ARGCHO_REMOVE_TYPE_SOURCEFILES = 'sourcefiles'
ARGCHO_REMOVE_TYPE_BOTH = 'both'
ARGCHO_REMOVE_TYPE = [
ARGCHO_REMOVE_TYPE_CHECKFILES,
ARGCHO_REMOVE_TYPE_SOURCEFILES,
ARGCHO_REMOVE_TYPE_BOTH
]
# Argument choice groups
ARGCHOGRP_CHECK_SPECIAL_SETSM_DEM_SCENELEVEL = [
ARGCHO_CHECK_SPECIAL_SCENEPAIRS,
ARGCHO_CHECK_SPECIAL_PAIRNAMES,
ARGCHO_CHECK_SPECIAL_DSP
]
ARGCHOGRP_CHECK_SPECIAL_SETSM_DEM_STRIPLEVEL = [
ARGCHO_CHECK_SPECIAL_STRIPSEGMENTS,
ARGCHO_CHECK_SPECIAL_STRIPS
]
ARGCHOGRP_CHECK_SPECIAL_SETSM_DEM = (
ARGCHOGRP_CHECK_SPECIAL_SETSM_DEM_SCENELEVEL
+ ARGCHOGRP_CHECK_SPECIAL_SETSM_DEM_STRIPLEVEL
)
ARGCHOGRP_CHECK_SPECIAL_SETSM_SCENELEVEL = ARGCHOGRP_CHECK_SPECIAL_SETSM_DEM_SCENELEVEL + [
ARGCHO_CHECK_SPECIAL_SCENEMETA
]
ARGCHOGRP_CHECK_SPECIAL_SETSM_STRIPLEVEL = ARGCHOGRP_CHECK_SPECIAL_SETSM_DEM_STRIPLEVEL + [
ARGCHO_CHECK_SPECIAL_STRIPMETA
]
ARGCHOGRP_CHECK_SPECIAL_SETSM = (
ARGCHOGRP_CHECK_SPECIAL_SETSM_SCENELEVEL
+ ARGCHOGRP_CHECK_SPECIAL_SETSM_STRIPLEVEL
)
# Argument choice settings
CHECK_SPECIAL_DEM_SUFFIX_ORTHO2 = 'ortho2.tif'
CHECK_SPECIAL_DEM_SUFFIX_ORTHO2_10M = 'ortho2_10m.tif'
CHECK_SPECIAL_DEM_SUFFIX_SCENELEVEL_MATCHTAG_SET = {'matchtag_mt.tif', 'meta_mt.txt'}
CHECK_SPECIAL_DEM_SUFFIX_OPTIONAL_SCENELEVEL_SET = {
'mask.tif',
'meta_or.txt'
}
CHECK_SPECIAL_DEM_SUFFIX_OPTIONAL_STRIPLEVEL_SET = {
'bitmask_10m.tif',
'matchtag_10m.tif',
'ortho_10m.tif',
CHECK_SPECIAL_DEM_SUFFIX_ORTHO2_10M,
'dem_10m.tif',
'dem_10m_masked.tif',
'dem_10m_shade.tif',
'dem_10m_shade_masked.tif',
'dem_40m_masked.tif',
'dem_40m_coverage.tif'
}
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_META = 'meta.txt'
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_INFO50CM = 'info50cm.txt'
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_SCENELEVEL = '/'.join([
# DEM suffix(es) will be set by --check-special-demtype script argument
'matchtag.tif',
'ortho.tif',
CHECK_SPECIAL_DEM_SUFFIX_ORTHO2,
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_META,
'/'.join(CHECK_SPECIAL_DEM_SUFFIX_SCENELEVEL_MATCHTAG_SET),
'/'.join(CHECK_SPECIAL_DEM_SUFFIX_OPTIONAL_SCENELEVEL_SET)
])
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_STRIPLEVEL = '/'.join([
'dem.tif',
'matchtag.tif',
'ortho.tif',
CHECK_SPECIAL_DEM_SUFFIX_ORTHO2,
'bitmask.tif',
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_META,
'/'.join(CHECK_SPECIAL_DEM_SUFFIX_OPTIONAL_STRIPLEVEL_SET)
])
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_DSP = '/'.join([
'matchtag.tif',
'ortho.tif',
ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_INFO50CM
])
# ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_SCENELEVEL = re.compile("(?P<scenepairname>(?P<strippairname>(?P<sensor>[A-Z0-9]{4})_(?P<timestamp>\d{8})_(?P<catid1>[A-Z0-9]{16})_(?P<catid2>[A-Z0-9]{16}))_(?P<tile1>R\d+C\d+-)?(?P<order1>\d{12}_\d{2})_(?P<part1>P\d{3})_(?P<tile2>R\d+C\d+-)?(?P<order2>\d{12}_\d{2})_(?P<part2>P\d{3})_(?P<res>\d{1}))_(?P<suffix>[_a-z0-9]+)\.(?P<ext>\w+)")
ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_SCENELEVEL = re.compile("^([A-Z0-9]{4}_\d{8}_[0-9A-F]{16}_[0-9A-F]{16}_(R\d+C\d+-)?\d{12}_\d{2}_P\d{3}_(R\d+C\d+-)?\d{12}_\d{2}_P\d{3}_\d{1}(-\d{2})?)_[a-z0-9_]+\.\w+$")
ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_STRIPLEVEL = re.compile("^((?:SETSM_s2s\d{3}_)?[A-Z0-9]{4}_\d{8}_[0-9A-F]{16}_[0-9A-F]{16}).*$")
ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_STRIPSEGMENT = re.compile("^((?:SETSM_s2s\d{3}_)?[A-Z0-9]{4}_\d{8}_[0-9A-F]{16}_[0-9A-F]{16}_\d+c?m(_lsf)?_seg\d+)_[a-z0-9_]+\.\w+$")
ARGCHOSET_CHECK_SPECIAL_SETTING_DICT = {
ARGCHO_CHECK_SPECIAL_ALL_TOGETHER: [
(ARGSTR_CHECKFILE_ROOT, "")
],
ARGCHO_CHECK_SPECIAL_ALL_SEPARATE: [
(ARGSTR_CHECKFILE_ROOT_REGEX, "^(.*)$")
],
ARGCHO_CHECK_SPECIAL_SCENEPAIRS: [
(ARGSTR_SRC_SUFFIX, ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_SCENELEVEL),
(ARGSTR_CHECKFILE_ROOT_REGEX, ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_SCENELEVEL)
],
ARGCHO_CHECK_SPECIAL_PAIRNAMES: [
(ARGSTR_SRC_SUFFIX, ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_SCENELEVEL),
(ARGSTR_CHECKFILE_ROOT_REGEX, ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_STRIPLEVEL)
],
ARGCHO_CHECK_SPECIAL_STRIPSEGMENTS: [
(ARGSTR_SRC_SUFFIX, ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_STRIPLEVEL),
(ARGSTR_CHECKFILE_ROOT_REGEX, ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_STRIPSEGMENT)
],
ARGCHO_CHECK_SPECIAL_STRIPS: [
(ARGSTR_SRC_SUFFIX, ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_STRIPLEVEL),
(ARGSTR_CHECKFILE_ROOT_REGEX, ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_STRIPLEVEL)
],
ARGCHO_CHECK_SPECIAL_SCENEMETA: [
(ARGSTR_SRC_SUFFIX, ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_META),
(ARGSTR_CHECKFILE_OFF, True),
],
ARGCHO_CHECK_SPECIAL_STRIPMETA: [
(ARGSTR_SRC_SUFFIX, ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_META),
(ARGSTR_CHECKFILE_OFF, True),
],
ARGCHO_CHECK_SPECIAL_DSP: [
(ARGSTR_SRC_SUFFIX, ARGCHOSET_CHECK_SPECIAL_DEM_SUFFIX_DSP),
(ARGSTR_CHECKFILE_ROOT_REGEX, ARGCHOSET_CHECK_SPECIAL_DEM_REGEX_SCENELEVEL)
]
}
ARGCHOSET_CHECK_SPECIAL_SUBGROUP_DICT = {
ARGCHO_CHECK_SPECIAL_PAIRNAMES: [
ARGCHO_CHECK_SPECIAL_SCENEPAIRS
],
ARGCHO_CHECK_SPECIAL_STRIPS: [
ARGCHO_CHECK_SPECIAL_STRIPSEGMENTS
]
}
ARGCHOSET_CHECK_SPECIAL_DEMTYPE_SUFFIX_DICT = {
ARGCHO_CHECK_SPECIAL_DEMTYPE_REGULAR: 'dem.tif',
ARGCHO_CHECK_SPECIAL_DEMTYPE_SMOOTH: 'dem_smooth.tif/smooth_result.txt',
}
ARGCHOSET_CHECK_SPECIAL_DEMTYPE_SUFFIX_DICT[ARGCHO_CHECK_SPECIAL_DEMTYPE_BOTH] = '/'.join(
sorted(ARGCHOSET_CHECK_SPECIAL_DEMTYPE_SUFFIX_DICT.values()))
ARGCHOSET_CHECK_SPECIAL_INDEX_MODE_DICT = {
ARGCHO_CHECK_SPECIAL_SCENEPAIRS: 'scene',
ARGCHO_CHECK_SPECIAL_STRIPS: 'strip',
ARGCHO_CHECK_SPECIAL_DSP: 'scene'
}
# Argument defaults
ARGDEF_SRC_SUFFIX = '.tif'
ARGDEF_DEPTH = script_utils.ARGNUM_POS_INF
ARGDEF_VERIFY_BY_PAIRNAME_DIR_DEPTH = 1
ARGDEF_CHECKFILE_EXT = '.check'
ARGDEF_CHECKERROR_EXT = '.err'
ARGDEF_SCRATCH = os.path.join(os.path.expanduser('~'), 'scratch', 'task_bundles')
##############################
## Batch settings
JOBSCRIPT_DIR = os.path.join(SCRIPT_DIR, 'jobscripts')
JOBSCRIPT_INIT = os.path.join(JOBSCRIPT_DIR, 'init.sh')
JOB_ABBREV = 'Check'
# BATCH_ARGDEF_WD = '/local' if RUNNING_AT_PGC else None
BATCH_ARGDEF_WD = None
JOB_WALLTIME_HR = 72
JOB_MEMORY_GB = 40
JOB_NCORES = 4
JOB_NODE = None
##############################
## Custom globals
INDEX_SETSM_SCRIPT = os.path.join(SCRIPT_DIR, '..', 'pgcdemtools', 'index_setsm.py')
GDAL_RASTER_SUFFIXES = ['.tif', '.tiff']
SETSM_RASTER_SUFFIX_VALIDRANGE_DICT = {
'_dem.tif': [-8000, 100000],
'_dem_smooth.tif': [-8000, 100000],
'_matchtag.tif': [0, 1],
'_matchtag_mt.tif': [0, 1],
}
SETSM_META_SUFFIX = '_meta.txt'
SETSM_STRIPMETA_SCENEMETA_SECTION_HEADER = 'Scene Metadata'
SETSM_STRIPMETA_SCENEMETA_ITEM_HEADER_REGEX = re.compile("^\s*scene \d+ name=.*$")
SETSM_META_REQUIRED_DICT = dict()
SETSM_META_KEY_TOKEN_DELIM_RE = '(?: +|_+)'
SETSM_META_SPACE_RE = '[ \t]*?'
SETSM_META_NEWLINE_START_RE = '(?:\r\n|\r|\n)'
SETSM_META_NEWLINE_END_RE = '(?=(?:\r\n|\r|\n))'
SETSM_META_KEY_PREFIX_IMAGE = 'image'.strip().lower()
SETSM_META_KEY_PREFIX_IMAGE_1 = ' '.join([SETSM_META_KEY_PREFIX_IMAGE, str(1)])
SETSM_META_KEY_PREFIX_IMAGE_2 = ' '.join([SETSM_META_KEY_PREFIX_IMAGE, str(2)])
SETSM_META_IMAGE_PREFIX_RE = SETSM_META_KEY_TOKEN_DELIM_RE.join([SETSM_META_KEY_PREFIX_IMAGE, '[12]'])
SETSM_META_WV_CORRECT_SATIDS = ['WV01', 'WV02']
def get_setsm_meta_item_regex(key_str, value_re, allow_missing_image_prefix=False):
if key_str is None:
key_re = SETSM_META_IMAGE_PREFIX_RE
else:
key_re = SETSM_META_KEY_TOKEN_DELIM_RE.join(key_str.replace('_', ' ').split())
if allow_missing_image_prefix:
key_re = '(?:{}|{})'.format(SETSM_META_KEY_TOKEN_DELIM_RE.join([SETSM_META_IMAGE_PREFIX_RE, key_re]), key_re)
else:
key_re = SETSM_META_KEY_TOKEN_DELIM_RE.join([SETSM_META_IMAGE_PREFIX_RE, key_re])
item_re = SETSM_META_SPACE_RE.join([SETSM_META_NEWLINE_START_RE, key_re, '=', value_re, SETSM_META_NEWLINE_END_RE])
return re.compile(item_re, re.I)
SETSM_META_ITEM_IS_KEY_VALUE = True
SETSM_META_ITEM_IS_NOT_KEY_VALUE = False
SETSM_META_ITEM_COUNT_SINGLE = 1
SETSM_META_ITEM_COUNT_PAIR = 2
SETSM_META_KEY = 'Image path'
SETSM_META_KEY_IMAGE_PATH = SETSM_META_KEY
SETSM_META_ITEM_RE = get_setsm_meta_item_regex(None, "[\d\w_\-/]+\.tif")
SETSM_META_REQUIRED_DICT[SETSM_META_KEY] = (SETSM_META_ITEM_RE, SETSM_META_ITEM_IS_KEY_VALUE, SETSM_META_ITEM_COUNT_PAIR)
SETSM_META_KEYGRP_GSD = [
# 'Mean_row_GSD',
# 'Mean_col_GSD',
# 'Mean_GSD'
]
for SETSM_META_KEY in SETSM_META_KEYGRP_GSD + [
'Mean_sun_azimuth_angle',
'Mean_sun_elevation',
'Mean_sat_azimuth_angle'
]:
SETSM_META_VALUE_RE = "\d+\.?\d*"
SETSM_META_ITEM_RE = get_setsm_meta_item_regex(SETSM_META_KEY, SETSM_META_VALUE_RE, allow_missing_image_prefix=True)
SETSM_META_REQUIRED_DICT[SETSM_META_KEY] = (SETSM_META_ITEM_RE, SETSM_META_ITEM_IS_KEY_VALUE, SETSM_META_ITEM_COUNT_PAIR)
SETSM_META_KEY = 'Mean_sat_elevation'
SETSM_META_ITEM_RE = get_setsm_meta_item_regex(SETSM_META_KEY, "\-?\d+\.?\d*", allow_missing_image_prefix=True)
SETSM_META_REQUIRED_DICT[SETSM_META_KEY] = (SETSM_META_ITEM_RE, SETSM_META_ITEM_IS_KEY_VALUE, SETSM_META_ITEM_COUNT_PAIR)
for SETSM_META_KEY in [
'effbw',
'abscalfact'
]:
SETSM_META_VALUE_RE = "\d+\.?\d*"
SETSM_META_ITEM_RE = get_setsm_meta_item_regex(SETSM_META_KEY, SETSM_META_VALUE_RE)
SETSM_META_REQUIRED_DICT[SETSM_META_KEY] = (SETSM_META_ITEM_RE, SETSM_META_ITEM_IS_KEY_VALUE, SETSM_META_ITEM_COUNT_PAIR)
for SETSM_META_KEY in [
'tdi',
'min',
'max'
]:
SETSM_META_VALUE_RE = "\d+"
SETSM_META_ITEM_RE = get_setsm_meta_item_regex(SETSM_META_KEY, SETSM_META_VALUE_RE)
SETSM_META_REQUIRED_DICT[SETSM_META_KEY] = (SETSM_META_ITEM_RE, SETSM_META_ITEM_IS_KEY_VALUE, SETSM_META_ITEM_COUNT_PAIR)
SETSM_META_KEY = 'wv_correct'
SETSM_META_KEY_WV_CORRECT = SETSM_META_KEY
SETSM_META_ITEM_RE = get_setsm_meta_item_regex(SETSM_META_KEY, "[01]")
SETSM_META_REQUIRED_DICT[SETSM_META_KEY] = (SETSM_META_ITEM_RE, SETSM_META_ITEM_IS_KEY_VALUE, SETSM_META_ITEM_COUNT_PAIR)
SETSM_META_KEY = 'ASP build ID'
SETSM_META_ITEM_RE = get_setsm_meta_item_regex(SETSM_META_KEY, "(?:[0-9A-F]+)?")
SETSM_META_REQUIRED_DICT[SETSM_META_KEY] = (SETSM_META_ITEM_RE, SETSM_META_ITEM_IS_KEY_VALUE, SETSM_META_ITEM_COUNT_PAIR)
SETSM_META_REQUIRED_KEY_SORTED_LIST = sorted(SETSM_META_REQUIRED_DICT.keys())
del SETSM_META_KEY, SETSM_META_ITEM_RE, SETSM_META_VALUE_RE
INFO50CM_RE = re.compile(
"""scenedemid=[A-Z][A-Z0-9]{2}\d{1}_\d{8}_[A-Z0-9]{16}_[A-Z0-9]{16}_(?:R\d+C\d+-)?\d{12}_\d{2}_P\d{3}_(?:R\d+C\d+-)?\d{12}_\d{2}_P\d{3}_0(?:-\d{2})?
stripdemid=[A-Z][A-Z0-9]{2}\d{1}_\d{8}_[A-Z0-9]{16}_[A-Z0-9]{16}_50cm_v\d{6}
filesz_dem=(\d+\.\d+([eE][-\+]?\d+)?)
filesz_lsf=((?:\d+\.\d+)?([eE][-\+]?\d+)?)
filesz_mt=(\d+\.\d+([eE][-\+]?\d+)?)
filesz_or=(\d+\.\d+([eE][-\+]?\d+)?)
filesz_or2=((?:\d+\.\d+)?([eE][-\+]?\d+)?)
\Z"""
)
##############################
class SETSMMetaParseError(Exception):
def __init__(self, msg=""):
super(Exception, self).__init__(msg)
class RasterFileReadError(Exception):
def __init__(self, msg=""):
super(Exception, self).__init__(msg)
def argparser_init():
parser = argparse.ArgumentParser(
formatter_class=script_utils.RawTextArgumentDefaultsHelpFormatter,
description=' '.join([
"Check existence and integrity of data files in batch."
])
)
# Positional arguments
parser.add_argument(
ARGSTR_SRC,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_SRC,
abspath_fn=os.path.abspath,
existcheck_fn=os.path.exists,
existcheck_reqval=True),
help=' '.join([
"Path to source file directory or single input file to check.",
"Accepts a task bundle text file listing paths to checkfile root paths."
])
)
# Optional arguments
parser.add_argument(
ARGSTR_DEPTH,
type=script_utils.ARGTYPE_NUM(
argstr=ARGSTR_DEPTH,
numeric_type=int,
allow_neg=False,
allow_zero=False,
allow_inf=True),
default=ARGDEF_DEPTH,
help=' '.join([
"Depth of recursive search into source directory for files to check.",
])
)
parser.add_argument(
ARGSTR_SRC_SUFFIX,
type=str,
default=ARGDEF_SRC_SUFFIX,
help=' '.join([
"'/'-delimited list of accepted source file suffixes to be checked.",
])
)
parser.add_argument(
ARGSTR_CHECK_METHOD,
type=str,
choices=ARGCHO_CHECK_METHOD,
default=ARGCHO_CHECK_METHOD_CHECKSUM,
help=' '.join([
"Method used to check integrity of source rasters.",
"\nIf '{}', simply attempt to read raster band(s).".format(ARGCHO_CHECK_METHOD_READ),
"\nIf '{}', attempt to compute checksum of each raster band.".format(ARGCHO_CHECK_METHOD_CHECKSUM),
"\n"
])
)
parser.add_argument(
ARGSTR_CHECK_SETSM_VALIDRANGE,
action='store_true',
help=' '.join([
"After successfully opening a source raster ending with a filename suffix listed in",
"script 'Custom globals' dictionary variable SETSM_RASTER_SUFFIX_VALIDRANGE_DICT, check that all",
"non-NoData values fall the raster band fall within the corresponding numerical range",
"(inclusive)."
])
)
parser.add_argument(
ARGSTR_CHECKFILE_OFF,
action='store_true',
help=' '.join([
"Ignore existing checkfiles and check all files, saving error files but not checkfiles."
])
)
parser.add_argument(
ARGSTR_CHECKFILE,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_CHECKFILE,
existcheck_fn=os.path.isdir,
existcheck_reqval=False),
default=None,
help=' '.join([
"Path to single checkfile (which may already exist) used to store filenames of",
"passing source file(s) selected by arguments {} and {}.".format(ARGSTR_SRC, ARGSTR_SRC_SUFFIX),
"Due to the issue of multiple processes attempting to write to a text file at once,",
"this argument is incompatible with job scheduler options.",
])
)
parser.add_argument(
ARGSTR_CHECKFILE_ROOT,
type=str,
default=None,
help=' '.join([
"Filename prefix by which to group source files for checking.",
"The default path of the checkfile becomes '[{}]/[{}].[{}]'".format(ARGSTR_SRC, ARGSTR_CHECKFILE_ROOT, ARGSTR_CHECKFILE_EXT),
"Use only if argument {} is a directory.".format(ARGSTR_SRC),
"Due to the issue of multiple processes attempting to write to a text file at once,",
"this argument is incompatible with job scheduler options."
])
)
parser.add_argument(
ARGSTR_CHECKFILE_ROOT_REGEX,
type=str,
default=None,
help=' '.join([
"Regex for filename prefix by which to group source files for checking.",
"Regex must contain one group for matching, which becomes the filename prefix for"
"a single bundle of source files to check.",
"The default path of each checkfile thus becomes '[{}]/[regex match group].[{}]'".format(ARGSTR_SRC, ARGSTR_CHECKFILE_ROOT, ARGSTR_CHECKFILE_EXT),
"Use only if argument {} is a directory.".format(ARGSTR_SRC),
"In the context of the job scheduler {} option, each unique regex match group becomes".format(ARGSTR_SCHEDULER),
"a single task by passing it as the {} argument to a 'fork' of this batch script".format(ARGSTR_CHECKFILE_ROOT)
])
)
parser.add_argument(
ARGSTR_CHECK_SPECIAL,
type=str,
choices=ARGCHO_CHECK_SPECIAL,
default=None,
help=' '.join([
"Popular options for quickly setting {} and {} arguments.".format(ARGSTR_SRC_SUFFIX, ARGSTR_CHECKFILE_ROOT_REGEX),
])
)
parser.add_argument(
ARGSTR_CHECK_SPECIAL_DEMTYPE,
type=str,
choices=ARGCHO_CHECK_SPECIAL_DEMTYPE,
default=ARGCHO_CHECK_SPECIAL_DEMTYPE_BOTH,
help=' '.join([
"Used in conjunction with argument {}, this determines which DEM file suffix(es)".format(ARGSTR_CHECK_SPECIAL),
"are set for argument {} source file selection".format(ARGSTR_SRC_SUFFIX)
])
)
parser.add_argument(
ARGSTR_VERIFY_BY_PAIRNAME_DIR,
action='store_true',
help=' '.join([
"Use PAIRNAME DIRECTORIES as check groups, writing check and error files next to ",
"the pairname directories."
])
)
parser.add_argument(
ARGSTR_VERIFY_BY_PAIRNAME_DIR_DEPTH,
type=script_utils.ARGTYPE_NUM(
argstr=ARGSTR_VERIFY_BY_PAIRNAME_DIR_DEPTH,
numeric_type=int,
allow_neg=False,
allow_zero=True,
allow_inf=True),
default=ARGDEF_VERIFY_BY_PAIRNAME_DIR_DEPTH,
help=' '.join([
"Depth of recursive search into source directory for PAIRNAME DIRECTORIES to check.",
])
)
parser.add_argument(
ARGSTR_INDEX_PAIRNAMES_TO_JSON,
action='store_true',
help=' '.join([
"Build index .json file alongside each PAIRNAME DIRECTORY after completely successful check.",
"Only applicable when {} option is also provided, and {} must be set to one of {}.".format(
ARGSTR_VERIFY_BY_PAIRNAME_DIR,ARGSTR_CHECK_SPECIAL, sorted(ARGCHOSET_CHECK_SPECIAL_INDEX_MODE_DICT.keys())
),
"Requires the 'pgcdemtools' repo to exist at alongside this repo."
])
)
parser.add_argument(
'-vqc', ARGSTR_VERIFY_QUICK_CHECK,
action='store_true',
help=' '.join([
"Scan {} directory for PAIRNAME DIRECTORIES and verify that all necessary checkfiles".format(ARGSTR_SRC),
"and JSON files have built successfully for processing region to be deemed complete",
"and ready for writing JSON indices to applicable database(s)."
])
)
parser.add_argument(
ARGSTR_CHECKFILE_EXT,
type=str,
default=ARGDEF_CHECKFILE_EXT,
help=' '.join([
"File extension of checkfile(s), unless argument {} is used, in which case the extension".format(ARGSTR_CHECKFILE),
"is considered to be included/excluded in the provided checkfile file path."
])
)
parser.add_argument(
ARGSTR_ERRFILE_EXT,
type=str,
default=ARGDEF_CHECKERROR_EXT,
help=' '.join([
"File extension of error files created when source files are deemed invalid during",
"checking procedures, containing error messages describing issues with the source file.",
"The full file path of an error file is constructed by simply appending this string",
"to the full file path of the corresponding source file."
])
)
parser.add_argument(
ARGSTR_CHECKFILE_WRITE_AT_END,
action='store_true',
help=' '.join([
"Write list of passing source files to check file at end of processing all "
"source files in check group, instead of appending as soon as each pass check."
])
)
parser.add_argument(
ARGSTR_ALLOW_MISSING_SUFFIX,
action='store_true',
help=' '.join([
"Allow checking of check groups that are missing source file suffixes."
])
)
parser.add_argument(
ARGSTR_ALLOW_MISSING_ORTHO2,
action='store_true',
help=' '.join([
"Allow checking of SETSM DEM check groups that are missing the '{}' source file.".format(
CHECK_SPECIAL_DEM_SUFFIX_ORTHO2
)
])
)
parser.add_argument(
ARGSTR_RETRY_ERRORS,
action='store_true',
help=' '.join([
"Attempt checking source files & groups with existing error files."
])
)
parser.add_argument(
ARGSTR_KEEP_CHECKFILE_WITH_ERRORS,
action='store_true',
help=' '.join([
"Continue writing group checkfile after errors in source files have been discovered."
])
)
parser.add_argument(
ARGSTR_SUPPRESS_ERRFILE_EXISTS,
action='store_true',
help=' '.join([
"Suppress printing all cases of existing error files among check group source files."
])
)
parser.add_argument(
ARGSTR_SUPPRESS_MISSING_SUFFIX,
action='store_true',
help=' '.join([
"Suppress printing all cases of source file suffixes missing from check group."
])
)
parser.add_argument(
ARGSTR_SUPPRESS_MISSING_CHECKED,
action='store_true',
help=' '.join([
"Suppress printing all files that are listed in checkfiles but cannot be found in source directory."
])
)
parser.add_argument(
ARGSTR_SUPPRESS_NEW_SOURCE,
action='store_true',
help=' '.join([
"Suppress printing all new source files that are to be added to existing checkfiles."
])
)
parser.add_argument(
ARGSTR_REMOVE_TYPE,
type=str,
choices=ARGCHO_REMOVE_TYPE,
default=ARGCHO_REMOVE_TYPE_CHECKFILES,
help=' '.join([
"Specify which files can be removed by the following arguments:",
ARGSTR_RMWHERE_ERRFILE_EXISTS,
ARGSTR_RMWHERE_MISSING_SUFFIX,
ARGSTR_RMWHERE_MISSING_CHECKED,
ARGSTR_RMWHERE_NEW_SOURCE
])
)
parser.add_argument(
ARGSTR_RMWHERE_ERRFILE_EXISTS,
action='store_true',
help=' '.join([
"Remove existing check/source files when error files exist among check group source files.",
"Use {} argument to specify which files can be removed.".format(ARGSTR_REMOVE_TYPE)
])
)
parser.add_argument(
ARGSTR_RMWHERE_MISSING_SUFFIX,
action='store_true',
help=' '.join([
"Remove existing check/source files when source file suffixes are missing from check group.",
"Use {} argument to specify which files can be removed.".format(ARGSTR_REMOVE_TYPE)
])
)
parser.add_argument(
ARGSTR_RMWHERE_MISSING_CHECKED,
action='store_true',
help=' '.join([
"Remove existing check/source files when files listed in checkfile cannot be found in source directory.",
"Use {} argument to specify which files can be removed.".format(ARGSTR_REMOVE_TYPE)
])
)
parser.add_argument(
ARGSTR_RMWHERE_NEW_SOURCE,
action='store_true',
help=' '.join([
"Remove existing check/source files when new source files are to be added to checkfile.",
"Use {} argument to specify which files can be removed.".format(ARGSTR_REMOVE_TYPE)
])
)
parser.add_argument(
ARGSTR_REMOVE_ONLY,
action='store_true',
help="Scan check/source files and possibly perform removal actions, then exit."
)
parser.add_argument(
ARGSTR_STATS_ONLY,
action='store_true',
help="Scan check/source files and report task completion status, then exit."
)
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_JOBNAME,
type=str,
default=JOB_ABBREV,
help="Prefix for names of jobs submitted to scheduler."
)
parser.add_argument(
ARGSTR_TASKS_PER_JOB,
type=int,
default=None,
help=' '.join([
"Number of tasks to bundle into a single job.",
"(requires {} option)".format(ARGSTR_SCHEDULER)
])
)
parser.add_argument(
ARGSTR_SCRATCH,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_SCRATCH,
existcheck_fn=os.path.isfile,
existcheck_reqval=False),
default=ARGDEF_SCRATCH,
help="Scratch directory to build task bundle text files."
)
parser.add_argument(
ARGSTR_WD,
type=script_utils.ARGTYPE_PATH(
argstr=ARGSTR_WD,
existcheck_fn=os.path.isdir,
existcheck_reqval=True),
default=None,
help=' '.join([
"Copy source files to this directory before checking, run checks on these copies,",
"then clean up the copies before moving on.",
"At PGC, this argument is meant to be used with {} argument to minimize the impact of".format(ARGSTR_SCHEDULER),
"file I/O on the network."
])
)
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_DO_DELETE,
action='store_true',
help="Perform file removal actions."
)
parser.add_argument(
ARGSTR_DRYRUN,
action='store_true',
help="Print actions without executing."
)
parser.add_argument(
ARGSTR_DEBUG,
action='store_true',
help="Change logger from INFO to DEBUG level."
)
return parser
def endswith_one_of_coll(check_string, string_ending_coll, case_sensitive=True, return_match=False):
for s_end in string_ending_coll:
if check_string.endswith(s_end) or (not case_sensitive and check_string.lower().endswith(s_end.lower())):
return s_end if return_match else True
return None if return_match else False
def ends_one_of_coll(string_ending, string_coll, case_sensitive=True, return_match=False):
for s in string_coll:
if s.endswith(string_ending) or (not case_sensitive and s.lower().endswith(string_ending.lower())):
return s if return_match else True
return None if return_match else False
def checkfile_incomplete(args,
checkfile_root, checkfile_ext, errfile_ext, src_suffixes,
src_rasters=None, return_incomplete_src_rasters=False,
srcfile_count=None, errfile_count=None,
missing_suffix_flag=None, checkfile_removed_flag=None,
warn_missing_suffix=True, warn_errfile_exists=True,
warn_missing_checked=True, warn_new_source=True):
if checkfile_ext is not None:
checkfile = checkfile_root+checkfile_ext
checkgroup_errfile = checkfile_root+errfile_ext
else:
checkfile = checkfile_root
checkgroup_errfile = None
if checkfile_ext is None and src_rasters is None:
raise DeveloperError("Checkfile {}; cannot locate corresponding source files when checkfile"
"is a full file path (assuming argument {} was provided)".format(checkfile, ARGSTR_CHECKFILE))
checkfile_dir = os.path.dirname(checkfile) if not os.path.isdir(checkfile_root) else checkfile_root
checkfile_exists = os.path.isfile(checkfile)
if src_rasters is not None and type(src_rasters) is list:
src_rasters = set(src_rasters)
checkfname = os.path.basename(checkfile)
check_group_is_xtrack = checkfname[1].isdigit()
find_src_rasters = ( return_incomplete_src_rasters
or warn_missing_suffix or args.get(ARGSTR_RMWHERE_MISSING_SUFFIX)
or warn_errfile_exists or args.get(ARGSTR_RMWHERE_ERRFILE_EXISTS))
delete_files = False
if checkfile_exists and not args.get(ARGSTR_CHECKFILE_OFF):
with open(checkfile, 'r') as checkfile_fp:
src_rasters_checked = set(checkfile_fp.read().splitlines())
if src_rasters is None:
src_rasters = {os.path.basename(f) for f in glob.glob(checkfile_root+'*') if endswith_one_of_coll(f, src_suffixes)}
src_rasters_to_check = src_rasters.difference(src_rasters_checked)
if src_rasters_to_check:
warnings.warn("There are more (new?) source files to be added to an existing checkfile")
if warn_new_source:
eprint("Checkfile {}; {} more (new?) source files are to be added to existing checkfile".format(
checkfile, len(src_rasters_to_check)))
for f in sorted(list(src_rasters_to_check)):
eprint(f)
delete_files = (delete_files or args.get(ARGSTR_RMWHERE_NEW_SOURCE))
src_rasters_checked_missing = src_rasters_checked.difference(src_rasters)
if src_rasters_checked_missing:
warnings.warn("Files listed in a checkfile were not captured in source selection")
if warn_missing_checked:
eprint("Checkfile {}; {} source files listed in checkfile are missing from source selection:".format(
checkfile, len(src_rasters_checked_missing)))
for f in sorted(list(src_rasters_checked_missing)):
eprint(f)
delete_files = (delete_files or args.get(ARGSTR_RMWHERE_MISSING_CHECKED))
elif return_incomplete_src_rasters or find_src_rasters:
if src_rasters is None:
src_rasters = {os.path.basename(f) for f in glob.glob(checkfile_root+'*') if endswith_one_of_coll(f, src_suffixes)}
src_rasters_to_check = src_rasters
else:
src_rasters_to_check = True
if src_rasters is not None:
check_special_missing_subgroups = [None]
if args.get(ARGSTR_CHECK_SPECIAL) is not None and args.get(ARGSTR_CHECK_SPECIAL) in ARGCHOSET_CHECK_SPECIAL_SUBGROUP_DICT:
check_special_missing_subgroups = check_special_missing_subgroups + ARGCHOSET_CHECK_SPECIAL_SUBGROUP_DICT[args.get(ARGSTR_CHECK_SPECIAL)]
if type(srcfile_count) is list and len(srcfile_count) == 1:
srcfile_count[0] = len(src_rasters)
for check_special_option in check_special_missing_subgroups:
if check_special_option is None:
cssgroup_ffileroot_srcfname_dict = {checkfile_root: src_rasters}
src_suffixes_subgroup = src_suffixes
else:
cssgroup_ffileroot_srcfname_dict = dict()
for check_special_set_argstr, check_special_set_value in ARGCHOSET_CHECK_SPECIAL_SETTING_DICT[check_special_option]:
if check_special_set_argstr == ARGSTR_SRC_SUFFIX:
src_suffixes = [s.strip() for s in check_special_set_value.split('/')]
elif check_special_set_argstr == ARGSTR_CHECKFILE_ROOT_REGEX:
subgroup_root_regex = check_special_set_value
for srcfname in src_rasters:
match = re.match(subgroup_root_regex, srcfname)
if match is None:
eprint("No regex match for check special subgroup {}='{}' setting {}='{}' with filename: {}".format(
ARGSTR_CHECK_SPECIAL, check_special_option, ARGSTR_CHECKFILE_ROOT_REGEX, subgroup_root_regex.pattern, srcfname
))
else:
cf_root_name = match.group(1)
cf_root_full = os.path.join(checkfile_dir, cf_root_name)
if cf_root_full not in cssgroup_ffileroot_srcfname_dict:
cssgroup_ffileroot_srcfname_dict[cf_root_full] = set()
cssgroup_ffileroot_srcfname_dict[cf_root_full].add(srcfname)
else:
eprint("No option to handle check special subgroup {}={} setting {}={}, exiting".format(
ARGSTR_CHECK_SPECIAL, check_special_option, check_special_set_argstr, check_special_set_value
))
sys.exit(1)
for checkfile_root_subgroup, src_rasters_subgroup in cssgroup_ffileroot_srcfname_dict.items():
# if ( (len(src_rasters_subgroup) == 1 and src_rasters_subgroup.pop().endswith('meta.txt'))
# and (check_special_option is not None and check_special_option == ARGCHO_CHECK_SPECIAL_SCENEPAIRS)):
# warnings.showwarning = script_utils.showwarning_stdout
# warnings.warn("Stray metadata file detected in check special 'scene' subgroup."
# " Stray metadata files are ignored for the purpose of flagging"
# " higher-level check special groups as incomplete due to missing suffixes.")
# warnings.showwarning = script_utils.showwarning_stderr
# continue
missing_suffixes = [s for s in src_suffixes_subgroup if not ends_one_of_coll(s, src_rasters_subgroup)]