U
     c?;                     @   s   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 d dl	m
Z
mZmZmZmZ edZdZdZddd	Zdd
dZdd Zdd Zdd Zdd Zdd ZdddZedkreejdd  dS )    N)resample)get_template_content)	arg_utilsreadfile	writefileutils	attributegeocodea  example:
  geocode.py velocity.h5
  geocode.py velocity.h5 -b -0.5 -0.25 -91.3 -91.1
  geocode.py velocity.h5 timeseries.h5 -t smallbaselineApp.cfg --outdir ./geo --update

  # geocode file using ISCE-2 lat/lon.rdr file
  geocode.py filt_fine.int --lat-file ../../geom_reference/lat.rdr --lon-file ../../geom_reference/lon.rdr

  # radar-code file in geo coordinates
  geocode.py swbdLat_S02_N01_Lon_W092_W090.wbd -l geometryRadar.h5 -o waterMask.rdr --geo2radar
  geocode.py geo_velocity.h5 --geo2radar
z
degrees     --> meters on equator
0.000925926 --> 100
0.000833334 --> 90
0.000555556 --> 60
0.000462963 --> 50
0.000277778 --> 30
0.000185185 --> 20
0.000092593 --> 10
c              
   C   s  d}t d t }tdd }tj||||| d}|jdddd	 |jd
ddd |jddddd |jdddd |jdddd |jdddddd |jdd d!d"d |d#}|jd$d%d&td'd(d)d* |jd+d,d-td.d/d0	t
d* |d1}|jd2d3d4d5d5d6hd7d8 |jd9d:ttjd;d< |jd=d>d?td@dAd< |jdBdCdDdDdEhdFd8 |jdGdHdIdJd |jdKdLdMdNd |jdOdPdQdRd t|}|S )SNz=Resample radar-coded files into geo-coordinates or vice versa
.)synopsisdescriptionepilog
subparsersfile+zFile(s) to be geocoded)nargshelpz-dz--dsetzdataset to be geocoded, for example:
height                        for geometryRadar.h5
unwrapPhase-20100114_20101017 for ifgramStack.h5)r   z-lz--lookup
lookupFilez0Lookup table file generated by InSAR processors.)destr   z
--lat-filelatFilezlookup table file for latitude.z
--lon-filelonFilez lookup table file for longitude.z--geo2radarz	--geo2rdr	radar2geostore_falsezcresample geocoded files into radar coordinates.
ONLY for lookup table in radar-coord (ISCE, Doris).)r   actionr   z-tz
--templatetemplateFilez%Template file with geocoding options.zgrid in geo-coordinatesz-bz--bboxSNWE   )SNWEzBounding box for the area of interest.
using coordinates of the uppler left corner of the first pixel
                 and the lower right corner of the last pixel
for radar2geo, it's the output spatial extent
for geo2radar, it's the input  spatial extent)r   typer   metavarr   z--laloz--lalo-steplaloStep   )ZLAT_STEPZLON_STEPz6output pixel size in degree in latitude / longitude.{}interpolationz-iz--interpinterpMethodnearestlinearz7interpolation/resampling method (default: %(default)s).)r   defaultchoicesr   z--fill	fillValuez4Fill value for extrapolation (default: %(default)s).)r   r#   r+   r   z-nz--nprocsnprocs   znumber of processors to be used for calculation (default: %(default)s).
Note: Do not use more processes than available processor cores.z
--softwaresoftware
pyresamplescipyzhsoftware/module used for interpolation (default: %(default)s)
Note: --bbox is not supported for -p scipyz--update
updateMode
store_truez?skip resampling if output file exists and newer than input filez-oz--outputoutfilez,output file name. Default: add prefix 'geo_'z--outdirz--output-dirout_dirzoutput directory.)TEMPLATEEXAMPLE__name__splitr   create_argument_parseradd_argumentadd_argument_groupfloatformat	DEG2METERnpnanintadd_memory_argument)r   r   r   nameparseroutinterp rI   E/home/exouser/operations/rsmas_insar/sources/MintPy/mintpy/geocode.pycreate_parser5   sh        






rK   c                 C   s0   t  }|j| d}|jr$t|j|}t|}|S )N)args)rK   
parse_argsr   read_template2inps_check_inps)iargsrF   inpsrI   rI   rJ   cmd_line_parseq   s    rR   c                 C   sn  t | j| _| jstdnt| jdkr2d | _| jsht | j| _| jsZ| jrZ| j| _| jsht	dt
| jd }d| kr| jrtd td td td n$d| kr| jstd	 td | jr| jstd
 td t
| j}d| krtd td t| j| _| jsj| jrLtd td | jdkrjtd td | S )NzERROR: no input file found!r/   z2No lookup table found! Can not geocode without it.r   Y_FIRSTzinput file is already geocodedzIto resample geocoded files into radar coordinates, use --geo2radar optionzexit without doing anything.zGinput file is already in radar coordinates, exit without doing anythingzAERROR: "--lalo-step" can NOT be used together with "--geo2radar"!zOERROR: "--lalo-step" can NOT be used with lookup table file in geo-coordinates!z<ERROR: "--geo2radar" can NOT be used together with "--bbox"!r2   z=ERROR: "--geo2radar" is NOT supported for "--software scipy"!)utget_file_listr   	Exceptionlenr5   r   get_lookup_filer   FileNotFoundErrorr   read_attributekeysr   printsysexitr%   check_num_processorr.   r   r0   )rQ   atrrI   rI   rJ   rO   }   sJ    





rO   c                    s   t d|   |st }t|}tj| ddgdtd  fddt| D }|D ]t} |  }|r^|dkrd	d |	d
D ||< q^|dkr|||< q^|dkr^d|
 krtj||< q^t|||< q^d}| kr| rt| |_|S )z/Read input template options into Namespace inpsz&read input option from template file: [])
skip_charszmintpy.geocode.c                    s    g | ]} |   kr|qS rI   )r[   .0iprefixtemplaterI   rJ   
<listcomp>   s      z&read_template2inps.<locals>.<listcomp>)r   r%   c                 S   s   g | ]}t |qS rI   )r>   rd   rI   rI   rJ   rj      s     ,)r(   r-   rB   zmintpy.compute.maxMemory)r\   rR   varsr   read_templaterT   check_template_auto_valuelistr[   r:   lowerrA   rB   r>   	maxMemory)template_filerQ   Z	inps_dictkey_listkeyvaluerI   rg   rJ   rN      s.    

rN   c                 C   sN   | s.dt jkrtt d} ntt  d } tt  | } td|  | S )a2  Check number of processors
    Note by Yunjun, 2019-05-02:
    1. conda install pyresample will install pykdtree and openmp, but it seems not working:
        geocode.py is getting slower with more processors
            Test on a TS HDF5 file in size of (241, 2267, 2390)
            Memory: up to 10GB
            Run time: 2.5 mins for nproc=1, 3 mins for nproc=4
    2. macports seems to have minor speedup when more processors
    Thus, default number of processors is set to 1; although the capability of using multiple
    processors is written here.
    OMP_NUM_THREADSr&   z"number of processor to be used: {})osenvironrC   getenv	cpu_countminr\   r?   )r.   rI   rI   rJ   r_      s    
r_   c                 C   s   t |jdkr|jr|jS |jr&d}nd}|jr@d||j}nd|tj| }|j	rtj
|j	st|j	 td|j	 tj|j	|}|S )Nr/   geo_Zrdr_z{}{}.h5z{}{}zcreate directory: {})rW   r   r5   r   dsetr?   rw   pathbasenamer6   isdirmakedirsr\   join)infilerQ   rh   r5   rI   rI   rJ   auto_output_filename   s    r   c                 C   s<  t   }tdd | jD }t| j| j| j| j| j	dd}| j
r\| jr\| j
|d< | j|d< tf | j| j| | j| jd|}|  |  | jD ]x}tdd	|  tj|| jd
}t|| }| jrtd tj||| jgddkrq| jrtj||d}ntj||d}tj !|d dk}|rNt"|}	t#j$||||	d nt }
tj%|| jd
}t&dd |D }|D ]R}|st'|j(|j)f|
|< t*|j+D ]}|j,| }|j-| }tddj|||tj .|d  tj/|||ddd }|j0||d}|j1dkr:d|j2d |d |d |d |d g}n|d |d |d |d g}|rtd|| t#j3||||dd n(||
| |d |d |d |d f< q|sztj4|
| |j5d|
|< qz|st6|
7 |d< t#j8|
|||d | j
r| jrt#j9||d  qt:t   | d!\}}td"|| |S )#zgeocode all input filesc                 S   s   g | ]}t j|qS rI   )rw   r~   getsizerd   rI   rI   rJ   rj     s     zrun_geocode.<locals>.<listcomp>T)interp_method
fill_valuer.   
max_memoryr0   	print_msglat_filelon_file)lut_filesrc_filer   	lalo_stepz2--------------------------------------------------z
resampling file: {})datasetNamezupdate mode: ON)in_fileskip)res_objr/   )z.h5z.he5)metadataref_filecompressionc                 S   s   g | ]}t |qS rI   )rW   rd   rI   rI   rJ   rj   >  s     z+
reading {d:<{w}} in block {b} from {f} ...)dwbfF)r   boxr   r   )src_databox_ind   r&   z"write data in block {} to file: {})datar   blockr   )dtypeBANDS)out_filer   r   )fname<   z(time used: {:02.0f} mins {:02.1f} secs.
);timerA   argmaxr   dictr(   r-   r.   rq   r0   r   r   r   r   r   r%   openpreparer\   r?   r   rZ   r}   r   r3   rT   run_or_skipr   attrupdate_attribute4radar2geoupdate_attribute4geo2radarrw   r~   splitextget_hdf5_compressionr   layout_hdf5get_dataset_listmaxzeroslengthwidthrangenum_boxsrc_box_listdest_box_listr   readrun_resamplendimshapewrite_hdf5_blockarrayr   rW   r[   writewrite_isce_xmldivmod)rQ   
start_timeZind_maxkwargsr   r   r`   r5   Zfile_is_hdf5r   dsDictdsNamesmaxDigitdsNamerf   src_boxdest_boxr   r   msrI   rI   rJ   run_geocode  s    






   


    
r   c                 C   s   t | }t| d S )N)rR   r   )rP   rQ   rI   rI   rJ   main|  s    r   __main__r/   )N)N)N)rw   r]   r   numpyrA   mintpy.objects.resampler   mintpy.defaults.templater   mintpy.utilsr   r   r   r   rT   r   r   r7   r8   r@   rK   rR   rO   rN   r_   r   r   r   r9   argvrI   rI   rI   rJ   <module>	   s&   

<
=!t
	