B
    Qa8                 @   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mZ d dlmZmZmZmZ dZdZdZd	d
 ZdddZdd Zdd Zdd Zdd Zdd ZdddZedkreej dd  dS )    N)resize)RegularGridInterpolator)
timeseries)ptimereadfile	writefileutilsa  references:
  Yu, C., Li, Z., Penna, N. T., & Crippa, P. (2018). Generic atmospheric correction model for Interferometric
    Synthetic Aperture Radar observations. Journal of Geophysical Research: Solid Earth, 123(10), 9202-9222.
  Yu, C., Li, Z., & Penna, N. T. (2018). Interferometric synthetic aperture radar atmospheric correction
    using a GPS-based iterative tropospheric decomposition model. Remote Sensing of Environment, 204, 109-121.
z--dir ./GACOS
  20060624.ztd
  20060624.ztd.rsc
  20061225.ztd
  20061225.ztd.rsc
  ...
  OR
  20060624.ztd.tif
  20061225.ztd.tif
  ...
zexample:
  tropo_gacos.py -f timeseries.h5 -g inputs/geometryRadar.h5 --dir ./GACOS
  tropo_gacos.py -f geo/geo_timeseries.h5 -g geo/geo_geometryRadar.h5 --dir ./GACOS
c              C   sr   t jdt jtd t d t d} | jdddddd	 | jd
ddddd	 | jdddddd | jdddd | S )NzBTropospheric correction using GACOS (http://www.gacos.net) delays

)descriptionformatter_classepilogz-fz--filedis_fileTz(timeseries HDF5 file, i.e. timeseries.h5)destrequiredhelpz-gz--geom	geom_filezgeometry file.z--dirz--GACOS-dir	GACOS_dirz./GACOSzAdirectory to downloaded GACOS delays data (default: %(default)s).)r   defaultr   z-ocor_dis_filez5Output file name for trospheric corrected timeseries.)r   r   )argparseArgumentParserRawTextHelpFormatter	REFERENCEDIR_DEMOEXAMPLEadd_argument)parser r   H/home/centos/operations/rsmas_insar/sources/MintPy/mintpy/tropo_gacos.pycreate_parser1   s    r   c             C   s  t  }|j| d}tj|j|_td|j x6dD ].}t|| }|r4tj|s4t	d
|q4W t|j}t|j}d| krdnd}d| krdnd}|dd	}	|dkr|	d
krd
|	}
|
d7 }
t|
||krHtdd |j|jgD }d}
|
dj
tj|j||d7 }
|
dj
tj|j||d7 }
t|
tjtj|jd|_|js|jdd d |_|S )zCommand line parser.)argsz Use GACOS products at directory:)r   r   zinput file not exist: {}Y_FIRSTgeoradar	PROCESSORisce)gammaroipacz*Radar-coded file from {} is NOT supported!zT
    Try to geocode the time-series and geometry files and re-run with them instead.c             s   s   | ]}t tj|V  qd S )N)lenospathbasename).0ir   r   r   	<genexpr>]   s    z!cmd_line_parse.<locals>.<genexpr>zCInput time-series and geometry file are NOT in the same coordinate!z"
    file {f:<{n}} coordinate: {c})fnczGACOS.h5.r   z	_GACOS.h5)r   
parse_argsr)   r*   abspathr   printvarsisfileFileNotFoundErrorformatr   read_attributer   r   keysget
ValueErrormaxr+   joindirname
tropo_filer   split)iargsr   inpskeyfnameatr1atr2Zcoord1Zcoord2procmsgr0   r   r   r   cmd_line_parseB   s6    


rK   c       	      C   s   t |d t |d  }}t|jdd||fd}t| }t||}tj| |dd }t|||fddddd	}|| }|d
9 }|S )aW  calc single path tropo delay in line-of-sight direction

    Parameters: ztd_file      - str, path of zenith delay file
                atr           - dict, dictionary of attribute for output file
                cos_inc_angle - 2D np.ndarray in float32, cos(inc_angle)
    Returns:    delay         - 2D np.ndarray in float32, LOS delay
    LENGTHWIDTHr   )	pixel_box)box   constantT)ordermodeanti_aliasingpreserve_range)	intut
coordinatebox_pixel2geor   r:   box_geo2pixelreadr   )	ztd_fileatrcos_inc_anglelengthwidthgeo_boxatr_ztdpix_boxdelayr   r   r   get_delay_geol   s    


rf   c       
      C   s~   t | \}}t|}tj|dd\}}t|}| | f}t||dddd}||}	|	|j	}	|	| }	|	d9 }	|	S )a`  calc single path tropo delay in line-of-sight direction

    Parameters: ztd_file      - str, path of zenith delay file
                cos_inc_angle - 2D np.ndarray in (len, wid) in float32, cos(inc_angle)
                pts_new       - 2D np.ndarray in (len*wid, 2) in float32
    Returns:    delay         - 2D np.ndarray in float32, LOS delay
    rP   )	dimensionnearestFr   )methodbounds_error
fill_valuerV   )
r   r\   npflipudrX   get_lat_lonflattenRGIreshapeshape)
r]   r_   pts_newZ	delay_ztdrc   latslonsZpts_ztdZRGI_funcre   r   r   r   get_delay_radar   s    	


rv   c                s  t |}|d }|dkr(t| }n6|dkrPt |d }t|d}ntd|g }t	j
t|t	jd}	xht|D ]\\}
 fdd	d
D }dd	 |D }t|dkr||d  qtd d|	|
< qW t	|	dkrt	||	  }dd fdd}||| |dkr,dS d|d< d|d< x&dD ]}|| krB|| qBW t|d t|d  }}t|}t	j|t	jd}|j|f|gt	j|||fdgd}tj| ||d td| t j|ddd }t	|t	j d }d | krd}n6td! t||\}}t	 |!d"d#|!d"d#f}tj"|d$}xt#|D ]}
||
 ||
 }d | krt$|||}nt%|||}|
|
d# d|d|g}tj&| |d|dd% |j'|
d# t(j)*|d& q\W |+  | S )'z2calculate delay time-series and write to HDF5 file	FILE_TYPEr   z.unwDATE12-z'un-supported displacement file type: {})dtypec          	      s"   g | ]}t j d |qS )z{}{})r)   r*   r?   r9   )r,   fext)r   date_strr   r   
<listcomp>   s    z.calculate_delay_timeseries.<locals>.<listcomp>)z.ztdz.ztd.tifc             S   s   g | ]}t j|r|qS r   )r)   r*   exists)r,   r/   r   r   r   r}      s    r   z7WARNING: NO ztd file found for {}! Continue without it.Fc             S   s   t | }|d |d fS )NrL   rM   )r   r:   )rF   r^   r   r   r   get_dataset_size   s    
z4calculate_delay_timeseries.<locals>.get_dataset_sizec          	      s   t d t d  d}tj | dddkr<d}t d nt d d	d
 | D } |ksxt fdd|D rd}t d| nZt d t d@}t|d dd d d d f dkrd}t d nt d W d Q R X t d| |S )Nzupdate mode: ONzoutput file: {}skipF)out_filein_file	print_msgrunzF1) output file either do NOT exist or is NOT newer than all ZTD files.z61) output file exists and is newer than all ZTD files.c             S   s    g | ]}t td |d qS )z\d{8}r   )strrefindall)r,   r-   r   r   r   r}      s    zCcalculate_delay_timeseries.<locals>.run_or_skip.<locals>.<listcomp>c             3   s   | ]}|t   kV  qd S )N)r   get_date_list)r,   r-   )rA   r   r   r.      s    zBcalculate_delay_timeseries.<locals>.run_or_skip.<locals>.<genexpr>zc2) output file does NOT have the same len/wid as the geometry file {} or does NOT contain all dateszO2) output file has the same len/wid as the geometry file and contains all datesrr   rV   r   z$3) output file is NOT fully written.z 3) output file is fully written.zrun or skip: {})	r5   r9   rX   run_or_skipanyh5pyFilerl   all)	ztd_filesrA   r   flag	date_listr/   )r   )rA   r   r      s*    

$
z/calculate_delay_timeseries.<locals>.run_or_skipr   NmUNIT)REF_DATEREF_XREF_YREF_LATREF_LONrL   rM   )dater   )metadataz!read incidenceAngle from file: {}incidenceAngle)datasetNameg     f@r!   z&get pixel coordinates in geometry filerV   rP   )maxValue)datar   blockr   )suffix),r   r:   r   r   r   yyyymmddrB   r=   r9   rl   onesr(   bool_	enumerateappendr5   r   arraytolistr;   poprW   string_rz   float32r   layout_hdf5r\   cospirX   rn   hstackrq   progressBarrangerf   rv   write_hdf5_blockupdater)   r*   r+   close)rA   r   r   r   r^   ftyper   date12r   r   r-   fnamesr   rE   r`   ra   num_datedatesds_name_dict	inc_angler_   rs   rt   ru   prog_barr]   re   r   r   )r   r|   r   r   calculate_delay_timeseries   sv    
#
 r   c             C   sH   t d t d ddlm} | |d|dg}t dd| || |S )	NzO
------------------------------------------------------------------------------z=correcting relative delay for input time-series using diff.pyr   )diffz-oz--forcezdiff.py )r5   mintpyr   r?   main)r   rA   r   r   rC   r   r   r   correct_timeseriesE  s    
r   c             C   s   t d t d t d|  tj| dd\}}t|d d\}}t d||| tj|d	|dd
 }|tj|d	|dd
 8 }|dtj t	|d  9 }t d| t
|| || |S )NzO
------------------------------------------------------------------------------z1correcting relative delay for input interferogramzread data from {}phase)r   rx   ry   z)calc tropospheric delay for {}-{} from {}ztimeseries-{}r   g      
WAVELENGTHzwrite corrected data to {})r5   r9   r   r\   r   r   rB   rl   r   floatr   write)r   rA   r   r   r^   date1date2Ztropor   r   r   correct_single_ifgramR  s    r   c             C   s~   t | }t|j|j|j|jd t|jd }|dkrNt|j|j|j	d n,|dkrlt
|j|j|j	d ntd| d S )N)rA   r   r   r   rw   r   )r   rA   r   z.unwzJinput file {} is not timeseries nor .unw, correction is not supported yet.)rK   r   rA   r   r   r   r   r:   r   r   r   r5   r9   )rC   rD   r   r   r   r   r   e  s     
r   __main__rP   )N)N)!r)   sysr   r   r   numpyrl   skimage.transformr   scipy.interpolater   rp   mintpy.objectsr   mintpy.utilsr   r   r   r   rX   r   r   r   r   rK   rf   rv   r   r   r   r   __name__argvr   r   r   r   <module>	   s.   

*$% 
