U
    cab	n                     @   s8  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Zd dlZd dl	Z	d dl
mZ d dlmZmZmZ d dlmZmZmZmZmZ d dlmZ d dlm  m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 Z#dd Z$dd Z%d&ddZ&dd Z'dd Z(d d! Z)d'd"d#Z*e+d$kr4e*  dS )(    N)readfile	writefileptime)giantIfgramStackgiantTimeseriesifgramStack
timeseriesHDFEOS)Profilea  example:
    Note:
    if you want to make sure the REF is also correct, please make the dominant image is at the east of the affiliate image!
    concatenate_offset.py $SCRATCHDIR/BogdSenDT33/mintpy/geo_velocity.h5 $SCRATCHDIR/BogdSenDT106/mintpy/geo_velocity.h5  --rewrite_affiliate --outdir /data/lxr/insarlab/SCRATCHDIR/BalochistanSenDT/cumulative/

    concatenate_offset.py $SCRATCHDIR/BogdSenDT33/mintpy/geo_velocity.h5 $SCRATCHDIR/BogdSenDT106/mintpy/geo_velocity.h5 --output mosaic --outdir /data/lxr/insarlab/SCRATCHDIR/BalochistanSenDT/cumulative/

    concatenate_offset.py $SCRATCHDIR/BogdSenDT33/mintpy/geo_velocity.h5 $SCRATCHDIR/BogdSenDT106/mintpy/geo_velocity.h5 --output Bogd_mosaic --plotpair --pro_num 1 --ll 99.5 45 -g $SCRATCHDIR/BogdSenDT33/mintpy/inputs/geo_geometry.h5 --outdir ./
    
    concatenate_offset.py $SCRATCHDIR/BogdSenDT33/mintpy/geo_velocity.h5 $SCRATCHDIR/BogdSenDT106/mintpy/geo_velocity.h5 --output Bogd_mosaic --plotpair --pro_num 3 -g $SCRATCHDIR/BogdSenDT33/mintpy/inputs/geo_geometry.h5 --outdir ./

    concatenate_offset.py $SCRATCHDIR/BogdSenDT33/mintpy/inputs/geo_geometryRadar.h5 $SCRATCHDIR/BogdSenDT106/mintpy/inputs/geo_geometryRadar.h5 -ot ave --output Bogd_mosaic --outdir ./

    concatenate_offset.py ../../SpainSenAT147/mintpy/timeseries/timeseries_demErr_ERA5.h5 ../../SpainSenAT74/mintpy/timeseries/timeseries_demErr_ERA5.h5 --output timeseries_AT147_74 --outdir ./

    concatenate_offset.py ../../KokoxiliBigSenAT114/velocity/velocity_lat30_41.h5 ../../KokoxiliBigSenAT41/velocity/velocity_lat30_41.h5 --output steeks --outdir ./ --plotpair -g ../../KokoxiliBigSenAT114/geometry/geo_lat30_41.h5 --pro_num 5

c               	   C   s   t jdt jtd} | jdddd | jdddd | jd	d
dtdddd | jddddd | jdd}|jddddd |jddtdd |jddtdd d! |jd"d#d$td%d | jd&d}|jd'd(d)d*td+d, |jd-d.dd/d0 | jd1d2tdd2d! | S )3Nz>Concatenating two different tracks based on the overlay region)descriptionformatter_classepilogdominant   zdominant track. 
)nargshelp	affiliatezaffiliate track. 
 z-bz--bboxSNWE   )SNWEzBounding box of area to be geocoded.
Include the uppler left corner of the first pixel    and the lower right corner of the last pixel)desttyper   metavarr   z--rewrite_affiliate
store_trueFz:whether rewrite affiliate *.h5 file after add the offset.
)actiondefaultr   z8whether plot profiles for overlay regions of both tracks)titlez
--plotpairz;whether plot profiles for overlay regions of both tracks. 
z	--pro_numpro_numzprofile numbers
)r   r   r   z--llLONLAT   zglongitude and latitude of point that you want to profile pass through.use this option when pro_num = 1.)r   r   r   r   z-gz
--geometrygeometryz geoemtry data of dominant track.zmosaic optionsz-otz--overlapTreatmentoverlapTreatment?a  process method of incidence and azimuth angle for overlapping region,average: using average value of dominant and affiliate track for the overlapping region;dominant: using dominant swath value for the overlapping region;affiliate: using affiliate swath value for the overlapping region)r   r   r   r   z--outputoutputzoutput name)r   r   r   z--outdiroutdir)	argparseArgumentParserRawTextHelpFormatterEXAMPLEadd_argumentfloatadd_argument_groupintstr)parserZplotpair_optmosaic r3   O/home/centos/operations/rsmas_insar/sources/MimtPy/mimtpy/concatenate_offset.pycreate_parser3   s0    r5   c                 C   s   t  }|j| d}|S )N)args)r5   
parse_args)iargsr1   inpsr3   r3   r4   cmd_line_parse\   s    r:   c                    s   t  d t  d  }}d  krxt d }t d }t d }t d }||d |  }||d |  }np fdd	d
D }	 fdd	d
D }
t|	dd }t|	dd }t|
ddd }t|
ddd }||||fS )zget lon/lat range
    lat0,lon0- starting latitude/longitude (first row/column)
    lat1,lon1- ending latitude/longitude (last row/column)
    LENGTHWIDTHY_FIRSTX_FIRSTY_STEPX_STEPr   c                    s   g | ]}t  d | qS )z	LAT_REF{}r-   format.0iatrr3   r4   
<listcomp>s   s     z$get_bounding_box.<locals>.<listcomp>)r   r"      r   c                    s   g | ]}t  d | qS )z	LON_REF{}rA   rC   rF   r3   r4   rH   t   s     r   r"   r   rI   )r/   keysr-   npmean)rG   lengthwidthlat0lon0lat_steplon_steplat1lon1latslonsr3   rF   r4   get_bounding_boxb   s    rW   c                 C   s0   t ||  | d }t || | d }||fS )N      ?r/   )rO   rP   Zlat_nZlon_nrQ   rR   rowcolmr3   r3   r4   calculate_rc{   s    r\   c                 C   s8   t ||  | d d }t || | d d }||fS )NrX   r   rY   )rO   rP   rS   rT   rQ   rR   rowscolmsr3   r3   r4   calculate_roco_overlay   s    r_   c                 C   s   | |kr| S |S d S Nr3   abr3   r3   r4   max   s    rd   c                 C   s   | |k r| S |S d S r`   r3   ra   r3   r3   r4   min   s    re   c           )   	   C   s<  t  }t|\}}}	}
t|\}}}}t||}t||}t|	|}t|
|}| jd krj|}|}|}|}nt| jd }t| jd }t| jd }t| jd }||k r|  tdnB||kr|  tdn(t||}t||}t||}t||}t||||t|d t|d \}}t	||||t|d t|d \}}t	||||t|d t|d \}} |dks|dkr$|||| ||| f }!|||| | | | f }"|!|" }#t
|#}$d	| kr|d
 }%|d }&|d }'|d }(n|d }'|d }(|$|||| ||||f	S |||| ||||fS d S )Nr   r"   r   rI   z/input bounding box error! Wrong latitude order!z0input bounding box error! Wrong longitude order!r?   r@   r=   REF_LATREF_LONREF_XREF_Y)r5   rW   re   rd   r   r-   print_usage	Exceptionr_   r\   rK   	nanmedianrJ   ))r9   m_atrm_datas_atrs_datatypeflagr1   m_lat0m_lon0m_lat1m_lon1s_lat0s_lon0s_lat1s_lon1Zover_lat0_tmpZover_lon0_tmpZover_lat1_tmpZover_lon1_tmp	over_lat0	over_lon0	over_lat1	over_lon1	user_lat0	user_lon0	user_lat1	user_lon1overlay_rowsoverlay_colmsm_row0m_colm0s_row0s_colm0	m_overlay	s_overlayZoffset_overlayoffsetref_latref_lonref_xref_yr3   r3   r4   calculate_overlay   sV    










&&&

	r   c              	   C   s   || }d tjd| jd dd dtjd| jd dd }| jd krf| jd }|| }| jrtj	|||d |S )N{}{}{} r   .r   z_offset.out_filemetadata)
rB   ospathsplitjoinr   r'   rewrite_affiliater   write)r9   r   ro   rp   s_data_offsetr   out_dirout_dir_filer3   r3   r4   r      s    J

r   c                 C   s   | j \}}tj||ftjdtj }t|D ]}t|D ]v}| ||f tjkr|||f tjkrt| ||f |||f g|||f< q8t| ||f |||f g|||f< q8q,|S )Ndtype)shaperK   zerosfloat32nanrangesumnansum)Zmatrix1Zmatrix2r]   r^   Z
matrix_sumrZ   r[   r3   r3   r4   sum_matrix_nan   s    
$(*r   c           R      C   s  t |}|j\}}|}|j\}}|||| ||| f }|||| ||| f }tt|| }tj||ftjd}t|}t|}d||< d||< ||@ }||B }tj	||< d|| < || }|r$| j
dkr||  || < d|| < n&| j
dkr$||  || < d|| < || }|| | }|| | }tj||ftjdtj	 } t|\}!}"}#}$t|\}%}&}'}(t|!|%})t|"|&}*t|#|'}+t|$|(},t|d }-t|d }.t|)|*|!|"|-|.\}/}0t|)|*|%|&|-|.\}1}2t|)|*|	|
|-|.\}3}4|| |/|/| |0|0| f< || |1|1| |2|2| f< || |3|3| |4|4| f< |}5||5d	< ||5d
< |*|5d< |)|5d< |)|5d< |)|5d< |)|5d< |d dkr |d |5d< |d |5d< |d |5d< |d |5d< |d |5d< |d |5d< |d |5d< |d |5d< n`|d |5d< |d |5d< |d |5d< |d |5d< |d |5d< |d |5d< |d |5d< |d |5d< | jr| jd }6| j}7tj|7ddd }8|8||| ||| f }9|	|d |-  }:|
|d |.  };|d }<td|<}=t|=d }>t|=d }?t|=d }@t|=d }At|@|> |A|?  }B| jdkrt| jd }Ct| jd }Dtd|B|C|D|||	|
|||6}E|E  |9|Ej|Ejf }Ft !|Ej"|Ej#|Ej$|Ej%|Ej&|Ej'|Ej(|Ej)|F|6
 nXt *| j|	|
|:|;||}Gg }Hg }I|Gdddf D ]}Jt+ }Ktt,|J|B|Gt,|Jd df |Gt,|Jd df |||	|
|||6}E|E  t,|J|Kd< t-|Ej"|Ej#g|Kd< t-|Ej$|Ej%g|Kd< |Ej&|Kd < |Ej'|Kd!< |H.|K t+ }Lt,|J|Ld< |9|Ej|Ejf |Ld"< |I.|L |Ej(}M|Ej)}Nqt /| j|H|I\}O}P|d# d$krd$}Qnd%}Qt 0|O|P|M|N|Q|6 | |5fS )&zmosaic two tracksr   r   r"   r   r   r   r?   r@   r;   r<   r>   r=   ORBIT_DIRECTIONZ
DESCENDINGLAT_REF1LON_REF1LAT_REF3LON_REF3LAT_REF2LON_REF2LAT_REF4LON_REF4heightdatasetNamescene_footprintz
([\d+\.]+)rI   NNOZp_startZp_endrn   rp   value	FILE_TYPEvelocitydisplacement)1copydeepcopyr   rK   nanmeanabsonesr   isnanr   r$   r   rW   rd   re   r-   r\   Zplotpairr'   r#   r   readrefindallmathatanr    r!   r
   Zprofile_extractZrow_noZcolm_noprofilesZprofile_plot	lon_start	lat_startZlon_endZlat_endZ	m_profileZ	s_profilem_names_nameZsearch_profilesdictr/   arrayappendZprofile_averageZprofiles_plot)Rr9   rm   rn   ro   r   r   r   r   r   rz   r{   r   r   dsliceZmm_atrm_rowsm_colmsrp   s_rowss_colmsr   r   Zms_differenceZmosaic_freqZ
m_over_posZ
s_over_posboth_nanZnone_nanZmosaic_overlay_tmpZmosaic_overlaymosaic_rowsmosaic_colmsmosaic_datarr   rs   rt   ru   rv   rw   rx   ry   Zmosaic_lat0Zmosaic_lon0Zmosaic_lat1Zmosaic_lon1Zmosaic_lat_stepZmosaic_lon_stepZ
m_row_loc0Zm_colm_loc0Z
s_row_loc0Zs_colm_loc0Zoverlay_row_loc0Zoverlay_colm_loc0
mosaic_atrr'   Zgeometry_fileZ
topographyZoverlap_demr|   r}   polygonZlonlatsZlon_urZlat_urZlon_lrZlat_lrZ	angle_radZ	point_lonZ	point_latZpro_objZdem_profileZpro_catalogZprofile_dict_listZprofile_dem_listZpro_NOZprofile_dictZprofile_demr   r   Zprofile_dict_finalZprofile_dem_finalfiletyper3   r3   r4   mosaic_tracks   s    













0@




r   c              	   C   s   | j dkrVdtjd| jd dd dtjd| jd dd }n4dd| j dtjd| jd dd }| jdkr| jd }|| }tj	|||d dS )	zwrite mosaic dataNr   r   r   r   r   z_mosaic.r   )
r&   rB   r   r   r   r   r   r'   r   r   )r9   r   r   r   r   r   r3   r3   r4   write_mosaic  s    
L4

r   c                 C   s@   | d }|dkrd}n&|dkr$d}n| ddkr8d}nd	}|S )
zOjudage dominant/affiliate image is data(velocity or .unw) or dataset (geometry)r   r#   r   r   r"   	coherencerI   r   )find)rm   	file_typerq   r3   r3   r4   judge_data_datasets  s    r   c                 C   s:  t | d }t |d }g }g }	g }
||krt|D ]n}|| }tt|| }||dk  }|jdkr:|| |  |
||  |	t||dk  d  q:|}n~t|D ]n}|| }tt|| }||dk  }|jdkr|	||  |
||  |t| |dk  d  q|	}|||	|
fS )z;match the date in dominant and affiliate timeseries datasetr   g{Gz?r   )r   date_list2vectorrK   aranger   r   sizer   )
m_dateList
s_dateListm_dims_dimm_bperps_bperpZm_datevectorZs_datevectorm_Dates_DatebperprE   dateZdate_subZdate_obj
date_finalr3   r3   r4   
date_match  s2    

r   c           1      C   s  t | }td|j}td|j}t|}|dkrtd|jd }td|jd }t||||||\	}}}	}
}}}}}t	||||}t
|||||||	|
|||||\}}t||| n|dkrdddddd	g}d|j}d|j}t }|D ]}tj||d
d }tj||d
d }t||||||\}}	}
}}}}}|dksh|dkrt
|||||||	|
||||||d\}}n$t
|||||||	|
|||||\}}|||< q
t||| n|dkr&d|j}d|j}tj|dd
d }tj|dd
d }t|d}|d }t| }t|d}|d }t| }|jd }|jdd \}} |jd }!|jdd \}"}#t }t||||!||\}$}%}&}'t|%}(t|||dddddf ||dddddf |\	}}}	}
}}}}}||" | })| |# | }*tj|(|)|*fd}+d},t|%|&D ]\}-}.tj||-d
d }/tj||.d
d }0t|||/||0|\	}}}	}
}}}}}t	||||0}t
|||/||||	|
|||||\|+|,ddddf< }|,d },q8tj|'tjd|d< tj|$tjd|d< |+|d< t|$d |d< t||| n|dkrd|j}d|j}t }t|d }t|d }t||||||\}}	}
}}}}}t
|||||||	|
|||||\}}t||| dS )zsimulate LOS displacementr   r   r   azimuthAngler   incidenceAnglelatitude	longitudeslantRangeDistancer   )r   r"   r   rr   rI   N)r   r   r   REF_DATE)r:   r   read_attributer   r   r   r   r   r   r   r   r   r   h5pyFiler   get_date_listr   r   lenrK   emptyzipr   r   string_r0   )1r8   r9   rm   ro   rq   rn   rp   r   r   r   r   r   rz   r{   r   r   r   r   r   Z	datasliceZm_fileZs_fileZmosaic_datasetr   Zm_bperp_dater   r   Zs_bperp_dater   r   r   r   r   r   r   r   r   r   r   r   Z
mosaic_dimr   r   Zmosaic_timeseriesrE   m_dates_dateZdominant_dataZaffiliate_datar3   r3   r4   main  s    $$
"*$


H$6
"$r  __main__)N)N)N),r   sysr(   r   numpyrK   jsonr   r   r   matplotlib.pyplotpyplotpltmintpy.utilsr   r   r   mintpy.objectsr   r   r   r   r	   Zmimtpy.objects.profilesr
   objectsr   r+   r5   r:   rW   r\   r_   rd   re   r   r   r   r   r   r   r   r  __name__r3   r3   r3   r4   <module>   s@   )
K
 0"
s
