U
    bb                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlm	Z
 d dlmZ d dlZejdedd d dlmZ d dlmZmZmZmZmZmZ d dlmZ d dlmZmZmZm Z!m"Z# d d	l$m%Z% d d
l&m'Z'm(Z( dZ)dZ*dd Z+d7ddZ,dd Z-dd Z.dd Z/d8ddZ0dd Z1d9ddZ2dd Z3g g dfd d!Z4d"d# Z5d$d% Z6d&d' Z7d(d) Z8d*d+ Z9d,d- Z:d:d/d0Z;G d1d2 d2Z<d;d3d4Z=e>d5kre=ej?d6d  dS )<    N)make_axes_locatableignore
matplotlib)categorymodule)giantIfgramStackgeometryDatasetNamesifgramDatasetNamesifgramStacktimeseriesKeyNames
timeseries)GPS)	arg_groupptimereadfileutilsplot)multilook_data)subsetversiona  example:
  view.py velocity.h5
  view.py velocity.h5 velocity --wrap --wrap-range -2 2 -c cmy --lalo-label
  view.py velocity.h5 --ref-yx  210 566                              #change reference pixel for display
  view.py velocity.h5 --sub-lat 31.05 31.10 --sub-lon 130.05 130.10  #subset in lalo / yx

  view.py timeseries.h5
  view.py timeseries.h5 -m no                   #do not use auto mask
  view.py timeseries.h5 --ref-date 20101120     #change reference date
  view.py timeseries.h5 --ex drop_date.txt      #exclude dates to plot
  view.py timeseries.h5 '*2017*' '*2018*'       #all acquisitions in 2017 and 2018
  view.py timeseries.h5 20200616_20200908       #reconstruct interferogram on the fly

  view.py ifgramStack.h5 coherence
  view.py ifgramStack.h5 unwrapPhase-           #unwrapPhase only in the presence of unwrapPhase_bridging
  view.py ifgramStack.h5 -n 6                   #the 6th slice
  view.py ifgramStack.h5 20171010_20171115      #all data      related with 20171010_20171115
  view.py ifgramStack.h5 'coherence*20171010*'  #all coherence related with 20171010
  view.py ifgramStack.h5 unwrapPhase-20070927_20100217 --zero-mask --wrap     #wrapped phase
  view.py ifgramStack.h5 unwrapPhase-20070927_20100217 --mask ifgramStack.h5  #mask using connected components

  # GPS (for one subplot in geo-coordinates only)
  view.py geo_velocity_msk.h5 velocity --show-gps --gps-label   #show locations of available GPS
  view.py geo_velocity_msk.h5 velocity --show-gps --gps-comp enu2los --ref-gps GV01
  view.py geo_timeseries_ERA5_ramp_demErr.h5 20180619 --ref-date 20141213 --show-gps --gps-comp enu2los --ref-gps GV01

  # Save and Output
  view.py velocity.h5 --save
  view.py velocity.h5 --nodisplay
  view.py geo_velocity.h5 velocity --nowhitespace
a\  Plot Setting:
  plot.name          = 'Yunjun et al., 2016, AGU, Fig 4f'
  plot.type          = LOS_VELOCITY
  plot.startDate     =
  plot.endDate       =
  plot.displayUnit   = cm/yr
  plot.displayMin    = -2
  plot.displayMax    = 2
  plot.colormap      = jet
  plot.subset.lalo   = 33.05:33.15, 131.15:131.27
  plot.seed.lalo = 33.0651, 131.2076
c               
   C   sP  t jdt jtd} | dd}|jdtdd |jdtd	g d
d |jddddtd	g dd |jddddd |jddddd	g dd | jddddd d | jd!d"d#t d$ | jd%d&dd'd | jd(d)d*d+d,d-d.d/hd0d1 t	
| } t	| } t	| } t	| } t	| } t	| } t	| } t	| } t	| } t	| } t	| } | S )2NzPlot InSAR Product in 2D)descriptionformatter_classepilogz
Input FilezFile/Dataset to displayfilezfile for display)typehelpdset*z8optional - dataset(s) to display (default: %(default)s).)r   nargsdefaultr   z-nz
--dset-numdsetNumListNUMzMoptional - order number of date/dataset(s) to display (default: %(default)s).)destmetavarr   r   r   r   z
--nosearchsearch_dsetstore_falsez#Disable glob search for input dset.)r"   actionr   z--exz	--exclude
exDsetListZDsetz3dates will not be displayed (default: %(default)s).)r"   r#   r   r   r   z--show-keptz--show-kept-ifgramplot_drop_ifgramz@display kept interferograms only, without dropped interferogramsz--plot-settingdisp_setting_filez!Template file with plot setting.
)r"   r   z--noverbose	print_msgz<Disable the verbose message printing (default: %(default)s).z--mathmath_operationsquaresqrtreverseinverserad2degdeg2radzApply the math operation before displaying [for single subplot ONLY].
E.g. plot the std. dev. of the variance file.
  square  = x^2
  sqrt    = x^1/2
  reverse = x * -1
  inverse = 1 / x)r"   choicesr   )argparseArgumentParserRawTextHelpFormatterEXAMPLEadd_argument_groupadd_argumentstrintPLOT_TEMPLATEr   add_data_disp_argumentadd_dem_argumentadd_figure_argumentadd_gps_argumentadd_mask_argumentadd_map_argumentadd_memory_argumentadd_point_argumentadd_reference_argumentadd_save_argumentadd_subset_argument)parserinfile rI   A/home/centos/operations/rsmas_insar/sources/MintPy/mintpy/view.pycreate_parser[   sT    












rK   c                 C   s  t  }|j| d}| r| ntjdd |_dD ]4}t|| }|dkr.tj|s.td	||q.|j
rxt|j
|_
|js|jsd|_|jrd|_|jr|jsd|_|jsd	|_d	|_d	|_|jsd	|_|js|jrd	|_d
dddddg}tt|t|j@ }|r<dt|j ! kr<|D ]}t"d| d q$|j#rHt"ndd a$|j#sjt"dd%|j |j&r~t'||j&}|jst()d |S )zCommand line parser.)args   N)r   dem_file	mask_filepts_file)Nnozinput {} file {} NOT exist!TrQ   Fz--coord
--show-gps--coastline--lalo-label--lalo-step
--scalebarY_FIRSTz	WARNING: zH is NOT supported for files in radar-coordinate, ignore it and continue.c                  _   s   d S NrI   rL   kwargsrI   rI   rJ   <lambda>       z cmd_line_parse.<locals>.<lambda>zview.py Agg)*rK   
parse_argssysargvvarsospathisfileFileNotFoundErrorformatr'   r   read_date_listoutfiledisp_figsave_fig	lalo_step
lalo_label	zero_maskrO   disp_whitespace	disp_axis
disp_title	disp_cbar	disp_tickflip_lrflip_ud	auto_fliplistsetr   read_attributer   keysprintr*   vprintjoinr)   %update_inps_with_display_setting_filepltswitch_backend)iargsrG   inpskeyfnameZgeo_opt_namesopt_namerI   rI   rJ   cmd_line_parse   sJ    
r   c              	   C   s   t d d}g }| jD ]V}|tjtj|dtj|g}dd |D }t|dkrh||d  qd}q|dkrtj	| j
}tdd |D }||krd}nt d	|| j
 |S )
Nzupdate mode: ONskippicc                 S   s   g | ]}t j|r|qS rI   )rc   rd   re   .0irI   rI   rJ   
<listcomp>   s      zrun_or_skip.<locals>.<listcomp>r   runc                 S   s   g | ]}t j|qS rI   )rc   rd   getmtimer   rI   rI   rJ   r      s     z4{} exist and are newer than input file: {} --> skip.)r|   ri   rc   rd   r}   dirnamebasenamelenappendr   r   minrg   )r   flagZoutfilesr   fnamestitorI   rI   rJ   run_or_skip   s     
$r   c                 C   s0  t |}| js&d| kr&|d | _| jsFd| krFt|d | _| jsfd| krft|d | _| jsd| kr|d | _| jsd| krdd |d 	dd	
 d
d D | _| jsd| krdd |d 	dd	
 dd D | _| js,d| kr,dd |d 	dd	
 D | _| S )z2Update inps using values from display setting filezplot.displayUnitzplot.displayMinzplot.displayMaxzplot.colormapzplot.subset.laloc                 S   s   g | ]}t |qS rI   floatr   nrI   rI   rJ   r      s     z9update_inps_with_display_setting_file.<locals>.<listcomp>,r]   r      c                 S   s   g | ]}t |qS rI   r   r   rI   rI   rJ   r      s        zplot.seed.laloc                 S   s   g | ]}t |qS rI   r   r   rI   rI   rJ   r      s     zplot.referenceLalo)r   read_template	disp_unitrz   disp_minr   disp_maxcolormap
subset_latreplacesplit
subset_lonref_lalo)r   Zdisp_set_fileZdisp_set_dictrI   rI   rJ   r~      s     


(( r~   c                    sJ  t |}tt |\ _ _| j _| j _dd j	 j
f _tdt j  tdt j  tdt| j  tdt j  td t jd  jd   jd	  jd  d
krd _ jrtd  jdkrd _tj| j jd  jd _ jrtd j  jsV|jsVtd td g  _n*| jd  jd  _td j  jr jr|j jd dd|j jd ddg _n0d| krt |d t |d g _nd  _t! | tj"| j# j$ j% jd\ _# _$t& | jd  j'st( fdddD s j)dkrr jd *dd dks jd d krd!d"g _'n j)d#ks j$r j% _' j+sЈ jrʈ j,rd$ _+nd" _+ j-rtj.| jd\ _/ _0 j1stj2|d%  jt d& _1td' j1   j3s>d( j1 j4g _3t5   S ))Nr   zdata   coverage in y/x: zsubset coverage in y/x: zdata   coverage in lat/lon: zsubset coverage in lat/lon: zH------------------------------------------------------------------------   rM   r   g     @@Fz=area exceed 2000 pixels, turn off default DEM contour displayT)datasetNamer*   z$input reference point in lat/lon: {}zbWARNING: --ref-lalo is NOT supported when 1) file is radar-coded AND 2) no lookup table file foundz1    --> ignore the --ref-lalo input and continue.z$input reference point in y  /x  : {}y
coord_typexREF_LATREF_LON)r   wrap
wrap_ranger*   r*   c                 3   s   | ]}| j  kV  qd S rX   )r   lowerr   r   rI   rJ   	<genexpr>@  s     z1update_inps_with_file_metadata.<locals>.<genexpr>)	coherencez.corr
   -)r   cmask              ?)z.intg?	FILE_PATH)datasetNames	inps_dictzfigure title: {}{})6ut
coordinater   subset_input_dict2boxrb   pix_boxgeo_boxcheck_box_within_data_coveragebox_pixel2geowidthlengthdata_boxr|   r9   maxdisp_dem_contourrN   multilook_num	multilookppauto_colormap_namer   r   r*   r   rg   lookup_filer{   	geo2radarref_yxyx2lalorz   r   read_pts2inpscheck_disp_unit_and_wrapr   r   r   check_map_projectionvlimanyr   r   transparencydisp_dem_shaderv   auto_flip_directionrt   ru   	fig_titleauto_figure_titleri   fig_extupdate_figure_setting)r   metadatacoordrI   r   rJ   update_inps_with_file_metadata   s    





r   Tc                 C   s   d| _ |dd | _| jr| jdr| jdkr| js@| jrd}| jdrlt	
 | _ |rt|d  np| jd	rd
| kr|d
 }t	|| _ |rt|d|   | jrtdntd| j td d| _| S )a_  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 radar
    NY_UNITdegreesdegmetergeoz!initiate cartopy map projection: r   PlateCarreer   UTM_ZONEz	UTM zone z1--lalo-label is NOT supported for projection: UTMz*WARNING: Un-recognized coordinate unit: {}z1    Switch to the native Y/X and continue to plotradar)map_proj_objgetr   
coord_unitr   
startswith	fig_coordrm   	coastlineccrsr   r{   rz   UTM
ValueErrorrg   )r   r   r*   msgutm_zonerI   rI   rJ   r   b  s8    


r   c                 C   s  |j rJz,|j d |jd  }|j d |jd  }W n   Y nX |jdkrt|t|jd  |j }t|t|jd  |j }t| jdkr| ||f }tj|st	|s| |8 } t
d|j  n"d||}|d7 }t| d |_ qPt| jdkrPd|  kr"| jd k rbn n<d|  krD| jd	 k rbn nt| d d ||f }nd|jd
kr|j d |j d |j d d |j d d g}tj|j|j|ddd }ntd|j tj|s&tt	| r&| t|d	ddd| jd | jd f8 } t
d|j  n"d||}|d7 }t| d |_ nd |_ tj| ||j|j|j|jd\} |_|_|_|jr|j|_|jrHt
d|j |jdkrt | } n|jdkrt!| } nt|jdkr| d9 } n^|jdkr d|  } nH|jdkr| dtj" 9 } n,|jdkr8| tj"d 9 } ntd|jt#| t$| g|_%|js~tj&| |jd\|_'|_t
d|j%|j t
d|j|j | |fS )Nr   rM   r   zset reference pixel to: {}zGWARNING: input reference pixel ({}, {}) has either masked or NaN value!z -> skip re-referencing.r   r   Fr   boxr*   z1input reference point {} is out of data coverage!)r   r   r   r   r*   zApply math operation: {}r,   r-   r.   g      r/   r   r0   g     f@r1   z un-recognized math operation: {}r   data    range: {} {}display range: {} {})(r   r   r   r:   r   shapenpma	is_maskedisnanr|   rg   r{   squeezer   r   readr   r   r   alltilereshaper   scale_data4disp_unit_and_rewrapr   r   r   r*   
disp_scaler   r+   r,   r-   pinanminnanmaxdlim'auto_adjust_colormap_lut_and_disp_limitcmap_lut)datar   r   ref_yref_xref_valr   ref_boxrI   rI   rJ   update_data_with_plot_inps  s    

D ",

r  c                    sl  j r
tndd as*tdgt|tjtrPtj	jj
jdj_jrvtjjjjj d\}tdtj  j\jrʈjdrʈjdkrtd	 jrtd
j | jjd jrtd tj| jj d t| td jrjrjrtjdjdd}  |d |d dd \}}|jd  |jd  f }|8 tdj d| d|ddj!  d_"jd jd jd jd f}	| j#jj$d j$d |	ddjj%dd
}
jdr<jd jd  dkr<d_&j&rttd j' tj(| jjj'j)j*d! j+rtj,j| j-j.j/j*j0j d" n| j1d#d$j*d%d%d%d%d& j"rj2r| j3j2d j2d j4j5d' td( j6d)k	rD| j3j6d)d)df j6d)d)df j7j8d*d+d, td- jrjd jd jd jd f}tj9| ||j d} jrt|j\ f
d.d/}|| _:nd0_td1 jrtd tj| d)j d td2 jd d3 jd d3 jd d3 jd d3 f}	| j#jj$d j$d |	djdd4}
| j1j*d5 j"rd6\}}j;rj;d j;d  }}n(d7|< krt=|d7 t=|d8  }}|r|r| j3||j4j5d' td( j>d)k	r>| j3j>d)d)df j>d)d)df j7j5d9d+d, td- d}|rt?@d:d;gd<d=gd<d>gd?d@gd:d;gg}| j3|d)d)df |d)d)df dAj5d9d+d, | A|	dd  | B|	ddB  tCjDEtCjDF|dC dDtCjDGrVz4tHjIdEjddFd 	tHjIdGjddFd 
W n2   dHtCjDJ}|dI7 }t| d)Y nX nd)	
fdJd/}|| _:d)}jKrtL| }|jMjNjOjOtPjQdK}tR|
|\}jSr| jTjUj*jVdL jWrtdM | X  jYrtdN | Z  j[s"| \dO tdP j]rD| j^_d% | j`_d% n| a bg  | c bg  | |
|fS )Qa?  Plot one slice of matrix
    Parameters: ax   : matplot.pyplot axes object
                data : 2D np.array,
                metadata : dictionary, attributes of data
                inps : Namespace, optional, 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:    import matplotlib.pyplot as plt
                import mintpy.utils.readfile as readfile
                import mintpy.view as pv
                data, atr = readfile.read('velocity.h5')
                fig = plt.figure()
                ax = fig.add_axes([0.1,0.1,0.8,0.8])
                ax = pv.plot_slice(ax, data, atr)[0]
                plt.show()
    c                  _   s   d S rX   rI   rY   rI   rI   rJ   r[     r\   zplot_slice.<locals>.<lambda> r  vlist)r   r   r*   zdisplay data in transparency: r   r   zplot in geo-coordinatez#draw coast line with resolution: {})
resolutionzplotting DEM background ...)axr   demr   r*   zplotting image ...)siteFr   r   rM   r   z<referencing InSAR data to the pixel nearest to GPS station: z at z by substrating z.3fr]   r   uppernearest)	cmapvminvmaxextentorigininterpolationalphaanimatedzorderr      zplot scale bar: {})r   unitloclabelpad	font_size)rl   lalo_loclalo_max_numr,  
projectionr*   bothinT)which	direction	labelsizeleftrighttopbottommszplot reference pointNkr   )r:  mecmewzplot points of interestc           	         sd  d | |} j| ddjd  } j|ddjd  }d|  krRk r`n nd|  krn	k r`n n||f }t|stj|r|d7 }n|d |7 }jr<j| ddd  }j|ddd  }d|  krk r<n nBd|  krk r<n n&||f }t|s<|d	 |7 }|d
 |jd  |jd  7 }|S )NzE={:.4f}, N={:.4f}lonr   r   latrM   , v=[]
, v={:.3f}z
, h={:.0f}z, x={:.0f}, y={:.0f})rg   lalo2yxr   r   r  r   r  rN   )	r   r   r   colrowvZdem_colZdem_rowh)
r   	coord_demr  r  dem_lendem_pix_boxdem_widr   num_colnum_rowrI   rJ   format_coordu  s&    6
6z plot_slice.<locals>.format_coordr   zplotting in Y/X coordinate ...zplotting Data ...      ?)r  r   r!  r"  r$  r%  r'  )r4  NNREF_YREF_Xblacki  i  i  i  i  i  i  r   r   r   zinputs/geometryRadar.h5latituder   	longitudez4WARNING: no latitude / longitude found in file: {}, z'skip showing lat/lon in the status bar.c                    s   d | |}tt| jd  }tt|jd  }d|  krPk rn nd|  krhk rn n ||f }t|stj|r|d7 }n|d |7 }jrЈ||f }t|s|d |7 }r|d ||f ||f 7 }|S )Nzx={:.1f}, y={:.1f}r   rM   r@  rA  z, h={:.0f} mz, lat={:.4f}, lon={:.4f})	rg   r:   r   rintr   r  r   r  rN   )r   r   r   rC  rD  rE  rF  )r  r  	geom_filer   latslonsrK  rL  rI   rJ   rM    s    0

 )pad
axes_class)fontsizecolorzflip figure left and rightzflip figure up and downoffzturn off axis display)dr*   r{   r|   r   r   
isinstancer   r9   r   ColormapExtr  
cmap_vlistrN   read_demr   r   r   r   r   r   r   r   rg   
coastlinesplot_dem_backgroundr   r   disp_gpsgps_componentref_gps_siter   Zget_stat_lat_lonr   r   disp_ref_pixelimshowr   	animationdisp_scalebarZscalebardraw_scalebarscalebar_padr,  rm   draw_lalo_labelrl   r-  r.  r   tick_paramsr   r   
ref_markerref_marker_sizepts_lalo
pts_markerpts_marker_sizeplot_gpsrM  r   rz   r:   pts_yxr   arrayset_xlimset_ylimrc   rd   r}   r   re   r   r  r   rr   r   append_axescbar_loc	cbar_sizer   Axesplot_colorbarrq   	set_titler   
font_colorrt   invert_xaxisru   invert_yaxisrp   axisrs   xaxisset_visibleyaxis	get_xaxis	set_ticks	get_yaxis)r  r  r   r   dem_metadataZref_site_lalor   r   ref_datar"  imSNWErM  r  r  Z	temp_testru  r   cbardividercaxrI   )r   rG  r  r  rH  rI  rJ  rV  r   rW  rX  rK  rL  rJ   
plot_slice  s~   





 
  &     (
    $   



     $  0
r  c                 C   s  t | j}d}| jds.|d|d 7 }|d|d tj| j7 }d| krj|d|d 7 }t	d	tj
ttj t	| t|d
 | _t|d | _|d | _tjtj
| jd | _tj| jd | _t	d| j| jf t j| jdd| _t| \} }| |fS )Nzinput file is )z.h5z.he5z{} 	PROCESSORz{} file: {}	FILE_TYPE	DATA_TYPEz in {} formatzrun {} in {}LENGTHWIDTHr   rM   zfile size in y/x: {}T)
no_complex)r   ry   r   endswithrg   rc   rd   abspathrz   r|   r   __file__r   version_descriptionr:   r   r   r   splitextZfileBaseZfileExtget_slice_list	sliceListread_dataset_input)r   atrr   rI   rI   rJ   read_input_file_info  s$    
r  c                    s   dd |D }|rt |tr"|g}g }|rj|D ]8dkrDddd|fdd D 7 }q.n| fdd|D 7 }ttt|}| fdd|D 7 }ttt|} fd	d|D }||fS )
z0Get dataset(es) from input dataset / dataset_numc                 S   s   g | ]}|qS rI   rI   r   r   rI   rI   rJ   r   5  s     z(search_dataset_input.<locals>.<listcomp>r   z*{}*z.*c                    s    g | ]}t  |d k	r|qS rX   )rematchr   e)dsrI   rJ   r   E  s    c                    s   g | ]}| kr|qS rI   rI   r   allListrI   rJ   r   I  s      c                    s   g | ]}  |qS rI   )indexr  r  rI   rJ   r   K  s     c                    s   g | ]} | qS rI   rI   r   r  rI   rJ   r   Q  s     )r^  r9   rg   r   sortedrw   rx   )r  ZinListZ	inNumListr$   tempListZ
outNumListZoutListrI   )r  r  rJ   search_dataset_input2  s"    

r  c           	         s  t jdkst jdkrt jdkr:tdj jdkr\d_tdj nHjdkrt jdkrdjd krjd d\}}|g_|_t	j
jjjd _njd	krd
g_njdkrdg_ntjdkrd_nbjdkr8tj}|jdd |j
d dd g_n&j
_jdkr^dd jD _t	j
jjjd _t	j
jg j\__g }tj}js|d d	krtd tj   fddj
D }fdd|D }ntd|d  d_tttjtj t| _fddjD _t j_jrjtkrtd_t	j
jgg jd d }|stdj d_n|_jdkrtdtjjt j
 td t j td!t j nPtdtjjt j
 td"t jj td#t jj jrjtkrtd$j jdkrd%}|d&j
7 }t|tjjjd dd d'}|fS )(zFCheck input / exclude / reference dataset input with file dataset listr   zinput dataset: "{}"velocityFz#turning glob search OFF for {} filer   rM   _r
   unwrapPhaseHDFEOSdisplacementgiantTimeseriesreconsr   r   r   geometryc                 S   s   g | ]}| d s|qS bperp)r   r  rI   rI   rJ   r   }  s     
 z&read_dataset_input.<locals>.<listcomp>r  z&do not show the dropped interferogramsc                    s"   g | ]}| d d  kr|qS )r   rM   r   r  )date12_drop_listrI   rJ   r     s      c                    s   g | ]} j |qS rI   )r  r  r  r   rI   rJ   r     s     zH--show-kept option does not apply to file type: {}, ignore and continue.Tc                    s   g | ]} j | qS rI   )r  r   r   rI   rJ   r     s     NzVWARNING: input reference date {} is not included in input file! Ignore it and continuer
   znum of datasets in file {}: {}znum of datasets to exclude: {}znum of datasets to display: {}zdatasets to exclude ({}):
{}zdatasets to display ({}):
{}zinput reference date: {}zNo input dataset found!z
available datasets:
{}r   )r   r   r    r|   rg   r   r$   r   ref_dater  r  r   r   openr'   ZexDsetNumListr   ry   r(   r
   get_drop_date12_listr  rw   rx   dsetNumr   r{   rc   rd   r   	Exception)	r   date1date2objZdrop_num_listr  Zdrop_slice_listr  r   rI   )r  r   rJ   r  V  s    
&





&   r  c                    s  t  jd  jd  }t  jd  jd  } jdkr jsFd _ js jr jdkrt jd  jd  }t jd  jd  }tj	||f j
 jd _n jstj _td jd  jd   jsd _ jt  j d	kr  jd7  _q jdkrx jdkrxt fd
ddD rx|d |g} jd d  jd g}t j|| j\ _ _tt  jt  j j  t _tdt j  tdt j  tdt j  tdt j   jsd _ j j dkrd _ jrZtj jd  _tjtj jd \ _  _! j!"  _!ntj j# _tjtj j#d  _  jd  jd   jd  jd   || k rƈ  j d7  _  j$r  j d7  _  j%d  j%d  dtj& kr  j t j%d  j%d  7  _  j'r:  j d j' 7  _  j(rP  j d7  _  jdkrrd j  j!g _n  fddt)d jd D  _ fdd jD  _ S )zUpdate figure setting based on number of subplots/datasets
    1) fig_size and font_size
    2) for multi: figure/row/column number
    3) for multi: output file name
    r   rM   r   r      r   )ds_shaperr   r*   zfigure size : [{:.2f}, {:.2f}]g      d@c                 3   s   | ]}| j kV  qd S rX   ra   r   r   rI   rJ   r     s     z(update_figure_setting.<locals>.<genexpr>)z--nrowsz--ncols皙?gffffff?zdataset number: zrow     number: zcolumn  number: zfigure  number:    2      _sub_wrapZ_refZ_exr   c                    s"   g | ]}d   jt| jqS )z{}_{}{})rg   outfile_baser9   r   r   jr   rI   rJ   r     s   z)update_figure_setting.<locals>.<listcomp>c                    s   g | ]}t j j|qS rI   )rc   rd   r}   outdir)r   ri   r   rI   rJ   r     s     )*r   r   r  r,  fig_sizer   r   absr   auto_figure_sizerr   r*   default_figsize_multir|   rg   fig_numfig_row_numfig_col_numr  auto_row_col_numr   ceilastyper:   r9   ri   rc   rd   r   r  r  r   r  r   r   r   r   r   r
  r  r'   range)r   r   r   
data_shapeZfig_size4plotrI   r   rJ   r     s    


"2 "
r   c              	      s  t j||  t jd  jd   j t jd  jd   j ft jd}t jdkr jdkrt	d  fdd	t
| |D }t| j j j jd
}|dddstj jf|d |dd< n*t	d t tj jf|d |dd<  jdkrB jd drB jrB j\}}|||d |d f}	tj j||	ddd }
t
|jd D ]8}||ddddf dk}|||f  |
| 8  < qhnt	d tj||   jd}t
| |D ]n}tj j j|  j j jdd
d }||||  ddddf< |j||  d  j| dd d q|   jrt	d j  tj j j j j jdd
d }
||
8 }t jdks jdkst fdddD s jdd d!gks jd"d	 t
t jD krd#}nd}|rt|| \} n&t fd$dd%D r,td& d _  j!rTt	d' t j"#|dk|} j$dk	rt	d( t % j$|jd ddf}t j"#|dk|}t &|t '|g _(|r
t fd)dd*D r
 jd d+r jr
 jd d,kr
t)j*|d-dd.\ _+ _,|S )/zIRead multiple datasets for one figure into 3D matrix based on i_start/endr   rM   r   r   dtype)r   r  r
   r  r  zreading data as a 3D matrix ...c                    s   g | ]} j | qS rI   )r   r   r   rI   rJ   r   "  s     z$read_data4figure.<locals>.<listcomp>r   r   xstepystepr*   r  float32complexNz;input data is complex, calculate its amplitude and continuer
   r  Fr   r   z)reading data as a list of 2D matrices ...maxValuer*   /r   suffixzconsider input reference date: )r   Z	inversionc                 3   s   | ]}| j kV  qd S rX   )dsetFamilyList)r   dr   rI   rJ   r   _  s     z#read_data4figure.<locals>.<genexpr>)
horizontalverticalr  modelresidualc                 S   s   g | ]}d  |d qS )zband{}rM   rg   r   rI   rI   rJ   r   a  s     Tc                 3   s   | ]}| j kV  qd S rX   r  r  r   rI   rJ   r   j  s     )z-uz--unitzeWARNING: -u/--unit option is disabled for multi-subplots with different units! Ignore it and continuemasking pixels with zero valuemasking datac                 3   s   | ]}| j kV  qd S rX   r  )r   argr   rI   rJ   r   z  s     )z-vz--vlimz--wrapunwrapr  
   )num_multilookr*   )-r   zerosr:   r   r   r  r   r  r   r|   r  dictr*   r   r   r   r  r   r  file_ref_yxr   r   progressBarr   updater   closer  r  r  r   r{   r   rn   r   masked_wheremskr  r  r  r  r   r  r  r   )i_starti_endr   r   r  	dset_listrZ   r  r  r  r  r   maskprog_barr  Zsame_unit4all_subplotsr  rI   r   rJ   read_data4figure  s    
"
*r  c              
   C   s  |j r&tj|d|j|j|j||jd |j}|dkrHt	|t
|g}|jd d |jd d |jd d |jd d f}|j||j|d |d d|j|dd	}|jrd
\}}	|jr|jd |jd  }}	n&d| krt|d t|d  }}	|r|	r|j|	||j|jd ||dd  ||dd  |jrV|j|j dkrr| g  | g  dd }
|
|_|jrd}|j t!ks|j"d #dr|j"|  $dd%dd }zt&j'(|d) dd }W n   |}Y nX n|j"|  }|j*+|}t,|j-dkrRd|krR|%dd }|j.d dkrR|j/+|}|j|j }|dkrn|}nfd|  k rdkrn nd0||}n<d|  k rdkrn n|$dd$dd}n
d0|}|r|j1rt2|j3d}tj4||d|d  nt2|j3d!}|j"|  |j5kr2d"|d#< d$|d%< np|6d&dd'kr|j7r|d( % |  }|d)krvtj8d |d#< ntj8d |d#< |d* % |  }|d+0|7 }|j9|f| |j:r|;  |j<r|=  |j>s|?d, |S )-zPlot one subplot for one 3D array
    1) Plot DEM, data and reference pixel
    2) axes setting: tick, ticklabel, title, axis etc.
    N)r  r   	dem_shadedem_contourdem_contour_seqr   r*   r   rN  r   r   rM   r  )r  r   r!  r$  r%  r"  r'  rO  rP  rQ  r9  r   r  c                 S   s   d | |S )Nzx={:.1f}, y={:.1f}, v =r  )r   r   rI   rI   rJ   rM    s    z)plot_subplot4figure.<locals>.format_coordr  r  r   z%Y%m%dr  r
         z{}
{}r  r  
z{})size)r*  prop)r[  crimsonr\  bold
fontweightPLATFORMSenZSENTINEL1_SENSORAZSENTINEL1_IPFz : {}r]  )@rN   r   rc  r  r  r  r*   r   r   r  r  r   rh  r   r   rg  r   rz   r:   r   ro  rp  rw  rx  rs   r  r  r  r  r  rM  rq   r   r   r   r   r   r   dtdatetimestrptime	isoformatr  r  r   r  r  
date12Listrg   fig_title_inr  r,  add_inner_titledropDatasetListr   disp_title4sentinel1	mplColorsr~  rt   r  ru   r  rp   r  )r   r   r  r  r   r   r"  r  r  r  rM  Zsubplot_titledate_strZ	title_strZ	title_indZnum_subplotr
  kwargZ	s1_sensorZs1_IPFrI   rI   rJ   plot_subplot4figure  s       





r  c              
   C   sP  d t| |j| d  }td t| tj| |j|j|jddd\}}|j	j
| | }| d |j |j }t|j||j|j  g}t||||}t|jtrtj|j|j|jdj|_td tj|| |jd}	t||D ]}
|
| }t|
||| ||d	d	d	d	f |d
}|jrt|jst|j||| ddddd}tj|j |j!|
 d"dd	}|rt|#| |	j$|d |j!|
 %dd d q|	&  ~t|| t'|D ]}
|(||
  qt)*|j+d |j,d gt)-|j+d |j,d gg|_+td |j,|j. |jr0td |j|j. dd }|jr|jstd td |/|jd d |jd  ||| nf||| d}|jd dkr|d }td  |j0d!d" |1d#d$| d d%|g}t2|||\}}n
||| |j3rLtd& t4j56|j| d  |j7 |j8|j| d  d'd|j7d( |j9sL|:  d	S ))zPlot one figure with multiple subplots
    1) create figure
    2) read all data into 3D array
    3) loop to plot each subplot using plot_subplot4figure()
    4) common colorbar and save
    zFigure {} - {}rM   (----------------------------------------T)numfigsizenrowsncolssharexshareyr  zplotting ...r  N)r  r  r   gQ?rN  r(  r  )r  rY  shrinkaspectorientationr  UNITr  r   r  r   r   r   c                 S   sH   | j ddddddd |js"|jr6| j |j|jd n|jrD|   d S )Ng{Gz?g\(\?g?)r5  r6  r8  r7  wspacehspace)r*  r)  )subplots_adjustfig_wid_spacefig_hei_spacefig_tight_layouttight_layout)figr   rI   rI   rJ   adjust_subplots_layout?  s      z+plot_figure.<locals>.adjust_subplots_layoutz-Note: different color scale for EACH subplot!z0Adjust figsize for the colorbar of each subplot.r  g?g       @r   zshow colorbarg(\?)r6  gGz?r   g{Gzt?save figure to {} with dpi={}tight)bbox_inchestransparentdpi);rg   r9   ri   r|   r   subplotsr  r  r  canvasmanagerset_window_titleflattenr   r  r  r^  r   r   r_  r  r`  r   r  r*   r  r  rr   r   colorbarr   ry   r   r   r   	set_labelr  r   r  r   delaxesr   r  dlim_allr  r  r   set_size_inchesr+  add_axesr}  rk   rc   rd   r  fig_dpisavefigrj   clf)r  r   r   r   r0  axsr  r  r  r  r   idxr  r  	data_unitr1  Zcbar_lengthr  rI   rI   rJ   plot_figure  s    


$

$rH  c           
         s  t ttdd | jD | _t ttdd | jD | _t| jdkrv| jd dkrvt ttdd | jD | _| j	dkr| j
rtd| j	 n2| jr| j	dkrtj| j| j| j | j| j
d	| _	| jd
k	r| j	dkrt| j| j	| j	dd| _d
| _| jdkrd krtd td  }}td td  }}d|  krb|k rn n6d|  kr~|k rn n||g| _td| j | jdkr|  jd  _n| jdkr|  jd  _g | _| jdkr<| jr<t| j }|j!dd |" }| jD ]"|  jfdd|D 7  _qtd | j#rt$%| j# t& fdddD rtdt'j()| j# t$j*| j#d | j| j	| j	dd!d }tj+|| | j
d"\| _,| _-| _.n(d
| _#d#| _/d$}	|	d%7 }	|	d&7 }	t|	 | S )'zPrepare for multiple subplots:
    1) check multilook to save memory
    2) read existed reference pixel info for unwrapPhase
    3) read dropIfgram info
    4) read and prepare DEM for background
    c                 s   s   | ]}| d d V  qdS )r   r   Nr  r  rI   rI   rJ   r   q  s     z)prepare4multi_subplots.<locals>.<genexpr>c                 s   s   | ]}| d dV  qdS )Stdr  N)r   r  rI   rI   rJ   r   r  s     rM   r  r
   c                 s   s   | ]}| d d V  qdS )r   rM   Nr  r  rI   rI   rJ   r   t  s     z/multilook {0} by {0} with nearest interpolation)
max_memoryr*   Nr  )methodr  rP  rQ  r  r  r   z#consider reference pixel in y/x: {}r  g      $@d   g      4@Fr   c                    s   g | ]}d   |qS )z{}-{}r  r  )r   rI   rJ   r     s     z*prepare4multi_subplots.<locals>.<listcomp>z@mark interferograms with 'dropIfgram=False' in red colored titlec                 3   s   | ]} | | kV  qd S rX   rI   r   )r  r   rI   rJ   r     s     )r  r  zreading DEM: {} ... heightr  )r  r   r*   r   z;WARNING: DEM file has a different size from the data file. zNThis feature is only supported for single subplot, and not for multi-subplots.z 
    --> Ignore it and continue.)0r  rw   rx   r   r  r   r  r  r  r   r*   r{   rg   r   r   auto_multilook_numr   r  r  	maxMemoryr  r   r  r   rz   r:   r|   r  rp  r  rq   r
   r   r  r  rN   r   ry   r  rc   rd   r   r  prepare_dem_backgroundr  r  r  r   )
r   r   r  r  r   r   r  ZdropDate12Listr  r   rI   )r  r   r   rJ   prepare4multi_subplotsj  s    8


 	rQ  Fc              	   C   sR  t |  dd }t|  t|\}}t||}tj|j|j|j	d |j
|j|j|jd\|_|_tj|j|j	d |j
|jd\}}|jr|tj|j|j|j
ddd 8 }|jdkr>|j	d dd d	r>d
| kr>t|d
 t|d  }}tj|j|j	d |||d |d fddd }||dk  |8  < |jrXtj|dk|}|jdk	rztj|jdk|}ntj|jtjd|_tj|r| j|j 9  _| jt|j  9  _n| jt| 9  _t!|||\}}|dkrDdd |j"D }|j#dk	r t$|j#dni }	t%j&|d|	d\}
}||||fS |||fS dS )a  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:
        subplot_kw = dict(projection=ccrs.PlateCarree())
        fig, ax = plt.subplots(figsize=[4, 3], subplot_kw=subplot_kw)
        W, N, E, S = (-91.670, -0.255, -91.370, -0.515)    # geo_box
        cmd = 'view.py geo_velocity.h5 velocity --mask geo_maskTempCoh.h5 --dem srtm1.dem --dem-nocontour '
        cmd += f'--sub-lon {W} {E} --sub-lat {S} {N} -c jet -v -3 10 '
        cmd += '--cbar-loc bottom --cbar-nbins 3 --cbar-ext both --cbar-size 5% '
        cmd += '--lalo-step 0.2 --lalo-loc 1 0 1 0 --scalebar 0.3 0.80 0.05 --notitle'
        data, atr ,inps = view.prep_slice(cmd)
        ax, inps, im, cbar = view.plot_slice(ax, data, atr, inps)
        plt.show()
    rM   Nr   rO   r   r   r   r!  r*   r   Fr  r   r  rP  rQ  r   r  Tc                 S   s   g | ]}|d  qS )g       @rI   r   rI   rI   rJ   r     s     zprep_slice.<locals>.<listcomp>r/  Figurer   r  
subplot_kw)'r   r   r|   r  r   r   	read_maskr   rO   r   r   	mask_vmin	mask_vmaxr*   r  r   r  r  r   r   rz   r:   rn   r   r   r  onesr   bool_r  r   r  r  r  r  r   r  r   r7  )cmdZauto_figr   r  r  r  r  r  r   rV  r0  r  rI   rI   rJ   
prep_slice  sn    
	



r]  c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
viewerzClass for view.py

    Example:
        import matplotlib.pyplot as plt
        from mintpy.view import viewer
        cmd = 'view.py timeseries.h5'
        obj = viewer(cmd)
        obj.configure()
        obj.plot()
    Nc                 C   s$   |r|  dd  }|| _|| _d S )NrM   )r   r\  r   )selfr\  r   rI   rI   rJ   __init__  s
    zviewer.__init__c              	   C   s   t | j}t|\}| _t|| j}d| _|jrH|jsHt|dkrHd| _|j	
 D ]\}}t| || qRtj| j| j| jd | j| j| j| jd\| _| _| jS )Nr   r   r   rR  )r   r   r  r  r   r   update_moderj   r   __dict__itemssetattrr   rW  r   rO   r   r   rX  rY  r*   r  )r_  r   r   valuerI   rI   rJ   	configure"  s"    
zviewer.configurec                 C   s  | j dkrtd tj| j| jd | jdd\}| _| jr\|tj| j| j| jddd 8 }| j	dkr| jd 
dd drd	| j krt| jd	 t| jd
  }}tj| j| jd |||d |d fddd }||dk  |8  < | jrtd tj|dk|}| jd k	r:td tj| jdk|}ntj|jtjd| _t| j}| jd k	rtd| j  tj|| jk|}n6|d k	rt|std|  tj||k|}tj|r|  j|j 9  _|  jt|j 9  _n|  jt| 9  _t|| j| \}} | jd k	r<t| jdni }tj | j!d|d\}}| j"sp|j#ddddd t$||| j| d } | j%rtd&t'j()| j*d | j+ | j"s|j,| j*d d| j+dd n|j,| j*d d| j+dd | j-s|.  ndddddddd g}	t/t0|	t0| j1@ }	|	D ]}
t2d!&|
 q*t3| | jd"} ddg| _4t5d| j6d D ]}t7|| | jd" qh| j6dkrtd# td$&| j4| j8 | j9rtd%&| j9| j8 | j-rtd& t:  d S )'NrM   zreading data ...r   Fr   r  r   r  rP  rQ  r   r  r  r  z%masking pixels with NO_DATA_VALUE of rS  rT  rU  )r5  r6  r8  r7  r2  T)r5  r6  
pad_inchesr3  )r5  r6  r4  rR   rS   rT   rU   rV   z--pts-yxz
--pts-laloz
--pts-filezHWARNING: {} is NOT supported for multi-subplots, ignore it and continue.)r   r  zall data range: {} {}zdisplay  range: {} {}zshowing ...);r  r|   r   r  r   r   r   r  r  r   r   r   rz   r:   rn   r   r   r  r  rZ  r   r[  get_no_data_valueno_data_valuer  r  r   r  r  r   r  r   r7  r  ro   r+  r  rk   rg   rc   rd   r  ri   rB  rC  rj   rD  rw   rx   ra   r{   rQ  r?  r  r  rH  r   r   show)r_  r  r  r  r  Zno_data_valrV  r0  r  Z	opt_namesr   r  rI   rI   rJ   r   ;  s    

 

  
zviewer.plot)NN)__name__
__module____qualname____doc__r`  rf  r   rI   rI   rI   rJ   r^    s   

r^  c                 C   s(   t | d}|  |jdkr$|  d S )N)r   r   )r^  rf  r   r   )r   r  rI   rI   rJ   main  s
    

ro  __main__rM   )N)T)N)F)N)@rc   r`   r  r3   r  r  numpyr   matplotlib.pyplotpyplotr   mpl_toolkits.axes_grid1r   warningsfilterwarningsUserWarningcartopy.crscrsr   mintpy.objectsr   r   r	   r
   r   r   Zmintpy.objects.gpsr   mintpy.utilsr   r   r   r   r   r   r   mintpy.multilookr   mintpyr   r   r6   r;   rK   r   r   r~   r   r   r  r  r  r  r  r   r  r  rH  rQ  r]  r^  ro  rk  ra   rI   rI   rI   rJ   <module>   sR     /
@i
5\
  #$iWnxnT
Q 
	
