forked from insarlab/MintPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readfile.py
2425 lines (2000 loc) · 84.9 KB
/
readfile.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
"""Utilities to read files."""
############################################################
# Program is part of MintPy #
# Copyright (c) 2013, Zhang Yunjun, Heresh Fattahi #
# Author: Zhang Yunjun, Heresh Fattahi, 2013 #
############################################################
# Recommend import:
# from mintpy.utils import readfile
import datetime as dt
import glob
import os
import re
import sys
import warnings
import xml.etree.ElementTree as ET
from typing import Union
import h5py
import numpy as np
from numpy.typing import DTypeLike
from mintpy.objects import (
DSET_UNIT_DICT,
HDFEOS,
geometry,
giantIfgramStack,
giantTimeseries,
ifgramStack,
sensor,
timeseries,
)
from mintpy.utils import ptime, utils0 as ut
SPEED_OF_LIGHT = 299792458 # meters per second
STD_METADATA_KEYS = {
# ROI_PAC/MintPy attributes
'ALOOKS' : ['azimuth_looks'],
'RLOOKS' : ['range_looks'],
'AZIMUTH_PIXEL_SIZE' : ['azimuthPixelSize', 'azimuth_pixel_spacing', 'az_pixel_spacing', 'azimuth_spacing'],
'RANGE_PIXEL_SIZE' : ['rangePixelSize', 'range_pixel_spacing', 'rg_pixel_spacing', 'range_spacing'],
'CENTER_LINE_UTC' : ['center_time'],
'DATA_TYPE' : ['dataType', 'data_type', 'image_format'],
'EARTH_RADIUS' : ['earthRadius', 'earth_radius_below_sensor', 'earth_radius'],
'HEADING' : ['HEADING_DEG', 'heading', 'centre_heading'],
'HEIGHT' : ['altitude', 'SC_height'],
'BANDS' : ['number_bands', 'bands'],
'INTERLEAVE' : ['scheme', 'interleave'],
'LENGTH' : ['length', 'FILE_LENGTH', 'lines', 'azimuth_lines', 'nlines', 'az_samp',
'interferogram_azimuth_lines', 'num_output_lines'],
'LAT_REF1' : ['first_near_lat'],
'LON_REF1' : ['first_near_long'],
'LAT_REF2' : ['first_far_lat'],
'LON_REF2' : ['first_far_long'],
'LAT_REF3' : ['last_near_lat'],
'LON_REF3' : ['last_near_long'],
'LAT_REF4' : ['last_far_lat'],
'LON_REF4' : ['last_far_long'],
'ORBIT_DIRECTION' : ['passDirection', 'pass'],
'NO_DATA_VALUE' : ['NoDataValue'],
'PLATFORM' : ['spacecraftName', 'sensor', 'mission'],
'POLARIZATION' : ['polarization'],
'PRF' : ['prf', 'pulse_repetition_frequency'],
'STARTING_RANGE' : ['startingRange', 'near_range_slc', 'near_range', 'slant_range_to_first_pixel'],
'WAVELENGTH' : ['wavelength', 'Wavelength', 'radarWavelength', 'radar_wavelength'],
'WIDTH' : ['width', 'Width', 'samples', 'range_samp', 'interferogram_width', 'num_samples_per_line'],
# from PySAR [MintPy<=1.1.1]
'REF_DATE' : ['ref_date'],
'REF_LAT' : ['ref_lat'],
'REF_LON' : ['ref_lon'],
'REF_X' : ['ref_x'],
'REF_Y' : ['ref_y'],
'SUBSET_XMIN' : ['subset_x0'],
'SUBSET_XMAX' : ['subset_x1'],
'SUBSET_YMIN' : ['subset_y0'],
'SUBSET_YMAX' : ['subset_y1'],
# from Gamma geo-coordinates - degree / meter
'X_FIRST' : ['corner_lon', 'corner_east'],
'Y_FIRST' : ['corner_lat', 'corner_north'],
'X_STEP' : ['post_lon', 'post_east'],
'Y_STEP' : ['post_lat', 'post_north'],
# HDF-EOS5 attributes
'beam_swath' : ['swathNumber'],
'first_frame' : ['firstFrameNumber'],
'last_frame' : ['lastFrameNumber'],
'relative_orbit' : ['trackNumber'],
}
## data type conventions [use numpy as reference]
# 1 - ENVI
# reference: https://subversion.renater.fr/efidir/trunk/efidir_soft/doc/Programming_C_EFIDIR/header_envi.pdf
DATA_TYPE_ENVI2NUMPY = {
'1' : 'uint8',
'2' : 'int16',
'3' : 'int32',
'4' : 'float32',
'5' : 'float64',
'6' : 'complex64',
'9' : 'complex128',
'12': 'uint16',
'13': 'uint32',
'14': 'int64',
'15': 'uint64',
}
DATA_TYPE_NUMPY2ENVI = {
'uint8' : '1',
'int16' : '2',
'int32' : '3',
'float32' : '4',
'float64' : '5',
'complex64' : '6',
'complex128': '9',
'uint16' : '12',
'uint32' : '13',
'int64' : '14',
'uint64' : '15',
}
# 2 - GDAL
# link: https://gdal.org/api/raster_c_api.html#_CPPv412GDALDataType
DATA_TYPE_GDAL2NUMPY = {
1 : 'uint8',
2 : 'uint16',
3 : 'int16',
4 : 'uint32',
5 : 'int32',
6 : 'float32',
7 : 'float64',
8 : 'cint16', # for translation purpose only, as numpy does not support complex int
9 : 'cint32', # for translation purpose only, as numpy does not support complex int
10: 'complex64',
11: 'complex128',
12: 'uint64',
13: 'int64',
14: 'int8', # GDAL >= 3.7
}
DATA_TYPE_NUMPY2GDAL = {
"uint8" : 1, # GDT_Byte
"uint16" : 2, # GDT_UInt16
"int16" : 3, # GDT_Int16
"uint32" : 4, # GDT_UInt32
"int32" : 5, # GDT_Int32
"float32" : 6, # GDT_Float32
"float64" : 7, # GDT_Float64
"cint16" : 8, # GDT_CInt16, for translation purpose only, as numpy does not support complex int
"cint32" : 9, # GDT_CInt32, for translation purpose only, as numpy does not support complex int
"complex64" : 10, # GDT_CFloat32
"complex128": 11, # GDT_CFloat64
"uint64" : 12, # GDT_UInt64 (GDAL >= 3.5)
"int64" : 13, # GDT_Int64 (GDAL >= 3.5)
"int8" : 14, # GDT_Int8 (GDAL >= 3.7)
}
# 3 - ISCE
DATA_TYPE_ISCE2NUMPY = {
'byte' : 'uint8',
'short' : 'int16',
'int' : 'int32',
'float' : 'float32',
'double': 'float64',
'cfloat': 'complex64',
}
DATA_TYPE_NUMPY2ISCE = {
'uint8' : 'BYTE',
'int16' : 'SHORT',
'int32' : 'INT',
'float32' : 'FLOAT',
'float64' : 'DOUBLE',
'complex64': 'CFLOAT',
}
# 4 - GAMMA
DATA_TYPE_GAMMA2NUMPY = {
'fcomplex' : 'float64',
}
# single file (data + attributes) supported by GDAL
# .cos file - TerraSAR-X complex SAR data (https://gdal.org/drivers/raster/cosar.html)
GDAL_FILE_EXTS = ['.tiff', '.tif', '.grd', '.cos']
ENVI_BAND_INTERLEAVE = {
'BAND' : 'BSQ',
'LINE' : 'BIL',
'PIXEL': 'BIP',
}
ENVI_BYTE_ORDER = {
'0': 'little-endian',
'1': 'big-endian',
}
SPECIAL_STR2NUM = {
'yes' : True,
'true' : True,
'no' : False,
'false' : False,
'none' : None,
'nan' : np.nan,
}
#########################################################################
def numpy_to_gdal_dtype(np_dtype: DTypeLike) -> int:
"""Convert NumPy dtype to GDAL dtype.
Modified from dolphin.utils.numpy_to_gdal_type().
Parameters: np_dtype - DTypeLike, NumPy dtype to convert.
Returns: gdal_code - int, GDAL type code corresponding to `np_dtype`.
"""
from osgeo import gdal_array, gdalconst
np_dtype = np.dtype(np_dtype)
# convert dtype using the GDAL function/attribute
if np.issubdtype(bool, np_dtype):
gdal_code = gdalconst.GDT_Byte
else:
gdal_code = gdal_array.NumericTypeCodeToGDALTypeCode(np_dtype)
# if provided dtype is not support GDAL, e.g. np.dtype('>i4')
if gdal_code is None:
raise TypeError(f"dtype {np_dtype} not supported by GDAL.")
return gdal_code
def gdal_to_numpy_dtype(gdal_dtype: Union[str, int]) -> np.dtype:
"""Convert GDAL dtype to NumPy dtype.
Modified from dolphin.utils.gdal_to_numpy_type().
Parameters: gdal_dtype - str/int, GDAL dtype to convert.
Returns: np_dtype - np.dtype, NumPy dtype
"""
from osgeo import gdal, gdal_array
if isinstance(gdal_dtype, str):
gdal_dtype = gdal.GetDataTypeByName(gdal_dtype)
np_dtype = np.dtype(gdal_array.GDALTypeCodeToNumericTypeCode(gdal_dtype))
return np_dtype
#########################################################################
## Slice-based data identification for data reading:
##
## slice : np.ndarray in 2D, with/without '-' in their names
## each slice is unique within a file
## dataset : np.ndarray in 2D or 3D, without '-' in their names
##
## one 2D dataset can be present as one slice
## e.g.: temporalCoherence
## velocity
## mask
## ...
## one 3D dataset can be present as multiple slices
## with '-' to connect dataset name and time info
## e.g.: unwrapPhase-20150115_20150127
## unwrapPhase-20150115_20150208
## ...
## timeseries-20150115
## timeseries-20150127
## ...
## one HDF5 file can be present as a combination of multiple 2D/3D datasets
## or as a list of slices
##
## ----------------------- Slice Nameing Examples -------------------------
## for version-1.x files:
## unwrapPhase-20150115_20150127
## unwrapPhase-20150115_20150208
## timeseries-20150115
## timeseries-20150127
## temporalCoherence
##
## for version-0.x files: (all in 2D dataset)
## /interferograms/diff_filt_100814-100918_4rlks.unw/diff_filt_100814-100918_4rlks.unw
## /coherence/diff_filt_100814-100918_4rlks.cor/diff_filt_100814-100918_4rlks.cor
## /timeseries/20100918
## /timeseries/20101103
## /velocity/velocity
##
## for HDF-EOS5 files:
## /HDFEOS/GRIDS/timeseries/observation/displacement-20150115
## /HDFEOS/GRIDS/timeseries/observation/displacement-20150127
## /HDFEOS/GRIDS/timeseries/quality/temporalCoherence
##
## for GIAnT v1.0 files:
## figram-20150115_20150127
## recons-20150115
## cmask
##
#########################################################################
#########################################################################
def read(fname, box=None, datasetName=None, print_msg=True, xstep=1, ystep=1, data_type=None,
no_data_values=None):
"""Read one dataset and its attributes from input file.
Parameters: fname - str, path of file to read
datasetName - str or list of str, slice names
box - 4-tuple of int area to read, defined in (x0, y0, x1, y1) in pixel coordinate
x/ystep - int, number of pixels to pick/multilook for each output pixel
data_type - numpy data type, e.g. np.float32, np.bool_, etc. Change the output data type
no_data_values - list of 2 numbers, change the no-data-value in the output
Returns: data - 2/3/4D matrix in numpy.array format, return None if failed
atr - dictionary, attributes of data, return None if failed
Examples:
from mintpy.utils import readfile
data, atr = readfile.read('velocity.h5')
data, atr = readfile.read('timeseries.h5')
data, atr = readfile.read('timeseries.h5', datasetName='timeseries-20161020')
data, atr = readfile.read('ifgramStack.h5', datasetName='unwrapPhase')
data, atr = readfile.read('ifgramStack.h5', datasetName='unwrapPhase-20161020_20161026')
data, atr = readfile.read('ifgramStack.h5', datasetName='coherence', box=(100,1100, 500, 2500))
data, atr = readfile.read('geometryRadar.h5', datasetName='height')
data, atr = readfile.read('geometryRadar.h5', datasetName='bperp')
data, atr = readfile.read('100120-110214.unw', box=(100,1100, 500, 2500))
"""
fname = os.fspath(fname) # Convert from possible pathlib.Path
# metadata
dsname4atr = None #used to determine UNIT
if isinstance(datasetName, list):
dsname4atr = datasetName[0].split('-')[0]
elif isinstance(datasetName, str):
dsname4atr = datasetName.split('-')[0]
atr = read_attribute(fname, datasetName=dsname4atr)
# box
length, width = int(atr['LENGTH']), int(atr['WIDTH'])
if not box:
box = (0, 0, width, length)
# read data
kwargs = dict(
datasetName=datasetName,
box=box,
xstep=xstep,
ystep=ystep,
)
fext = os.path.splitext(os.path.basename(fname))[1].lower()
if fext in ['.h5', '.he5']:
data = read_hdf5_file(fname, print_msg=print_msg, **kwargs)
else:
data, atr = read_binary_file(fname, **kwargs)
# customized output data type
if data_type is not None and data_type != data.dtype:
if print_msg:
print(f'convert numpy array from {data.dtype} to {data_type}')
data = np.array(data, dtype=data_type)
# convert no-data-value
if isinstance(no_data_values, list):
if print_msg:
print(f'convert no-data-value from {no_data_values[0]} to {no_data_values[1]}')
data[data == no_data_values[0]] = no_data_values[1]
return data, atr
#########################################################################
def read_hdf5_file(fname, datasetName=None, box=None, xstep=1, ystep=1, print_msg=True):
"""
Parameters: fname : str, name of HDF5 file to read
datasetName : str or list of str, dataset name in root level with/without date info
'timeseries'
'timeseries-20150215'
'unwrapPhase'
'unwrapPhase-20150215_20150227'
'HDFEOS/GRIDS/timeseries/observation/displacement'
'recons'
'recons-20150215'
['recons-20150215', 'recons-20150227', ...]
'20150215'
'cmask'
'igram-20150215_20150227'
...
box : 4-tuple of int area to read, defined in (x0, y0, x1, y1) in pixel coordinate
x/ystep : int, number of pixels to pick/multilook for each output pixel
Returns: data : 2/3/4D array
atr : dict, metadata
"""
# File Info: list of slice / dataset / dataset2d / dataset3d
slice_list = get_slice_list(fname)
ds_list = []
for i in [i.split('-')[0] for i in slice_list]:
if i not in ds_list:
ds_list.append(i)
ds_2d_list = [i for i in slice_list if '-' not in i]
ds_3d_list = [i for i in ds_list if i not in ds_2d_list]
# Input Argument: convert input datasetName into list of slice
if not datasetName:
datasetName = [ds_list[0]]
elif isinstance(datasetName, str):
datasetName = [datasetName]
# if datasetName is all date info, add dsFamily as prefix
# a) if all digit, e.g. YYYYMMDD
# b) if in isoformat(), YYYY-MM-DDTHH:MM, etc.
if all(x.isdigit() or x[:4].isdigit() for x in datasetName):
datasetName = [f'{ds_3d_list[0]}-{x}' for x in datasetName]
# Input Argument: decompose slice list into dsFamily and inputDateList
dsFamily = datasetName[0].split('-')[0]
inputDateList = [x.replace(dsFamily,'') for x in datasetName]
inputDateList = [x[1:] for x in inputDateList if x.startswith('-')]
# read hdf5
with h5py.File(fname, 'r') as f:
# get dataset object
dsNames = [i for i in [datasetName[0], dsFamily] if i in f.keys()]
# support for old mintpy-v0.x files
dsNamesOld = [i for i in slice_list if f'/{datasetName[0]}' in i]
if len(dsNames) > 0:
ds = f[dsNames[0]]
elif len(dsNamesOld) > 0:
ds = f[dsNamesOld[0]]
else:
raise ValueError(f'input dataset {datasetName} not found in file {fname}')
# output size for >=2D dataset if x/ystep > 1
xsize = int((box[2] - box[0]) / xstep)
ysize = int((box[3] - box[1]) / ystep)
# 2D dataset
if ds.ndim == 2:
# read data
data = ds[box[1]:box[3],
box[0]:box[2]]
# sampling / nearest interplation in y/xstep
if xstep * ystep > 1:
data = data[int(ystep/2)::ystep,
int(xstep/2)::xstep]
data = data[:ysize, :xsize]
# 3D dataset
elif ds.ndim == 3:
# define flag matrix for index in time domain
slice_flag = np.zeros((ds.shape[0]), dtype=np.bool_)
if not inputDateList or inputDateList == ['']:
slice_flag[:] = True
else:
date_list = [i.split('-', 1)[1] for i in
[j for j in slice_list if j.startswith(dsFamily)]]
for d in inputDateList:
slice_flag[date_list.index(d)] = True
# read data
num_slice = np.sum(slice_flag)
inds = np.where(slice_flag)[0].tolist()
if xstep * ystep == 1:
if num_slice / slice_flag.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]][slice_flag]
else:
# sampling / nearest interplation in y/xstep
# use for loop to save memory
data = np.zeros((num_slice, ysize, xsize), ds.dtype)
for i, ind in enumerate(inds):
# print out msg
if print_msg:
sys.stdout.write('\r' + f'reading 2D slices {i+1}/{num_slice}...')
sys.stdout.flush()
# read and index
d2 = ds[ind,
box[1]:box[3],
box[0]:box[2]]
d2 = d2[int(ystep/2)::ystep,
int(xstep/2)::xstep]
data[i, :, :] = d2[:ysize, :xsize]
if print_msg:
print('')
if any(i == 1 for i in data.shape):
data = np.squeeze(data)
# 4D dataset
elif ds.ndim == 4:
# custom flag for the time domain is ignore for now
# a.k.a. read the entire first 2 dimensions
num1, num2 = ds.shape[0], ds.shape[1]
shape = (num1, num2, ysize, xsize)
if print_msg:
ram_size = num1 * num2 * ysize * xsize * ds.dtype.itemsize / 1024**3
print(f'initiate a 4D matrix in size of {shape} in {ds.dtype} in the memory ({ram_size:.1f} GB) ...')
data = np.zeros(shape, ds.dtype) * np.nan
# loop over the 1st dimension [for more verbose print out msg]
for i in range(num1):
if print_msg:
sys.stdout.write('\r' + f'reading 3D cubes {i+1}/{num1}...')
sys.stdout.flush()
d3 = ds[i, :,
box[1]:box[3],
box[0]:box[2]]
# sampling / nearest interpolation in y/xstep
if xstep * ystep > 1:
d3 = d3[:,
int(ystep/2)::ystep,
int(xstep/2)::xstep]
data[i, :, :, :] = d3[:, :ysize, :xsize]
if print_msg:
print('')
if any(i == 1 for i in data.shape):
data = np.squeeze(data)
return data
def read_binary_file(fname, datasetName=None, box=None, xstep=1, ystep=1):
"""Read data from binary file, such as .unw, .cor, etc.
Parameters: fname : str, path/name of binary file
datasetName : str, dataset name for file with multiple bands of data
e.g.: incidenceAngle, azimuthAngle, rangeCoord, azimuthCoord, ...
box : 4-tuple of int area to read, defined in (x0, y0, x1, y1) in pixel coordinate
x/ystep : int, number of pixels to pick/multilook for each output pixel
Returns: data : 2D array in size of (length, width) in BYTE / int16 / float32 / complex64 / float64 etc.
atr : dict, metadata of binary file
"""
# Basic Info
fext = os.path.splitext(os.path.basename(fname))[1].lower()
# metadata
atr = read_attribute(fname, datasetName=datasetName)
processor = atr['PROCESSOR']
length = int(atr['LENGTH'])
width = int(atr['WIDTH'])
box = box if box else (0, 0, width, length)
# default data structure
data_type = atr.get('DATA_TYPE', 'float32').lower()
byte_order = atr.get('BYTE_ORDER', 'little-endian').lower()
num_band = int(atr.get('BANDS', '1'))
interleave = atr.get('INTERLEAVE', 'BIL').upper()
# default data to read
band = 1
if datasetName:
if datasetName.startswith(('mag', 'amp')):
cpx_band = 'magnitude'
elif datasetName in ['phase', 'angle']:
cpx_band = 'phase'
elif datasetName.lower() == 'real':
cpx_band = 'real'
elif datasetName.lower().startswith('imag'):
cpx_band = 'imag'
else:
cpx_band = 'complex'
else:
# use phase as default value, since it's the most common one.
cpx_band = 'phase'
# ISCE
if processor in ['isce']:
# convert default short name for data type from ISCE
if data_type in DATA_TYPE_ISCE2NUMPY.keys():
data_type = DATA_TYPE_ISCE2NUMPY[data_type]
ftype = atr['FILE_TYPE'].lower().replace('.', '')
if ftype in ['unw', 'cor', 'ion']:
band = min(2, num_band)
if datasetName and datasetName in ['band1','intensity','magnitude']:
band = 1
elif ftype in ['slc']:
if datasetName:
if datasetName in ['amplitude','magnitude','intensity']:
cpx_band = 'magnitude'
elif datasetName in ['band2','phase']:
cpx_band = 'phase'
else:
cpx_band = 'complex'
else:
cpx_band = 'complex'
elif ftype.startswith('los') and datasetName and datasetName.startswith(('band2','az','head')):
band = min(2, num_band)
elif ftype in ['incLocal']:
band = min(2, num_band)
if datasetName and 'local' not in datasetName.lower():
band = 1
elif datasetName:
if datasetName.lower() == 'band2':
band = 2
elif datasetName.lower() == 'band3':
band = 3
else:
# flexible band list
ds_list = get_slice_list(fname)
if datasetName in ds_list:
band = ds_list.index(datasetName) + 1
band = min(band, num_band)
# check file size
fsize = os.path.getsize(fname)
dsize = np.dtype(data_type).itemsize * length * width * num_band
if dsize != fsize:
warnings.warn(f'file size ({fsize}) does NOT match with metadata ({dsize})!')
# ROI_PAC
elif processor in ['roipac']:
# data structure - file specific based on file extension
if fext in ['.unw', '.cor', '.hgt', '.msk']:
num_band = 2
band = 2
elif fext in ['.int']:
data_type = 'complex64'
elif fext in ['.amp']:
data_type = 'complex64'
cpx_band = 'magnitude'
elif fext in ['.dem', '.wgs84']:
data_type = 'int16'
elif fext in ['.flg', '.byt']:
data_type = 'bool_'
elif fext in ['.trans']:
num_band = 2
if datasetName and datasetName.startswith(('az', 'azimuth')):
band = 2
# Gamma
elif processor == 'gamma':
# data structure - auto
byte_order = atr.get('BYTE_ORDER', 'big-endian')
# convert default short name for data type from GAMMA
if data_type in DATA_TYPE_GAMMA2NUMPY.keys():
data_type = DATA_TYPE_GAMMA2NUMPY[data_type]
if fext in ['.unw', '.cor', '.hgt_sim', '.dem', '.amp', '.ramp']:
pass
elif fext in ['.int']:
data_type = data_type if 'DATA_TYPE' in atr.keys() else 'complex64'
elif fext.endswith(('to_rdc', '2_rdc', '2rdc')):
data_type = data_type if 'DATA_TYPE' in atr.keys() else 'float32'
interleave = 'BIP'
num_band = 2
if datasetName and datasetName.startswith(('az', 'azimuth')):
band = 2
elif fext == '.slc':
data_type = data_type if 'DATA_TYPE' in atr.keys() else 'complex32'
cpx_band = 'magnitude'
elif fext in ['.mli']:
byte_order = 'little-endian'
# SNAP
# BEAM-DIMAP data format
# https://www.brockmann-consult.de/beam/doc/help/general/BeamDimapFormat.html
elif processor == 'snap':
# data structure - auto
interleave = atr.get('INTERLEAVE', 'BSQ').upper()
# byte order
byte_order = atr.get('BYTE_ORDER', 'big-endian')
if 'byte order' in atr.keys() and atr['byte order'] == '0':
byte_order = 'little-endian'
# GDAL / GMTSAR / ASF HyP3
elif processor in ['gdal', 'gmtsar', 'hyp3', 'cosicorr', 'uavsar']:
# try to recognize custom dataset names if specified and recognized.
if datasetName:
slice_list = get_slice_list(fname)
if datasetName in slice_list:
band = slice_list.index(datasetName) + 1
else:
print(f'Unknown InSAR processor: {processor}')
# reading
kwargs = dict(
box=box,
band=band,
cpx_band=cpx_band,
xstep=xstep,
ystep=ystep,
)
if processor in ['gdal', 'gmtsar', 'hyp3', 'cosicorr']:
data = read_gdal(fname, **kwargs)
else:
data = read_binary(
fname,
shape=(length, width),
data_type=data_type,
byte_order=byte_order,
num_band=num_band,
interleave=interleave,
**kwargs
)
if 'DATA_TYPE' not in atr:
atr['DATA_TYPE'] = data_type
return data, atr
#########################################################################
def get_slice_list(fname, no_complex=False):
"""Get list of 2D slice existed in file (for display).
Parameters: fname - str, path to the data file
no_complex - bool, convert complex into real/imag parts
Returns: slice_list - list(str), list of names for 2D matrices
"""
fbase, fext = _get_file_base_and_ext(fname)
atr = read_attribute(fname)
ftype = atr['FILE_TYPE']
global slice_list
# HDF5 Files
if fext in ['.h5', '.he5']:
with h5py.File(fname, 'r') as f:
d1_list = [i for i in f.keys() if isinstance(f[i], h5py.Dataset)]
if ftype == 'timeseries' and ftype in d1_list:
obj = timeseries(fname)
obj.open(print_msg=False)
slice_list = obj.sliceList
elif ftype in ['geometry'] and ftype not in d1_list:
obj = geometry(fname)
obj.open(print_msg=False)
slice_list = obj.sliceList
elif ftype in ['ifgramStack']:
obj = ifgramStack(fname)
obj.open(print_msg=False)
slice_list = obj.sliceList
elif ftype in ['HDFEOS']:
obj = HDFEOS(fname)
obj.open(print_msg=False)
slice_list = obj.sliceList
elif ftype in ['giantTimeseries']:
obj = giantTimeseries(fname)
obj.open(print_msg=False)
slice_list = obj.sliceList
elif ftype in ['giantIfgramStack']:
obj = giantIfgramStack(fname)
obj.open(print_msg=False)
slice_list = obj.sliceList
elif ftype == 'timeseries' and 'slc' in d1_list:
with h5py.File(fname, 'r') as f:
dates = f['date'][:]
slice_list = ['slc-{}'.format(i.decode('UTF-8')) for i in dates]
else:
## Find slice by walking through the file structure
length, width = int(atr['LENGTH']), int(atr['WIDTH'])
def get_hdf5_2d_dataset(name, obj):
global slice_list
if isinstance(obj, h5py.Dataset) and obj.shape[-2:] == (length, width):
if obj.ndim == 2:
slice_list.append(name)
elif obj.ndim == 3:
slice_list += [f'{name}-{i+1}' for i in range(obj.shape[0])]
else:
warnings.warn(f'file has un-defined {obj.ndim}D dataset: {name}')
# get slice_list
slice_list = []
with h5py.File(fname, 'r') as f:
f.visititems(get_hdf5_2d_dataset)
# special order for velocity / time func file
if ftype == 'velocity':
slice_list = _sort_dataset_list4velocity(slice_list)
# Binary Files
else:
num_band = int(atr.get('BANDS', '1'))
dtype = atr.get('DATA_TYPE', 'float32')
if fext in ['.trans'] or fext.endswith(('to_rdc', '2_rdc', '2rdc')):
# roipac / gamma lookup table
slice_list = ['rangeCoord', 'azimuthCoord']
elif fbase.startswith('los') and num_band == 2:
# isce los file
slice_list = ['incidenceAngle', 'azimuthAngle']
elif fext in ['.unw', '.ion']:
slice_list = ['magnitude', 'phase']
elif fext in ['.int', '.slc'] or (dtype.startswith('c') and num_band == 1):
if no_complex:
slice_list = ['magnitude', 'phase']
else:
slice_list = ['complex']
elif 'offset' in fbase and num_band == 2:
# ampcor offset file, e.g. offset.bip, dense_offsets.bil
slice_list = ['azimuthOffset', 'rangeOffset']
elif 'offset' in fbase and '_cov' in fbase and num_band == 3:
# ampcor offset covariance file, e.g. offset_cov.bip, dense_offsets_cov.bil
slice_list = ['azimuthOffsetVar', 'rangeOffsetVar', 'offsetCovar']
elif fext in ['.lkv']:
slice_list = ['east', 'north', 'up']
elif fext in ['.llh']:
slice_list = ['latitude', 'longitude', 'height']
else:
slice_list = [f'band{i+1}' for i in range(num_band)]
return slice_list
def get_dataset_list(fname, datasetName=None):
"""Get list of 2D and 3D dataset to facilitate systematic file reading.
Parameters: fname - str, path to the data file
datasetName - str, dataset of interest
Returns: ds_list - list(str), list of names for 2D/3D datasets
"""
if datasetName:
return [datasetName]
global ds_list
fext = os.path.splitext(fname)[1].lower()
if fext in ['.h5', '.he5']:
# get length/width
atr = read_attribute(fname)
length, width = int(atr['LENGTH']), int(atr['WIDTH'])
def get_hdf5_dataset(name, obj):
global ds_list
if isinstance(obj, h5py.Dataset) and obj.shape[-2:] == (length, width):
ds_list.append(name)
# get dataset list
ds_list = []
with h5py.File(fname, 'r') as f:
f.visititems(get_hdf5_dataset)
# special order for velocity / time func file
if atr['FILE_TYPE'] == 'velocity':
ds_list = _sort_dataset_list4velocity(ds_list)
else:
ds_list = get_slice_list(fname)
return ds_list
def _sort_dataset_list4velocity(ds_list_in):
"""Sort the dataset list for velocity file type.
1. time func datasets [required]: velocity
2. time func datasets [optional]: alphabetic order
3. time func STD datasets [optional]: velocityStd
4. time func STD datasets [optional]: alphabetic order
5. residue
Parameters: ds_list - list(str), list of names for 2D/3D datasets
Returns: ds_list - list(str), list of names for 2D/3D datasets
"""
ds_list1 = [x for x in ['velocity'] if x in ds_list_in]
ds_list3 = [x for x in ['velocityStd'] if x in ds_list_in]
ds_list5 = [x for x in ['intercept', 'interceptStd', 'residue'] if x in ds_list_in]
ds_list4 = sorted([x for x in ds_list_in if x.endswith('Std') and x not in ds_list1 + ds_list3 + ds_list5])
ds_list2 = sorted([x for x in ds_list_in if x not in ds_list1 + ds_list3 + ds_list4 + ds_list5])
ds_list = ds_list1 + ds_list2 + ds_list3 + ds_list4 + ds_list5
return ds_list
def get_hdf5_dataset_attrs(fname, key='UNIT'):
"""Get the top-level dataset attribute for the given HDF5 file.
Parameters: fname - str, path to the HDF5 file
Returns: attrs - dict, key/value of all top-level datasets
"""
fext = os.path.splitext(fname)[1]
if fext not in ['.h5', '.he5']:
return None
# default output: empty
attrs = {}
# grab attrs from input file for the given key
with h5py.File(fname) as f:
# get top-level dataset names
ds_names = [x for x in f.keys() if isinstance(f[x], h5py.Dataset)]
# extract given attribute to the output dict
for ds_name in ds_names:
if key in f[ds_name].attrs.keys():
attrs[ds_name] = f[ds_name].attrs[key]
return attrs
def get_hdf5_compression(fname):
"""Get the compression type of input HDF5 file"""
ext = os.path.splitext(fname)[1].lower()
if ext not in ['.h5','.he5']:
return None
compression = None
ds_name = get_dataset_list(fname)[0]
with h5py.File(fname, 'r') as f:
compression = f[ds_name].compression
return compression
def get_no_data_value(fname):
"""Grab the NO_DATA_VALUE of the input file.
Parameters: fname - str, path to the data file
Returns: val - number, no data value
"""
val = read_attribute(fname).get('NO_DATA_VALUE', None)
val = str(val).lower()
if ut.is_number(val):
val = float(val)
elif val in SPECIAL_STR2NUM.keys():
val = SPECIAL_STR2NUM[val]
else:
raise ValueError(f'Un-recognized no-data-value type: {val}')
return val
def _get_file_base_and_ext(fname):
"""Grab the meaningful file basename and extension.
Parameters: fname - str, path to the (meta)data file
Returns: fbase - str, file basename
fext - str, file extension in lower case
"""
fbase, fext = os.path.splitext(os.path.basename(fname))
fext = fext.lower()
# ignore certain meaningless file extensions
while fext in ['.geo', '.rdr', '.full', '.mli', '.wgs84', '.grd', '.bil', '.bip']:
fbase, fext = os.path.splitext(fbase)
# set fext to fbase if nothing left
fext = fext if fext else fbase
return fbase, fext
#########################################################################
def read_attribute(fname, datasetName=None, metafile_ext=None):
"""Read attributes of input file into a dictionary