-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprep_Planet_stack.py
917 lines (784 loc) · 36.5 KB
/
prep_Planet_stack.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
############################################################
# Program is part of MintPy #
# Copyright (c) 2013, Zhang Yunjun, Heresh Fattahi #
# modified by Bodo Bookhagen, Apr-July 2023 #
############################################################
import datetime as dt
import os, sys, glob, argparse
import numpy as np
from mintpy.utils import ptime, readfile, utils1 as ut, writefile
# from mintpy.utils.arg_utils import create_argument_parser
from mintpy.objects import geometry, ifgramStack, sensor
from mintpy.objects.stackDict import geometryDict, ifgramDict, ifgramStackDict
from mintpy import subset
from mintpy.objects import (
GEOMETRY_DSET_NAMES,
IFGRAM_DSET_NAMES,
geometry,
ifgramStack,
sensor,
)
EXAMPLE = """example:
prep_Planet_stack.py \
--dx_fn "disparity_maps/*-F_EW.vrt" \
--dy_fn "disparity_maps/*-F_NS.vrt" \
--dx_confidence_fn "confidence/*_confidence.tif" \
--dy_confidence_fn "confidence/*_confidence.tif" \
--mask_fn "confidence/*_mask.tif" \
--meta_file /raid/PS2_aoi3/PS2_aoi3_metadata.txt --pixel_size 3.0 \
--template_file /raid/PS2_aoi3/mintpy/PS2_aoi3_config.cfg \
--h5_stack_fn /raid/PS2_aoi3/mintpy/inputs/geo_offsetStack_aoi3.h5 \
--h5_dem_fn /raid/PS2_aoi3/mintpy/inputs/geo_DEM_aoi3.h5
"""
DESCRIPTION = """
Prepare PlanetScope stack for MintPy processing. Use metadata and read in offset and confidence results and generate h5 stackcalculations generates virtual files for further processing (e.g., loading into a mintpy container).
Aug-2023, Bodo Bookhagen (bodo.bookhagen@uni-potsdam.de) and Ariane Mueting (mueting@uni-potsdam.de)
"""
def cmdLineParser():
from argparse import RawTextHelpFormatter
parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EXAMPLE, formatter_class=RawTextHelpFormatter)
parser.add_argument('--dx_fn', help='List of dx files', required=True)
parser.add_argument('--dy_fn', help='List of dy files', required=True)
parser.add_argument('--dx_confidence_fn', help='List of dx confidence files', required=False)
parser.add_argument('--dy_confidence_fn', help='List of dy confidence files', required=False)
parser.add_argument('--mask_fn', help='List of mask files. Only pixels with 1 are used for the inversion.', required=False)
parser.add_argument('-m', '--meta_file', help='Metadata file (created with prep_Planet_metadats.py)', required=True)
parser.add_argument('-p', '--pixel_size', type=np.float32, default=3.0, help='Pixel Size in m', required=False)
parser.add_argument('--template_file', help='Template file containing directories and processing information for MintPy.', required=True)
parser.add_argument('--h5_stack_fn', help='Output H5 stack file.', required=True)
parser.add_argument('--h5_dem_fn', default='', help='Output H5 DEM file.', required=False)
return parser.parse_args()
IFG_DSET_NAME2TEMPLATE_KEY = {
'unwrapPhase' : 'mintpy.load.unwFile',
'coherence' : 'mintpy.load.corFile',
'connectComponent': 'mintpy.load.connCompFile',
'wrapPhase' : 'mintpy.load.intFile',
'magnitude' : 'mintpy.load.magFile',
}
OFF_DSET_NAME2TEMPLATE_KEY = {
'azimuthOffset' : 'mintpy.load.azOffFile',
'azimuthOffsetStd': 'mintpy.load.azOffStdFile',
'rangeOffset' : 'mintpy.load.rgOffFile',
'rangeOffsetStd' : 'mintpy.load.rgOffStdFile',
'offsetSNR' : 'mintpy.load.offSnrFile',
}
GEOM_DSET_NAME2TEMPLATE_KEY = {
'height' : 'mintpy.load.demFile',
'latitude' : 'mintpy.load.lookupYFile',
'longitude' : 'mintpy.load.lookupXFile',
'azimuthCoord' : 'mintpy.load.lookupYFile',
'rangeCoord' : 'mintpy.load.lookupXFile',
'incidenceAngle' : 'mintpy.load.incAngleFile',
'azimuthAngle' : 'mintpy.load.azAngleFile',
'shadowMask' : 'mintpy.load.shadowMaskFile',
'waterMask' : 'mintpy.load.waterMaskFile',
'bperp' : 'mintpy.load.bperpFile',
}
OBS_DSET_NAMES = ['height', 'rangeOffset', 'azimuthOffset']
#########################################################################
def add_cosicorr_metadata(fname, date12_dict, meta):
'''Read/extract attribute data from cosicorr metadata file and add to metadata dictionary
Parameters: fname - str, offset or SNR file name
date12_dict - dict, key for file name, value for date12 pairs
meta - dict, metadata dictionary
Returns: meta - dict, metadata dictionary
'''
# add general attributes
meta['PROCESSOR'] = 'cosicorr'
meta['P_BASELINE_TOP_HDR'] = 0.0 #placeholder
meta['P_BASELINE_BOTTOM_HDR'] = 0.0 #placeholder
meta['RANGE_PIXEL_SIZE'] = np.abs(meta['X_STEP'])
meta['AZIMUTH_PIXEL_SIZE'] = np.abs(meta['Y_STEP'])
meta['RLOOKS'] = 1
meta['ALOOKS'] = 1
# Time attributes
date1_str, date2_str = date12_dict[os.path.basename(fname)].split('-')
meta['DATE12'] = f'{date1_str}-{date2_str}'
date1 = dt.datetime.strptime(date1_str, '%Y%m%d')
date2 = dt.datetime.strptime(date2_str, '%Y%m%d')
date_avg = date1 + (date2 - date1) / 2
date_avg_seconds = (date_avg - date_avg.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
meta['CENTER_LINE_UTC'] = date_avg_seconds
# add LAT/LON_REF1/2/3/4
N = float(meta['Y_FIRST'])
W = float(meta['X_FIRST'])
S = N + float(meta['Y_STEP']) * int(meta['LENGTH'])
E = W + float(meta['X_STEP']) * int(meta['WIDTH'])
meta['LAT_REF1'] = str(S)
meta['LAT_REF2'] = str(S)
meta['LAT_REF3'] = str(N)
meta['LAT_REF4'] = str(N)
meta['LON_REF1'] = str(W)
meta['LON_REF2'] = str(E)
meta['LON_REF3'] = str(W)
meta['LON_REF4'] = str(E)
return(meta)
def prep_AMES(inps, pixel_size=3):
"""Prepare the AMES metadata."""
# open and read hyp3 metadata
date12_dict = {}
with open(inps.meta_file) as f:
for line in f:
name, date1, date2 = line.strip().split(' ')
date12_dict[name] = f'{date1}-{date2}'
# loop over each filename
inps.file = ut.get_file_list(inps.file, abspath=True)
for fname in inps.file:
# extra metadata
meta = readfile.read_gdal_vrt(fname)
meta = add_cosicorr_metadata(fname, date12_dict, meta)
if meta['RANGE_PIXEL_SIZE'] == 1:
meta['RANGE_PIXEL_SIZE'] = pixel_size
meta['AZIMUTH_PIXEL_SIZE'] = pixel_size
# write metadata into RSC file
rsc_file = fname+'.rsc'
writefile.write_roipac_rsc(meta, out_file=rsc_file)
return
def read_inps2dict(inps):
"""Read input Namespace object info into iDict.
It grab the following contents into iDict
1. inps & all template files
2. configurations: processor, autoPath, updateMode, compression, x/ystep
3. extra metadata: PLATFORM, PROJECT_NAME,
4. translate autoPath
Parameters: inps - namespace, input arguments from command line & template file
Returns: iDict - dict, input arguments from command line & template file
"""
# Read input info into iDict
iDict = vars(inps)
iDict['PLATFORM'] = 'Planet'
iDict['processor'] = 'cosicorr'
# Read template file
template = {}
for fname in inps.template_file:
temp = readfile.read_template(fname)
temp = ut.check_template_auto_value(temp)
template.update(temp)
for key, value in template.items():
iDict[key] = value
# group - load
prefix = 'mintpy.load.'
key_list = [i.split(prefix)[1] for i in template.keys() if i.startswith(prefix)]
for key in key_list:
value = template[prefix+key]
if key in ['processor', 'autoPath', 'updateMode', 'compression']:
iDict[key] = template[prefix+key]
elif value:
iDict[prefix+key] = template[prefix+key]
print('processor : {}'.format(iDict['processor']))
if iDict['compression'] is False:
iDict['compression'] = None
# group - multilook
prefix = 'mintpy.multilook.'
key_list = [i.split(prefix)[1] for i in template.keys() if i.startswith(prefix)]
for key in key_list:
value = template[prefix+key]
if key in ['xstep', 'ystep', 'method']:
iDict[key] = template[prefix+key]
iDict['xstep'] = int(iDict.get('xstep', 1))
iDict['ystep'] = int(iDict.get('ystep', 1))
iDict['method'] = str(iDict.get('method', 'nearest'))
# PROJECT_NAME --> PLATFORM
if not iDict['PROJECT_NAME']:
cfile = [i for i in list(inps.template_file) if os.path.basename(i) != 'smallbaselineApp.cfg']
iDict['PROJECT_NAME'] = sensor.project_name2sensor_name(cfile)[1]
msg = 'SAR platform/sensor : '
sensor_name = sensor.project_name2sensor_name(str(iDict['PROJECT_NAME']))[0]
if sensor_name:
msg += str(sensor_name)
iDict['PLATFORM'] = str(sensor_name)
else:
msg += 'unknown from project name "{}"'.format(iDict['PROJECT_NAME'])
print(msg)
# update file path with auto
if iDict.get('autoPath', False):
print('use auto path defined in mintpy.defaults.auto_path for options in auto')
iDict = auto_path.get_auto_path(processor=iDict['processor'],
work_dir=os.getcwd(),
template=iDict)
return iDict
def prepare_metadata(iDict):
"""Prepare metadata via prep_{processor}.py scripts."""
processor = iDict['processor']
script_name = f'prep_{processor}.py'
print('-'*50)
print(f'prepare metadata files for {processor} products')
if processor not in PROCESSOR_LIST:
msg = f'un-recognized InSAR processor: {processor}'
msg += f'\nsupported processors: {PROCESSOR_LIST}'
raise ValueError(msg)
# import prep_{processor}
# prep_module = importlib.import_module(f'mintpy.cli.prep_{processor}')
if processor in ['gamma', 'hyp3', 'roipac', 'snap', 'cosicorr']:
# run prep_module
for key in [i for i in iDict.keys()
if (i.startswith('mintpy.load.')
and i.endswith('File')
and i != 'mintpy.load.metaFile')]:
if len(glob.glob(str(iDict[key]))) > 0:
# print command line
iargs = [iDict[key]]
if processor == 'gamma' and iDict['PLATFORM']:
iargs += ['--sensor', iDict['PLATFORM'].lower()]
elif processor == 'cosicorr':
iargs += ['--metadata', iDict['mintpy.load.metaFile']]
# ut.print_command_line(script_name, iargs)
# run
# prep_module.main(iargs)
elif processor == 'isce':
from mintpy.utils import isce_utils, s1_utils
# --meta-file
meta_files = sorted(glob.glob(iDict['mintpy.load.metaFile']))
if len(meta_files) > 0:
meta_file = meta_files[0]
else:
warnings.warn('No input metadata file found: {}'.format(iDict['mintpy.load.metaFile']))
meta_file = 'auto'
# --baseline-dir / --geometry-dir
baseline_dir = iDict['mintpy.load.baselineDir']
geom_dir = os.path.dirname(iDict['mintpy.load.demFile'])
# --dset-dir / --file-pattern
obs_keys = [
'mintpy.load.unwFile',
'mintpy.load.ionUnwFile',
'mintpy.load.rgOffFile',
'mintpy.load.azOffFile',
]
obs_paths = [iDict[key] for key in obs_keys if iDict[key].lower() != 'auto']
obs_paths = [x for x in obs_paths if len(glob.glob(x)) > 0]
# --geom-files for the basenames only
geom_names = ['dem', 'lookupY', 'lookupX', 'incAngle', 'azAngle', 'shadowMask', 'waterMask']
geom_keys = [f'mintpy.load.{i}File' for i in geom_names]
geom_files = [os.path.basename(iDict[key]) for key in geom_keys
if iDict.get(key, 'auto') not in ['auto', 'None', 'no', None, False]]
# compose list of input arguments
iargs = ['-m', meta_file, '-g', geom_dir]
if baseline_dir:
iargs += ['-b', baseline_dir]
if len(obs_paths) > 0:
iargs += ['-f'] + obs_paths
if geom_files:
iargs += ['--geom-files'] + geom_files
# run module
ut.print_command_line(script_name, iargs)
try:
prep_module.main(iargs)
except:
warnings.warn('prep_isce.py failed. Assuming its result exists and continue...')
# [optional] for topsStack: SAFE_files.txt --> S1A/B_date.txt
if os.path.isfile(meta_file) and isce_utils.get_processor(meta_file) == 'topsStack':
safe_list_file = os.path.join(os.path.dirname(os.path.dirname(meta_file)), 'SAFE_files.txt')
if os.path.isfile(safe_list_file):
s1_utils.get_s1ab_date_list_file(
mintpy_dir=os.getcwd(),
safe_list_file=safe_list_file,
print_msg=True)
elif processor == 'aria':
## compose input arguments
# use the default template file if exists & input
default_temp_files = [fname for fname in iDict['template_file']
if fname.endswith('smallbaselineApp.cfg')]
if len(default_temp_files) > 0:
temp_file = default_temp_files[0]
else:
temp_file = iDict['template_file'][0]
iargs = ['--template', temp_file]
# file name/dir/path
ARG2OPT_DICT = {
'--stack-dir' : 'mintpy.load.unwFile',
'--unwrap-stack-name' : 'mintpy.load.unwFile',
'--coherence-stack-name': 'mintpy.load.corFile',
'--conn-comp-stack-name': 'mintpy.load.connCompFile',
'--dem' : 'mintpy.load.demFile',
'--incidence-angle' : 'mintpy.load.incAngleFile',
'--azimuth-angle' : 'mintpy.load.azAngleFile',
'--water-mask' : 'mintpy.load.waterMaskFile',
}
for arg_name, opt_name in ARG2OPT_DICT.items():
arg_value = iDict.get(opt_name, 'auto')
if arg_value.lower() not in ['auto', 'no', 'none']:
if arg_name.endswith('dir'):
iargs += [arg_name, os.path.dirname(arg_value)]
elif arg_name.endswith('name'):
iargs += [arg_name, os.path.basename(arg_value)]
else:
iargs += [arg_name, arg_value]
# configurations
if iDict['compression']:
iargs += ['--compression', iDict['compression']]
if iDict['updateMode']:
iargs += ['--update']
## run
ut.print_command_line(script_name, iargs)
try:
prep_module.main(iargs)
except:
warnings.warn('prep_aria.py failed. Assuming its result exists and continue...')
elif processor == 'gmtsar':
# use the custom template file if exists & input
custom_temp_files = [fname for fname in iDict['template_file']
if not fname.endswith('smallbaselineApp.cfg')]
if len(custom_temp_files) == 0:
raise FileExistsError('Custom template file NOT found and is required for GMTSAR!')
# run prep_*.py
iargs = [custom_temp_files[0]]
ut.print_command_line(script_name, iargs)
try:
prep_module.main(iargs)
except:
warnings.warn('prep_gmtsar.py failed. Assuming its result exists and continue...')
return
def get_extra_metadata(iDict):
"""Extra metadata with key names in MACRO_CASE to be written into stack file.
Parameters: iDict - dict, input arguments from command lines & template file
extraDict - dict, extra metadata from template file:
E.g. PROJECT_NAME, PLATFORM, ORBIT_DIRECTION, SUBSET_X/YMIN, etc.
"""
extraDict = {}
# all keys in MACRO_CASE
upper_keys = [i for i in iDict.keys() if i.isupper()]
for key in upper_keys:
value = iDict[key]
if key in ['PROJECT_NAME', 'PLATFORM']:
if value:
extraDict[key] = value
else:
extraDict[key] = value
return extraDict
def read_subset_box(iDict):
"""read the following items:
geocoded - bool, if the stack of observations geocoded or not
box - tuple of 4 int, pixel box for stackObj and geomRadarObj, for obs in geo & radar coordinates
box4geo - tuple of 4 int, pixel box for geomGeoObj, box4geo is the same as box, except for:
obs in radar coordinate with lookup table [for gamma and roipac], where box4geo is
the geo bounding box of the box above.
"""
# Read subset info from template
iDict['box'] = None
iDict['box4geo'] = None
pix_box, geo_box = subset.read_subset_template2box(iDict['template_file'][0])
# Grab required info to read input geo_box into pix_box
lookup_y_files = glob.glob(str(iDict['mintpy.load.lookupYFile']))
lookup_x_files = glob.glob(str(iDict['mintpy.load.lookupXFile']))
if len(lookup_y_files) > 0 and len(lookup_x_files) > 0:
lookup_file = [lookup_y_files[0], lookup_x_files[0]]
else:
lookup_file = None
# use DEM file attribute as reference, because
# 1) it is required AND
# 2) it is in the same coordinate type as observation files
dem_files = glob.glob(iDict['mintpy.load.demFile'])
if len(dem_files) > 0:
atr = readfile.read_attribute(dem_files[0])
else:
atr = dict()
geocoded = True if 'Y_FIRST' in atr.keys() else False
iDict['geocoded'] = geocoded
# Check conflict
if geo_box and not geocoded and lookup_file is None:
geo_box = None
print('WARNING: mintpy.subset.lalo is not supported'
' if 1) no lookup file AND'
' 2) radar/unkonwn coded dataset')
print('\tignore it and continue.')
if not geo_box and not pix_box:
# adjust for the size inconsistency problem in SNAP geocoded products
# ONLY IF there is no input subset
# Use the min bbox if files size are different
if iDict['processor'] == 'snap':
fnames = ut.get_file_list(iDict['mintpy.load.unwFile'])
pix_box = update_box4files_with_inconsistent_size(fnames)
if not pix_box:
return iDict
# geo_box --> pix_box
coord = ut.coordinate(atr, lookup_file=lookup_file)
if geo_box is not None:
pix_box = coord.bbox_geo2radar(geo_box)
pix_box = coord.check_box_within_data_coverage(pix_box)
print(f'input bounding box of interest in lalo: {geo_box}')
print(f'box to read for datasets in y/x: {pix_box}')
# Get box for geocoded lookup table (for gamma/roipac)
box4geo_lut = None
if lookup_file is not None:
atrLut = readfile.read_attribute(lookup_file[0])
if not geocoded and 'Y_FIRST' in atrLut.keys():
geo_box = coord.bbox_radar2geo(pix_box)
box4geo_lut = ut.coordinate(atrLut).bbox_geo2radar(geo_box)
print(f'box to read for geocoded lookup file in y/x: {box4geo_lut}')
iDict['box'] = pix_box
iDict['box4geo'] = box4geo_lut if box4geo_lut else pix_box
return iDict
def read_inps_dict2geometry_dict_object(iDict, dset_name2template_key):
"""Read input arguments into geometryDict object(s).
Parameters: iDict - dict, input arguments from command line & template file
Returns: geomGeoObj - geometryDict object in geo coordinates or None
geomRadarObj - geometryDict object in radar coordinates or None
"""
# eliminate lookup table dsName for input files in radar-coordinates
if iDict['processor'] in ['isce', 'doris']:
# for processors with lookup table in radar-coordinates, remove azimuth/rangeCoord
dset_name2template_key.pop('azimuthCoord')
dset_name2template_key.pop('rangeCoord')
elif iDict['processor'] in ['roipac', 'gamma']:
# for processors with lookup table in geo-coordinates, remove latitude/longitude
dset_name2template_key.pop('latitude')
dset_name2template_key.pop('longitude')
elif iDict['processor'] in ['aria', 'gmtsar', 'hyp3', 'snap', 'cosicorr']:
# for processors with geocoded products support only, do nothing for now.
# check again when adding products support in radar-coordiantes
pass
else:
print('Un-recognized InSAR processor: {}'.format(iDict['processor']))
# iDict --> dsPathDict
print('-'*50)
print('searching geometry files info')
print('input data files:')
max_digit = max(len(i) for i in list(dset_name2template_key.keys()))
dsPathDict = {}
for dsName in [i for i in GEOMETRY_DSET_NAMES if i in dset_name2template_key.keys()]:
key = dset_name2template_key[dsName]
if key in iDict.keys():
files = sorted(glob.glob(str(iDict[key])))
if len(files) > 0:
if dsName == 'bperp':
bperpDict = {}
for file in files:
date = ptime.yyyymmdd(os.path.basename(os.path.dirname(file)))
bperpDict[date] = file
dsPathDict[dsName] = bperpDict
print(f'{dsName:<{max_digit}}: {iDict[key]}')
print(f'number of bperp files: {len(list(bperpDict.keys()))}')
else:
dsPathDict[dsName] = files[0]
print(f'{dsName:<{max_digit}}: {files[0]}')
# Check required dataset
dsName0 = GEOMETRY_DSET_NAMES[0]
if dsName0 not in dsPathDict.keys():
print(f'WARNING: No reqired {dsName0} data files found!')
# extra metadata from observations
# e.g. EARTH_RADIUS, HEIGHT, etc.
obsMetaGeo = None
obsMetaRadar = None
for obsName in OBS_DSET_NAMES:
obsFiles = sorted(glob.glob(iDict[dset_name2template_key[obsName]]))
if len(obsFiles) > 0:
atr = readfile.read_attribute(obsFiles[0])
if 'Y_FIRST' in atr.keys():
obsMetaGeo = atr.copy()
else:
obsMetaRadar = atr.copy()
break
# dsPathDict --> dsGeoPathDict + dsRadarPathDict
dsNameList = list(dsPathDict.keys())
dsGeoPathDict = {}
dsRadarPathDict = {}
for dsName in dsNameList:
if dsName == 'bperp':
atr = readfile.read_attribute(next(iter(dsPathDict[dsName].values())))
else:
atr = readfile.read_attribute(dsPathDict[dsName])
if 'Y_FIRST' in atr.keys():
dsGeoPathDict[dsName] = dsPathDict[dsName]
else:
dsRadarPathDict[dsName] = dsPathDict[dsName]
geomGeoObj = None
geomRadarObj = None
if len(dsGeoPathDict) > 0:
geomGeoObj = geometryDict(
processor=iDict['processor'],
datasetDict=dsGeoPathDict,
extraMetadata=obsMetaGeo)
if len(dsRadarPathDict) > 0:
geomRadarObj = geometryDict(
processor=iDict['processor'],
datasetDict=dsRadarPathDict,
extraMetadata=obsMetaRadar)
return geomGeoObj, geomRadarObj
def run_or_skip(outFile, inObj, box, updateMode=True, xstep=1, ystep=1, geom_obj=None):
"""Check if re-writing is necessary.
Do not write HDF5 file if ALL the following meet:
1. HDF5 file exists and is readable,
2. HDF5 file constains all the datasets and in the same size
3. For ifgramStackDict, HDF5 file contains all date12.
Parameters: outFile - str, path to the output HDF5 file
inObj - ifgramStackDict or geometryDict, object to write
box - tuple of int, bounding box in (x0, y0, x1, y1)
updateMode - bool
x/ystep - int
geom_obj - geometryDict object or None, for ionosphere only
Returns: flag - str, run or skip
"""
flag = 'run'
# skip if there is no dict object to write
if not inObj:
flag = 'skip'
return flag
# run if not in update mode
if not updateMode:
return flag
if ut.run_or_skip(outFile, readable=True) == 'skip':
kwargs = dict(box=box, xstep=xstep, ystep=ystep)
if inObj.name == 'ifgramStack':
in_size = inObj.get_size(geom_obj=geom_obj, **kwargs)[1:]
in_dset_list = inObj.get_dataset_list()
in_date12_list = inObj.get_date12_list()
outObj = ifgramStack(outFile)
outObj.open(print_msg=False)
out_size = (outObj.length, outObj.width)
out_dset_list = outObj.datasetNames
out_date12_list = outObj.date12List
if (out_size[1:] == in_size[1:]
and set(in_dset_list).issubset(set(out_dset_list))
and set(in_date12_list).issubset(set(out_date12_list))):
print('All date12 exists in file {} with same size as required,'
' no need to re-load.'.format(os.path.basename(outFile)))
flag = 'skip'
elif inObj.name == 'geometry':
in_size = inObj.get_size(**kwargs)
in_dset_list = inObj.get_dataset_list()
outObj = geometry(outFile)
outObj.open(print_msg=False)
out_size = (outObj.length, outObj.width)
out_dset_list = outObj.datasetNames
if (out_size == in_size
and set(in_dset_list).issubset(set(out_dset_list))):
print('All datasets exists in file {} with same size as required,'
' no need to re-load.'.format(os.path.basename(outFile)))
flag = 'skip'
return flag
def read_inps_dict2ifgram_stack_dict_object(iDict, ds_name2template_key):
"""Read input arguments into ifgramStackDict object.
Parameters: iDict - dict, input arguments from command line & template file
ds_name2template_key - dict, to relate the HDF5 dataset name to the template key
Returns: stackObj - ifgramStackDict object or None
"""
if iDict['only_load_geometry']:
return None
if 'mintpy.load.unwFile' in ds_name2template_key.values():
obs_type = 'interferogram'
elif 'mintpy.load.ionUnwFile' in ds_name2template_key.values():
obs_type = 'ionosphere'
elif 'mintpy.load.azOffFile' in ds_name2template_key.values():
obs_type = 'offset'
# iDict --> dsPathDict
print('-'*50)
print(f'searching {obs_type} pairs info')
print('input data files:')
max_digit = max(len(i) for i in list(ds_name2template_key.keys()))
dsPathDict = {}
for dsName in [i for i in IFGRAM_DSET_NAMES if i in ds_name2template_key.keys()]:
key = ds_name2template_key[dsName]
if key in iDict.keys():
files = sorted(glob.glob(str(iDict[key])))
if len(files) > 0:
dsPathDict[dsName] = files
print(f'{dsName:<{max_digit}}: {iDict[key]}')
# Check 1: required dataset
dsName0s = [x for x in OBS_DSET_NAMES if x in ds_name2template_key.keys()]
dsName0 = [i for i in dsName0s if i in dsPathDict.keys()]
if len(dsName0) == 0:
print(f'WARNING: No data files found for the required dataset: {dsName0s}! Skip loading for {obs_type} stack.')
return None
else:
dsName0 = dsName0[0]
# Check 2: data dimension for unwrapPhase files
dsPathDict = skip_files_with_inconsistent_size(
dsPathDict=dsPathDict,
pix_box=iDict['box'],
dsName=dsName0)
# Check 3: number of files for all dataset types
# dsPathDict --> dsNumDict
dsNumDict = {}
for key in dsPathDict.keys():
num_file = len(dsPathDict[key])
dsNumDict[key] = num_file
print(f'number of {key:<{max_digit}}: {num_file}')
dsNumList = list(dsNumDict.values())
if any(i != dsNumList[0] for i in dsNumList):
msg = 'WARNING: NOT all types of dataset have the same number of files.'
msg += ' -> skip interferograms with missing files and continue.'
print(msg)
#raise Exception(msg)
# dsPathDict --> pairsDict --> stackObj
dsNameList = list(dsPathDict.keys())
#####################################
# A dictionary of data file paths for a list of pairs, e.g.:
# pairsDict = {
# ('date1', 'date2') : ifgramPathDict1,
# ('date1', 'date3') : ifgramPathDict2,
# ...,
# }
pairsDict = {}
for i, dsPath0 in enumerate(dsPathDict[dsName0]):
# date string used in the file/dir path
# YYYYDDD for gmtsar [modern Julian date]
# YYYYMMDDTHHMM for uavsar
# YYYYMMDD for all the others
date6s = readfile.read_attribute(dsPath0)['DATE12'].replace('_','-').split('-')
if iDict['processor'] == 'gmtsar':
date12MJD = os.path.basename(os.path.dirname(dsPath0))
else:
date12MJD = None
#####################################
# A dictionary of data file paths for a given pair.
# One pair may have several types of dataset, e.g.:
# ifgramPathDict1 = {
# 'unwrapPhase': /dirPathToFile/filt_fine.unw,
# 'coherence' : /dirPathToFile/filt_fine.cor,
# ...
# }
# All path of data file must contain the reference and secondary date, in file/dir name.
ifgramPathDict = {}
for dsName in dsNameList:
# search the matching data file for the given date12
# 1st guess: file in the same order as the one for dsName0
dsPath1 = dsPathDict[dsName][i]
if (all(d6 in dsPath1 for d6 in date6s)
or (date12MJD and date12MJD in dsPath1)):
ifgramPathDict[dsName] = dsPath1
else:
# 2nd guess: any file in the list
dsPath2 = [p for p in dsPathDict[dsName]
if (all(d6 in p for d6 in date6s)
or (date12MJD and date12MJD in dsPath1))]
if len(dsPath2) > 0:
ifgramPathDict[dsName] = dsPath2[0]
else:
print(f'WARNING: {dsName:>18} file missing for pair {date6s}')
# initiate ifgramDict object
ifgramObj = ifgramDict(datasetDict=ifgramPathDict)
# update pairsDict object
date8s = ptime.yyyymmdd(date6s)
pairsDict[tuple(date8s)] = ifgramObj
if len(pairsDict) > 0:
stackObj = ifgramStackDict(pairsDict=pairsDict, dsName0=dsName0)
else:
stackObj = None
return stackObj
def skip_files_with_inconsistent_size(dsPathDict, pix_box=None, dsName='unwrapPhase'):
"""Skip files by removing the file path from the input dsPathDict."""
atr_list = [readfile.read_attribute(fname) for fname in dsPathDict[dsName]]
length_list = [int(atr['LENGTH']) for atr in atr_list]
width_list = [int(atr['WIDTH']) for atr in atr_list]
# Check size requirements
drop_inconsistent_files = False
if any(len(set(size_list)) > 1 for size_list in [length_list, width_list]):
if pix_box is None:
drop_inconsistent_files = True
else:
# if input subset is within the min file sizes: do NOT drop
max_box_width, max_box_length = pix_box[2:4]
if max_box_length > min(length_list) or max_box_width > min(width_list):
drop_inconsistent_files = True
# update dsPathDict
if drop_inconsistent_files:
common_length = ut.most_common(length_list)
common_width = ut.most_common(width_list)
# print out warning message
msg = '\n'+'*'*80
msg += '\nWARNING: NOT all input unwrapped interferograms have the same row/column number!'
msg += f'\nThe most common size is: ({common_length}, {common_width})'
msg += '\n'+'-'*30
msg += '\nThe following dates have different size:'
dsNames = list(dsPathDict.keys())
date12_list = [atr['DATE12'] for atr in atr_list]
num_drop = 0
for date12, length, width in zip(date12_list, length_list, width_list):
if length != common_length or width != common_width:
dates = ptime.yyyymmdd(date12.split('-'))
# update file list for all datasets
for dsName in dsNames:
fnames = [i for i in dsPathDict[dsName]
if all(d[2:8] in i for d in dates)]
if len(fnames) > 0:
dsPathDict[dsName].remove(fnames[0])
msg += f'\n\t{date12}\t({length}, {width})'
num_drop += 1
msg += '\n'+'-'*30
msg += f'\nSkip loading the above interferograms ({num_drop}).'
msg += f'\nContinue to load the rest interferograms ({len(date12_list) - num_drop}).'
msg += '\n'+'*'*80+'\n'
print(msg)
return dsPathDict
#### Main Code
if __name__ == '__main__':
inps = cmdLineParser()
# Only for Testing and Debugging
# subparsers=None
# synopsis = 'Prepare L8 correlation metadata files.'
# epilog = "TEST"
# name = "cosicorr"
# parser = create_argument_parser(
# name, synopsis=synopsis, description=synopsis, epilog=epilog, subparsers=subparsers)
# inps = parser.parse_args()
# inps.pixel_size = 3.0
# inps.dx_fn="disparity_maps/*-F_EW.vrt"
# inps.dy_fn="disparity_maps/*-F_NS.vrt"
# inps.dx_confidence_fn= "confidence/*_confidence.tif"
# inps.dy_confidence_fn = "confidence/*_confidence.tif"
# inps.meta_file = "/raid/PS2_aoi3/PS2_aoi3_metadata.txt"
# inps.template_file = ['/raid/PS2_aoi3/mintpy/PS2_aoi3_config.cfg']
# inps.h5_stack_fn = 'mintpy/inputs/geo_offsetStack_aoi3.h5'
inps.PROJECT_NAME = 'AMES'
inps.processor='cosicorr'
inps.updateMode='auto'
inps.template_file = [inps.template_file] #make sure that this is a list # Ariane: It seems like we dont really need the template file
# inps.file = ["disparity_maps/*-F_EW.vrt", "disparity_maps/*-F_NS.vrt", "confidence/*_confidence.tif", "confidence/*_confidence.tif"]
inps.file = [inps.dy_fn, inps.dx_fn, inps.dy_confidence_fn, inps.dx_confidence_fn, inps.mask_fn]
inps.file = ut.get_file_list(inps.file, abspath=True)
inps.compression = 'lzf'
prep_AMES(inps, pixel_size=inps.pixel_size)
iDict = read_inps2dict(inps)
PROCESSOR_LIST = ['isce', 'aria', 'hyp3', 'gmtsar', 'snap', 'gamma', 'roipac', 'cosicorr', 'gdal']
## 1. prepare metadata
prepare_metadata(iDict)
extraDict = get_extra_metadata(iDict)
print('-'*50)
print('updateMode : {}'.format(iDict['updateMode']))
print('compression: {}'.format(iDict['compression']))
print('multilook x/ystep: {}/{}'.format(iDict['xstep'], iDict['ystep']))
print('multilook method : {}'.format(iDict['method']))
kwargs = dict(updateMode=iDict['updateMode'], xstep=iDict['xstep'], ystep=iDict['ystep'])
# read subset info [need the metadata from above]
iDict = read_subset_box(iDict)
# Can add DEM loading here - if DEM with exact same coordinates exists - needs to be geometric dataset
# # geometry in geo / radar coordinates
if len(inps.h5_dem_fn) > 0:
#store DEM to HDF file
geom_dset_name2template_key = {
**GEOM_DSET_NAME2TEMPLATE_KEY
}
geom_geo_obj, geom_radar_obj = read_inps_dict2geometry_dict_object(iDict, geom_dset_name2template_key)
geom_geo_file = os.path.abspath(inps.h5_dem_fn)
if run_or_skip(geom_geo_file, geom_geo_obj, iDict['box4geo'], **kwargs) == 'run':
geom_geo_obj.write2hdf5(
outputFile=geom_geo_file,
access_mode='w',
box=iDict['box4geo'],
xstep=iDict['xstep'],
ystep=iDict['ystep'],
compression='lzf')
stack_ds_name2tmpl_key_list = [
OFF_DSET_NAME2TEMPLATE_KEY
]
iDict['only_load_geometry'] = None
iDict['geocoded'] = True
stack_files = [inps.h5_stack_fn]
stack_files = [os.path.abspath(x) for x in stack_files]
for ds_name2tmpl_opt, stack_file in zip(stack_ds_name2tmpl_key_list, stack_files):
# initiate dict objects
stack_obj = read_inps_dict2ifgram_stack_dict_object(iDict, ds_name2tmpl_opt)
# use geom_obj as size reference while loading ionosphere
geom_obj = None
# write dict objects to HDF5 files
if run_or_skip(stack_file, stack_obj, iDict['box'], geom_obj=geom_obj, **kwargs) == 'run':
stack_obj.write2hdf5(
outputFile=stack_file,
access_mode='w',
box=iDict['box'],
xstep=iDict['xstep'],
ystep=iDict['ystep'],
mli_method=iDict['method'],
compression=iDict['compression'],
extra_metadata=extraDict,
geom_obj=geom_obj)