B
    Qaj9                 @   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 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	 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_group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~  t jdt jtd t 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-d.t	d( | d/}|jd0d1d2d3d3d4hd5d6 |jd7d8tt
jd9d: |jd;d<d=td>d?d: |jd@dAdBdBdChdDd6 | jdEdFdGdHd | jdIdJdKdLd | jdMdNdOdPd t| } | S )QNz;Resample radar coded files into geo coordinates, or reverse
)descriptionformatter_classepilog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softwareZ
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.)argparseArgumentParserRawTextHelpFormatterTEMPLATEEXAMPLEadd_argumentadd_argument_groupfloatformat	DEG2METERnpnanintr   add_memory_argument)parseroutinterp rD   D/home/centos/operations/rsmas_insar/sources/MintPy/mintpy/geocode.pycreate_parser6   sF    






rF   c             C   s0   t  }|j| d}|jr$t|j|}t|}|S )N)args)rF   
parse_argsr   read_template2inps_check_inps)iargsrA   inpsrD   rD   rE   cmd_line_parsep   s    rM   c             C   s.  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| _| 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 anythingz=ERROR: --lalo-step can NOT be used together with --geo2radar!zMERROR: --lalo-step can NOT be used with lookup table file in geo-coordinates!)utget_file_listr   	Exceptionlenr1   r   get_lookup_filer   FileNotFoundErrorr   read_attributekeysr   printsysexitr"   check_num_processorr+   )rL   atrrD   rD   rE   rJ   |   s<    



rJ   c                s  t d|   |st }t|}t| td  fddt| D }x|D ]} |  }|rX|dkr|	dd	dd	d	d
}dd |
 D ||< qX|dkr|||< qX|dkrXd| krtj||< qXt|||< qXW d}| kr| rt| |_|S )z/Read input template options into Namespace inpsz&read input option from template file: zmintpy.geocode.c                s    g | ]} |   kr|qS rD   )rV   ).0i)prefixtemplaterD   rE   
<listcomp>   s    z&read_template2inps.<locals>.<listcomp>)r   r"   [ ], c             S   s   g | ]}t |qS rD   )r:   )r\   r]   rD   rD   rE   r`      s    )r%   r*   r>   zmintpy.compute.maxMemory)rW   rM   varsr   read_templaterO   check_template_auto_valuelistrV   replacesplitlowerr=   r>   r:   	maxMemory)template_filerL   Z	inps_dictkey_listkeyvaluerD   )r^   r_   rE   rI      s0    



rI   c             C   sN   | s.dt jkrtt d} ntt  d } tt  | } td|  | S )a  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
    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environr?   getenv	cpu_countminrW   r;   )r+   rD   rD   rE   rZ      s    	
rZ   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: {})rR   r   r1   r   dsetr;   rs   pathbasenamer2   isdirmakedirsrW   join)infilerL   r^   r1   rD   rD   rE   auto_output_filename   s    r   c             C   sN  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|}|  |  x| jD ]}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}|rRt"|}	t#j$||||	d nt }
tj%|| jd
}t&dd |D }xb|D ]X}|st'|j(|j)f|
|< xt*|j+D ]}|j,| }|j-| }tddj|||tj .|d  tj/|||ddd }|j0||d}|j1dkrFd|j2d |d |d |d |d g}n|d |d |d |d g}|rtd|| t#j3||||dd n(||
| |d |d |d |d f< qW |stj4|
| |j5d|
|< qW |st6|
7 |d< t#j8|
|||d | j
r| jrt#j9||d  qW t:t   | d!\}}td"|| |S )#zgeocode all input filesc             S   s   g | ]}t j|qS rD   )rs   rz   getsize)r\   r]   rD   rD   rE   r`      s    zrun_geocode.<locals>.<listcomp>T)Zinterp_method
fill_valuer+   
max_memoryr-   	print_msgZlat_fileZlon_file)Zlut_fileZ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 rD   )rR   )r\   r]   rD   rD   rE   r`   0  s    z+
reading {d:<{w}} in block {b} from {f} ...)dwbfF)r   boxr   r   )Zsrc_dataZ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.
);timer=   argmaxr   dictr%   r*   r+   rm   r-   r   r   r   r   r   r"   openZpreparerW   r;   r   rU   ry   r   r/   rO   run_or_skipr   attrZupdate_attribute4radar2geoZupdate_attribute4geo2radarrs   rz   splitextget_hdf5_compressionr   layout_hdf5get_dataset_listmaxzeroslengthwidthrangenum_boxZsrc_box_listZdest_box_listr{   readZrun_resamplendimshapewrite_hdf5_blockarrayr   rR   rV   writewrite_isce_xmldivmod)rL   
start_timeZind_maxkwargsr   r   r[   r1   Zfile_is_hdf5r   dsDictdsNamesmaxDigitdsNamer]   Zsrc_boxZdest_boxr   r   msrD   rD   rE   run_geocode   s    







.r   c             C   s   t | }t| d S )N)rM   r   )rK   rL   rD   rD   rE   mainn  s    r   __main__r,   )N)N)rs   rX   r   r3   numpyr=   Zmintpy.objects.resampler   mintpy.defaults.templater   mintpy.utilsr   r   r   r   rO   r   r   r6   r7   r<   rF   rM   rJ   rI   rZ   r   r   r   __name__argvrD   rD   rD   rE   <module>	   s(   
:
2"t
	