U
     cX5                     @   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edZe	ej
 d dlmZmZmZmZ d dlmZ dZdddZddd	Zd
d ZdddZddd d d d gdfddZdddZedkreejdd  dS )    Nnumpy)readfile	writefileutils1	attribute)create_argument_parserzexample:
  multilook.py  velocity.h5  -r 15 -a 15
  multilook.py  srtm30m.dem  -r 10 -a 10  -o srtm30m_300m.dem

  # Ignore / skip marginal pixels
  multilook.py ../../geom_reference/hgt.rdr.full -r 300 -a 100 --margin 58 58 58 58 -o hgt.rdr
c              
   C   s   d}t }td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 |jdddtddddgdd  |jd!d"td#d$d%d%d%d%gd&d' |S )(NzMultilook the input file.)synopsisdescriptionepilog
subparsersfile+zFile(s) to multilook)nargshelpz-rz--rangez-xlks_x   zEnumber of multilooking in range  /x direction (default: %(default)s).)desttypedefaultr   z-az	--azimuthz-ylks_yzEnumber of multilooking in azimuth/y direction (default: %(default)s).z-oz	--outfilez7Output file name. Disabled when more than 1 input files)r   z-mz--methodmethodmeanmediannearestz_downsampling method (default: %(default)s) 
e.g. nearest for geometry, average for observations)r   r   r   choicesr   z--marginmargin   )ZTOPZBOTTOMLEFTRIGHTr   z?number of pixels on the margin to skip, (default: %(default)s).)r   r   r   metavarr   r   )EXAMPLE__name__splitr   add_argumentintstr)r   r
   r   nameparser r*   G/home/exouser/operations/rsmas_insar/sources/MintPy/mintpy/multilook.pycreate_parser'   s8        
 r,   c                 C   sb   t  }|j| d}t|j|_|jdkr<|jdkr<tdt|jdkr^|j	r^d |_	t
d |S )N)argsr   z,ERROR: no multilooking specified: lks_x/y=1!z<more than one file is input, disable custom output filename.)r,   
parse_argsutget_file_listr   r   r   
SystemExitlenoutfileprint)iargsr)   inpsr*   r*   r+   cmd_line_parse=   s    r7   c              	   C   s  | j \}}t|}t|}|dkr.|dkr.| S tt|| }tt|| }t||f}t||f}t  tjdtd t	|D ]8}	t
| dd|	| |	d | f d|dd|	f< qt	|D ]8}
t
||
| |
d | ddf d||
ddf< qW 5 Q R X ~ ~|S )zObsolete multilooking functionsr   ignorecategoryNr   )shaper&   npfloorzeroswarningscatch_warningssimplefilterRuntimeWarningrangenanmean)matrixr   r   rowscolsZrows_mliZcols_mliZmatrix_CmliZ
matrix_mlicrr*   r*   r+   multilook_matrixN   s"    

6@rJ   r   r   c              	   C   s
  dddg}||kr2d |}|d |7 }t|t|}t|}|| dkrR| S | j}tj| jtd}t|d | }t|d | }	t|d	kr|d
krTt	|||f 
t||f }
| d|
d d|
d f }||
d | ||
d | |f}t F tjdtd |dkr0tj|dd}n|dkrHtj|dd}W 5 Q R X nV|dkr| t|d	 d|t|d	 d|f }|j||	fkr|d|d|	f }nJt|dkr|d
krt	|d||f 
td||f }
| d|
d d|
d d|
d	 f }||
d |
d | ||
d	 | |f}t F tjdtd |dkrjtj|dd}n|dkrtj|dd}W 5 Q R X nj|dkr| ddt|d	 d|t|d	 d|f }|jdd ||	fkr|ddd|d|	f }tj||d}|S )a  Modified from Praveen on StackOverflow:

    link: https://stackoverflow.com/questions/34689519/how-to-coarser-the-2-d-array-data-resolution

    Parameters: data        : 2D / 3D np.array in real or complex
                lks_y       : int, number of multilook in y/azimuth direction
                lks_x       : int, number of multilook in x/range direction
                method      : str, multilook method, mean, median or nearest
    Returns:    coarse_data : 2D / 3D np.array after multilooking in last two dimension
    r   r   r   z#un-supported multilook method: {}. zAvailable methods: {}r   )dtyper      )r   r   Nr8   r9   )r      )axisrM   )rL   r   )format
ValueErrorr&   rK   r<   arrayr;   floatr2   r=   astypereshaper?   r@   rA   rB   rD   	nanmedian)datar   r   r   Zmethod_listmsgrK   r;   ysizexsize	new_shapeZ	crop_datatempZcoarse_datar*   r*   r+   multilook_dataf   s    


 
 





$

 
 





r]   r   c              
   C   s  t |}t |}t| }t |d t |d  }}	|d }
td|d |
|  td|  td|  td| |d	d	d	d	gk	r|d
 |d	 |	|d  ||d  f}td| nd	d	|	|f}tj| d }|s:t tj	tj
| kr.tj| d	 d t| d t| d | }ntj| }tj||||d}|dkrftj||| d t| }tdd |D }t }|D ]T}tdj||tj| d |dkr(t| d}|| }t|jd }W 5 Q R X t t|d |d  }t t|| d d }t|d}n|d |d  }t t|d |d  ||  }t|D ]z}|d || |  }|d || |d   }t||d }|d	 ||d
 |f}t |d	 |d	  | t ||d  | t |d
 |d	  | t ||d  | f}td| |dkr>tj| ||||ddd	 }n&tj| ||dd d	 }t||||d!}|jdkrd	|jd	 |d |d |d	 |d
 g}n|d |d |d	 |d
 g}|dkrtj ||||dd" n|||< qbqt!|" d
krDtj| d dkrD|#d#d$$ d$krDtd%|d#  td& d$|d#< |dkrt!|" |d'< tj%|||| d( tj&| d) stj&| d* rt'|| |S )+aA   Multilook input file
    Parameters: infile - str, path of input file to be multilooked.
                lks_y  - int, number of looks in y / row direction.
                lks_x  - int, number of looks in x / column direction.
                margin - list of 4 int, number of pixels to be skipped during multilooking.
                         useful for offset product, where the marginal pixels are ignored during
                         cross correlation matching.
                outfile - str, path of output file
    Returns:    outfile - str, path of output file
    LENGTHWIDTH	FILE_TYPEzmultilooking {} {} file: {}	PROCESSORz,number of looks in y / azimuth direction: %dz,number of looks in x / range   direction: %dzmultilook method: {}r   rL   rM   r   z@number of pixels to skip in top/bottom/left/right boundaries: {}_Zalks_Zrlks)box)z.h5z.he5)metadataref_filec                 S   s   g | ]}t |qS r*   )r2   ).0ir*   r*   r+   
<listcomp>   s     z"multilook_file.<locals>.<listcomp>z"multilooking {d:<{w}} from {f} ...)dwfrI   r   i   @
   zbox: {}r   F)datasetNamerc   xstepystep	print_msg)rm   rc   rp   )r   )rW   rm   blockrp   
INTERLEAVEBILz=the input binary file has 2 bands with band interleave as: {}zIfor the output binary file, change the band interleave to BIL as default.BANDS)out_filerd   re   z.xmlz.aux.xml)(r&   r   read_attributer4   rP   ospathsplitextgetcwddirnameabspathr'   basenameattrupdate_attribute4multilookr   layout_hdf5get_dataset_listmaxdicth5pyFiler<   prodr;   ceilrintrC   minreadr]   ndimwrite_hdf5_blockr2   keysgetupperwriteisfilewrite_isce_xml)infiler   r   r3   r   r   
max_memoryatrlengthwidthkrc   extdsNamesmaxDigitZdsDictdsNamerk   dsds_sizenum_steprow_steprg   r0r1Zbox_iZbox_orW   rq   r*   r*   r+   multilook_file   s    
$2


  

"

   

$r   c              	   C   s>   t | }|jD ]"}t||j|j|j|j|jd qtd d S )N)r   r   r3   r   r   zDone.)	r7   r   r   r   r   r3   r   r   r4   )r5   r6   r   r*   r*   r+   mainE  s    
r   __main__)N)N)r   r   r   )N)rw   sysr?   r   r   r<   logging	getLoggerZ	np_loggersetLevelWARNINGmintpy.utilsr   r   r   r/   r   r~   Zmintpy.utils.arg_utilsr   r"   r,   r7   rJ   r]   r   r   r#   argvr*   r*   r*   r+   <module>	   s&   
	


Y 
