-
Notifications
You must be signed in to change notification settings - Fork 267
/
Copy pathview.py
1723 lines (1464 loc) · 64.5 KB
/
view.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
############################################################
# Program is part of MintPy #
# Copyright (c) 2013, Zhang Yunjun, Heresh Fattahi #
# Author: Zhang Yunjun, Heresh Fattahi, 2013 #
############################################################
# Recommend import:
# from mintpy.view import prep_slice, plot_slice, viewer
import datetime as dt
import os
import re
import warnings # suppress UserWarning from matplotlib
warnings.filterwarnings("ignore", category=UserWarning, module="matplotlib")
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mintpy import subset, version
from mintpy.multilook import multilook_data
from mintpy.objects import (
TIMESERIES_KEY_NAMES,
giantIfgramStack,
gnss,
ifgramStack,
)
from mintpy.utils import plot as pp, ptime, readfile, utils as ut
##################################################################################################
def run_or_skip(inps):
vprint('update mode: ON')
flag = 'skip'
# run if showing figures
if inps.disp_fig:
flag = 'run'
return flag
# get existed output file names
outfiles = []
for fname in inps.outfile:
fnames = [fname, os.path.join(os.path.dirname(fname), 'pic', os.path.basename(fname))]
fnames = [i for i in fnames if os.path.isfile(i)]
if len(fnames) > 0:
outfiles.append(fnames[0])
else:
flag = 'run'
if flag == 'skip':
ti = os.path.getmtime(inps.file)
to = min(os.path.getmtime(i) for i in outfiles)
if ti > to:
flag = 'run'
else:
vprint(f'{outfiles} exist and are newer than input file: {inps.file} --> skip.')
return flag
##################################################################################################
def update_inps_with_file_metadata(inps, metadata):
# Subset
# Convert subset input into bounding box in radar / geo coordinate
# geo_box = None if atr is not geocoded.
coord = ut.coordinate(metadata)
inps.pix_box, inps.geo_box = subset.subset_input_dict2box(vars(inps), metadata)
inps.pix_box = coord.check_box_within_data_coverage(inps.pix_box)
inps.geo_box = coord.box_pixel2geo(inps.pix_box)
# Out message
inps.data_box = (0, 0, inps.width, inps.length)
vprint('data coverage in y/x: '+str(inps.data_box))
vprint('subset coverage in y/x: '+str(inps.pix_box))
vprint('data coverage in lat/lon: '+str(coord.box_pixel2geo(inps.data_box)))
vprint('subset coverage in lat/lon: '+str(inps.geo_box))
vprint('------------------------------------------------------------------------')
# DEM contour display
if max(inps.pix_box[3] - inps.pix_box[1],
inps.pix_box[2] - inps.pix_box[0]) > 2e3:
inps.disp_dem_contour = False
if inps.dem_file:
vprint('area exceed 2000 pixels, turn off default DEM contour display')
# Multilook, if too many subplots in one figure for less memory and faster speed
if inps.multilook_num > 1:
inps.multilook = True
# Colormap
inps.colormap = pp.auto_colormap_name(
metadata,
inps.colormap,
datasetName=inps.dset[0],
print_msg=inps.print_msg,
)
# Reference Point
# Convert ref_lalo if existed, to ref_yx, and use ref_yx for the following
# ref_yx is referenced to input data coverage, not subseted area for display
if inps.ref_lalo:
vprint(f'input reference point in lat/lon: {inps.ref_lalo}')
if not inps.geo_box and not coord.lookup_file:
print('WARNING: --ref-lalo is NOT supported when 1) file is radar-coded AND 2) no lookup table file found')
print(' --> ignore the --ref-lalo input and continue.')
inps.ref_lalo = []
else:
inps.ref_yx = coord.geo2radar(inps.ref_lalo[0], inps.ref_lalo[1])[:2]
vprint(f'input reference point in y /x : {inps.ref_yx}')
# ref_lalo
if inps.ref_yx and inps.geo_box:
inps.ref_lalo = coord.radar2geo(inps.ref_yx[0], inps.ref_yx[1])[:2]
elif 'REF_LAT' in metadata.keys():
inps.ref_lalo = [float(metadata['REF_LAT']), float(metadata['REF_LON'])]
else:
inps.ref_lalo = None
# Points of interest
inps = pp.read_pts2inps(inps, coord)
# Unit and Wrap
inps.disp_unit, inps.wrap = pp.check_disp_unit_and_wrap(
metadata,
disp_unit=inps.disp_unit,
wrap=inps.wrap,
wrap_range=inps.wrap_range,
print_msg=inps.print_msg,
)
# Map Projection via cartopy
inps = check_map_projection(inps, metadata, print_msg=inps.print_msg)
# Min / Max - Display
if not inps.vlim:
if (any(i in inps.key.lower() for i in ['coherence', '.cor'])
or (inps.key == 'ifgramStack' and inps.dset[0].split('-')[0] in ['coherence'])
or inps.dset[0] == 'cmask'):
inps.vlim = [0.0, 1.0]
elif inps.key in ['.int'] or inps.wrap:
inps.vlim = inps.wrap_range
# Transparency - Alpha
if not inps.transparency:
# Auto adjust transparency value when showing shaded relief DEM
if inps.dem_file and inps.disp_dem_shade:
inps.transparency = 0.8
else:
inps.transparency = 1.0
# Flip Left-Right / Up-Down
if inps.auto_flip:
inps.flip_lr, inps.flip_ud = pp.auto_flip_direction(metadata, print_msg=inps.print_msg)
# Figure Title
if not inps.fig_title:
inps.fig_title = pp.auto_figure_title(
metadata['FILE_PATH'],
datasetNames=inps.dset,
inps_dict=vars(inps),
)
vprint('figure title: '+inps.fig_title)
# Figure output file name
if not inps.outfile:
# ignore whitespaces in the filename
fbase = inps.fig_title.replace(' ', '')
if not inps.disp_whitespace:
fbase += '_nws'
inps.outfile = [f'{fbase}{inps.fig_ext}']
inps = update_figure_setting(inps)
return inps
def check_map_projection(inps, metadata, print_msg=True):
"""Check/initiate the map projection object via cartopy based on inps and metadata.
Cartopy requires that:
1. file is geocoded AND
2. file coordinates are in the unit of degrees / meters AND
3. set to display in geo-coordinates
Use cartopy (by initiating inps.map_proj_obj) ONLY IF:
1. show fancy lat/lon label via --lalo-label OR
2. show coastline via --coastline
This function will update the following variables:
inps.map_proj_obj # cartopy.crs.* object or None
inps.coord_unit # degree or meter
inps.fig_coord # geo or yx
"""
inps.map_proj_obj = None
inps.coord_unit = metadata.get('Y_UNIT', 'degrees').lower()
if (inps.geo_box
and inps.coord_unit.startswith(('deg', 'meter'))
and inps.fig_coord == 'geo'
and (inps.lalo_label or inps.coastline)):
# get projection name from the data coord unit
# https://scitools.org.uk/cartopy/docs/latest/crs/projections.html
msg = 'initiate cartopy map projection: '
if inps.coord_unit.startswith('deg'):
inps.map_proj_obj = ccrs.PlateCarree()
print(msg + 'PlateCarree')
elif inps.coord_unit.startswith('meter'):
if 'UTM_ZONE' in metadata.keys():
utm_zone = metadata['UTM_ZONE']
inps.map_proj_obj = ccrs.UTM(utm_zone)
print(msg + f'UTM zone {utm_zone}')
# check --lalo-label (works for PlateCarree only)
if inps.lalo_label:
raise ValueError('--lalo-label is NOT supported for projection: UTM')
else:
print(f'WARNING: Un-recognized coordinate unit: {inps.coord_unit}')
print(' Switch to the native Y/X and continue to plot')
inps.fig_coord = 'yx'
return inps
##################################################################################################
def update_data_with_plot_inps(data, metadata, inps):
# 1. spatial referencing with respect to the seed point
if inps.ref_yx:
inps.ref_box = [inps.ref_yx[1], inps.ref_yx[0],
inps.ref_yx[1] + 1, inps.ref_yx[0] + 1]
# update ref_y/x to subset
ref_y = inps.ref_yx[0] - inps.pix_box[1]
ref_x = inps.ref_yx[1] - inps.pix_box[0]
# update ref_y/x for multilooking
if inps.multilook_num > 1:
ref_y = int((ref_y - int(inps.multilook_num / 2)) / inps.multilook_num)
ref_x = int((ref_x - int(inps.multilook_num / 2)) / inps.multilook_num)
if len(data.shape) == 2:
# read ref_val
if 0 <= ref_y < data.shape[-2] and 0 <= ref_x < data.shape[-1]:
ref_val = data[ref_y, ref_x]
else:
ref_val = readfile.read(
inps.file,
datasetName=inps.dset[0],
box=inps.ref_box,
print_msg=False,
)[0]
# applying spatial referencing
if not np.ma.is_masked(ref_val) and not np.isnan(ref_val):
data -= ref_val
vprint(f'set reference pixel to: {inps.ref_yx}')
else:
msg = f'WARNING: input reference pixel ({ref_y}, {ref_x}) has either masked or NaN value!'
msg += ' -> skip re-referencing.'
print(msg)
inps.ref_yx = None
elif len(data.shape) == 3:
# read ref_val
if 0 <= ref_y < data.shape[-2] and 0 <= ref_x < data.shape[-1]:
ref_val = np.squeeze(data[:, ref_y, ref_x])
elif inps.key == 'timeseries':
ref_val = readfile.read(
inps.file,
datasetName=inps.dset,
box=inps.ref_box,
print_msg=False,
)[0]
else:
raise ValueError(f'input reference point {inps.ref_yx} is out of data coverage!')
# apply spatial referencing
if not np.ma.is_masked(ref_val) and np.all(~np.isnan(ref_val)):
data -= np.tile(ref_val.reshape(-1, 1, 1), (1, data.shape[1], data.shape[2]))
vprint(f'set reference pixel to: {inps.ref_yx}')
else:
msg = f'WARNING: input reference pixel ({ref_y}, {ref_x}) has either masked or NaN value!'
msg += ' -> skip re-referencing.'
print(msg)
inps.ref_yx = None
else:
inps.ref_yx = None
# 2. scale data based on the display unit and re-wrap
(data,
inps.disp_unit,
inps.disp_scale,
inps.wrap) = pp.scale_data4disp_unit_and_rewrap(
data,
metadata=metadata,
disp_unit=inps.disp_unit,
wrap=inps.wrap,
wrap_range=inps.wrap_range,
print_msg=inps.print_msg,
)
if inps.wrap:
inps.vlim = inps.wrap_range
# math operation
if inps.math_operation:
vprint(f'Apply math operation: {inps.math_operation}')
if inps.math_operation == 'square' : data = np.square(data)
elif inps.math_operation == 'sqrt' : data = np.sqrt(data)
elif inps.math_operation == 'reverse': data *= -1.
elif inps.math_operation == 'inverse': data = 1. / data
elif inps.math_operation == 'rad2deg': data *= 180. / np.pi
elif inps.math_operation == 'deg2rad': data *= np.pi / 180.
else: raise ValueError(f'un-recognized math operation: {inps.math_operation}')
# 4. update display min/max
inps.dlim = [np.nanmin(data), np.nanmax(data)]
if not inps.vlim: # and data.ndim < 3:
(inps.cmap_lut,
inps.vlim,
inps.unique_values) = pp.auto_adjust_colormap_lut_and_disp_limit(data, print_msg=inps.print_msg)
vprint(f'data range: {inps.dlim} {inps.disp_unit}')
vprint(f'display range: {inps.vlim} {inps.disp_unit}')
return data, inps
##################################################################################################
def prep_slice(cmd, auto_fig=False):
"""Prepare data from command line as input, for easy call plot_slice() externally.
Parameters: cmd - string, command to be run in terminal
Returns: data - 2D np.ndarray, data to be plotted
atr - dict, metadata
inps - namespace, input argument for plot setup
Example:
from cartopy import crs as ccrs
from mintpy.view import prep_slice, plot_slice
# initiate matplotlib figure/axes
subplot_kw = dict(projection=ccrs.PlateCarree())
fig, ax = plt.subplots(figsize=[4, 3], subplot_kw=subplot_kw)
# compose view.py command
cmd = 'view.py geo_velocity.h5 velocity --mask geo_maskTempCoh.h5 --dem srtm1.dem --dem-nocontour '
cmd += f'--sub-lon -91.7 -91.4 --sub-lat -0.5 -0.3 -c jet -v -3 10 '
cmd += '--cbar-loc bottom --cbar-nbins 3 --cbar-ext both --cbar-label "LOS velocity [cm/year]" '
cmd += '--lalo-step 0.2 --lalo-loc 1 0 1 0 --scalebar 0.3 0.80 0.05 --notitle'
# call prep/plot_slice()
data, atr, inps = prep_slice(cmd)
ax, inps, im, cbar = plot_slice(ax, data, atr, inps)
plt.show()
"""
# parse
from mintpy.cli.view import cmd_line_parse
iargs = cmd.split()[1:]
# support option inputs of a list of characters (separated by whitespaces but quoted)
# e.g.: --cbar-label "LOS velocity [cm/yar]" --title "S1 asc. velocity"
# to be consistent with the behavior in command line parsing
if any(x.startswith(('"', '\'')) for x in iargs):
# backup and reset
temp_iargs = list(iargs)
iargs = []
# get index of quoted list of characters
ind0s = np.where([x.startswith(('"', '\'')) for x in temp_iargs])[0]
ind1s = np.where([x.endswith(('"', '\'')) for x in temp_iargs])[0]
for i, temp_iarg in enumerate(temp_iargs):
if any(ind0 <= i <= ind1 for ind0, ind1 in zip(ind0s, ind1s)):
# quoted list of characters
for ind0, ind1 in zip(ind0s, ind1s):
if i == ind0:
temp = temp_iarg[1:]
elif ind0 < i < ind1:
temp += ' ' + temp_iarg
elif i == ind1:
temp += ' ' + temp_iarg[:-1]
iargs.append(temp)
break
else:
# regular unquoted list of characters
iargs.append(temp_iarg)
# run parse
inps = cmd_line_parse(iargs)
global vprint
vprint = print if inps.print_msg else lambda *args, **kwargs: None
# read input args
inps, atr = read_input_file_info(inps)
inps = update_inps_with_file_metadata(inps, atr)
inps.msk, inps.mask_file = pp.read_mask(
inps.file,
mask_file=inps.mask_file,
datasetName=inps.dset[0],
box=inps.pix_box,
vmin=inps.mask_vmin,
vmax=inps.mask_vmax,
print_msg=inps.print_msg,
)
# read data
data, atr = readfile.read(
inps.file,
datasetName=inps.dset[0],
box=inps.pix_box,
print_msg=inps.print_msg,
)
# reference in time
if inps.ref_date:
data -= readfile.read(
inps.file,
datasetName=inps.ref_date,
box=inps.pix_box,
print_msg=False,
)[0]
# reference in space for unwrapPhase
if (inps.key in ['ifgramStack']
and inps.dset[0].split('-')[0].startswith('unwrapPhase')
and 'REF_Y' in atr.keys()):
ref_y, ref_x = int(atr['REF_Y']), int(atr['REF_X'])
ref_data = readfile.read(
inps.file,
datasetName=inps.dset[0],
box=(ref_x, ref_y, ref_x+1, ref_y+1),
print_msg=False,
)[0]
data[data != 0.] -= ref_data
# masking
if inps.zero_mask:
data = np.ma.masked_where(data == 0., data)
if inps.msk is not None:
data = np.ma.masked_where(inps.msk == 0., data)
else:
inps.msk = np.ones(data.shape, dtype=np.bool_)
# update/save mask info
if np.ma.is_masked(data):
inps.msk *= ~data.mask
inps.msk *= ~np.isnan(data.data)
else:
inps.msk *= ~np.isnan(data)
data, inps = update_data_with_plot_inps(data, atr, inps)
# matplotlib.Axes
if auto_fig:
figsize = [i/2.0 for i in inps.fig_size]
subplot_kw = dict(projection=inps.map_proj_obj) if inps.map_proj_obj is not None else {}
ax = plt.subplots(figsize=figsize, subplot_kw=subplot_kw)[1]
return data, atr, inps, ax
else:
return data, atr, inps
##################################################################################################
def plot_slice(ax, data, metadata, inps):
"""Plot one slice of matrix
Parameters: ax : matplot.pyplot axes object
data : 2D np.ndarray,
metadata : dictionary, attributes of data
inps : Namespace, input options for display
Returns: ax : matplot.pyplot axes object
inps : Namespace for input options
im : matplotlib.image.AxesImage object
cbar : matplotlib.colorbar.Colorbar object
Example: See prep_slice() above for example usage.
"""
global vprint
vprint = print if inps.print_msg else lambda *args, **kwargs: None
def extent2meshgrid(extent: tuple, ds_shape: list):
"""Get mesh grid coordinates for a given extent and shape.
Parameters: extent - tuple of float for (left, right, bottom, top) in data coordinates
shape - list of int for [length, width] of the data
Returns: xx/yy - 1D np.ndarray of the data coordinates
"""
height, width = ds_shape
x = np.linspace(extent[0], extent[1], width)
y = np.linspace(extent[2], extent[3], height)[::-1] # reverse the Y-axis
xx, yy = np.meshgrid(x, y)
return xx.flatten(), yy.flatten()
# colormap: str -> object
if isinstance(inps.colormap, str):
inps.colormap = pp.ColormapExt(
inps.colormap,
cmap_lut=inps.cmap_lut,
vlist=inps.cmap_vlist,
).colormap
# read DEM
if inps.dem_file:
dem, dem_metadata, dem_pix_box = pp.read_dem(
inps.dem_file,
pix_box=inps.pix_box,
geo_box=inps.geo_box,
print_msg=inps.print_msg,
)
vprint('display data in transparency: '+str(inps.transparency))
num_row, num_col = data.shape
lalo_digit = ut.get_lalo_digit4display(metadata, coord_unit=inps.coord_unit)
# common options for data visualization
kwargs = dict(cmap=inps.colormap, vmin=inps.vlim[0], vmax=inps.vlim[1], alpha=inps.transparency, zorder=1)
#----------------------- Plot in Geo-coordinate --------------------------------------------#
if (inps.geo_box
and inps.coord_unit.startswith(('deg', 'meter'))
and inps.fig_coord == 'geo'):
vprint('plot in geo-coordinate')
# extent info for matplotlib.imshow and other functions
inps.extent = (inps.geo_box[0], inps.geo_box[2], inps.geo_box[3], inps.geo_box[1]) # (W, E, S, N)
SNWE = (inps.geo_box[3], inps.geo_box[1], inps.geo_box[0], inps.geo_box[2])
# Draw coastline using cartopy resolution parameters
if inps.coastline:
vprint(f'draw coast line with resolution: {inps.coastline}')
ax.coastlines(resolution=inps.coastline, linewidth=inps.coastline_linewidth)
# Plot DEM
if inps.dem_file:
vprint('plotting DEM background ...')
pp.plot_dem_background(
ax=ax,
geo_box=inps.geo_box,
dem=dem,
inps=inps,
print_msg=inps.print_msg,
)
# Reference (InSAR) data to a GNSS site
coord = ut.coordinate(metadata)
if inps.disp_gnss and inps.gnss_component and inps.ref_gnss_site:
gnss_obj = gnss.get_gnss_class(inps.gnss_source)(site=inps.ref_gnss_site)
ref_site_lalo = gnss_obj.get_site_lat_lon()
y, x = coord.geo2radar(ref_site_lalo[0], ref_site_lalo[1])[0:2]
ref_data = data[y - inps.pix_box[1], x - inps.pix_box[0]]
data -= ref_data
vprint('referencing InSAR data to the pixel nearest to GNSS station: '
f'{inps.ref_gnss_site} at [{ref_site_lalo[0]:.6f}, {ref_site_lalo[1]:.6f}] '
f'by substrating {ref_data:.3f} {inps.disp_unit}')
# do not show the original InSAR reference point
inps.disp_ref_pixel = False
# Plot data
if inps.disp_dem_blend:
im = pp.plot_blend_image(ax, data, dem, inps, print_msg=inps.print_msg)
elif inps.style == 'image':
vprint(f'plotting data as {inps.style} via matplotlib.pyplot.imshow ...')
im = ax.imshow(data, extent=inps.extent, origin='upper', interpolation=inps.interpolation,
animated=inps.animation, **kwargs)
elif inps.style == 'scatter':
vprint(f'plotting data as {inps.style} via matplotlib.pyplot.scatter (can take some time) ...')
xx, yy = extent2meshgrid(inps.extent, data.shape)
im = ax.scatter(xx, yy, c=data.flatten(), marker='o', s=inps.scatter_marker_size, **kwargs)
ax.axis('equal')
else:
raise ValueError(f'Un-recognized plotting style: {inps.style}!')
# Draw faultline using GMT lonlat file
if inps.faultline_file:
pp.plot_faultline(
ax=ax,
faultline_file=inps.faultline_file,
SNWE=SNWE,
linewidth=inps.faultline_linewidth,
min_dist=inps.faultline_min_dist,
print_msg=inps.print_msg,
)
# Scale Bar
if inps.coord_unit.startswith('deg') and (inps.geo_box[2] - inps.geo_box[0]) > 30:
# do not plot scalebar if the longitude span > 30 deg
inps.disp_scalebar = False
if inps.disp_scalebar:
vprint(f'plot scale bar: {inps.scalebar}')
pp.draw_scalebar(
ax=ax,
geo_box=inps.geo_box,
unit=inps.coord_unit,
loc=inps.scalebar,
labelpad=inps.scalebar_pad,
font_size=inps.font_size,
linewidth=inps.scalebar_linewidth,
)
# Lat Lon labels
if inps.lalo_label:
pp.draw_lalo_label(
ax=ax,
geo_box=inps.geo_box,
lalo_step=inps.lalo_step,
lalo_loc=inps.lalo_loc,
lalo_max_num=inps.lalo_max_num,
lalo_offset=inps.lalo_offset,
font_size=inps.lalo_font_size if inps.lalo_font_size else inps.font_size,
projection=inps.map_proj_obj,
print_msg=inps.print_msg)
else:
ax.tick_params(which='both', direction='in', labelsize=inps.font_size,
left=True, right=True, top=True, bottom=True)
# Plot Reference Point
if inps.disp_ref_pixel and inps.ref_lalo:
ax.plot(inps.ref_lalo[1], inps.ref_lalo[0],
inps.ref_marker, ms=inps.ref_marker_size)
vprint('plot reference point')
# Plot points of interest
if inps.pts_lalo is not None:
ax.plot(inps.pts_lalo[:, 1], inps.pts_lalo[:, 0],
inps.pts_marker, ms=inps.pts_marker_size,
mec='k', mew=1.)
vprint('plot points of interest')
# Show UNR GNSS stations
if inps.disp_gnss:
ax = pp.plot_gnss(ax, SNWE, inps, metadata, print_msg=inps.print_msg)
# Status bar
if inps.dem_file:
coord_dem = ut.coordinate(dem_metadata)
dem_len, dem_wid = dem.shape
def format_coord(x, y):
# lat/lon
msg = f'E={x:.{lalo_digit}f}, N={y:.{lalo_digit}f}'
# value
row, col = coord.lalo2yx(y, x)
row -= inps.pix_box[1]
col -= inps.pix_box[0]
if 0 <= col < num_col and 0 <= row < num_row:
v = data[row, col]
msg += ', v=[]' if np.isnan(v) or np.ma.is_masked(v) else f', v={v:.3f}'
# DEM
if inps.dem_file:
dem_row, dem_col = coord_dem.lalo2yx(y, x)
dem_row -= dem_pix_box[1]
dem_col -= dem_pix_box[0]
if 0 <= dem_col < dem_wid and 0 <= dem_row < dem_len:
h = dem[dem_row, dem_col]
msg += ', h=[]' if np.isnan(h) else f', h={h:.1f}'
# x/y
msg += f', x={col+inps.pix_box[0]:.0f}'
msg += f', y={row+inps.pix_box[1]:.0f}'
return msg
ax.format_coord = format_coord
#------------------------ Plot in Y/X-coordinate ------------------------------------------------#
else:
inps.fig_coord = 'yx'
vprint('plotting in Y/X coordinate ...')
# Plot DEM
if inps.dem_file:
vprint('plotting DEM background ...')
pp.plot_dem_background(
ax=ax,
geo_box=None,
dem=dem,
inps=inps,
print_msg=inps.print_msg,
)
# extent = (left, right, bottom, top) in data coordinates
inps.extent = (inps.pix_box[0]-0.5, inps.pix_box[2]-0.5,
inps.pix_box[3]-0.5, inps.pix_box[1]-0.5)
# Plot Data
if inps.disp_dem_blend:
im = pp.plot_blend_image(ax, data, dem, inps, print_msg=inps.print_msg)
elif inps.style == 'image':
vprint('plotting data via matplotlib.pyplot.imshow ...')
im = ax.imshow(data, extent=inps.extent, interpolation=inps.interpolation, **kwargs)
elif inps.style == 'scatter':
vprint('plotting data via matplotlib.pyplot.scatter (can take some time) ...')
xx, yy = extent2meshgrid(inps.extent, data.shape)
im = ax.scatter(xx, yy, c=data.flatten(), marker='o', s=inps.scatter_marker_size, **kwargs)
ax.axis('equal')
else:
raise ValueError(f'Un-recognized plotting style: {inps.style}!')
ax.tick_params(labelsize=inps.font_size)
# Plot Seed Point
if inps.disp_ref_pixel:
ref_y, ref_x = None, None
if inps.ref_yx:
ref_y, ref_x = inps.ref_yx[0], inps.ref_yx[1]
elif 'REF_Y' in metadata.keys():
ref_y, ref_x = int(metadata['REF_Y']), int(metadata['REF_X'])
if ref_y and ref_x:
ax.plot(ref_x, ref_y, inps.ref_marker, ms=inps.ref_marker_size)
vprint('plot reference point')
# Plot points of interest
if inps.pts_yx is not None:
ax.plot(inps.pts_yx[:, 1], inps.pts_yx[:, 0],
inps.pts_marker, ms=inps.ref_marker_size,
mec='black', mew=1.)
vprint('plot points of interest')
# temporary test code
temp_test = False
if temp_test:
# Champlain Towers South AOI
pts_yx = np.array([
[929,1456],
[933,1457],
[933,1436],
[930,1431],
[929,1456],
])
ax.plot(pts_yx[:, 1], pts_yx[:, 0], '-', ms=inps.ref_marker_size, mec='black', mew=1.)
ax.set_xlim(inps.extent[0:2])
ax.set_ylim(inps.extent[2:4])
# Status bar
# read lats/lons if exist
geom_file = os.path.join(os.path.dirname(metadata['FILE_PATH']), 'inputs/geometryRadar.h5')
if os.path.isfile(geom_file):
geom_ds_list = readfile.get_dataset_list(geom_file)
if all(x in geom_ds_list for x in ['latitude', 'longitude']):
lats = readfile.read(geom_file, datasetName='latitude', box=inps.pix_box, print_msg=False)[0]
lons = readfile.read(geom_file, datasetName='longitude', box=inps.pix_box, print_msg=False)[0]
else:
msg = f'WARNING: no latitude / longitude found in file: {os.path.basename(geom_file)}, '
msg += 'skip showing lat/lon in the status bar.'
vprint(msg)
geom_file = None
else:
geom_file = None
def format_coord(x, y):
# y/x
msg = f'x={x:.1f}, y={y:.1f}'
# value
col = int(np.rint(x - inps.pix_box[0]))
row = int(np.rint(y - inps.pix_box[1]))
if 0 <= col < num_col and 0 <= row < num_row:
v = data[row, col]
msg += ', v=[]' if np.isnan(v) or np.ma.is_masked(v) else f', v={v:.3f}'
# DEM
if inps.dem_file:
h = dem[row, col]
msg += ', h=[]' if np.isnan(h) else f', h={h:.1f} m'
# lat/lon
if geom_file:
msg += f', E={lons[row, col]:.{lalo_digit}f}'
msg += f', N={lats[row, col]:.{lalo_digit}f}'
return msg
ax.format_coord = format_coord
#---------------------- Figure Setting ----------------------------------------#
# 3.1 Colorbar
cbar = None
if inps.disp_cbar:
divider = make_axes_locatable(ax)
cax = divider.append_axes(inps.cbar_loc, inps.cbar_size, pad=inps.cbar_size, axes_class=plt.Axes)
inps, cbar = pp.plot_colorbar(inps, im, cax)
# 3.2 Title
if inps.disp_title:
ax.set_title(inps.fig_title, fontsize=inps.font_size, color=inps.font_color)
# 3.3 Flip Left-Right / Up-Down
if inps.flip_lr:
vprint('flip figure left and right')
ax.invert_xaxis()
if inps.flip_ud:
vprint('flip figure up and down')
ax.invert_yaxis()
# 3.4 Turn off axis
if not inps.disp_axis:
ax.axis('off')
vprint('turn off axis display')
# 3.5 Tick labels
if inps.disp_tick:
# move x-axis tick label to the top if colorbar is at the bottom
if inps.cbar_loc == 'bottom':
ax.tick_params(bottom=False, top=True, labelbottom=False, labeltop=True)
# manually turn ON to enable tick labels for UTM with cartopy
# link: https://github.com/SciTools/cartopy/issues/491
ax.xaxis.set_visible(True)
ax.yaxis.set_visible(True)
else:
# turn off tick labels
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
# rotate Y-axis tick labels
# link: https://stackoverflow.com/questions/10998621
if inps.ylabel_rot:
tick_kwargs = dict(rotation=inps.ylabel_rot)
# center the vertical alignment for vertical tick labels
if inps.ylabel_rot % 90 == 0:
tick_kwargs['va'] = 'center'
plt.setp(ax.get_yticklabels(), **tick_kwargs)
vprint(f'rotate Y-axis tick labels by {inps.ylabel_rot} deg')
return ax, inps, im, cbar
##################################################################################################
def read_input_file_info(inps):
# File Basic Info
atr = readfile.read_attribute(inps.file)
msg = 'input file is '
if not inps.file.endswith(('.h5', '.he5')):
msg += '{} '.format(atr['PROCESSOR'])
msg += '{} file: {}'.format(atr['FILE_TYPE'], os.path.abspath(inps.file))
if 'DATA_TYPE' in atr.keys():
msg += ' in {} format'.format(atr['DATA_TYPE'])
vprint(f'run {os.path.basename(__file__)} in {version.version_description}')
vprint(msg)
## size and name
inps.length = int(atr['LENGTH'])
inps.width = int(atr['WIDTH'])
inps.key = atr['FILE_TYPE']
inps.fileBase = os.path.splitext(os.path.basename(inps.file))[0]
inps.fileExt = os.path.splitext(inps.file)[1]
vprint(f'file size in y/x: {(inps.length, inps.width)}')
# File dataset List
inps.sliceList = readfile.get_slice_list(inps.file, no_complex=True)
# Read input list of dataset to display
inps, atr = read_dataset_input(inps)
return inps, atr
def search_dataset_input(all_list, in_list=[], in_num_list=[], search_dset=True):
"""Get dataset(es) from input dataset / dataset_num"""
# make a copy to avoid weird variable behavior
in_num_list = [x for x in in_num_list]
# in_list --> in_num_list --> outNumList --> outList
if in_list:
if isinstance(in_list, str):
in_list = [in_list]
tempList = []
if search_dset:
for ds in in_list:
# style of regular expression
if '*' not in ds:
ds = f'*{ds}*'
ds = ds.replace('*','.*')
# search
tempList += [e for e in all_list if re.match(ds, e) is not None]
else:
tempList += [i for i in in_list if i in all_list]
tempList = sorted(list(set(tempList)))
in_num_list += [all_list.index(e) for e in tempList]
# in_num_list --> outNumList
outNumList = sorted(list(set(in_num_list)))
# outNumList --> outList
outList = [all_list[i] for i in outNumList]
return outList, outNumList
def read_dataset_input(inps):
"""Check input / exclude / reference dataset input with file dataset list"""
# read inps.dset + inps.dsetNumList --> inps.dsetNumList
if len(inps.dset) > 0 or len(inps.dsetNumList) > 0:
# message
if len(inps.dset) > 0:
vprint(f'input dataset: "{inps.dset}"')
# special rule for special file types
if inps.key == 'velocity':
inps.search_dset = False
vprint(f'turning glob search OFF for {inps.key} file')
elif inps.key == 'timeseries' and len(inps.dset) == 1 and '_' in inps.dset[0]:
date1, date2 = inps.dset[0].split('_')
inps.dset = [date2]
inps.ref_date = date1
# search
inps.dsetNumList = search_dataset_input(
all_list=inps.sliceList,
in_list=inps.dset,
in_num_list=inps.dsetNumList,
search_dset=inps.search_dset)[1]
else:
# default dataset to display for certain type of files
if inps.key == 'ifgramStack':
inps.dset = ['unwrapPhase']
elif inps.key == 'HDFEOS':
inps.dset = ['displacement']
elif inps.key == 'giantTimeseries':
inps.dset = 'recons'
elif inps.key == 'giantIfgramStack':
obj = giantIfgramStack(inps.file)
obj.open(print_msg=False)
inps.dset = [obj.sliceList[0].split('-')[0]]
else:
inps.dset = inps.sliceList
# do not plot 3D-bperp by default
if inps.key == 'geometry':
inps.dset = [x for x in inps.dset if not x.startswith('bperp')]
inps.dsetNumList = search_dataset_input(
all_list=inps.sliceList,
in_list=inps.dset,
in_num_list=inps.dsetNumList,
search_dset=inps.search_dset)[1]
# read inps.exDsetList
inps.exDsetList, inps.exDsetNumList = search_dataset_input(
all_list=inps.sliceList,
in_list=inps.exDsetList,
in_num_list=[],
search_dset=inps.search_dset)
# read inps.plot_drop_ifgram
drop_num_list = []
ftype = readfile.read_attribute(inps.file)['FILE_TYPE']
if not inps.plot_drop_ifgram:
if ftype == 'ifgramStack':
vprint('do not show the dropped interferograms')
date12_drop_list = ifgramStack(inps.file).get_drop_date12_list()
drop_slice_list = [x for x in inps.sliceList if x.split('-')[1] in date12_drop_list]
drop_num_list = [inps.sliceList.index(x) for x in drop_slice_list]
else:
print(f'WARNING: --show-kept option does not apply to file type: {ftype}, ignore and continue.')
inps.plot_drop_ifgram = True
# get inps.dset
inps.dsetNumList = sorted(list(set(inps.dsetNumList) - set(inps.exDsetNumList) - set(drop_num_list)))
inps.dset = [inps.sliceList[i] for i in inps.dsetNumList]
inps.dsetNum = len(inps.dset)
if inps.ref_date:
if inps.key not in TIMESERIES_KEY_NAMES:
inps.ref_date = None
ref_date = search_dataset_input(
all_list=inps.sliceList,
in_list=[inps.ref_date],
in_num_list=[],
search_dset=inps.search_dset)[0][0]
if not ref_date:
msg = f'WARNING: input reference date {inps.ref_date} is not included in input file!'
msg += 'Ignore it and continue'
print(msg)
inps.ref_date = None
else:
inps.ref_date = ref_date
if inps.key in ['ifgramStack']:
vprint(f'num of datasets in file {os.path.basename(inps.file)}: {len(inps.sliceList)}')
vprint(f'num of datasets to exclude: {len(inps.exDsetList)}')
vprint(f'num of datasets to display: {len(inps.dset)}')
else:
vprint(f'num of datasets in file {os.path.basename(inps.file)}: {len(inps.sliceList)}')
vprint(f'datasets to exclude ({len(inps.exDsetList)}):\n{inps.exDsetList}')