o
    gRec                     @   s  d dl Z d dlZd dlZd dlmZ ed d dlm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mZ d dlmZ dGdd	Zd
d Zdd Zdd Zdd Z dd Z!dd Z"dd Z#dd Z$dd Z%dd Z&dd Z'd d! Z(d"d# Z)d$d% Z*d&d' Z+d(d) Z,d*d+ Z-d,d- Z.dHd0d1Z/dId2d3Z0dId4d5Z1d6d7 Z2d8d9 Z3d:d; Z4dJd=d>Z5d?d@ Z6dAdB Z7dCdD Z8dEdF Z9dS )K    Nagg)LightSource)sensor)ptimereadfile	writefileutils)
timeseries c                 C   s>   | D ]}t |tr|d t| }q|d t| }q| S )z1 parse list array(list item or values) to string  )
isinstancelistseparate_string_by_spacestrstrip)arrdstk r   V/home/exouser/operations/rsmas_insar/tools/MimtPy/mimtpy/utils/multitrack_utilities.pyr      s
   
r   c                 C   s2   t jt j| \}}t j|\}}|||fS )z; return directory(filepath), filename(shotname), extension )ospathsplitabspathsplitext)r   filepathtempfilenamefilename	extensionr   r   r   separate_filename_extension"   s   
r   c                 C   s&   | j d | d | j d | j }|S )zset output directory/_)outdir	startDateendDate)inpsZmodelsoftwaredirnamer   r   r   
set_outdir(   s   "r'   c                 C   sv   t d}d|d gg}g }|D ]"}t |D ]}t jt j||r3t|| dkr3|| qqt	|}|S )8find the project folder and sort the folder in [*AT *DT]
SCRATCHDIRr
   r    )
r   getenvjoinlistdirr   isdirr   findappendsortedr   dirfoldersZproject_folderfolderxZproject_folder_sortr   r   r   find_folder-   s   
&
r7   c                 C   s   g }d}d}t | D ]!}t j|d dkr,t||dkr,t||dkr,|| qg }|D ]}t|t|kr=|}q1|S )Hfind timeseries***.h5 file. The best results is timeseries_***_demErr.h5r	   Residual   .h5r*   r   r-   r   r   r   r/   r0   len)datadir	datafileskey1key2filedatafiler   r   r   find_timeseries9   s    
rD   c                 C   s:   g }t | D ]}t j|d dkr|| q|d S )zfind full name for S1 datatyper:   .he5r   )r   r-   r   r   r0   r>   r?   rB   r   r   r   find_HDFEOS_fullnameH   s   
rG   c                 C   Z   g }t | D ]!}t j|d dkr(t j|dd ddkr(|| q|d S )z!find full name for S1**_*PSDS.he5r:   rE   r!   r*   ZPSDSr   r   r-   r   r   basenamer   r/   r0   rF   r   r   r   find_PSDS_HDFEOS_fullnameP      4
rK   c                 C   rH   )zfind full name for S1**_*PS.he5r:   rE   r!   r*   ZPSr   rI   rF   r   r   r   find_PS_HDFEOS_fullnameY   rL   rM   c           
      C   s   t | }ttd|dddg}|dkrtd td tjdr/tdd}|	 }|
  d	|dd
 }g }d}|D ]2}	t|	|dkrptt|	d
d t|d
d  |k rptt|	d
d t|d
d  }|	}q>| S )z$get the date close to the given datezinfo.pyz--date>zdate_list.txtr:   zerror when runing info.pyr   rr
         r*      )rG   r   systemr   printexitr   isfileopen	readlinescloser,   r   r/   absintr   )
r>   daterC   completion_statusflinesZ	date_partdate2subdatesr   r   r   find_nearest_dateb   s&   
($rc   c                 C   s>   |dkr|}nt | |}|dkr|}||fS t | |}||fS )z,find the startdate and enddate of each trackNone)rc   )r>   r#   r$   Z
startdate2Zenddate2r   r   r   find_start_end_datew   s   

re   c                 C   s   g }g }| D ]8}t dt dd | d g tdt dd | d g}t|}||d  ||d  qtt	|dkrKt
dtt	|dkrWt
d	d
S )zWfor S1*h5 file, check whether the lat_step and lon_step are same for different projectsr
   r)   r    z/mintpy/X_STEPY_STEPr:   z5error! lon_Step between different tracks is not same!z5error! lat_Step between different tracks is not same!T)r   chdirr,   r+   rG   r   read_attributer0   r=   set	Exception)r4   x_stepy_stepprojectrC   atrr   r   r   check_X_Y_step   s   $"
rp   c           	         s  t d| j  i }t| j}t|}| jd   fdd| D }g }|D ]}|dd }|	| q(t | |D ]}| |  }|r|dkr\t
tdd |dD ||< q=|d	kre|||< q=|d
krzt
tdd |dD ||< q=|dv rt|||< q=|dv r|||< q=|dv r|||< q=|dv rt
tdd |dD ||< q=|dv r|||< q=|dv r|||< q=|S )z/Read input template options into Namespace inpsz&read input option from template file: .c                    s    g | ]}t | d kr|qS )r*   )r   r/   .0iprefixr   r   
<listcomp>   s     z&read_template2inps.<locals>.<listcomp>r*   ZDataSetc                 S      g | ]}|qS r   r   rr   r   r   r   rw          ,DataTypeSNWEc                 S   s   g | ]}t |qS r   )floatrr   r   r   r   rw          )ZlatStepZlonStep)r#   r$   )	mask_file)ref_laloc                 S   rx   r   r   rr   r   r   r   rw      ry   )maskfile)outname)rT   templateFiler   read_templateutcheck_template_auto_valueZModelSoftwarekeysr   r0   r   tupler}   )	r%   	inps_dicttemplateZkey_list_tmpkey_listrt   Zkey_wordkeyvaluer   ru   r   read_template2inps   sD   

"
"

"
r   c                 C   s   t d\}}t| j| jgd \}}||| jd 9 }dtj t	|d  }||9 }d|d< d|d	< d
|d< dd
| j| j }tj|||d dS )zbcalculated displacement during startDate_endDate period based on linear assumption and velocity.h5zgeo_velocity.h5r   g     v@g      
WAVELENGTHroipac	PROCESSORz.unw	FILE_TYPEradianUNITgeo_z	{}_{}.unw)out_filemetadataN)r   readr   date_list2vectorr#   r$   daysnppir}   formatr   write)r%   dataro   dt1dt2range2phaser   r   r   r   velocity_displacement   s   r   c                 C   sJ   t | D ]}t j|d |kr"t||dkr"t | d |  qdS )zSdelete all geo_*.h5 files in $MODLEDIR/project/SenAT(DT)/geodmod_startdate_enddate/r:   r*   r    N)r   r-   r   r   r   r/   remove)r>   r@   rA   rB   r   r   r   delete_temporalGeofile   s   r   c                    s    fddt t| d D }d}d}t t| D ]=}t t D ]4}| |  | krU|| | d ||d  |d < ||d  |d  |krU||d  |d  }|d }q!q| || | |fS )Nc                    s&   g | ]}d d t t d D qS )c                 S   s   g | ]}d qS r   r   rr   r   r   r   rw      ry   z5find_intersection_part.<locals>.<listcomp>.<listcomp>r:   ranger=   )rs   js2r   r   rw      s   & z*find_intersection_part.<locals>.<listcomp>r:   r   r   )s1r   mmmaxprt   r   r   r   r   find_intersection_part   s    r   c                 C   sl   d |d gg}g }|D ]"}t|D ]}tjtj ||r.t|| dkr.|| qqt|}|S )r(   r
   r    r*   )	r,   r   r-   r   r.   r   r/   r0   r1   r2   r   r   r   find_folder_horzvert   s   &
r   c                 C   s   g }d}d}d}t | D ])}t j|d dkr6t||dkr6t||dkr6t||dkr6|| qg }|D ]}t|t|krG|}q;|S )r8   r	   r9   mskr:   r;   r*   r<   )r>   r?   r@   rA   Zkey3rB   rC   r   r   r   find_timeseries_horzvert   s   0
r   c              
   C   s   d}d}| t j d } |t j d }| dddf dk}| d|f |d  }|d|d d  d	|d  d
  d|d  d  | d|f  d	|d  d d	|d  d  d|d  d  t d| d|f    d|d  d d|d  d  t d| d|f    d|d  d t d| d|f     }|d|d d  d	|d  d
  d|d  d  |d  d	|d  d d	|d  d  d|d  d  t d|d    d|d  d d|d  d  t d|d    d|d  d t d|d     }|t d|d t | d|f d    }|t | d|f  }	t jdt|ftd}
|dt | d|f   t |	 |
d|f< || |dt | d|f   dt |	   |
d|f< | d| f |d  }|| |
d| f< | |
d| f< |
d }
|
S )zConverts from longitude and latitude to local coorindates
      given an origin.  llh (lon; lat; height) and origin should
      be in decimal degrees. Note that heights are ignored and
      that xy is in kmg   @TXAg4n-$?   r:   Nr            @      rP      rR       -   i      #   i   )dtype  )	r   r   sinsqrtzerosr=   r}   tancos)ZllhoriginaezZdlambdaMM0NExyr   r   r   llh2xy   s$   ,,8r   c                 C   s   | }|}d}|t jd 9 }|dk r|d7 }|t jd 9 }t |}t |t | }	t |t | }
|| ||	  ||
  }|S )zyinc is 1*1 value, head is 1*1 value,north_disp/east_disp/up_disp is n*1 matrix
        positive value means north/east/upZ   g     f@g        g     v@)r   r   r   r   )incheadZ
north_dispZ	east_dispZup_disp	inc_angle
head_angleaz_angleZA_upZA_northZA_eastZlos_simr   r   r   calculate_LOS_value+  s   
r   =Tc                 C   s  i }i }d}g }t j| rt| d}| }n
t| tr"| d}|D ]{}	|	 }	dd |	|dD }
t	|
dk s@|	
dr`|	
d	rJi }d
}n|r]|	
ds]|	
ds]d}|| t q$|
d }t|
d dddd  }t j|}t j|}|rt|r|||< q$d}|| |||< q$|dkr|||< q$t j| r|  |r|| t	|dkrt||d< |S )a{  Reads the template file into a python dictionary structure.
    Parameters: fname : str
                    full path to the template file
                delimiter : str
                    string to separate the key and value
                print_msg : bool
                    print message or not
    Returns:    template_dict : dict
                    file content
    Examples:
        tmpl = read_template(KyushuT424F610_640AlosA.template)
        tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
        from mintpy.defaults.auto_path import isceAutoPath
        tmpl = read_template(isceAutoPath, print_msg=False)
    FrO   
c                 S   s   g | ]}|  qS r   )r   rr   r   r   r   rw   i  r~   z!read_template.<locals>.<listcomp>r:   r   )%#rN   Tr   r   r   r
   plotAttributes)r   r   rV   rW   rX   r   r   r   r   r=   
startswithr0   nextreplace
expanduser
expandvarsZis_plot_attributerY   jsondumps)fname	delimiter	print_msgZtemplate_dictZplotAttributeDictZinsidePlotObjectr   r^   r_   linecZatrNameZatrValuer   r   r   r   G  sP   





 



r   c                 C   s    |t j t | |  | }|S )av  
    Function to calculate displacements/velocities due to slip on a deep 
    screw dislocation (infinitely long strike slip fault. 
    After Savage and Burford (1973).
    v = (s/pi)*arctan((x+xc)/d)
    INPUTS
        x = vector of distances from fault
        s = slip or slip rate on deep dislocation
        d = locking depth [same units as x]
        c = scalar offset in y [same unit as s]
        xc = offset to fault location [same units as x]
    OUTPUTS
        v = vector of displacements or velocities at locations defined by x
          [same units as s]
          
    USEAGE:
        v = deepdisloc(x, s, d)
    r   r   arctan)r6   sdr   xcvr   r   r   
screw_disc  s   r   c                 C   s\   |t j t | | |  | |dt j t | | |  | dkd  | dkd    }|S )a  
    Model for interseismic strain accumulation and fault creep.
    Taken from Hussain et al. (2016).
    INPUTS
        x = vector of distances from fault
        s1 = slip or slip rate on deep dislocation
        s2 = creep or creep rate
        d1 = locking depth
        d2 = depth to bottom of creeping section
        c = scalar offset in y [same unit as s]
        xc = offset of fault location
    OUTPUTS
        v = vector of displacements or velocities at locations defined by x
          [same units as s]
    r:   r   g      ?r   )r6   r   r   d1d2r   r   r   r   r   r   fault_creep  s   Xr   c              	   C   sF   |t | |d |d |d  }tdtt||t| }|S )a@  
    INPUTS
        x = vector of distances from fault
        v = velocities at locations defined by x
        m = model parameters, [0] = slip (mm/yr), [1] = locking depth (km), [2] = scalar offset (mm/yr)
        W = weight matrix (inverse of the VCM)
    OUTPUTS
        ll = value of the loglikelihood function
    r   r:   r   g{Gz)r   r   nansumdot	transpose)r6   r   r   Wdiffllr   r   r   loglike  s   $r   c                 C   s&   t t | |kt | |k@ }|S )z
    INPUTS
        m = model values
        m_min = lower model limits
        m_max = upper model limits
    OUTPUTS
        lp = true if within limits, false if any aren't
    )r   all)r   m_minm_maxlpr   r   r   logprior  s   "
r   c                 C   s   t t | | d }|S )zs
    INPUTS
        a,b = two arrays of same length
    OUTPUTS
        rms = rms misfit between a and b (a-b)
    r   )r   r   nanmean)r   brmsr   r   r   
rms_misfit  s   r  '  c           	      C   s  t | D ]}| }|d tjjddddd  |d< |d tjjddddd  |d< |d tjjddddd  |d< t|ttsQ|d7 }|t	|ddf< qt
tt|t}t
tt|t}t|| tjjddddkrz|}|}|d7 }n|d7 }|t	|ddf< |t|< qt	dddf d t	dddf< t	dddf d t	dddf< t	dddf d t	dddf< t	ttddf }dS )	z
    Bayesian monte carlo inversion taken from the main notebook.
    Re-packaged as a function here to minimise code repeats.
    r   g      @r:   )locscalesizer   r   N)lowhighr  )r   copyr   randomnormallibr   r   r   Zmodels_savedr   r6   r   r   expuniformZll_saved	nanargmax)	n_iterationsiiZ	m_currentZm_trialZn_rejectZ
ll_currentZll_trialZn_acceptZ
best_modelr   r   r   run_inversion  s,   """ 

   r  c           )   	   C   s  t | |\}}t |}t |}t |d |d  d |d |d  d  }t d||d d }	|	dd |	dd  d }
t dd|d d }|| }|d ||d   }|d ||d   }|d d | t j| }||d  }||d  }||d  }||d  }t |dd }t |}t	|d |d f|d |d f|d |d f|d |d fg}|
t | | g}||j}|| }|| }|| }td|d D ]b}t || ||d  ||d  || g}t || ||d  ||d  || g}t	|d |d f|d |d f|d |d f|d |d fg}|
t ||g}|| }t |||< qt |d |d |d |d g}t |d |d |d |d g}t ||fj} t | t | d	 | d
 gf} t	|d |d f|d |d f|d |d f|d |d fg}|
t ||g}|| }!|| }"|| }#|d |d  |d |d   }$|d |# |d |"  }%t |%|$ d|$|%   }&t |d |# d |d |" d  }'|'t |& }(||
|!|(| fS )a  
    Generates a profile through gridded data.
    
    INPUTS:
    data = numpy array of values to profile
    x = vector of coords for the x axis
    y = vector of coords for the y axis
    prof_start = (x, y) pair for the start of the profile line
    prof_end = (x, y) pair for the end of the profile line
    params = dictionary of parameters for the profiler (currently nbins and width)
    
    r:   r   r   nbinsNr*   widthr   r   r   r   r:   )r   meshgridarrayr   linspacelinalgnorm
zeros_liker   Pathcontains_pointsr   flattenreshapeshaper   r   vstackTr   r   ))r6   yr   
prof_startprof_endparamsxxyyZ	prof_distZprof_bin_edgesZprof_bin_midsZbin_midsZbin_gradZx_midsZy_midsZbin_grad_normZbin_x1Zbin_x2Zbin_y1Zbin_y2Zbin_valZbin_stdZ	full_polyZpoly_pointsZ	trim_dataZtrim_xxZtrim_yyr  Zpoly_xZpoly_ypolyZin_poly_valsZpoints_polyZ
points_valZpoints_xZpoints_yprof_mZpoints_mZpoints_prof_angleZpoints2prof_startZpoints_distr   r   r   profile_data"  sZ   

.
B**B"" B &r+  c              	   C   s  t |jd d D ]}t| |||ddf ||d ddf r$|} nq	|||d ddf }| d |d  | d |d   }|d |d  |d |d   }t|| d||   }t| ||dddf |dddf g}	t|	td	f}
t|
d |
d }t|
d |
d
 }t||\}}}t	|| || g}t
|d | d  d |d | d  d  }|t|fS )aX  
    Calculates the distance along a profile at which it intersects a fault, and 
    the angle between the two at this point.
    
    INPUTS:
        prof_start = (x,y) coord
        prof_end = (x,y) coords
        fault_trace = x and y coords of fault trace
        
    OUTPUTS:
        intersection_distance
        intersection_angle
    r   r:   Nr   r  )r:   r:   r  )r:   r   )r   r:   r   )r   r   	intersectr   r   r!  hstackonescrossr  r   rad2deg)r$  r%  Zfault_traceindZ	inter_indZfault_inter_coordsr*  Zfault_mZintersection_angler   hl1l2r6   r#  r   Zintersection_pointZintersection_distancer   r   r   profile_fault_intersectionz  s"   *  *.r5  c                 C   s@   |d | d  |d | d   |d | d  |d | d   kS )Nr:   r   r   )ABCr   r   r   ccw  s   @r9  c                 C   s0   t | ||t |||kot | ||t | ||kS )N)r9  )r6  r7  r8  Dr   r   r   r,    s   0r,  )r
   )r   Tr   )r  ):r   argparsestringmatplotlib.pyplotpyplotpltswitch_backendmatplotlib.colorsr   shutilnumpyr   re
subprocessZsubpZmatplotlib.pathr   mintpymintpy.workflowmintpy.objectsr   mintpy.utilsr   r   r   r   r   r	   r   r   r'   r7   rD   rG   rK   rM   rc   re   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r+  r5  r9  r,  r   r   r   r   <module>   s\   

			(,

L

/X+