o
    <c	n                     @   s:  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re*  dS 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   N/home/exouser/operations/rsmas_insar/tools/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  v r<t d }t d }t d }t d }||d |  }||d |  }n8 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                       g | ]}t  d | qS )z	LAT_REF{}r-   format.0iatrr3   r4   
<listcomp>s       z$get_bounding_box.<locals>.<listcomp>)r   r"      r   c                    rA   )z	LON_REF{}rB   rD   rG   r3   r4   rI   t   rJ   r   r"   r   rK   )r/   keysr-   npmean)rH   lengthwidthlat0lon0lat_steplon_steplat1lon1latslonsr3   rG   r4   get_bounding_boxb   s   rY   c                 C   s0   t ||  | d }t || | d }||fS )N      ?r/   )rQ   rR   Zlat_nZlon_nrS   rT   rowcolmr3   r3   r4   calculate_rc{   s   r^   c                 C   s8   t ||  | d d }t || | d d }||fS )NrZ   r   r[   )rQ   rR   rU   rV   rS   rT   rowscolmsr3   r3   r4   calculate_roco_overlay   s   ra   c                 C   s   | |kr| S |S Nr3   abr3   r3   r4   max      rf   c                 C   s   | |k r| S |S rb   r3   rc   r3   r3   r4   min   rg   rh   c           )   	   C   s0  t  }t|\}}}	}
t|\}}}}t||}t||}t|	|}t|
|}| jd kr5|}|}|}|}nHt| jd }t| jd }t| jd }t| jd }||k r]|  td||kri|  td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	| v r|d
 }%|d }&|d }'|d }(n|d }'|d }(|$|||| ||||f	S |||| ||||fS )Nr   r"   r   rK   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   rY   rh   rf   r   r-   print_usage	Exceptionra   r^   rM   	nanmedianrL   ))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r3| jd }|| }| jrBtj	|||d |S )N{}{}{} r   .r   z_offset.out_filemetadata)
rC   ospathsplitjoinr   r'   rewrite_affiliater   write)r9   r   rr   rs   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 ]B}t|D ];}| ||f tjkrD|||f tjkrDt| ||f |||f g|||f< qt| ||f |||f g|||f< qq|S )Ndtype)shaperM   zerosfloat32nanrangesumnansum)Zmatrix1Zmatrix2r_   r`   Z
matrix_sumr\   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< n0|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rVt| 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
 | |5fS t *| j|	|
|:|;||}Gg }Hg }I|Gdddf D ]s}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qnt /| 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datasetNameZscene_footprintz
([\d+\.]+)rK   NNOZp_startZp_endrq   rs   value	FILE_TYPEvelocitydisplacement)1copydeepcopyr   rM   nanmeanabsonesr   isnanr   r$   r   rY   rf   rh   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   rp   rq   rr   r   r   r   r   r   r}   r~   r   r   dsliceZmm_atrm_rowsm_colmsrs   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_dataru   rv   rw   rx   ry   rz   r{   r|   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   














,!@




r   c              	   C   s   | j dkr+dtjd| jd dd dtjd| jd dd }ndd| j dtjd| jd dd }| jdkrO| jd }|| }tj	|||d dS )	zwrite mosaic dataNr   r   r   r   r   z_mosaic.r   )
r&   rC   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   sF   | d }|dkrd}|S |dkrd}|S | ddkrd}|S d	}|S )
zOjudage dominant/affiliate image is data(velocity or .unw) or dataset (geometry)r   r#   r   r   r"   	coherencerK   r   )find)rp   	file_typert   r3   r3   r4   judge_data_datasets  s   r   c                 C   s:  t | d }t |d }g }g }	g }
||krXt|D ]7}|| }tt|| }||dk  }|jdkrT|| |  |
||  |	t||dk  d  q|}n?t|D ]7}|| }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_list2vectorrM   aranger   r   sizer   )
m_dateList
s_dateListm_dims_dimm_bperps_bperpZm_datevectorZs_datevectorm_Dates_DatebperprF   dateZdate_subZdate_obj
date_finalr3   r3   r4   
date_match  s6   

r   c           1      C   s  t | }td|j}td|j}t|}|dkrgtd|jd }td|jd }t||||||\	}}}	}
}}}}}t	||||}t
|||||||	|
|||||\}}t||| dS |dkrg d}d|j}d|j}t }|D ]X}tj||dd }tj||dd }t||||||\}}	}
}}}}}|dks|dkrt
|||||||	|
||||||d\}}nt
|||||||	|
|||||\}}|||< qt||| dS |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 ]O\}-}.tj||-dd }/tj||.dd }0t|||/||0|\	}}}	}
}}}}}t	||||0}t
|||/||||	|
|||||\|+|,ddddf< }|,d },qtj|'tjd|d< tj|$tjd|d< |+|d
< t|$d |d< t||| dS |dkrYd|j}d|j}t }t|d }t|d }t||||||\}}	}
}}}}}t
|||||||	|
|||||\}}t||| dS dS )zsimulate LOS displacementr   r   r   )azimuthAngler   incidenceAnglelatitude	longitudeslantRangeDistancer   r   r   )r   r"   r   rr   rK   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   lenrM   emptyzipr   r   string_r0   )1r8   r9   rp   rr   rt   rq   rs   r   r   r   r   r   r}   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_timeseriesrF   m_dates_dateZdominant_dataZaffiliate_datar3   r3   r4   main  s   $$"*$



H$6
"$r  __main__rb   ),r   sysr(   r   numpyrM   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:   rY   r^   ra   rf   rh   r   r   r   r   r   r   r   r  __name__r3   r3   r3   r4   <module>   sD   
)K
 0
"s
