o
    <cM                     @   s   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Z	dd Z
dd Zdd Zdd	 Zd
d Zdd Zdd ZG dd dZdS )    Nc           '      C   s  |d }t d|}|d }	t d|	}
t|}t|
}|dddf |k|dddf |k |dddf |k |dddf |k }|dddf |k|dddf |k |dddf |k |dddf |k }t|| || f}tj|dddf dd}|d }|d }|dddf |k rt|dddf |kd }nt|dddf |kd }|dddf |k rt|dddf |kd }nt|dddf |kd }|d	 d
krV||ddf d ||ddf d kr*|dks|dkrd| }|dks|dkrd| }n|dks%|dkr)d| }n|dks4|dkr8d| }|dksB|dkrGd| }n{|dksQ|dkrUd| }nl||ddf d ||ddf d kr|dksu|dkryd| }|dks|dkrd| }n:|dks|dkrd| }n+|dks|dkrd| }|dks|dkrd| }n|dks|dkrd| }||ddf }||ddf }||ddf }||ddf }t||||\}}||ddf d ||ddf d kr	||ddf }n||ddf }tj	| dft
d}|d }|d } |}!|}"td| d }#|#| d  }$||$|!|   }%| |$|"|    }&t|#|dddf< t|%|dddf< t|&|dddf< |S )a  Search lon/lat of one point located on the profiles, respectively
    Parameters: profile_num      : int, number of profiles
                m_atr : dictory, metadata for master dataset
                s_atr : dictory, metadata for slave dataset
                min_num_solution : int, minimum number of solutions available
    Returns:    profile_catalog : 2D np.array of string for number of profile, lon/lat of point that was passed by profile 
    scene_footprintz(-?[\d+\.]+)N   r   axis   )r   r   Zflight_directionD      dtype)refindalltrack_outline_matrixnpvstacksortanyargwherecalculate_cross_linesemptyfloatarange	transpose)'profile_num	over_lat0	over_lon0	over_lat1	over_lon1m_atrs_atrZ	m_polygonZm_footprintZ	s_polygonZs_footprintZ	m_outlineZ	s_outlineZ	m_idx_tmpZ	s_idx_tmpZoverlap_footprintZresult_sortZtarget1Ztarget2m_idxs_idxZ	m_end_idxZ	s_end_idxZline0_startZ	line0_endZline1_startZ	line1_endZ	cross_lonZ	cross_latZprofile_startZprofiles_catalogx1y1x2y2Z
profile_NoZgrade_factorZprofile_lonsZprofile_lats r&   L/home/exouser/operations/rsmas_insar/tools/MimtPy/mimtpy/objects/profiles.pysearch_profiles   s   &&  *

*

*r(   c              	   C   sp   t  }| }tt|d t|d gt|d t|d gt|d t|d gt|d t|d gg}|S )	z4store lon/lat of each points for track as dictionaryr   r   r   r      r	         )dictr   arrayr   )	footprintoutlinelonlatsr&   r&   r'   r      s   0,r   c                 C   s   | d |d  }|d | d  }| d |d  |d | d   }|d |d  }|d |d  }|d |d  |d |d   }	|| ||  }
|
dkrNdS ||	 ||  d |
 }|| |	|  d |
 }||fS )a  calculate the intersect point for two lines
       param line0_pos0: the start point for the first line
       param line0_pos1: the end point for the first line
       param line1_pos0: the start point for the second line
       param line1_pos1: the end point for the second line 
    r   r   Ng      ?r&   )Z
line0_pos0Z
line0_pos1Z
line1_pos0Z
line1_pos1Zline0_aZline0_bZline0_cZline1_aZline1_bZline1_cdZintersect_lonZintersect_latr&   r&   r'   r      s     r   c                 C   st  t |d d }tj| |ftd}tj| |ftd}tj| |ftd}t||D ]0\}}|d |t|d d ddf< |d |t|d d ddf< |d |t|d d < q(tj|dd	}	tj|dd	}
tj|dd	}t }d
|d< |	|d< |
|d< t }d|d< tt|	|
 }||d< t }d
|d< ||d< t	
|}|| || t	
|}|| ||fS )a  for multiprofiles, calculate the average value
       the input parameters is a list composed by dict
       for profile_dict_list:
       [{'NO':1, 'p_start':array([lon_s,lat_s]), 'p_end':array([lon_e,lat_e]), 'm_data':array([1, 2, 3, 4, 5]),'s_data':array([1, 2, 3, 4, 5])},{}...]
       for profile_dem_list:
       [{'NO':1, 'value':array([1,2,3,4,5])},{}...]
       the output:
       profile_dict_final:
       [{'NO':1, 'p_start':array([lon_s,lat_s]), 'p_end':array([lon_e,lat_e]), 'm_data':array([1, 2, 3, 4, 5]),'s_data':array([1, 2, 3, 4, 5])},{}...
        ,{'NO':'average','m_data':array([]),'s_data':([])}]
       profile_dem_final:
       [{'NO':1, 'value':array([1,2,3,4,5])},{}...,{'NO':'average', 'value':array([])}]
    r   m_datar
   NOr   Ns_datavaluer   average
differencedata)lenr   r   r   zipintnanmeanr,   abscopydeepcopyappend)r   profile_dict_listprofile_dem_listlengthZm_sumZs_sumZdem_sumprodemZ	m_averageZ	s_averageZdem_averageprofile_averageZprofile_differenceZsubtractionZdem_dictprofile_dict_finalprofile_dem_finalr&   r&   r'   rF      s8     




rF   c              	   C   s  ddg}t jdd|d\}}|}td t| d d }	td|	d }
| D ]W}|d d	krS|d d
krS|j|
|d d dddd |j|
|d d d dddd q&|d d
kr}|d d	kr}|j|
|d d dd|d |j|
|d d d dd|d q&|jdddddddd |	 }|d }|j|
|d ddd  |
t|d t|d d!  |jdddddddd d"d#d$d%}|d&| |d'| |d(| t| d d) d }t| d d) d }t| d d* d }t| d d* d }t||||}tjdtt|ddd+}|tjd|	ddd+ |d,d- |D  | |  }d.d- |D  |jd/|d0 d1| d2 | d3 }|| }|j|d4d5d6 d7S )8z*plot multi profiles with the average value
      r   figsizeD*****************************ploting profile************************r   r2   r3   r6   r7   d   .	lightgray      ?)markercalphar4   g?lightskyblueblack-color	linestylelabelbluebothin   TFwhich	direction	labelsizebottomtopleftrightr5   magentarY   rZ     serifnormal      2@familyweightsizeDistance [km]LOS Displacement [cm]Elevation [km]p_startp_endnumendpointc                 S      g | ]
}t tt|qS r&   strr;   round.0ir&   r&   r'   
<listcomp>      z!profiles_plot.<locals>.<listcomp>c                 S      g | ]}| d qS rl   set_fontnamer   r[   r&   r&   r'   r         
upper leftlocpropZ	Profiles__.png,  tightdpibbox_inchesN)pltsubplotsprintr9   r   r   scatterplottick_paramstwinxset_ylimnanminnanmax
set_xlabel
set_ylabelr>   r?   distance_2pointslinspacer;   ceil
set_xticksset_xticklabelsget_xticklabelsget_yticklabelslegendsavefig)rG   rH   m_names_nameoutdirfigure_sizefigaxesax1rC   x_axisrD   ax2Zdem_avefont1lon_slat_slon_elat_edistancexticklabelsfig_name
fig_outputr&   r&   r'   profiles_plot   sR   " $r   c
              	   C   s  ddg}
t jdd|
d\}}|}td tdt|d }|j||dd|d |j||d	d|d |jd
ddddddd | }|j||ddd |	t
|t|d  |jd
ddddddd dddd}|d| |d| |d| t| |||}tjdtt|ddd}|tjdt|ddd |dd |D  | |  }dd |D  |jd|d  d!| d" | d# }|	| }|j|d$d%d& d'S )(z,plot master and slave data along one profilerI   rJ   r   rK   rM   rV   rW   rX   r\   r]   r^   r_   Tr`   ri   rj   rk   Frl   rm   rn   ro   rs   rt   ru   r   rx   c                 S   r{   r&   r|   r   r&   r&   r'   r   /  r   z profile_plot.<locals>.<listcomp>c                 S   r   r   r   r   r&   r&   r'   r   2  r   r   r   ZProfile_r   r   r   r   r   N)r   r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r   r;   r   r   r   r   r   r   r   )r   r   r   r   	m_profile	s_profiler   r   dem_profiler   r   r   r   r   r   r   r   r   r   r   r   r   r&   r&   r'   profile_plot  s:   r   c                 C   s   d}t | }t |}t |}t |}|| }	|| }
t |
d d t |t | t |	d d   }dt t |t d|  }|| }|S )z@calculate distance[km] between two points based on their lat/long     @r   r   )mathradianssincosatan2sqrt)r   r   r   r   RZ	lon_s_radZ	lat_s_radZ	lon_e_radZ	lat_e_radZdlonZdlatarS   r   r&   r&   r'   r   ;  s   



8 r   c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )Profilea  Profile class for profiles
    Example:
      import matplotlib.pyplot as plt
      from mimtpy.objects.profiles import Profile
      import mimtpy.objects.profiles as profiles
      pro_no, pro_lons, pro_lats = profiles.search_profiles(3,over_lat0, over_lon0, over_lat1, over_lon1, m_atr, s_atr)
      pro_obj = Profile(1, pi/6, pro_lon, pro_lat, m_overlay, s_overlay, over_lat0, over_lon0, m_atr, s_atr, outdir='$SCRATCHDIR/project/'+pro_No)
      pro_obj.profile_extract()
    c                 C   sF   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
d S )N)r3   	pro_anglepro_lonpro_lat	m_overlay	s_overlayr   r   r   r   r   )selfr3   r   r   r   r   r   r   r   r   r   r   r&   r&   r'   __init__X  s   
zProfile.__init__c                 C   s\   t | jd }t | jd }t| j| j | d | _t| j| j | d | _| j| jfS )z<transfer lon/lat of user selected points to local coordinateY_STEPX_STEPrQ   )	r   r   r;   r   r   row_yr   r   colm_x)r   lat_steplon_stepr&   r&   r'   lonlat2rowcolme  s
   zProfile.lonlat2rowcolmc                 C   s@   t | jd }t | jd }| j||  }| j||  }||fS )z#transfer row/colm to geo coordinater   r   )r   r   r   r   )r   rowcolmr   r   lonlatr&   r&   r'   
rowcolm2lln  s
   zProfile.rowcolm2llc                 C   s  | j d | d }t|dd}|d |dtt| j| jdtt| j| jdtt| j	| j
dtt| j	| j
dg	 |d	 |d
 |d |d |d |d |d |d |t| jdt| j	dg |t| jdt| j
dg |  dS )z4write lon/lat of two ends of profile into gmt formatZprofile_latlon_z.gmtw)modez# @VGMT1.0 @GLINESTRING 
z# @R/
z# @Je4326 
z,# @Jp"+proj=longlat +datum=WGS84 +no_defs" 
aY  # @Jw"GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\",EAST],AUTHORITY[\"EPSG\",\"4326\"]]" 
z# @NId 
z# @Tinteger 
z# FEATURE_DATA 
>z# @D0 
 N)r   openwrite
writelinesr}   min	lon_startlon_endmax	lat_startlat_endclose)r   nameZgmt_filefr&   r&   r'   profile_gmtx  s    
T







zProfile.profile_gmtc                 C   sJ   | j | j| j| j| j | j d}t| j| d d	t
| dS )zAsave each profile geometry info and data along value as json file)r   r   r   r   r2   r4   z.jsonr   N)r   r   r   r   r   tolistr   r   r   r   jsondumps)r   r   profile_datar&   r&   r'   profile_json  s   $zProfile.profile_jsonc                 C   s6  t | j\}}|   | j}| j}| j}|dt j d kr\|dt j d kr\t |}|dt j d krHdt	
| }t || | | }n>|dt j d kr[t t || }n*t |}|dkrxdt	
| }t || | | }ntdkrt t || }|jt jd| _|jt jd| _| j| j| jf | _| j| j| jf | _t j| j| jdk< t j| j| jdk< | jd }	| jd }
| jd }| jd }| |	|\| _| _| |
|\| _| _| jd }td	|d
 | _| jd }td	|d
 | _ | jd | j  d t!| j" }| #| | $| dS )z6extract m_overlay and s_overlay data along the profile-         Z   rh   r   r
   	FILE_PATHzSen([^/]+)/r   r   N)%r   shaper   r   r   r   r   pir   r   tanr   onesZanlgeastyper;   row_nocolm_nor   r   r   nanr   r   r   r   r   r   r   searchr   r   r   r}   r3   r   r   )r   rowscolmsr   r   angler  Z	tan_valuer   	row_startrow_endZ
colm_startZcolm_endZ
m_name_tmpZ
s_name_tmpZpro_namer&   r&   r'   profile_extract  sN   $









zProfile.profile_extractN)
__name__
__module____qualname____doc__r   r   r   r   r   r	  r&   r&   r&   r'   r   M  s    
	
r   )osr   r>   r   r   matplotlib.pyplotpyplotr   numpyr   r(   r   r   rF   r   r   r   r   r&   r&   r&   r'   <module>   s   
n36*