o
    e'                     @   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Zd dlZd dlmZ d dlmZmZmZ 	 dZdZd dd	Zd
d Zdd Zdd Zdd Zdd Zdd Zd!ddZdd Zdd Z dd Z!dS )"    N)box)readfile	arg_utilsutilsa  example:
            view_persistent_scatterers.py velocity.h5 --mask ../maskPS.h5 --subset-lalo 25.8755:25.879,-80.1226:-80.1205
            view_persistent_scatterers.py velocity.h5 --mask ../maskPS.h5 --subset-lalo 25.875:25.8795,-80.123:-80.1205 --backscatter --vlim -0.6 0.6
zFPlots velocity, DEM error, and estimated elevation on the backscatter.oTc                 C   s  |j dks
|j dkr| j|j|j|j|j|j|d}n3|j dkrN|j|jj	d k |j
|jj	d k @ }|j
| }|j| }|j| }| j||||j|j|d}|rytj|| dddd	}	|	|j |jd ury|jd |jd f}
||
d |
d  | j d
 | j d
 d S )NZopen_streep_mapgeotiff)cscmapmarkerbackscatterr      Z
horizontalg?)axZshrinkZorientationZpadF)
backgroundZscatterlonlatdata
point_sizecolormapyv	amplitudeshapexvpltcolorbarZ	set_label
cbar_labelvlimZset_climZaxesZ	get_xaxisZset_visibleZ	get_yaxis)r   inpsr   r   ZimmaskZxv_filteredZyv_filteredZdata_filteredZcbarZclim r   D/home/exouser/operations/rsmas_insar/minsar/persistent_scatterers.pyplot_scatter$   s*   "
$



r!   c           	   
   C   s   t | d^}|d }|j}tj|d |d fdd}td|d d}|D ]/}|d }||d	 kr6|d }tjt|d d
d
||d
d
f dd|||d
d
f< q&t|| W d
   d
S 1 sgw   Y  d
S )z
    Calculate the mean amplitude from the SLC stack and save it to a file.

    Args:
        slcStack (str): Path to the SLC stack file.
        out_amplitude (str): Path to the output amplitude file.

    Returns:
        None
    rZslcr      float32Zdtyper   d   N)Zaxis)	h5pyZFiler   npZzerosZarangeZmeanabsZsave)	ZslcStackout_amplitudefZslcsZs_shapeZmean_amplitudelinestlastr   r   r    calculate_mean_amplitude@   s   @"r0   c           #      C   s  g d}dd | j dddD \}}}}dd t|||||gD | _t| jd }tj| jd |d d	\}}tj| j	d
d	d }	tj| j	dd	d }
tj| j	dd	d }|d dkri|d | _
d| _n$|d dkr|| _
d|d  | _| jr|| | j | _
d|d  | _| jr| jd }| jd }t||g}||d |d dd \}}|d dkr|  j
| j
||f 8  _
tj|jtjd}d||	|k < d||	|k< d||
|k < d||
|k< | jrtj| jdd	d }||9 }t|	|dk | _t|
|dk | _t| j
|dk | _
| jdkrt|| j	}|||dd \}}|||dd \}}|||dd \}}|||dd \}}td|||| td|||| td|||| td|||| t||||}t||||}t||||}t||||}td|jd d |jd } td|jd d |jd }!t| |!\} }!|t| |dk  | _ t|!|dk | | _!t" }"t#j$%| j&st'|"| j& t(t)| j&||||f | _*dS dS )z|
    Extract relevant data based on specified coordinates and masks.

    inps:
        inps (Namespace):

    Returns:
    )lat1lat2lon1lon2c                 S   s   g | ]}t |qS r   )float).0valr   r   r    
<listcomp>h   s    z*update_input_namespace.<locals>.<listcomp>:,c                 S   s   i | ]\}}||qS r   r   )r6   keyr7   r   r   r    
<dictcomp>i   s    
z*update_input_namespace.<locals>.<dictcomp>r   )ZdatasetNamelatitude	longitudeZheightZvelocityr&   zVelocity [cm/yr]Zdemz
Dem error ZUNITzEstimated elevation r   Nr#   r%   r   r   zLat, Lon, y, x: )+subset_laloreplacesplitzipcoordsr   Zget_dataset_list	data_filereadgeometry_filer   r   estimated_elevation
dem_offsetref_lalor)   ZarrayZ	geo2radarZonesr   r$   r   r   r   r   utZ
coordinateprintminmaxZlinspaceZmeshgridr   r   default_backscatter_fileospathexistsr+   r0   Zfliplrloadr   )#r   keysr1   r2   r3   r4   Zdataset_namesr   Zatrr=   r>   ZDEMZref_latZref_lonZpoints_laloZcoordZref_yZref_xr   Zmask_psZyg1Zxg1Zyg2Zxg2Zyg3Zxg3Zyg4Zxg4ZyminZymaxZxminZxmaxxyZbackscatter_filer   r   r    update_input_namespace]   sz   
&


 (rV   c                  C   sF   ddg} | D ]}t j|rtd| d |  S qtd|  d)Nzmean_amplitude.npyz../inputs/slcStack.h5zUsing z for backscatter.zNo backscatter file found .)rO   rP   rQ   rK   FileNotFoundError)optionsoptionr   r   r    rN      s   rN   c                 C   sx   | j tjd< | j tjd< | j tjd< | j tjd< | j tjd< | jr)t| j| _ntd| _tj| jd\}}||fS )aj  
    Configure plot settings based on command-line arguments.

    inps:
        inps (argparse.Namespace): Parsed command-line arguments.

    Returns:
        matplotlib.figure.Figure, matplotlib.axes._subplots.AxesSubplot,
        matplotlib.colors.Colormap, matplotlib.colors.Normalize: Figure, Axes,
        colormap, and normalization for color scale.
    z	font.sizezaxes.labelsizezxtick.labelsizezytick.labelsizezaxes.titlesizejet)figsize)fontsizer   ZrcParamsr   Zget_cmapZsubplotsr\   r   Zfigr   r   r   r    configure_plot_settings   s   r_   c                 C   s   t |d |d |d |d g}tjd|idd}|j| ddd	 tj| |jtjjj	d
 | 
|d |d  | |d |d  |   d S )Nr3   r1   r4   r2   geometryz	EPSG:4326)crsZnone)r   Z	facecolorZ	edgecolor)ra   source)r   gpdZGeoDataFrameZplotctxZadd_basemapra   Z	providersZOpenStreetMapZMapnikZset_xlimZset_ylimZset_axis_off)r   rC   r`   Zgdfr   r   r    add_open_street_map_image   s    re   c                 C      d S Nr   )r   r   r   r    add_satellite_image      rh   Greys_r<   rl   c                 C   sR   |d |d |d |d f}t j|d|dd}| j|j|j||d |d	 d
 d S )Nr3   r4   r1   r2   allT)ZbandsZ	load_dataZlatlonr   r   )extentr
   vminvmax)	georasterZMultiBandRasterimshowr"   rn   )r   ZgtifrC   r
   Zclim_rasterZdata_coordsZmy_imager   r   r    add_geotiff_image   s   
rs   c                 C   rf   rg   r   )r   r   r   r   r    add_dsm_image   ri   rt   c                 C   s   | j |dddd d S )NZgrayr   i,  )r
   ro   rp   )rr   )r   r   r   r   r    add_backscatter_image   s   ru   c                 C   s   t |  t| \}}| jdkrt|| j n*| jdkr"t|| j n| jdkr,t| n| jdkr:t|| j	| j nt
d| jt|| d |  | jrstd| j d| j  | jsh|j| jd	| jd
d n|j| jd	| jdd t  d S )Nopen_street_mapr   Z	satelliter   z,USER ERROR: background option not supported:)r   r   zsave figure to z
 with dpi=Tg        )transparentdpiZ
pad_inchesZtight)rw   rx   Zbbox_inches)rV   r_   r   re   rC   ru   r   rh   rs   r   	Exceptionr!   Ztight_layoutsave_figrK   outfilefig_dpidisp_whitespaceZsavefigr   Zshowr^   r   r   r    persistent_scatterers   s&   




r~   )r   T)rj   rk   )"argparserO   sysZnumpyr)   Z	geopandasrc   Z
contextilyrd   Zshapely.geometryr   rq   r(   Zmatplotlib.pyplotZpyplotr   Zmintpy.utilsr   r   r   rJ   EXAMPLEDESCRIPTIONr!   r0   rV   rN   r_   re   rh   rs   rt   ru   r~   r   r   r   r    <module>   s4   	
X	
