U
    bb&                     @   s   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 d dlmZmZmZmZ edZdZdZdd	 Zdd
dZdd Zdd ZdddZdddZedkreejdd  dS )    N)make_axes_locatable)get_template_content)readfileptimeutilsplotresidual_RMSzexample:
  timeseries_rms.py  timeseriesResidual.h5
  timeseries_rms.py  timeseriesResidual.h5  --template smallbaselineApp.cfg
  timeseries_rms.py  timeseriesResidual.h5  -m maskTempCoh.h5  --cutoff 3
zreference:
Rousseeuw, P. J., and M. Hubert (2011), Robust statistics for outlier detection,
    Wiley Interdisciplinary Reviews: Data Mining and Knowledge Discovery, 1(1),
    73-79, doi:doi:10.1002/widm.2.
c               	   C   s   t jdt jtd t d} | jddd | jddd	d
d | jdddddd | jddddddd | jdddtdd | jdddtd d!d"gd#d$ | jd%d&td'd(d) | S )*NzHCalculate Root Mean Square (RMS) of deramped residual phase time-series.
)descriptionformatter_classepilogtimeseries_filezTimeseries file)helpz-tz
--templatetemplate_fileztemplate file with options)destr   z-mz--maskmaskFilezmaskTempCoh.h5zmask file for estimation)r   defaultr   z-rz--rampz--derampderamp	quadraticzXramp type to be remove for RMS calculation.
Default - quadratic; no - do not remove rampz--cutoffcutoff3ziM-score used for outlier detection based on standardised residuals
Recommend range: [3, 4], default is 3.)r   r   typer   z	--figsizefig_size)WIDLEN   g      @      @z(figure size in inches - width and length)r   metavarr   nargsr   r   z--tick-year-numtick_year_num   zYear number per major tick)r   r   r   r   )argparseArgumentParserRawTextHelpFormatterTEMPLATEEXAMPLEadd_argumentfloatint)parser r*   K/home/centos/operations/rsmas_insar/sources/MintPy/mintpy/timeseries_rms.pycreate_parser#   s:    


    r,   c                 C   s   t  }|j| d}|S )zCommand line parser.)args)r,   
parse_args)iargsr)   inpsr*   r*   r+   cmd_line_parse;   s    r1   c                    s   |s
t  }t|}tdtj|   t| t	d  fddt
| D }|D ]:} |  }|r^|dkr|||< q^|dkr^t|||< q^|S )z>Update inps with mintpy.residualRMS.* option from templateFilez!read options from template file: zmintpy.residualRMS.c                    s    g | ]} |   kr|qS r*   )keys.0iprefixtemplater*   r+   
<listcomp>L   s      z&read_template2inps.<locals>.<listcomp>)r   r   r   )r1   varsprintospathbasenamer   read_templateutcheck_template_auto_valuelistr2   r'   )templateFiler0   inpsDictkeyListkeyvaluer*   r6   r+   read_template2inpsB   s     


rI   c              	      s  t  }tdd| |  |   d}tj||j|j|jgdddkr~t	|d}|
| | d  W 5 Q R X td	|  ztj d
|jdW n    t  d |j Y nX  fdd D }tdd|j  d}|rN|D ]}td| |  |  qt	|d$}|D ]}|
| | d  qW 5 Q R X td|  n td tj|rnt| tj|jd d }	tj|jd\}
}td|j t|| t  d |jd}|
j|	ddd td|	  |S )Nz2--------------------------------------------------z
date with min RMS: {} - {:.4f}zreference_date.txtF)out_filein_filecheck_readablerunwr	   zsave date to file:         centerr   g/$?c                    s   g | ]}|kr  |qS r*   )indexr3   rms_listrms_thresholdr*   r+   r9   k   s      zanalyze_rms.<locals>.<listcomp>z,
date(s) with RMS > {} * median RMS ({:.4f})zexclude_date.txtz{} - {:.4f}zsave date(s) to file: zNone.r   z.pdf)figsizezcreate figure in size:g     @@r:   tightT)bbox_inchestransparentzsave figure to file: )npargminr<   formatrA   run_or_skipr   r   r   openwritemedian_abs_deviation_thresholdr   medianr=   r>   isfileremovesplitextrms_filepltsubplotsr   plot_rms_bararraysavefig)	date_listrT   r0   ref_idxZref_date_filefex_idxZex_date_filer5   Zfig_filefigaxr*   rS   r+   analyze_rmsW   sR    
  
rq   r      r    bestTFResidual phase RMS [mm]c              	   C   s2  t |\}}t|}z(ttjt| ddd d }W n(   tt| d d }Y nX t|}| j	|||j
tjd d t|}| j	|| || |j
tjd dd	 tj|d
|d}||k}t|dks| j	|| || |j
ddd	 tj| |||d\} }}| jt||gt||gdd|d tj| t|||d
d} | j|
|d | jdd|ddddd |rt| }|jdddd}|jt|jtjd |ddtjd d  |jt|jtj| d || ddtjd d  t|dks<|jt|jtj| d || dddd  |tddgt||gd ||   |ddg |jdd|ddddd |  g  |! "g  |r| j#|d|d! |	r.|  \}}|| d" }|| d||  kr |d#9 }| j$d|||| d$  || fd%d&|d' | S )(a   Bar plot Phase Residual RMS
    Parameters: ax : Axes object
                date_list : list of string in YYYYMMDD format
                rms    : 1D np.array of float for RMS value in mm
                cutoff : cutoff value of MAD outlier detection
                tick_year_num : int, number of years per major tick
                legend_loc : 'upper right' or (0.5, 0.5)
    Returns:    ax : Axes object
    r   )k      r   )colorr    zReference date)rx   labelrO   rP   FdarkgrayzExclude date)
every_yearz--kzMedian Abs Dev * {})ry   )ymin)fontsizebothinT)which	direction	labelsizebottomtopleftrightr   z10%z2%)padg      ?onone)mfcrx   )locframeonr}   g?g      g?ru   data)xyrx   xycoordsr}   )%r   date_list2vectorrZ   ri   minrA   most_commondifftolistbardayspp	mplColorsr[   r`   allauto_adjust_xaxis_dater   r\   auto_adjust_yaxisappend
set_ylabeltick_paramsr   append_axesonesshapefloat32set_ylimget_ylimset_xlim	get_xaxis	set_ticks	get_yaxisset_ticklabelslegendannotate)rp   rk   rmsr   	font_sizer   
legend_locdisp_legendZdisp_side_plotZdisp_thres_textylabeldates
datevector	bar_widthrl   rU   rn   xminxmaxdividerax2r|   ymaxyoffr*   r*   r+   rh      st    
("

$
   *2,"
     rh   c                 C   sZ   t d t| }|jr$t|j|}tj|j|j|j	d\|_
|_|_t|j|j
| d S )NAgg)	mask_file	ramp_type)rf   switch_backendr1   r   rI   rA   get_residual_rmsr   r   r   rT   rk   re   rq   )r/   r0   r*   r*   r+   main   s    
r   __main__)N)r   rr   r    rs   TTFrt   )N)r=   sysr!   numpyrZ   matplotlib.pyplotpyplotrf   mpl_toolkits.axes_grid1r   mintpy.defaults.templater   mintpy.utilsr   r   r   rA   r   r   r$   r%   	REFERENCEr,   r1   rI   rq   rh   r   __name__argvr*   r*   r*   r+   <module>	   s2   
0          
O
