U
    bb6X                     @   sD  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
mZmZmZmZ zd dlmZ W n ek
r   edY nX d dlZ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
Z"dd Z#d'ddZ$d(ddZ%d)ddZ&dd Z'dd Z(d*ddZ)dd  Z*d!d" Z+d+d#d$Z,e-d%kr@e,ej.d&d  dS ),    N)etree)ZipFile)pyplotcolorscolorbarticker)KML_ElementMakerzCan not import pykml!)timeseriesKeyNames)	arg_group	attributeptimereadfileutilsplot)subseta  example:
  save_kmz.py geo/geo_velocity.h5 
  save_kmz.py geo/geo_velocity.h5 -u cm --wrap --wrap-range -3 7

  save_kmz.py geo/geo_timeseries_ERA5_ramp_demErr.h5 20101120
  save_kmz.py geo/geo_timeseries_ERA5_demErr.h5 20200505_20200517

  save_kmz.py geo/geo_ifgramStack.h5 20101120_20110220
  save_kmz.py geo/geo_geometryRadar.h5 height --cbar-label Elevation

  # to generate placemarks for the file in radar coordinates, the corresponding
  # geometry file with latitude & longitude in radar coordinates are required,
  # such as provided by ISCE + MintPy workflow
  save_kmz.py velocity.h5 --sub-x 300 800 --sub-y 1000 1500 --step 1
c               	   C   s  t jdt jtd} | jddd | jdddd	 | jd
ddddd | jddddd | jddddd | jddddddd | jdd d!dd"d | jd#d$td%d&d' | jd(d)d*d+d,td-d. | jd/d0d1d2d | jd3d4d5d6d7d8d9 | jd:dd;d< | jd=d>td+d?tj tjgd,d@dA | 	dB}|jdCdDdEtdFdGdH |jdIdJdKtd+dLdM |jdNdOdPdQdRdSgdPdTdU |jdVdWdXdYdZd[ |jd\d]dEtd^d_ | 	d`}|jdadbdcddd |jdedfdgdhdid[ |jdjdkdEtd%dldH |jdmdndodpdqd[ t
| } | S )rNz[Generate Google Earth KMZ file (overlay / placemarks for files in geo / radar coordinates).)descriptionformatter_classepilogfilezfile to be converted, in geo or radar coordinate.
Note: for files in radar-coordinate, the corresponding lookup table
in radar-coordinate (as provided by ISCE) is required.)helpdset?z?date of timeseries, or date12 of interferograms to be converted)nargsr   z-mz--mask	mask_fileFILEzmask file for display)destmetavarr   z--zero-mask	zero_mask
store_truezMask pixels with zero value.)r   actionr   z-oz--outputoutfilez3output file base name. Extension is fixed with .kmz)r   r   z--kkz
--keep-kmlz--keep-kml-filekeep_kml_filezJDo not remove KML and data/resource files after compressing into KMZ file.z-gz--geom	geom_filezDgeometry file with lat/lon. [required for file in radar coordinates]z--stepstep   zroutput one point per {step} pixels, to reduce file size (default: %(default)s).
For file in radar-coordinate ONLY.)r   typedefaultr   z-vz--vlimvlim   )MINMAXzY/value limits for plotting.)r   r   r   r%   r   z-u	disp_unitUNITzunit for display.z-cz--cmz
--colormapcolormapjetz#Colormap for plotting. Default: jet)r   r&   r   z--wrapz(re-wrap data to display data in fringes.)r   r   z--wrap-range
wrap_rangeg      z5range of one cycle after wrapping, default: [-pi, pi])r   r%   r   r&   r   r   Figurez--dpifig_dpiNUMiX  z(Figure DPI (dots per inch). Default: 600)r   r   r%   r&   r   z	--figsizefig_size)WIDLENz(Figure size in inches - width and length)r   r   r%   r   r   z
--cbar-loccbar_loc
lower leftzlower rightz
upper leftzupper rightz8Location of colorbar in the screen. Default: lower left.)r   choicesr&   r   z--cbar-label
cbar_labelZLABELMean LOS velocityz*Colorbar label. Default: Mean LOS velocity)r   r   r&   r   z--cbar-bin-numcbar_bin_numz+Colorbar bin number (default: %(default)s).)r   r   r%   r   zReference Pixelz--noreferencedisp_ref_pixelstore_falsezdo not show reference pointz--ref-colorref_marker_colorZCOLORkzmarker color of reference pointz
--ref-sizeref_marker_sizez6marker size of reference point (default: %(default)s).z--ref-marker
ref_markerZSYMBOLsz marker symbol of reference point)argparseArgumentParserRawTextHelpFormatterEXAMPLEadd_argumentintfloatnppiadd_argument_groupr
   add_subset_argument)parserfigref rQ   E/home/centos/operations/rsmas_insar/sources/MintPy/mintpy/save_kmz.pycreate_parser8   sr    
 


rS   c                 C   s   t  }|j| d}tjtj|j|_t	|j}d|
 krddg}|jsdtj||jdd|_|jrxtj|jstd| d|js|d	 d
gt krtd|d	 td |S )N)argsY_FIRSTlatitude	longituderadar)work_dircoordzNo geometry file with z in radar coord found!	FILE_TYPEifgramStackz/No date/date12 input.
It's required for {} fileAgg)rS   
parse_argsospathabspathdirnamer   rY   r   read_attributekeysr"   utget_geometry_fileisfileFileNotFoundErrorr   r	   	Exceptionformatpltswitch_backend)iargsrN   inpsatrZgeom_ds_listrQ   rQ   rR   cmd_line_parset   s$    
rp   cm/yearr.   g
ףp=
?g@r:   c                 C   s   t j|d\}}	tj||d}
tj|	t ||
dd}|jd||dd |rft	j
|d|_|  |jjd	dd
 |jd |jd td|  |j| d| dd | S )N)figsizevminvmaxvertical)cmapnormorientationz{} [{}]   )fontsize)nbinsboth)which	labelsizewhitegffffff?writingtighti,  )bbox_inches	facecolordpi)rk   subplotsr   	Normalizer   ColorbarBaseget_cmap	set_labelrj   r   MaxNLocatorlocatorupdate_ticksaxtick_paramspatchset_facecolor	set_alphaprintsavefigget_facecolor)out_fileru   rv   unitrx   rs   r}   labelrO   caxry   cbarrQ   rQ   rR   plot_colorbar   s    
r   r7   c                 C   s   t | ||||||d} | d dkr0d\}}	n| d dkrHd\}}	| d dkrbd\}
}n| d d	krzd\}
}ttd
ttdtj	
| tdtj|
|dddtj||	dddtjdddddtdtdtd}|S )N)r   ru   rv   r   rx   r}   r   r   lower)0r   upper)1r      leftrightr   z{}g      ?fraction)xyxunitsyunitsr   Z250pixel)r   splitKMLZScreenOverlaynameIconhrefrj   r_   r`   basenameZviewBoundScaleZ	overlayXYZscreenXYsizerotationZ
visibilityopen)	cbar_fileru   rv   r   rx   locr}   r   oysyoxsxcbar_overlayrQ   rQ   rR   generate_cbar_element   s>    

r   c                 C   s>   ||| }t j|d |d |d |d gdddd }|S )a
  Get color name in hex format.
    Parameters: v        : float, number of interest
                colormap : matplotlib.colors.Colormap instance
                norm     : matplotlib.colors.Normalize instance
    Returns:    c_hex    : color name in hex format
       r(   r   r   T)
keep_alphaN)r   to_hex)vr-   ry   rgbaZc_hexrQ   rQ   rR   get_hex_color   s    .r   c                 C   s   t t t t t||j|jt dt 	t 
|t t jt | ddddt jt |ddddt jt |dddt jt |dd	dt jt |d
d|j ddt t | d|  }|S )a]  Create an KMZ Placemark element.
    Parameters: lat/lon   - float, latitude / longitude in degrees
                row/col   - int, row / column number
                val       - float, value
                icon_file - str, path of the icon file
                inps      - Namespace object
    Returns:    placemark - KMZ.Placemark() object
    g      ?z.6fu   ˚Latitude)r   	Longitudez.0fZRowColumnz.2f Value,)r   Z	PlacemarkStyle	IconStylecolorr   r-   ry   scaler   r   ZExtendedDataDatavaluer+   Pointcoordinates)latlonrowcolval	icon_filern   	placemarkrQ   rQ   rR   create_placemark_element   sF    

)r   Fc              	   C   sv  |dkrg n|}|dkrg n|}t j| }d| }d| }t }|| td|  t|d }	|		t
j|ddd W 5 Q R X |rt jt jtjd	}
|D ]4}t j|
t j|}t|| td
| qt jt  }t | t|dL}|g| | D ]6}|	t j| |st | td| qW 5 Q R X t | td| |S )zWrite KML and KMZ files.
    Parameters: out_file_base - str, output file name without extension
                kml_doc       - KML.Document() object
                res_files     - list of str, rel path of resource files
    Nz{}.kml{}.kmzzwriting wT)pretty_printutf8datazcopy {} to the local directoryz	remove {}zmerged all files to {})r_   r`   rb   rj   r   kmlappendr   r   writer   tostringdecodejoinmintpy__file__r   shutilcopy2ra   getcwdchdirr   relpathremove)out_file_basekml_doc
data_files	res_filesr!   rY   Zkml_filekmz_filer   fZres_dirfnamesrc_fileZrun_dirfzrQ   rQ   rR   write_kmz_file  s6    


$


r   c                 C   sH  t |\}}}}td |js<tj|| || gdd|_tj|jdd}|ddddg}	|		  |	j
| |jd |jd	 |jd
dd |dd}
|dd}|jr|
dk	r|dk	r|	jt|
t||j|j|jd td ntd t|d }t|d }|	d|g |	|dg tj|d }|d }td||j tj|dd|jd t }tjtj|d }tt |t!t"tj|t#dt$t%t&|t't&|t(t&|t)t&|}|*| d|}t+||jd |jd	 |j,|j|j-|j.|j/d}|*| t0||||g|j1d}|S )a  Generate Google Earth Overlay KMZ file for data in GEO coordinates.
    Parameters: data     - 2D np.array in int/float, data matrix to write
                meta     - dict, containing the following attributes:
                           WIDTH/LENGTH      : required, file size
                           X/Y_FIRST/STEP    : required, for lat/lon spatial converage
                           REF_X/Y           : optional, column/row number of reference pixel
                out_file - string, output file name
                inps     - Namespace, optional, input options for display
    Returns:    kmz_file - string, output KMZ filename
    zplotting data ...g       @)ds_shaper   F)rs   frameon              ?r   r   autonearest)ru   rv   rx   aspectinterpolationREF_XNREF_Y)r   mszshow reference pointzno plot for reference point.WIDTHLENGTHz.pngzwriting {} with dpi={}T)
pad_inchestransparentr   ZclampToGround{}_cbar.pngru   rv   r   rx   r   r}   r   )r   r!   )2re   four_cornersr   r3   ppauto_figure_sizerk   figureadd_axesset_axis_offimshowr'   r-   getr<   r   rH   rA   r>   r@   set_xlimset_ylimr_   r`   splitextrj   r1   r   r   Documentr   ZGroundOverlayr   r   r   ZaltitudeModeZ	LatLonBoxnorthstreastsouthwestr   r   r+   r6   r;   r9   r   r!   )r   metar   rn   r  r  r  r  rO   r   rxrywidthlengthr   Zdata_png_filer   Zimg_nameZimg_overlayr   r   r   rQ   rQ   rR   write_kmz_overlayF  s~     




r  c                 C   sN  t j|d }d}d}tj|d|jdd }tj|d|jdd }	t }
td d	|}t
||jd |jd	 |j|j|j|j|jd
}|
| t|dd}t|dd}d| krDtd t|d t|d  }}|||f }|	||f }t|||| || d||d}d|_d|jj_|
| tj| ||f< ttd}td	|j | j\}}tj |d}t!d||jD ]}t!d||jD ]^}| ||f }t"|s|||f }|	||f }t|||| || |||d}|| q|j#|d	 d	d|d	  d| d q|$  |
| t%||
||g|j&d}|S )a  Generate Google Earth Placemark KMZ file for data in RADAR coordinates.
    Parameters: data      - 2D np.array in int/float, data matrix to write
                meta      - dict, containing the following attributes:
                            WIDTH/LENGTH      : required, file size
                            X/Y_FIRST/STEP    : required, for lat/lon spatial converage
                            REF_X/Y           : optional, column/row number of reference pixel
                geom_file - str, path of the geometry file with latitude/longitude datasets
                out_file  - string, output file name
                inps      - Namespace, optional, input options for display
    Returns:    kmz_file  - string, output KMZ filename
    r   zshaded_dot.pngzstar.pngrV   datasetNameboxrW   z0plot and add colorbar as a ScreenOverlay elementr  r   r  SUBSET_XMINSUBSET_YMINr   z"add reference point as a star iconr   r   )r   r   r   r   r   r   rn   ZReferencePointr   r   z4generating point element with step size of {} pixels)maxValuezrow=/)everysuffix)r   r!   )'r_   r`   r  r   readpix_boxr   r  r   rj   r   r'   r+   r-   r6   r;   r9   r   rH   r  rd   r   r   r   r   r   rJ   nanZFolderr#   shaper   progressBarrangeisnanupdatecloser   r!   )r   r  r   r"   rn   r   Zdot_fileZ	star_filelatslonsr   r   r   xminyminr  r  ZrlatZrlonZ	ref_pointZdata_folderr  r  prog_barr   r   r   r   r   r   r   rQ   rQ   rR   write_kmz_placemark  s    


	


	(
r3  c                 C   s  t | }t|jd }|dkrF|jrFd|jkrF|jd\|_|_nd |_tj|j|jd}tt	||d |_
t||j
|_
ddt|d t|d f}td| td	|j
 t||j
}tj|j|j|j
d
d }|dkr|jr|tj|j|j|j
d
d 8 }tj|j|j|j|j
dd }|d k	r`td|j tj||dk< |jr~td tj||dk< ~tj|||j|j|jd\}|_|_|_|jr|j|_d}|jst |\}|_t!||j"|_"t#|j"|j"|_"t$j%|jd |jd d|_&tj'|j|jt	|d|_(|j)sBd|j(|_)t*j+,|j)|_)d|- krtt.|||j)|d nt/|||j)|j0|d |j)S )Nr[   
timeseries_)r  r   r   r   zdata   coverage in y/x: {}zsubset coverage in y/x: {}r  )r   r  r  z.masking out pixels with zero value in file: {}z"masking out pixels with zero value)metadatar+   wrapr/      r   rt   )datasetNames	inps_dictr   rU   )r  r   rn   )r  r   r"   rn   )1rp   r   rc   r   r   r   ref_dater   subset_input_dict2boxvarsr&  re   
coordinatecheck_box_within_data_coveragerH   r   rj   attrupdate_attribute4subsetr%  r  	read_maskr   rJ   r'  r   scale_data4disp_unit_and_rewrapr+   r7  r/   
disp_scaler'   'auto_adjust_colormap_lut_and_disp_limitauto_colormap_namer-   ColormapExtr   r   ry   auto_figure_title	fig_titler    r_   r`   ra   rd   r  r3  r"   )rm   rn   r?   ro   data_boxr   maskcmap_lutrQ   rQ   rR   main  sx    
	rM  __main__r   )N)rq   r.   rr   Nr:   )rq   r.   r7   Nr:   )NNF)N)/r_   sysr   rC   numpyrJ   lxmlr   zipfiler   
matplotlibr   rk   r   r   r   Zpykml.factoryr   r   ImportErrorr   mintpy.objectsr	   mintpy.utilsr
   r   r@  r   r   r   re   r   r  r   rF   rS   rp   r   r   r   r   r   r  r3  rM  __name__argvrQ   rQ   rQ   rR   <module>   sD    <
    
    
)6
3^i
W
