B
    Qa{>                 @   s   d dl Z d dlZd dlZd dlmZ d dlmZmZm	Z	m
Z
 d dlmZmZ d dlT d dlT d dlmZ dd
dZdddZdddZdddZdddZdd ZdS )    N)map_coordinates)geometryDatasetNamesgeometryifgramStack
timeseries)ptimereadfile)*)
coordinate./TFc                s*  d}| st  } t j| } dddg}t j| dg}t|dd}|dk	rt|  jdd	 t fd
d|D rd	|}|dd| 7 }t
|d jkrd jkrtd	| nttjt tjdt|}d| krt j| dg}nt j| dg}t|dd}	|	dk	rZt|	  jdd	 td }
|
 jkrpt
d	|
|	nttjt tjdt j| dg}t|d|d}d| krN|dk	r6t|  jdd	 |d dkrtdd }n.|d dkrtdd }ntd 	|d xF|D ]&}
|
 jkr
d}td	|
|q
W nttjt tjdntd! |r|rnt j|n|}|	rt j|	n|	}	|rt j|n|}|rtd"	|d  d| krtd# ntd$ td%	| td&	|	 td'	| |rtd( td) td( |||	|fS )*a`  Check the result of loading data for the following two rules:
        1. file existance
        2. file attribute readability

    Parameters: work_dir  : string, MintPy working directory
                print_msg : bool, print out message
    Returns:    True, if all required files and dataset exist; otherwise, ERROR
                    If True, PROCESS, SLC folder could be removed.
                stack_file  :
                geom_file   :
                lookup_file :
    Example:    work_dir = os.path.expandvars('./FernandinaSenDT128/mintpy')
                ut.check_loaded_dataset(work_dir)
    TunwrapPhaserangeOffsetazimuthOffsetzinputs/ifgramStack.h5)abspathNF)	print_msgc             3   s   | ]}| j kV  qd S )N)datasetNames).0x)obj H/home/centos/operations/rsmas_insar/sources/MintPy/mintpy/utils/utils.py	<genexpr>9   s    z'check_loaded_dataset.<locals>.<genexpr>z'required dataset is missing in file {}:
z OR 	coherencez*WARNING: "coherence" is missing in file {}z./inputs/ifgramStack.h5X_FIRSTzinputs/geometryGeo.h5zinputs/geometryRadar.h5r   z+required dataset "{}" is missing in file {}z./inputs/geometry*.h5zinputs/geometry*.h5)r   r   	PROCESSOR)isceZdoris      )gammaroipac   zInSAR processor: {}z8Input data seems to be geocoded. Lookup file not needed.z2Loaded dataset are processed by InSAR software: {}z$Loaded dataset is in GEO coordinatesz&Loaded dataset is in RADAR coordinateszInterferograms Stack: {}zGeometry File       : {}zLookup Table File   : {}z2--------------------------------------------------zPAll data needed found/loaded/copied. Processed 2-pass InSAR data can be removed.)osgetcwdpathr   joinZis_file_existr   openallformat
ValueErrorr   printFileNotFoundErrorerrnoENOENTstrerrorr   read_attributekeysr   r   Zget_lookup_fileAttributeError	Exceptionrelpath)work_dirr   r3   load_completeds_listflist
stack_filemsgatr	geom_fileZdnamelookup_fileZdnamesr   )r   r   check_loaded_dataset   s    






r=   r   mmeanc             C   s   t |}t||d}|| |dd \}}|
rRtd| | td|| d\}}|dk	rz|||dd \}}t|||||||||	dd	
\}}}|||fS )
a   Read time-series of one pixel with input lat/lon
    Parameters: lat/lon     - float, latitude/longitude
                ts_file     - string, filename of time-series HDF5 file
                lookup_file - string, filename of lookup table file
                ref_lat/lon - float, latitude/longitude of reference pixel
                zero_first  - bool, shift the time-series so that it starts from zero
                win_size    - int, windows size centered at point of interest
                unit        - str, output displacement unit
                method      - str, method to calculate the output displacement and its dispersity
    Returns:    dates       - 1D np.ndarray of datetime.datetime objects, i.e. datetime.datetime(2010, 10, 20, 0, 0)
                dis         - 1D np.ndarray of float32, displacement
                dis_std     - 1D np.ndarray of float32, displacement dispersity
    )r<   r      zinput lat / lon: {} / {}zcorresponding y / x: {} / {})NNNF)ref_yref_x
zero_firstwin_sizeunitmethodr   )r   r/   r
   Z	geo2radarr*   r(   read_timeseries_yx)latlonts_filer<   ref_latref_lonrC   rD   rE   rF   r   r:   coordyr   rA   rB   datesdisdis_stdr   r   r   read_timeseries_lalo   s$    
rR   c
             C   s  t |}
|
jdd t|
jd }t|}|	rBtd| | || |d | d f}t	j
||dd }d}|dkrt|d }|| | | || d | | d f}t	j
||dd |
jd	}|d
krtj|dd}tj|dd}n0|dkr
tj|dd}t|}ntd||dk	rL|||d |d f}|t	j
||dd 8 }|r^||d 8 }|dkrjnF|dkr|d9 }|d9 }n*|dkr|d9 }|d9 }ntd||||fS )aE   Read time-series of one pixel with input y/x
    Parameters: y/x        - int, row/column number of interest
                ts_file    - string, filename of time-series HDF5 file
                ref_y/x    - int, row/column number of reference pixel
                zero_first - bool, shift the time-series so that it starts from zero
                win_size   - int, windows size centered at point of interest
                unit       - str, output displacement unit
                method     - str, method to calculate the output displacement and its dispersity
    Returns:    dates      - 1D np.ndarray of datetime.datetime objects, i.e. datetime.datetime(2010, 10, 20, 0, 0)
                dis        - 1D np.ndarray of float32, displacement
                dis_std    - 1D np.ndarray of float32, displacement dispersity
    F)r   r   zinput y / x: {} / {}r   )boxNr@   r?   )axismedianzun-recognized method: {}r>   cmg      Y@mmg     @@zun-supported output unit: {})r   r&   r   date_list2vectordateListnparrayr*   r(   r   readintreshapenumDatenanmeannanstd	nanmedianZmedian_abs_deviationr)   )rN   r   rJ   rA   rB   rC   rD   rE   rF   r   r   rO   rS   rP   rQ   bufZbox_winZdis_winZref_boxr   r   r   rG      sF    

$







rG   nearestc                sd  |  }|\}}|\}}t|d t|d   t fddt||g||gD sd}	|	d|7 }	|	d|7 }	|	d 7 }	t|	tt|| || }
tj|||
tj	d	}tj|||
tj	d	}|d
kr| t
|tjt
|tjf }nbdddd}|| krBd|}	|	d| 7 }	t|	||   }t| t||f|d}d}d| krt|j||gdd\}}|| d }t|d tj d | t|tj d  }t|d tj d | }nt|}t|}t|| | || | }t| }||dk9 }i }|| |d< || |d< || |d< || |d< |S ) a{  Extract 2D matrix (z) value along the line [x0,y0;x1,y1]
    Link: http://stackoverflow.com/questions/7878398/how-to-extract-an-arbitrary-line-of-values-from-a-numpy-array

    Parameters: z : (np.array) 2D data matrix
                atr : (dict) attribute
                start_yx : (list) y,x coordinate of start point
                end_yx : (list) y,x coordinate of end   point
                interpolation : str, sampling/interpolation method, including:
                    'nearest' - nearest neighbour
                    'linear'  - linear  spline interpolation (order of 1)
                    'cubic'   - cubic   spline interpolation (order of 3)
                    'quintic' - quintic spline interpolation (order of 5)

    Returns:    transect: (dict) containing 1D matrix:
                    'X' - 1D np.array for X/column coordinates in float32
                    'Y' - 1D np.array for Y/row.   coordinates in float32
                    'value' - 1D np.array for z value in float32
                    'distance' - 1D np.array for distance in float32

    Example: transect = transect_yx(dem, demRsc, [10,15], [100,115])
    LENGTHWIDTHc             3   sB   | ]:\}}d |  kok n  o8d |  ko4 k n  V  qdS )r   Nr   )r   ij)lengthwidthr   r   r     s    ztransect_yx.<locals>.<genexpr>z-input start/end point is out of data coveragez
start_yx: {}z

end_yx:{}z
data size: ({}, {}))dtypere   r   r   r!   )linearZcubicZquinticz%un-supported interpolation method: {}z
available methods: {})orderg    TXAY_FIRSTrN   )
coord_typeg       @X_STEPg     f@   Y_STEPg        YXvaluedistance)lowerr^   r'   zipr(   r)   r[   hypotlinspacefloat32rintastyper0   r   vstackr
   Zyx2lalofloatpicosZrange_ground_resolutionZazimuth_ground_resolutionisnan)zr:   Zstart_yxZend_yxinterpolationy0x0y1x1r9   Znum_ptsysxsZz_lineZinterpolate_name2orderZinterp_orderearth_radiusZlat0Zlat1Zlat_cx_stepy_stepZ	dist_linemasktransectr   )rj   rk   r   transect_yx   sT    &
*
.r   c             C   s`   t |}|j|d |d gdd\}}|j|d |d gdd\}}	t| |||g||	g|}
|
S )zAExtract 2D matrix (z) value along the line [start_lalo, end_lalo]r   rH   )rp   r   rI   )r
   Zlalo2yxr   )r   r:   
start_laloend_lalor   rM   r   r   r   r   r   r   r   r   transect_laloI  s
    r   c             C   s  i }d}g |d< xt t|D ]}|| d || d  }}d| krXt| |||}nt| |||}|d  |7  < |dkrxV| D ]\}	}
tj|
tjd||	< qW n,x*| D ]\}	}
t	||	 |
f||	< qW |d 
| |d d }qW tj|d tjd|d< |S )a  Extract 2D matrix (z) value along multiple lines
    Parameters: z     : 2D np.ndarray in size of (l,w)
                atr   : dict, metadata of matrix z
                lines : list of lines with each line is defined as:
                    [[lat0, lon0], [lat1, lon1]] for geo coordinates
                    [[y0, x0], [y1, x1]] for radar coordinates
    Returns: transect : (dict) containing 1D matrix:
                    'X' - 1D np.array for X/column coordinates in float32
                    'Y' - 1D np.array for Y/row.   coordinates in float32
                    'value' - 1D np.array for z value in float32
                    'distance' - 1D np.array for distance in float32
    r   start_distancer   ro   rw   )rl   rT   )rangelenr0   r   r   itemsr[   r\   r|   concatenateappend)r   r:   linesr   r   rh   r   r   segkeyrv   r   r   r   transect_linesR  s$    r   )r   TF)NNNTr   r>   r?   T)NNTr   r>   r?   T)re   )re   )r"   r,   numpyr[   Zscipy.ndimager   mintpy.objectsr   r   r   r   mintpy.utilsr   r   Zmintpy.utils.utils0Zmintpy.utils.utils1Zmintpy.objects.coordr
   r=   rR   rG   r   r   r   r   r   r   r   <module>
   s    
i 
' 
C
W
	