o
    BdAC                     @   s   d dl Z d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
 d dlmZmZmZmZ dd Zddd	Zdd
dZdd Zdd ZdddZdS )    N)IFGRAM_DSET_NAMESclustergiantTimeseriesifgramStack
timeseries)ptimereadfile	time_func	writefilec           	      C   s   |  dd}| dd}||krd}n|}|  dd|  ddg}| dd| ddg}||kr6d\}}n|\}}|durBt|nd}|durLt|nd}|||fS )zCheck reference date and point
    Parameters: atr1/2   - dict, metadata of file1/2
    Returns:    ref_date - str, None for re-referencing in time  is NOT needed
                ref_y/x  - int, None for re-referencing in space is NOT needed
    REF_DATENREF_YREF_X)NN)getint)	atr1atr2Z	ref_date1Z	ref_date2ref_dateZref_yx1Zref_yx2ref_yref_x r   D/home/exouser/operations/rsmas_insar/tools/MintPy/src/mintpy/diff.pycheck_reference   s   	

r   F    קAc              	      s>  t | }t |}|d }|d }t|   |dkr%t| d}	n|dkr1t| d}	t||\}
}}fdd D }tjt tj	d}| krt
d	| d
|   |rtt t| }t
d t
d|  d|t fdd|D < ntd|r|r|||d |d f}t j|||dd |	 }nd}tj|| d t|d t|d }}ttt | | | }tjdd||f|ddd\}}t|D ]\}}|dkrt
d|d  d| d t
d|  t
d|  t j|||dd |	 }|dur2t
dtj| d| d |  |t|d!ddd|jd |jd" f8 }|
r_t
dtj| d#|
  ||
}|t||ddddf |jd ddf8 }t
d|   t j| |d$d }|d%k}||  |8  < d%||< ~d|jd |d |d& |d |d" g}tj||||d' q|S )(a  Calculate the difference between two time-series files.

    Parameters: file1         - str, path of file1
                file2         - str, path of file2
                out_file      - str, path of output file
                force_diff    - bool, overwrite existing output file
                max_num_pixel - float, maximum number of pixels for each block
    Returns:    out_file      - str, path of output file
    	FILE_TYPEr   g      ?r   gMbP?c                       g | ]}| v r|qS r   r   .0i)
date_list2r   r   
<listcomp>V       z#diff_timeseries.<locals>.<listcomp>dtypez	WARNING: z does not contain all dates in zBContinue and enforce the differencing for their shared dates only.z4	with following dates are ignored for differencing:
r   c                    s   g | ]}  |qS r   )indexr   )
date_list1r   r   r   ^       z7To enforce the differencing anyway, use --force option.   datasetNameboxNref_fileLENGTHWIDTHyTr)   Z	num_split	dimension	print_msg
------- processing patch  out of  --------------box: zread from file: * referencing data from 	 to y/x: /   
 to date: r)              datar(   block)r   read_attributer   get_date_listr   r   nponeslenbool_printlistsetarray	Exceptionreadr
   layout_hdf5r   ceilr   split_box2sub_boxes	enumerateospathbasenametilereshapeshaper#   write_hdf5_block)file1file2out_file
force_diffmax_num_pixelr   r   k1k2Zunit_facr   r   r   Zdate_list_sharedZdate_flag_sharedZdate_list_exref_boxref_vallengthwidthnum_boxbox_listr   r)   data2ref_indr@   maskrA   r   )r$   r   r   diff_timeseries:   sr   




",
.&ri   c           !   	   C   s  t | }t |}t|  }t|}t||\}}	}
|	r5|
r5|
|	|
d |	d f}t j|d|dd }nd}t |}dd |D }d|vrOtd| d	|dgkrat	d
 t	dd |D  t
j|| d t|d t|d }}ttt|| | | }tjdd||f|ddd\}}t|D ]\}}|d |d  }|d |d  }|| }|dkrt	d|d  d| d t	d|  t	d|  t j|d|dd }|durt	d|	 d|
 d|d dd ||8 }ddi}tj||d }t	d!tj| d"|  tt|| g}t||}|d#||}d$| v rUt	d%tj| d&|d$   ||d$ }|t||ddddf |ddf8 }t	d'|   t j| |d(d }|d)k}||8 }d)||< ~d||d |d |d |d g} t
j||d*| d+ q|S ),a  Calculate the difference between a time-series file and a velocity file.

    Parameters: file1         - str, path of file1 (time series)
                file2         - str, path of file2 (velocity)
                out_file      - str, path of output file
                max_num_pixel - float, maximum number of pixels for each block
    Returns:    out_file      - str, path of output file
    r&   velocityr'   r   Nc                 S   s   g | ]	}| d s|qS )Std)endswithr   xr   r   r   r      s    z0diff_timeseries_and_velocity.<locals>.<listcomp>z$No velocity dataset found in file2: !zPWARNING: ONLY velocity is supported, ignore the following datasets and continue:c                 S   s   g | ]}|d kr|qS )rj   r   rm   r   r   r   r      r    r*   r,   r-   r.   Tr/   r:   r>   r2   r3   r4   r5   zread velocity from file2: z* referencing velocity to y/x: r8   z with value of d   z.2fz cm/year
polynomial)modelz"* reconstructing time-series from z with model r9   r   z&* referencing time-series from file2: r;   zread time-series from file1: r<   r=   r   r?   ) r   rB   r   rC   rF   r   rM   get_dataset_list
ValueErrorrH   r
   rN   r   rD   rO   r   rP   rQ   r	   Zget_design_matrix4time_funcrR   rS   rT   vstackzerosflattenmatmulrV   keysr#   rU   rX   )!rY   rZ   r[   r]   r   r   	date_listnum_date_r   r   r`   ra   ds_namesrb   rc   rd   re   r   r)   box_widbox_len	num_pixelZvelorr   ZG_fitmZts_fitrf   rg   r@   rh   rA   r   r   r   diff_timeseries_and_velocity   sp   





" ( r   c                    s  t | }|  t |}|  tt|jt|j@  t dkr&td fddtD d }td| d|  d t	j
| |dd }td| d| d t	j
||dd }d	| v rtd
|j d|j d |dd|j|jf }|dd|j|jf }	t|jd D ]2}
||
ddf ||
ddf dk  ||
 8  < ||
ddf ||
ddf dk  |	|
 8  < qtj||dk< tj||dk< || }~~d|t|< ||i}tj||| d |S )a  Calculate the difference between two ifgramStack files.

    Parameters: file1    - str, path of file1
                file2    - str, path of file2
                out_file - str, path of output file
    Returns:    out_file - str, path of output file
    r   z$no common dataset between two files!c                    r   r   r   r   r}   r   r   r     r    z%diff_ifgram_stack.<locals>.<listcomp>zreading z from file  ...r(   Zunwrapphasezreferencing to pixel (,z) ...Nr=   )r[   r+   )r   openrI   rJ   datasetNamesrF   rt   r   rH   r   rM   lowerrefYrefXrangerW   rD   nanisnanr
   write)rY   rZ   r[   Zobj1obj2ds_namedata1rf   Zref1Zref2r   r@   ds_dictr   r   r   diff_ifgram_stack   s6   	02r   c              	   C   sz  t | }|dd}|drdnd}td| d|   t j| |d\}}t|d	 d
\}}td| d| d
| d|  t j||dd }	|	t j||dd 8 }	|drqtd| d |	dt	j
 t|d  9 }	||	8 }d| v rt|d t|d }
}|||
|f 8 }td|
 d| d |d dkrtd|   t j| ddd }||d}n|}td|  t||| dD ]q}|  d| }| d| }tj|r:t|| td| d | d! | d| }t|}| }W d"   n	1 sw   Y  |tj| tj|}t|d#}|| W d"   n	1 s5w   Y  q|S )$as  Calculate the difference between two unwrapped interferogram files.

    Parameters: unw_file - str, path of the interferogram file
                ts_file  - str, path of the time-series file, e.g. ERA5.h5, SET.h5
                cor_file - str, path of output corrected interferogram file
    Returns:    cor_file - str, path of output corrected interferogram file
    UNITradianZradphase zread z from r   DATE12-zcalc z for r   zconvert z from radian to meterg      
WAVELENGTHr   r   zre-referencing to pixel (z, )r   .unwzread magnitude from 	magnitude)r   r   zwrite corrected data to )xmlZvrt.zcopy z to z and update the filenameNw)r   rB   r   
startswithrH   rM   r   yyyymmddsplitrD   pifloatry   r   r
   r   rR   rS   isfileshutilcopy2r   replacerT   )unw_filets_filecor_fileatrdunitZdnamer@   date1date2delayr   r   magr   extZunw_meta_fileZcor_meta_fileZ	meta_filefsr   r   r   diff_ifgram_and_timeseries+  sT   
	 



r   c              	   C   s  t   }t|  d| d|  t| }t|d }|d }|d }	td|  |dkrX|	dvr;td td	|	d
v rJt| |d ||| n|	dkrWt| |d || ntdd ||	fD rlt| |d | n|dv r~|	dkr~t	| |d |d ndd | g| D }
t
tjtt|
 }tdd |
D r|
d }td| t|dk rtd| g|  i }|D ]}td| d tj| |dd }|j}t|D ]\\}}t|
|d  dkrdn|}tj||dd }|dkrt||dd \}}|r|rtdtj|d  d| d|  ||||f 8 }tj|tjdtj|tjd }qtj||d||< qtd|   tj|||| d tt   | d \}}td!|d"d#|d$d% |S )&a_  calculate/write file1 - file2

    Parameters: file1         - str, path of file1
                file2         - list(str), path of file2(s)
                out_file      - str, path of output file
                force_diff    - bool, overwrite existing output file
                max_num_pixel - float, maximum number of pixels for each block
    z - z --> r   r   zthe 1st input file is: r   )r   r   rj   zZIf the first file is timeseries, the following file must be either timeseries or velocity.z8Input multiple dataset files are not the same file type!)r   r   rj   c                 s   s    | ]}|d kV  qdS )r   Nr   r   r   r   r   	<genexpr>  s    zdiff_file.<locals>.<genexpr>)r   displacementz.off)r   r   r   c                 S   s   g | ]}t |qS r   )r   rs   rm   r   r   r   r     r%   zdiff_file.<locals>.<listcomp>c                 s   s    | ]	}t |d kV  qdS )r&   N)rF   rm   r   r   r   r     s    z&List of common datasets across files: r&   z&No common datasets found among files:
zdifferencing r   r   Nr6   r7   r8   r!   z use metadata from the 1st file: )r[   metadatar+   <   ztime used: z02.0fz mins z02.1fz secs)timerH   r   rB   rL   ri   r   allr   r   rI   rJ   intersectionmaprF   rt   rM   r"   rQ   r   rR   rS   rT   rD   rK   float32r
   r   divmod)rY   rZ   r[   r\   r]   
start_timer   r   r^   r_   ds_names_listr}   dsDictr   r@   r"   r   fnameds_name2readrf   r   r   r   r   r   r   r   	diff_filen  s^   	


&"r   )Fr   )r   )rR   r   r   numpyrD   mintpy.objectsr   r   r   r   r   mintpy.utilsr   r   r	   r
   r   ri   r   r   r   r   r   r   r   r   <module>   s   
!
^d/C