B
    QaY                 @   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mZm	Z	m
ZmZ d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ejfddZdddZdd ZdddZedkreejdd  dS )     N)ptimereadfile	writefileutils	attributea  template
## if both yx and lalo are specified, use lalo option unless a) no lookup file AND b) dataset is in radar coord
mintpy.subset.yx       = auto    #[1800:2000,700:800 / no], auto for no
mintpy.subset.lalo     = auto    #[31.5:32.5,130.5:131.0 / no], auto for no
a  example:
  subset.py inputs/ifgramStack.h5 -y 400  1500 -x 200   600
  subset.py geo_velocity.h5       -l 30.5 30.8 -L 130.3 130.9
  subset.py 030405_090801.unw     -t SinabungT495F50AlosA.template

  # subset to the same coverage as the reference file
  subset.py geo_incidence.h5 -r subset_geo_velocity.h5

  # multiple files input
  subset.py *velocity*.h5 timeseries*.h5  -y 400 1500  -x 200 600

  # crop to larger area with custom fill value 
  subset.py geo_velocity.h5 -l 32.2 33.5  --outfill-nan
  subset.py Mask.h5 -x 500 3500 --outfill 0

  # "tight" subset for geocoded lookup table larger than data file
  subset.py geomap_4rlks.trans --tight
c           
   C   s  t jdt jtd t d} | jdddd | jdd	d
dtddd | jddddtddd | jdddddtddd | jdddddtddd | jd d!d"d#d$ | jd%d&d'd( | jd)d*d+d, | jd-d.td/d0 | jd1d2d3d4d5d6 | jd7d8d9d:d$ | d;d<}|jd=d>d?d$ | S )@Nz#Generate a subset from file/dataset
)descriptionformatter_classepilogfile+zFile(s) to subset/crop)nargshelpz-xz--sub-xz
--subset-xsubset_x   z.subset range in x/cross-track/column direction)desttyper   r   z-yz--sub-yz
--subset-ysubset_yz+subset range in y/along-track/row directionz-lz--latz	--sub-latz--subset-lat
subset_latzsubset range in latitudez-Lz--lonz	--sub-lonz--subset-lon
subset_lonzsubset range in column

z-tz
--templatetemplate_filez}template file with subset setting.  i.e. 
mintpy.subset.yx    = 300:800,1000:3500
mintpy.subset.lalo  = 30.2:30.5,130.1:131.3)r   r   z-rz--referencez9reference file, subset to the same lalo as reference file)r   z--tight
store_truezsubset geomap_*.trans file based on non-zero values.
For geocoded file(s) onlyA convenient way to get rid of extra wide space due to "too large" DEM.

)actionr   z	--outfill
fill_valuezyfill subset area out of data coverage with input value. i.e. 
np.nan, 0, 1000, ... 
By default, it's None for no-outfill.)r   r   r   z--no-parallelparallelstore_falseTz=Disable parallel processing. Diabled auto for 1 input file.

)r   r   defaultr   z-oz--outputoutfilezloutput file name
add prefix "sub_" if input/output files are in the same directory;
same filename otherwise.DatasetszpCreate a subset of entire dataset in radar using y/x or lat/lon option
Including *.trans and *.dem in geo coord.z--lookuplookup_filezcalculate bounding box in geo/radar coord from input radar/geo subset range
using transformation file, i.e. geomap_4rlks.trans
All input radar coord file should be same size/coverage; same for all geo coord files.)	argparseArgumentParserRawTextHelpFormatterTEMPLATEEXAMPLEadd_argumentintfloatadd_argument_group)parserZ
dset_group r*   C/home/centos/operations/rsmas_insar/sources/MintPy/mintpy/subset.pycreate_parser2   s:    


r,   c             C   s8   t  }|j| d}t|j|_t|jdkr4d |_|S )N)args   )r,   
parse_argsutget_file_listr   lenr   )iargsr)   inpsr*   r*   r+   cmd_line_parseb   s    r5   c             C   s   t | d }t | d }yXt| d }t| d }t| d }t| d }|||  }|||  }||||f}	W n tk
r   d}	Y nX y0t | d t | d	 t | d
 t | d f}
W n tk
r   d}
Y nX |
|	fS )zGet Coverage Box of data in geo and pixel coordinates
    Inputs: atr - dict, meta data dictionary
    Outputs:
        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WIDTHY_STEPX_STEPY_FIRSTX_FIRSTNSUBSET_XMINSUBSET_YMINSUBSET_XMAXSUBSET_YMAX)r&   r'   
ValueError)atrlengthwidthlat_steplon_stepZul_latZul_lonZlr_latZlr_longeo_boxpix_boxr*   r*   r+   get_coverage_boxo   s(    




rH   c             C   s  t | }yhdd |d dD }tdd |d dD \}}tdd |d	 dD \}}||||f}W n   d
}Y nX yhdd |d dD }tdd |d dD \}}	tdd |d	 dD \}
}|
|||	f}W n   d
}Y nX ||fS )ziRead mintpy.subset.lalo/yx option from template file into box type
    Return None if not specified.
    c             S   s$   g | ]}|  d dddqS )[ ])stripreplace).0ir*   r*   r+   
<listcomp>   s    z,read_subset_template2box.<locals>.<listcomp>zmintpy.subset.lalo,c             S   s   g | ]}t | qS r*   )r'   rL   )rN   rO   r*   r*   r+   rP      s    r   :c             S   s   g | ]}t | qS r*   )r'   rL   )rN   rO   r*   r*   r+   rP      s    r.   Nc             S   s$   g | ]}|  d dddqS )rI   rJ   rK   )rL   rM   )rN   rO   r*   r*   r+   rP      s    zmintpy.subset.yxc             S   s   g | ]}t | qS r*   )r&   rL   )rN   rO   r*   r*   r+   rP      s    c             S   s   g | ]}t | qS r*   )r&   rL   )rN   rO   r*   r*   r+   rP      s    )r   read_templatesplitsorted)r   tmploptslat0lat1lon0lon1rF   y0y1x0x1rG   r*   r*   r+   read_subset_template2box   s     
  
  
r`   c             C   sp   |r*|d |d g| _ |d |d g| _nd| _ d| _|r`|d |d g| _|d |d g| _nd| _d| _| S )z9Update inps.subset_y/x/lat/lon from pixel_box and geo_boxr   r   r.      N)r   r   r   r   )r4   rG   rF   r*   r*   r+   subset_box2inps   s    rb   c       
      C   s  t | d |d }t | d |d }t| d |d }t| d |d }||ksX||krd}|d| 7 }|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

    Inputs:
        box1/2 : 4-tuple of int, indicating coverage of box1/2
                 defining in (x0, y0, x1, y1)
    Outputs:
        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   ra   z(No overlap between two input box range!
z
box 1: {}
z
box 2: {}
)maxminformatr@   )
Zbox1Zbox2r^   r\   r_   r]   msgZoverlap_boxZoverlap_idx_box1Zoverlap_idx_box2r*   r*   r+   get_box_overlap_index   s&    rg   c       	      C   s   t t|d }t t|d }t|}| ddrJ|j| d dd}n| d r\| d }nd|g}| d	dr|j| d	 d
d}n| d r| d }nd|g}t|}t|}|d |d |d |d f}||}||fS )aO  Convert subset inputs dict into box in radar and/or geo coord.
    Inputs:
        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
    Outputs:
        # box defined by 4-tuple of number, defining (left, upper, right, lower) coordinate,
        #                                            (UL_X, UL_Y,  LR_X,  LR_Y )
        pixel_box   : 4-tuple of int, in pixel unit - 1
        geo_box     : 4-tuple of float, in  lat/lon unit - degree
                      None if file is in radar coordinate.
    example:
        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}
        pixel_box          = subset_input_dict2box(subset_dict, meta_dict)[0]
        pixel_box, geo_box = subset_input_dict2box(subset_dict, meta_dict)
    r7   r6   r   Nlatitude)
coord_typer   r   r   	longituder   r.   )r&   r'   r0   
coordinategetlalo2yxrU   box_pixel2geo)	subset_dict	meta_dictrC   rB   coordsub_ysub_x	pixel_boxrF   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rt	|d	 |d
  |d |d  f|j
| }	||	|d
 |d	 |d |d f< nh|d	krt	|d |d	 |d
  |d |d  f|j
| }	||	d d |d
 |d	 |d |d f< |	S )Nzreading z in z from z ...F)datasetNamebox	print_msgr   r   ra   r.   )printospathbasenamer   readshaper2   nponesdtype)
fnamedsNamerG   pix_box4datapix_box4subsetr   datads_shapeds_ndimdata_outr*   r*   r+   subset_dataset"  s     $&

*r   c             C   s  t | }t|d }t|d }|d }td| d |  d  | }t||\}}	t|}
d}d| kr|d rd	}nd}|s|
	|}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| krv|d rvdtj| d
 tj| d }ndtj|  }ntj| }td|  t||}t | }tj|d }|dkr*tj||| d x|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
t|d d
t|d g}tj"||||d	d |dkrt#j$|d
 d}xt%|d
 D ]}|||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W |'  td"| W dQ R X qW nt( }x*|D ]"}t)| |||||d d#||< q6W t*| |d$< tj+|||| d% tj,| d& stj,| d' rt-|| |S )(a?  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
                    fill_value : float, optional. filled value for area outside of data coverage. default=None
                                 None/not-existed to subset within data coverage only.
                    tight   : bool, tight subset or not, for lookup table file, i.e. geomap*.trans
                out_file    : str, path/name of output file
    Outputs:    out_file    : str, path/name of output file
                    out_file = 'sub_'+fname, if fname is in current directory;
                    out_file = fname, if fname is not in the current directory.
    r7   r6   	FILE_TYPEzsubset z file: z ...Fr   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.tightz
{}_tight{}r.   Zsub_zwriting >>> )z.h5z.he5)metadataref_filerz cropping {d} in {b} from {f} ...)dbfr   ra   )r   )r   rv   blockrx   )maxValueNz{}/{})suffixzfinished writing to file: {})r   BANDS)out_filer   r   z.xmlz.aux.xml).r   read_attributer&   ry   copyru   r0   rk   keyscheck_box_within_data_coverager   nanrn   re   rg   rz   getcwdr{   dirnameabspathsplitextr|   attrupdate_attribute4subsetget_dataset_listr   layout_hdf5h5pyFiler~   ndimr   r   arraywrite_hdf5_blockr   progressBarrangeupdateclosedictr   r2   writeisfilewrite_isce_xml)r   Zsubset_dict_inputr   rA   rC   rB   kro   rG   rF   rq   Zoutfilldata_boxr   r   dsNamesextr   fidsr   r   r   r   r   prog_barrO   dsDictr*   r*   r+   subset_file?  s    








$
*$( 
$r   c             C   s  t dd | j| j| j| jgD r| jrTt| j}t|\}}t	d| j  nT| j
rzt| j
\}}t	d| j
  n.| jrt| j| _| jstdt| j}t|}d| krJtj| jddd }tj|d	d
\}}t||t|  k\}	}
t|
d t|	d t|
d t|	d f}||}~nTt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 )Nr*   )rN   rO   r*   r*   r+   	<genexpr>  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   )rv   r   T)return_inverse
   rh   rj   zNo subset inputs found!)allr   r   r   r   	referencer   r   rH   ry   r   r`   r   r0   get_lookup_filer   	Exceptionrk   r   r}   r   uniquewherebincountargmaxrd   rc   rn   nanminnanmaxrb   )r4   Zref_atrrG   rF   Zatr_lutrq   Zrg_lutZ	rg_uniqueZrg_posidx_rowidx_collatlonr*   r*   r+   read_aux_subset2inps  sD    
 
r   c             C   s@   t | }t|}x*|jD ] }td t|t||jd qW d S )Nz------------------------------)r   )r5   r   r   ry   r   varsr   )r3   r4   r   r*   r*   r+   main  s    r   __main__r.   )N)N)N)rz   sysr    r   numpyr   mintpy.utilsr   r   r   r   r0   r   r   r#   r$   r,   r5   rH   r`   rb   rg   ru   r   r   r   r   r   __name__argvr*   r*   r*   r+   <module>	   s*   0
#(<
  2
