-
Notifications
You must be signed in to change notification settings - Fork 260
/
stack.py
1557 lines (1324 loc) · 61.5 KB
/
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
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
"""Classes for HDF5/MintPy file operations."""
############################################################
# Program is part of MintPy #
# Copyright (c) 2013, Zhang Yunjun, Heresh Fattahi #
# Author: Zhang Yunjun, Heresh Fattahi, 2018 #
############################################################
# Recommend import:
# from mintpy.objects import timeseries, ifgramStack, geometry
import datetime as dt
import itertools
import os
import time
import h5py
import numpy as np
from scipy import ndimage
from mintpy.utils import ptime
##------------------ Global Variables ---------------------##
DATA_TYPE_DICT = {
'bool': np.bool_, 'byte': np.bool_, 'flag': np.bool_,
'int': np.int16, 'int16': np.int16, 'short': np.int16, 'int32': np.int32,
'int64': np.int64, 'long': np.int64,
'float': np.float32, 'float32': np.float32,
'float_': np.float64, 'float64': np.float64,
'complex': np.complex64, 'complex64': np.complex64, 'cpx_float32': np.complex64,
'cfloat': np.complex64, 'cfloat32': np.complex64,
'complex128': np.complex128, 'complex_': np.complex128, 'cpx_float64': np.complex128,
}
TIMESERIES_KEY_NAMES = ['timeseries', 'HDFEOS', 'giantTimeseries']
TIMESERIES_DSET_NAMES = [
'timeseries',
'raw',
'troposphericDelay',
'topographicResidual',
'ramp',
'displacement',
]
GEOMETRY_DSET_NAMES = [
# coordinates
'height',
'latitude',
'longitude',
'rangeCoord',
'azimuthCoord',
# others
'incidenceAngle',
'azimuthAngle',
'slantRangeDistance',
'shadowMask',
'waterMask',
'commonMask',
'bperp',
]
IFGRAM_DSET_NAMES = [
# interferogram
'unwrapPhase',
'unwrapPhase_bridging_phaseClosure',
'unwrapPhase_bridging',
'unwrapPhase_phaseClosure',
'coherence',
'connectComponent',
'wrapPhase',
'magnitude',
# offset
'azimuthOffset',
'azimuthOffsetStd',
'rangeOffset',
'rangeOffsetStd',
'offsetSNR',
'refPhase',
]
DSET_UNIT_DICT = {
# interferogram
'unwrapPhase' : 'radian',
'coherence' : '1',
'connectComponent' : '1',
'wrapPhase' : 'radian',
'magnitude' : '1',
# offset
'azimuthOffset' : 'pixel',
'azimuthOffsetStd' : 'pixel',
'rangeOffset' : 'pixel',
'rangeOffsetStd' : 'pixel',
'offsetSNR' : '1',
# geometry
'height' : 'm',
'latitude' : 'degree',
'longitude' : 'degree',
'rangeCoord' : '1',
'azimuthCoord' : '1',
'incidenceAngle' : 'degree',
'azimuthAngle' : 'degree',
'slantRangeDistance' : 'm',
'shadowMask' : '1',
'waterMask' : '1',
'commonMask' : '1',
'bperp' : 'm',
# time-series
'timeseries' : 'm',
'raw' : 'm',
'troposphericDelay' : 'm',
'topographicResidual' : 'm',
'ramp' : 'm',
'displacement' : 'm',
# others
'temporalCoherence' : '1',
'velocity' : 'm/year',
'acceleration' : 'm/year^2',
'mask' : '1',
# giant
'giantTimeseries' : 'mm',
'recons' : 'mm',
'rawts' : 'mm',
'sar_aps' : 'mm',
'igram_aps' : 'mm',
'figram' : 'mm',
'igram' : 'mm',
'cmask' : '1',
'ifgcnt' : '1',
# binary
'unw' : 'radian',
'int' : 'radian',
'flat' : 'radian',
'cor' : '1',
'dem' : 'm',
'hgt' : 'm',
'hgt_sim' : 'm',
'intensity' : '1',
}
################################ timeseries class begin ################################
class timeseries:
"""
Time-series object for displacement of a set of SAR images from the same platform and track.
It contains three datasets in root level: date, bperp and timeseries.
File structure: https://mintpy.readthedocs.io/en/latest/api/data_structure/#timeseries
"""
def __init__(self, file=None):
self.file = file
self.name = 'timeseries'
def close(self, print_msg=True):
try:
self.f.close()
if print_msg:
print(f'close timeseries file: {os.path.basename(self.file)}')
except:
pass
return None
def open(self, print_msg=True):
if print_msg:
print(f'open {self.name} file: {os.path.basename(self.file)}')
self.get_metadata()
self.get_size()
self.get_date_list()
self.numPixel = self.length * self.width
with h5py.File(self.file, 'r') as f:
try:
self.pbase = f['bperp'][:]
self.pbase -= self.pbase[self.refIndex]
except:
self.pbase = None
# time info
self.dateFormat = ptime.get_date_str_format(self.dateList[0])
self.times = np.array([dt.datetime.strptime(i, self.dateFormat) for i in self.dateList])
# add hh/mm/ss info to the datetime objects
if 'T' not in self.dateFormat or all(i.hour==0 and i.minute==0 for i in self.times):
if 'CENTER_LINE_UTC' in self.metadata.keys():
utc_sec = float(self.metadata['CENTER_LINE_UTC'])
self.times = np.array([i + dt.timedelta(seconds=utc_sec) for i in self.times])
self.tbase = np.array([(i.days + i.seconds / (24 * 60 * 60))
for i in (self.times - self.times[self.refIndex])],
dtype=np.float32)
# list of float for year, 2014.95
self.yearList = [i.year + (i.timetuple().tm_yday-1)/365.25 for i in self.times]
self.sliceList = [f'{self.name}-{i}' for i in self.dateList]
return None
def get_metadata(self):
with h5py.File(self.file, 'r') as f:
self.metadata = dict(f.attrs)
dates = f['date'][:]
for key, value in self.metadata.items():
try:
self.metadata[key] = value.decode('utf8')
except:
self.metadata[key] = value
# ref_date/index
dateList = [i.decode('utf8') for i in dates]
if 'REF_DATE' not in self.metadata.keys():
self.metadata['REF_DATE'] = dateList[0]
self.refIndex = dateList.index(self.metadata['REF_DATE'])
self.metadata['START_DATE'] = dateList[0]
self.metadata['END_DATE'] = dateList[-1]
return self.metadata
def get_size(self):
with h5py.File(self.file, 'r') as f:
self.numDate, self.length, self.width = f[self.name].shape[-3:]
return self.numDate, self.length, self.width
def get_date_list(self):
with h5py.File(self.file, 'r') as f:
self.dateList = [i.decode('utf8') for i in f['date'][:]]
return self.dateList
def read(self, datasetName=None, box=None, squeeze=True, print_msg=True):
"""Read dataset from timeseries file
Parameters: self : timeseries object
datasetName : (list of) string in YYYYMMDD format
box : tuple of 4 int, indicating x0,y0,x1,y1 of range
Returns: data : 2D or 3D dataset
Examples: from mintpy.objects import timeseries
tsobj = timeseries('timeseries_ERA5_demErr.h5')
data = tsobj.read(datasetName='20161020')
data = tsobj.read(datasetName='20161020', box=(100,300,500,800))
data = tsobj.read(datasetName=['20161020','20161026','20161101'])
data = tsobj.read(box=(100,300,500,800))
"""
if print_msg:
print(f'reading {self.name} data from file: {self.file} ...')
self.open(print_msg=False)
# convert input datasetName into list of dates
if not datasetName or datasetName == 'timeseries':
datasetName = []
elif isinstance(datasetName, str):
datasetName = [datasetName]
datasetName = [i.replace('timeseries', '').replace('-', '') for i in datasetName]
with h5py.File(self.file, 'r') as f:
ds = f[self.name]
if isinstance(ds, h5py.Group): # support for old mintpy files
ds = ds[self.name]
# Get dateFlag - mark in time/1st dimension
dateFlag = np.zeros((self.numDate), dtype=np.bool_)
if not datasetName:
dateFlag[:] = True
else:
for e in datasetName:
dateFlag[self.dateList.index(e)] = True
# Get Index in space/2_3 dimension
if box is None:
box = [0, 0, self.width, self.length]
xsize = box[2] - box[0]
ysize = box[3] - box[1]
# read
num_slice = np.sum(dateFlag)
inds = np.where(dateFlag)[0].tolist()
if num_slice / dateFlag.size < 0.05:
# single indexing if only a small fraction is read
data = np.zeros((num_slice, ysize, xsize), dtype=ds.dtype)
for i, ind in enumerate(inds):
data[i] = ds[ind,
box[1]:box[3],
box[0]:box[2]]
else:
data = ds[:,
box[1]:box[3],
box[0]:box[2]][dateFlag]
if squeeze and any(i == 1 for i in data.shape):
data = np.squeeze(data)
return data
def write2hdf5(self, data, outFile=None, dates=None, bperp=None, metadata=None, refFile=None, compression=None):
"""
Parameters: data : 3D array of float32
dates : 1D array/list of string in YYYYMMDD format
bperp : 1D array/list of float32 (optional)
metadata : dict
outFile : string
refFile : string
compression : string or None
Returns: outFile : string
Examples:
from mintpy.objects import timeseries
##Generate a new timeseries file
tsobj = timeseries('timeseries.h5')
timeseries.write(data, dates=dateList, bperp=bperp, metadata=atr)
##Generate a timeseries with same attributes and same date/bperp info
tsobj = timeseries('timeseries_demErr.h5')
timeseries.write(data, refFile='timeseries.h5')
"""
if not outFile:
outFile = self.file
if refFile:
refobj = timeseries(refFile)
refobj.open(print_msg=False)
if metadata is None:
metadata = refobj.metadata
if dates is None:
dates = refobj.dateList
if bperp is None:
bperp = refobj.pbase
# get ref file compression type if input compression is None
if compression is None:
with h5py.File(refFile, 'r') as rf:
compression = rf[TIMESERIES_DSET_NAMES[0]].compression
refobj.close(print_msg=False)
data = np.array(data, dtype=np.float32)
dates = np.array(dates, dtype=np.bytes_)
bperp = np.array(bperp, dtype=np.float32)
metadata = dict(metadata)
metadata['FILE_TYPE'] = self.name
# directory
outDir = os.path.dirname(os.path.abspath(outFile))
if not os.path.isdir(outDir):
os.makedirs(outDir)
print(f'create directory: {outDir}')
# 3D dataset - timeseries
print(f'create timeseries HDF5 file: {outFile} with w mode')
with h5py.File(outFile, 'w') as f:
print(('create dataset /timeseries of {t:<10} in size of {s} '
'with compression={c}').format(t=str(data.dtype),
s=data.shape,
c=compression))
f.create_dataset('timeseries',
data=data,
chunks=True,
compression=compression)
# 1D dataset - date / bperp
print(f'create dataset /dates of {str(dates.dtype):<10} in size of {dates.shape}')
f.create_dataset('date', data=dates)
if bperp.shape != ():
print(f'create dataset /bperp of {str(bperp.dtype):<10} in size of {bperp.shape}')
f.create_dataset('bperp', data=bperp)
# Attributes
for key, value in metadata.items():
f.attrs[key] = str(value)
print(f'finished writing to {outFile}')
return outFile
def timeseries_std(self, maskFile=None, outFile=None):
"""Calculate the standard deviation (STD) for acquisition of time-series,
output result to a text file.
"""
# Calculate STD
data = self.read()
if maskFile:
mask = singleDataset(maskFile).read()
print('read mask from file: '+maskFile)
data[:, mask == 0] = np.nan
self.std = np.nanstd(data, axis=(1, 2))
# Write text file
header = 'Standard Deviation in space for each acquisition of time-series\n'
header += f'Timeseries file: {self.file}\n'
header += f'Mask file: {maskFile}\n'
header += 'Date\t\tSTD (m)'
if not outFile:
outFile = os.path.join(os.path.dirname(os.path.abspath(self.file)),
f'std_{os.path.splitext(os.path.basename(self.file))[0]}.txt')
np.savetxt(outFile, np.hstack((np.array(self.dateList).reshape(-1, 1), self.std.reshape(-1, 1))),
fmt='%s', delimiter='\t', header=header)
print(f'save timeseries STD to text file: {outFile}')
return outFile
def timeseries_rms(self, maskFile=None, outFile=None):
"""Calculate the Root Mean Square for each acquisition of time-series
and output result to a text file.
"""
# Get date list
date_list = self.get_date_list()
num_date = len(date_list)
# Get mask
if maskFile and os.path.isfile(maskFile):
print('read mask from file: '+maskFile)
mask = singleDataset(maskFile).read()
# Calculate RMS one date at a time
self.rms = np.zeros(num_date) * np.nan
print(f'reading {self.name} data from file: {self.file} ...')
prog_bar = ptime.progressBar(maxValue=num_date)
for i in range(num_date):
data = self.read(datasetName=f'{date_list[i]}', print_msg=False)
if maskFile and os.path.isfile(maskFile):
data[mask == 0] = np.nan
self.rms[i] = np.sqrt(np.nanmean(np.square(data), axis=(0, 1)))
prog_bar.update(i+1, suffix=f'{i+1}/{num_date}')
prog_bar.close()
# Write text file
header = 'Root Mean Square in space for each acquisition of time-series\n'
header += f'Timeseries file: {self.file}\n'
header += f'Mask file: {maskFile}\n'
header += 'Date\t\tRMS (m)'
if not outFile:
outFile = os.path.join(os.path.dirname(os.path.abspath(self.file)),
f'rms_{os.path.splitext(os.path.basename(self.file))[0]}.txt')
np.savetxt(outFile, np.hstack((np.array(self.dateList).reshape(-1, 1), self.rms.reshape(-1, 1))),
fmt='%s', delimiter='\t', header=header)
print(f'save timeseries RMS to text file: {outFile}')
return outFile
def spatial_average(self, maskFile=None, box=None, reverseMask=False, threshold=None):
self.open(print_msg=False)
data = self.read(box=box)
if maskFile and os.path.isfile(maskFile):
print('read mask from file: '+maskFile)
mask = singleDataset(maskFile).read(box=box)
data[:, mask == int(reverseMask)] = np.nan
# calculate area ratio if threshold is specified
# percentage of pixels with value above the threshold
if threshold is not None:
data[data > threshold] = 1
data[data <= threshold] = 0
dmean = np.nanmean(data, axis=(1, 2))
return dmean, self.dateList
def temporal_average(self):
print(f'calculating the temporal average of timeseries file: {self.file}')
self.open(print_msg=False)
data = self.read(squeeze=False)
dmean = np.nanmean(data, axis=0)
return dmean
def temporal_derivative(self, out_file):
print(f'calculating the temporal derivative of timeseries file: {self.file}')
# read
print('reading timeseries data')
self.open(print_msg=False)
ts_data = self.read(print_msg=False)
# calculate
print('calculate the 1st derivative of timeseries data')
ts_data_1d = np.zeros(ts_data.shape, np.float32)
ts_data_1d[1:, :, :] = np.diff(ts_data, n=1, axis=0)
# write
if not out_file:
fbase = os.path.splitext(self.file)[0]
out_file = f'{fbase}_1stDiff.h5'
self.write2hdf5(ts_data_1d, outFile=out_file, refFile=self.file)
return out_file
def temporal_filter(self, time_win=1.0, filter_type='guassian', out_file=None):
"""Filter the time-series in time with a moving window.
Parameters: time_win - float, sigma of Gaussian distribution in time in months (30.4 days)
filter_type - str, filter type: gaussian, median
out_file - str, output file name
Returns: out_file - str, output file name
"""
# use integer type if possible for shorter default output file name
time_win = int(time_win) if float(time_win).is_integer() else time_win
# output file
if not out_file:
fbase = os.path.splitext(self.file)[0]
out_file = f'{fbase}_temp{filter_type.capitalize()}{time_win}.h5'
print(f'output file: {out_file}')
# read
self.open()
ts_data = self.read().reshape(self.numDate, -1)
print('-'*50)
ts_data_filt = np.zeros(ts_data.shape, np.float32)
if filter_type == 'gaussian':
print(f'temporal filtering via a Gaussian window of {time_win} months')
tbase = self.tbase.reshape(-1, 1) / 365.25 * 12 # months (30.4 days)
prog_bar = ptime.progressBar(maxValue=self.numDate)
for i in range(self.numDate):
# calc weight from Gaussian (normal) distribution in time
tbase_diff = tbase[i] - tbase
weight = np.exp(-0.5 * (tbase_diff**2) / (time_win**2))
weight /= np.sum(weight)
# smooth the current acquisition via Gaussian weighting
ts_data_filt[i, :] = np.sum(ts_data * weight, axis=0)
prog_bar.update(i+1, suffix=self.dateList[i])
prog_bar.close()
elif filter_type == 'median':
print(f'temporal filtering via scipy.ndimage.median_filter of {time_win} acquisitions')
ts_data_filt = ndimage.median_filter(
ts_data,
size=(time_win, 1),
mode='nearest',
)
else:
raise ValueError(f'un-supported temporal filter: {filter_type}!')
del ts_data
# prepare for writing: temporal referencing + reshape
ts_data_filt -= ts_data_filt[self.refIndex, :]
ts_data_filt = np.reshape(ts_data_filt, (self.numDate, self.length, self.width))
# write
self.write2hdf5(ts_data_filt, outFile=out_file, refFile=self.file)
return
def save2bl_list_file(self, out_file='bl_list.txt'):
"""Generate bl_list.txt file from timeseries h5 file."""
self.open(print_msg=False)
date6_list = [i[2:8] for i in self.dateList]
pbase_list = self.pbase.tolist()
print(f'write baseline list info to file: {out_file}')
with open(out_file, 'w') as f:
for d, pbase in zip(date6_list, pbase_list):
f.write(f'{d}\t{pbase}\n')
return out_file
################################ timeseries class end ##################################
################################# geometry class begin #################################
class geometry:
""" Geometry object.
File structure: https://mintpy.readthedocs.io/en/latest/api/data_structure/#geometry
"""
def __init__(self, file=None):
self.file = file
self.name = 'geometry'
def close(self, print_msg=True):
try:
self.f.close()
if print_msg:
print(f'close geometry file: {os.path.basename(self.file)}')
except:
pass
def open(self, print_msg=True):
if print_msg:
print(f'open {self.name} file: {os.path.basename(self.file)}')
self.get_metadata()
self.get_size()
self.numPixel = self.length * self.width
self.geocoded = False
if 'Y_FIRST' in self.metadata.keys():
self.geocoded = True
with h5py.File(self.file, 'r') as f:
self.datasetNames = [i for i in f.keys() if isinstance(f[i], h5py.Dataset)]
self.sliceList = list(self.datasetNames)
if 'bperp' in f.keys():
self.dateList = [i.decode('utf8') for i in f['date'][:]]
self.numDate = len(self.dateList)
# Update bperp datasetNames
try:
self.sliceList.remove('bperp')
except:
pass
self.sliceList += ['bperp-'+d for d in self.dateList]
else:
self.dateList = None
def get_size(self):
with h5py.File(self.file, 'r') as f:
dsName = [i for i in f.keys() if i in GEOMETRY_DSET_NAMES][0]
dsShape = f[dsName].shape
if len(dsShape) == 3:
self.length, self.width = dsShape[1:3]
else:
self.length, self.width = dsShape
return self.length, self.width
def get_metadata(self):
with h5py.File(self.file, 'r') as f:
self.metadata = dict(f.attrs)
for key, value in self.metadata.items():
try:
self.metadata[key] = value.decode('utf8')
except:
self.metadata[key] = value
return self.metadata
def read(self, datasetName=GEOMETRY_DSET_NAMES[0], box=None, print_msg=True):
"""Read 2D / 3D dataset with bounding box in space
Parameters: datasetName : (list of) string, to point to specific 2D dataset, e.g.:
height
incidenceAngle
bperp
...
bperp-20161020
bperp-20161026
bperp-...
box : tuple of 4 int, for (x0,y0,x1,y1)
print_msg : bool
Returns: data : 2D or 3D array
Example:
obj = geometry('./inputs/geometryRadar.h5')
obj.read(datasetName='height')
obj.read(datasetName='incidenceAngle')
obj.read(datasetName='bperp')
obj.read(datasetName='bperp-20161020')
obj.read(datasetName=['bperp-20161020',
'bperp-20161026'])
"""
self.open(print_msg=False)
if box is None:
box = (0, 0, self.width, self.length)
if datasetName is None:
datasetName = GEOMETRY_DSET_NAMES[0]
elif isinstance(datasetName, str):
datasetName = [datasetName]
with h5py.File(self.file, 'r') as f:
familyName = datasetName[0].split('-')[0]
ds = f[familyName]
if print_msg:
print(f'reading {familyName:<15} data from file: {self.file} ...')
if len(ds.shape) == 1:
data = ds[:]
elif len(ds.shape) == 2:
data = ds[box[1]:box[3], box[0]:box[2]]
else:
# get dateFlag - mark in time/1st dimension
dateFlag = np.zeros((ds.shape[0]), dtype=np.bool_)
datasetName = [i.replace(familyName, '').replace('-', '') for i in datasetName]
if any(not i for i in datasetName):
dateFlag[:] = True
else:
for e in datasetName:
dateFlag[self.dateList.index(e)] = True
# read
data = ds[:,
box[1]:box[3],
box[0]:box[2]][dateFlag]
if any(i == 1 for i in data.shape):
data = np.squeeze(data)
return data
################################# geometry class end ###################################
################################# ifgramStack class begin ##############################
class ifgramStack:
""" Interferograms Stack object.
File structure: https://mintpy.readthedocs.io/en/latest/api/data_structure/#ifgramstack
"""
def __init__(self, file=None):
self.file = file
self.name = 'ifgramStack'
def close(self, print_msg=True):
try:
self.f.close()
if print_msg:
print(f'close {self.name} file: {os.path.basename(self.file)}')
except:
pass
def open(self, print_msg=True):
"""
Time format/rules:
All datetime.datetime objects named with time
All string in YYYYMMDD named with date (following roipac)
"""
if print_msg:
print(f'open {self.name} file: {os.path.basename(self.file)}')
self.get_metadata()
self.get_size()
self.read_datetimes()
self.numPixel = self.length * self.width
# time info
self.date12List = [f'{i}_{j}' for i, j in zip(self.mDates, self.sDates)]
self.tbaseIfgram = np.array([i.days + i.seconds / (24 * 60 * 60)
for i in (self.sTimes - self.mTimes)],
dtype=np.float32)
with h5py.File(self.file, 'r') as f:
self.dropIfgram = f['dropIfgram'][:]
self.pbaseIfgram = f['bperp'][:]
# get existed datasetNames in the order of IFGRAM_DSET_NAMES
dsNames = [i for i in f.keys()
if (isinstance(f[i], h5py.Dataset)
and f[i].shape[-2:] == (self.length, self.width))]
self.datasetNames = [i for i in IFGRAM_DSET_NAMES if i in dsNames]
self.datasetNames += [i for i in dsNames if i not in IFGRAM_DSET_NAMES]
# Get sliceList for self.read()
self.sliceList = []
for dsName in self.datasetNames:
self.sliceList += [f'{dsName}-{i}' for i in self.date12List]
# Time in timeseries domain
self.dateList = self.get_date_list(dropIfgram=False)
self.numDate = len(self.dateList)
# Reference pixel
try:
self.refY = int(self.metadata['REF_Y'])
self.refX = int(self.metadata['REF_X'])
except:
self.refY = None
self.refX = None
try:
self.refLat = float(self.metadata['REF_LAT'])
self.refLon = float(self.metadata['REF_LON'])
except:
self.refLat = None
self.refLon = None
def get_metadata(self):
# read metadata from root level
with h5py.File(self.file, 'r') as f:
self.metadata = dict(f.attrs)
dates = f['date'][:].flatten()
# decode metadata
for key, value in self.metadata.items():
try:
self.metadata[key] = value.decode('utf8')
except:
self.metadata[key] = value
# START/END_DATE
dateList = sorted(i.decode('utf8') for i in dates)
self.metadata['START_DATE'] = dateList[0]
self.metadata['END_DATE'] = dateList[-1]
return self.metadata
def get_size(self, dropIfgram=False, datasetName=None):
with h5py.File(self.file, 'r') as f:
# get default datasetName
if datasetName is None:
datasetName = [i for i in ['unwrapPhase', 'rangeOffset', 'azimuthOffset'] if i in f.keys()][0]
# get 3D size
self.numIfgram, self.length, self.width = f[datasetName].shape
# update 1st dimension size
if dropIfgram:
self.numIfgram = np.sum(f['dropIfgram'][:])
return self.numIfgram, self.length, self.width
def read_datetimes(self):
"""Read date1/2 into array of datetime.datetime objects"""
with h5py.File(self.file, 'r') as f:
dates = f['date'][:]
# grab the date string format
self.dateFormat = ptime.get_date_str_format(dates[0, 0])
# convert date from str to datetime.datetime objects
self.mDates = np.array([i.decode('utf8') for i in dates[:, 0]])
self.sDates = np.array([i.decode('utf8') for i in dates[:, 1]])
self.mTimes = np.array([dt.datetime.strptime(i, self.dateFormat) for i in self.mDates])
self.sTimes = np.array([dt.datetime.strptime(i, self.dateFormat) for i in self.sDates])
def read(self, datasetName='unwrapPhase', box=None, print_msg=True, dropIfgram=False):
"""Read 3D dataset with bounding box in space
Parameters: datasetName : string, to point to specific 2D dataset, e.g.:
unwrapPhase
coherence
connectComponent
...
unwrapPhase-20161020_20161026
unwrapPhase-...
coherence-20161020_20161026
...
['unwrapPhase-20161020_20161026',
'unwrapPhase-20161020_20161101',
...]
box : tuple of 4 int, for (x0,y0,x1,y1)
print_msg : bool
Returns: data : 2D or 3D array
Example:
obj = ifgramStack('./inputs/ifgramStack.h5')
obj.read(datasetName='unwrapPhase')
obj.read(datasetName='coherence')
obj.read(datasetName='unwrapPhase-20161020_20161026')
obj.read(datasetName=['unwrapPhase-20161020_20161026',
'unwrapPhase-20161020_20161101'])
"""
self.get_size(dropIfgram=False)
date12List = self.get_date12_list(dropIfgram=False)
# convert input datasetName into list
if datasetName is None:
datasetName = ['unwrapPhase']
elif isinstance(datasetName, str):
datasetName = [datasetName]
with h5py.File(self.file, 'r') as f:
familyName = datasetName[0].split('-')[0]
ds = f[familyName]
if print_msg:
print(f'reading {familyName} data from file: {self.file} ...')
# get dateFlag - mark in time/1st dimension
dateFlag = np.zeros((self.numIfgram), dtype=np.bool_)
datasetName = [i.replace(familyName, '').replace('-', '') for i in datasetName]
if any(not i for i in datasetName):
if dropIfgram:
dateFlag = f['dropIfgram'][:]
else:
dateFlag[:] = True
else:
for e in datasetName:
dateFlag[date12List.index(e)] = True
# get index in space/2-3 dimension
if box is None:
box = (0, 0, self.width, self.length)
# read
data = ds[:,
box[1]:box[3],
box[0]:box[2]][dateFlag]
if any(i == 1 for i in data.shape):
data = np.squeeze(data)
return data
def spatial_average(self, datasetName='coherence', maskFile=None, box=None, useMedian=False,
reverseMask=False, threshold=None):
""" Calculate the spatial average."""
if datasetName is None:
datasetName = 'coherence'
if useMedian:
print(f'calculating spatial median of {datasetName} in file {self.file} ...')
else:
print(f'calculating spatial mean of {datasetName} in file {self.file} ...')
# read mask
if maskFile and os.path.isfile(maskFile):
print('read mask from file: '+maskFile)
mask = singleDataset(maskFile).read(box=box)
else:
maskFile = None
# calculation
with h5py.File(self.file, 'r') as f:
dset = f[datasetName]
numIfgram = dset.shape[0]
dmean = np.zeros((numIfgram), dtype=np.float32)
prog_bar = ptime.progressBar(maxValue=numIfgram)
for i in range(numIfgram):
prog_bar.update(i+1, suffix=f'{i+1}/{numIfgram}')
# read
data = dset[i, box[1]:box[3], box[0]:box[2]]
if maskFile:
data[mask == int(reverseMask)] = np.nan
# ignore ZERO value for coherence
if datasetName == 'coherence':
data[data == 0] = np.nan
# calculate area ratio if threshold is specified
# percentage of pixels with value above the threshold
if threshold is not None:
data[data > threshold] = 1
data[data <= threshold] = 0
if useMedian:
dmean[i] = np.nanmedian(data)
else:
dmean[i] = np.nanmean(data)
prog_bar.close()
return dmean, self.date12List
# Functions considering dropIfgram value
def get_date12_list(self, dropIfgram=True):
with h5py.File(self.file, 'r') as f:
dates = f['date'][:]
if dropIfgram:
dates = dates[f['dropIfgram'][:], :]
mDates = np.array([i.decode('utf8') for i in dates[:, 0]])
sDates = np.array([i.decode('utf8') for i in dates[:, 1]])
date12List = [f'{i}_{j}' for i, j in zip(mDates, sDates)]
return date12List
def get_drop_date12_list(self):
with h5py.File(self.file, 'r') as f:
dates = f['date'][:]
dates = dates[~f['dropIfgram'][:], :]
mDates = np.array([i.decode('utf8') for i in dates[:, 0]])
sDates = np.array([i.decode('utf8') for i in dates[:, 1]])
date12List = [f'{i}_{j}' for i, j in zip(mDates, sDates)]
return date12List
def get_date_list(self, dropIfgram=False):
with h5py.File(self.file, 'r') as f:
dates = f['date'][:]
if dropIfgram:
dates = dates[f['dropIfgram'][:], :]
mDates = [i.decode('utf8') for i in dates[:, 0]]
sDates = [i.decode('utf8') for i in dates[:, 1]]
dateList = sorted(list(set(mDates + sDates)))
return dateList
def get_reference_phase(self, unwDatasetName='unwrapPhase', skip_reference=False, dropIfgram=False):
"""Get reference value
Parameters: unwDatasetName : string, unwrapPhase, or unwrapPhase_unwCor
skip_reference : bool, skip reference value (for simulation only)
dropIfgram : bool, skip ifgrams marked as dropped or not
Returns: ref_phase : 1D np.array in size of (num_ifgram,) in float32
"""
self.open(print_msg=False)
if skip_reference:
ref_phase = np.zeros(self.get_size(dropIfgram=dropIfgram)[0], np.float32)
print('skip checking reference pixel info - This is for offset and testing ONLY.')
elif 'REF_Y' not in self.metadata.keys():
raise ValueError('No REF_X/Y found!\nrun reference_point.py to select reference pixel.')
else:
print(f'reference pixel in y/x: ({self.refY}, {self.refX}) from dataset: {unwDatasetName}')
ref_phase = self.read(datasetName=unwDatasetName,
box=(self.refX, self.refY, self.refX+1, self.refY+1),
dropIfgram=dropIfgram,
print_msg=False)
return ref_phase
def nonzero_mask(self, datasetName=None, print_msg=True, dropIfgram=True):
"""Return the common mask of pixels with non-zero value in dataset of all ifgrams.
Ignoring dropped ifgrams
"""
self.open(print_msg=False)
with h5py.File(self.file, 'r') as f:
if datasetName is None:
datasetName = [i for i in ['connectComponent', 'unwrapPhase']
if i in f.keys()][0]
print(f'calculate the common mask of pixels with non-zero {datasetName} value')
dset = f[datasetName]
mask = np.ones(dset.shape[1:3], dtype=np.bool_)
dropIfgramFlag = np.ones(dset.shape[0], dtype=np.bool_)
if dropIfgram:
dropIfgramFlag = self.dropIfgram
num2read = np.sum(dropIfgramFlag)
idx2read = np.where(dropIfgramFlag)[0]
# Loop to save memory usage
prog_bar = ptime.progressBar(maxValue=num2read)
for i in range(num2read):
prog_bar.update(i+1, suffix=f'{i+1}/{num2read}')
data = dset[idx2read[i], :, :]
mask[data == 0.] = 0
mask[np.isnan(data)] = 0
prog_bar.close()
return mask