o
    ldH                     @   s   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 Zdd Zdd Zd	d
 Zdd ZejfddZdddZdd ZdS )    N)	attributeptimereadfileutils	writefilec                    s   t  d }t  d }t fdddD rBt d }t d }t d }t d	 }|||  }|||  }||||f}	nd
}	t fdddD rit  d t  d t  d t  d f}
|
|	fS d
}
|
|	fS )zGet Coverage Box of data in geo and pixel coordinates.

    Parameters: atr     - dict, meta data dictionary
    Returns:    pix_box - 4-tuple of int, defining in (UL_X, UL_Y, LR_X, LR_Y)
                geo_box - 4-tuple of float in lat/lon
    LENGTHWIDTHc                 3   s    | ]	}|   v V  qd S Nkeys.0xatr F/home/exouser/operations/rsmas_insar/tools/MintPy/src/mintpy/subset.py	<genexpr>#   s    z#get_coverage_box.<locals>.<genexpr>)Y_STEPX_STEPY_FIRSTX_FIRSTr   r   r   r   Nc                 3   s"    | ]}d |    v V  qdS )ZSUBSET_Nr
   r   r   r   r   r   /   s     )YMINXMINYMAXXMAXZSUBSET_XMINZSUBSET_YMINZSUBSET_XMAXZSUBSET_YMAX)intallfloat)r   lengthwidthZlat_stepZlon_stepZul_latZul_lonZlr_latZlr_longeo_boxpix_boxr   r   r   get_coverage_box   s(   



	r#   c                 C   s  d\}}t | }d}|| v rD|| dddd}|dd}dd	 |dD }t|d
krDdd |D \}}}	}
|	||
|f}d}|| v r|| dddd}|dd}dd	 |dD }t|d
krdd |D \}}}}||||f}||fS )zRead mintpy.subset.lalo/yx option from template file into box type.

    Parameters: template_file - str, path to the template file
    Returns     pix/geo_box   - tuple of 4 int or None
    )NNzmintpy.subset.yx[ ]:,c                 S      g | ]}|  qS r   stripr   ir   r   r   
<listcomp>P       z,read_subset_template2box.<locals>.<listcomp>   c                 s       | ]}t |V  qd S r	   )r   r,   r   r   r   r   R       z+read_subset_template2box.<locals>.<genexpr>zmintpy.subset.laloc                 S   r)   r   r*   r,   r   r   r   r.   ]   r/   c                 s   r1   r	   )r   r,   r   r   r   r   _   r2   )r   Zread_templater   replacesplitlen)template_filer"   r!   ZtmplkeyZopt_strZopt_str_listy0y1x0x1Zlat0Zlat1Zlon0Zlon1r   r   r   read_subset_template2box<   s&   
r<   c                 C   sr   |r|d |d g| _ |d |d g| _nd| _ d| _|r1|d |d g| _|d |d g| _| S d| _d| _| S )z9Update inps.subset_y/x/lat/lon from pixel_box and geo_boxr            N)
subset_lon
subset_latsubset_xsubset_y)inpsr"   r!   r   r   r   subset_box2inpse   s   rE   c           
      C   s  t | d |d }t | d |d }t| d |d }t| d |d }||ks,||krBd}|d|  d7 }|d| d7 }t|||||f}|d | d  |d | d  |d | d  |d | d  f}|d |d  |d |d  |d |d  |d |d  f}	||	fS )	a{  Get index box overlap area of two input boxes.

    Parameters: box1/2             - 4-tuple of int, indicating coverage of box1/2
                                     defining in (x0, y0, x1, y1)
    Returns:    overlap_idx_box1/2 - 4-tuple of int, indicating index of overlap area in box1/2
                                     defining in (idx_x0, idx_y0, idx_x1, idx_y1)
    r   r>   r=   r?   z(No overlap between two input box range!
zbox 1: 
zbox 2: )maxmin
ValueError)
Zbox1Zbox2r:   r8   r;   r9   msgZoverlap_boxZoverlap_idx_box1Zoverlap_idx_box2r   r   r   get_box_overlap_indexv   s*   rK   c           	      C   s   t t|d }t t|d }t|}| ddr%|j| d dd}n| d r.| d }nd|g}| d	drB|j| d	 d
d}n| d rK| d }nd|g}t|}t|}|d |d |d |d f}||}||fS )a  Convert subset inputs dict into box in radar and/or geo coord.
    Parameters: subset_dict - dict, including the following 4 objects:
                              subset_x   : list of 2 int,   subset in x direction,   default=None
                              subset_y   : list of 2 int,   subset in y direction,   default=None
                              subset_lat : list of 2 float, subset in lat direction, default=None
                              subset_lon : list of 2 float, subset in lon direction, default=None
                meta_dict   - dict, including the following items:
                              'WIDTH'      : int
                              'LENGTH': int
                              'X_FIRST'    : float, optional
                              'Y_FIRST'    : float, optional
                              'X_STEP'     : float, optional
                              'Y_STEP'     : float, optional
    Returns:    pix_box     - 4-tuple of int, in pixel unit of 1, in (x0, y0, x1, y1)
                geo_box     - 4-tuple of float, in lat/lon unit (degree)
                              None if file is in radar coordinate.
    Examples:
        subset_dict = {'subset_x': None, 'subset_y': None, 'subset_lat': [30.5, 31.0], 'subset_lon': [130.0, 131.0]}
        subset_dict = {'subset_x': [100, 1100], 'subset_y': [2050, 2550], 'subset_lat': None, 'subset_lon': None}
        pix_box          = subset_input_dict2box(subset_dict, meta_dict)[0]
        pix_box, geo_box = subset_input_dict2box(subset_dict, meta_dict)
    r   r   rA   Nlatitude)Z
coord_typerC   r   r@   	longituderB   r>   )r   r   ut
coordinategetZlalo2yxsortedbox_pixel2geo)	subset_dictZ	meta_dictr    r   coordZsub_yZsub_xr"   r!   r   r   r   subset_input_dict2box   s$   



rU   c           
   	   C   s  t d| d| dtj|  d tj| ||ddd }|j}t|}|dkrSt	|d	 |d
  |d |d  f|j
| }	||	|d
 |d	 |d |d f< |	S |d	krt	|d |d	 |d
  |d |d  f|j
| }	||	d d |d
 |d	 |d |d f< |	S )Nzreading z in z from  ...F)datasetNamebox	print_msgr   r=   r?   r>   )printospathbasenamer   readshaper5   nponesdtype)
fnamedsNamer"   pix_box4datapix_box4subset
fill_valuedatads_shapeds_ndimdata_outr   r   r   subset_dataset   s@   $
rl   c                 C   s  t | }t|d }t|d }td|d  d|  d | }t||\}}t|}	d}
d| v r=|d r=d	}
nd}
|
sK|		|}t
j|d< |	|}d
d
||f}td|  td|  td|	|  td|  ||krtd | S t||\}}|st tjtj| krd| v r|d rtj| \}}| d| }ndtj|  }ntj| }td|  t||}t | }tj| d }tj|d }|dv rF|dv rtj||| d nt }|D ]>}t| d,}|| }|j}|j}tdj||tj| d |dkr||d |d |d
 |d f }t
 |d |d  |d |d
  f|j!|d  }|||d |d |d
 |d f< t
j"||j!d}|dv rd
t|d d
t|d g}tj#||||d	d n|||< n|dkr&|dvrt$d| dt%j&|d
 d }t'|d
 D ]s}|||d |d |d
 |d f }t
 d|d |d  |d |d
  f|j!|d  }||d!d!|d |d |d
 |d f< ||d d
t|d d
t|d g}tj#||||dd |j(|d |d  d"|d
  d# q|)  td$|  W d!   n	1 s1w   Y  q|dvrDtj*|||d% |S t }|D ]}t+| |||||d d&||< qKt,| |d'< tj*|||| d( |dvrtj-| d) stj-| d* rt.|| |S )+ai  Subset file with
    Parameters: fname       - str, path/name of file
                subset_dict - dict, subsut parameter, including the following items:
                    subset_x   : list of 2 int,   subset in x direction,   default=None
                    subset_y   : list of 2 int,   subset in y direction,   default=None
                    subset_lat : list of 2 float, subset in lat direction, default=None
                    subset_lon : list of 2 float, subset in lon direction, default=None
                    tight      : bool, tight subset or not, for lookup table file, i.e. geomap*.trans
                    fill_value : float, optional. filled value for area outside of data coverage. default=None
                                 None/not-existed to subset within data coverage only.
                out_file    - str, path/name of output file
    Returns:    out_file    - str, path/name of output file
                              default: add prefix 'sub_',   if fname     in the current directory;
                                       keep the same fname, if fname not in the current directory.
    r   r   zsubset 	FILE_TYPEz file: rV   Frg   Tr   zdata   range in (x0,y0,x1,y1): zsubset range in (x0,y0,x1,y1): zdata   range in (W, N, E, S): zsubset range in (W, N, E, S): z7Subset range == data coverage, no need to subset. Skip.tight_tightZsub_zwriting >>> r>   )z.h5z.he5)metadataref_filerz cropping {d} in {b} from {f} ...)dbfr=   r?   )rb   )rh   rW   blockrY   zWriting 3D dataset z# into binary file is NOT supported!)ZmaxValueN/)suffixzfinished writing to file: )out_filerp   )rg   ZBANDS)ry   rp   rq   z.xmlz.aux.xml)/r   read_attributer   rZ   copyrU   rN   rO   r   check_box_within_data_coverager`   nanrR   rK   r[   getcwdr\   dirnameabspathsplitextr]   attrZupdate_attribute4subsetZget_dataset_listr   Zlayout_hdf5dicth5pyZFiler_   ndimformatra   rb   arrayZwrite_hdf5_blockrI   r   ZprogressBarrangeupdateclosewriterl   r5   isfileZwrite_isce_xml)rc   Zsubset_dict_inputry   r   r    r   rS   r"   r!   rT   Zoutfilldata_boxre   rf   fbasefextZdsNamesZin_extZout_extZdsDictrd   fidsri   rj   rh   rk   rv   Zprog_barr-   r   r   r   subset_file   s  













$(
F	.r   c                 C   s  t dd | j| j| j| jfD r| jr(t| j}t|\}}t	d| j  n| j
r:t| j
\}}t	d| j
  n| jrt| j| _| jsKtdt| j}t|}d| v rtj| jddd }tj|d	d
\}}t||t|  k\}	}
t|
d t|	d t|
d t|	d f}||}~n/tj| jddd }tj| jddd }t|t|t|t|f}d }~~ntdt| ||} | S )Nc                 s   s    | ]}| V  qd S r	   r   r,   r   r   r   r     s    z'read_aux_subset2inps.<locals>.<genexpr>zusing subset info from z<No lookup file found! Can not use --tight option without it.r   r   )rW   r   T)return_inverse
   rL   rM   zNo subset inputs found!)r   rB   rC   rA   r@   Z	referencer   rz   r#   rZ   r6   r<   rn   rN   get_lookup_filelookup_file	ExceptionrO   r   r^   r`   uniquewherebincountargmaxrH   rG   rR   nanminnanmaxrE   )rD   Zref_atrr"   r!   Zatr_lutrT   Zrg_lutZ	rg_uniqueZrg_posZidx_rowZidx_collatlonr   r   r   read_aux_subset2inps  sJ   

 
r   r	   )r[   r   numpyr`   mintpy.utilsr   r   r   r   r   rN   r   r#   r<   rE   rK   rU   r}   rl   r   r   r   r   r   r   <module>   s   
%)&8
 5