o
    <ch                     @   sV   d dl Z d dlZd dlZd dlmZ d dlZd dlZe Zg dZ	G dd dZ
dS )    N)	auto_path)lsfpbsslurmlocalc                   @   s   e Zd ZdddZdd Zdd Zdd	 Zd
d Zedd Z	dd Z
edd Zedd Zedd Zedd Zedd Zedd ZdS )MiaplPyParserNc                 C   s<   || _ || _tjdd| _| jd}|jddddd d S )	NzMiaplPy scripts parserdescriptionzGeneral options:-v	--version
store_truePrint software version and exitactionhelp)iargsscriptargparseArgumentParserparseradd_argument_groupadd_argument)selfr   r   Zcommonp r   P/home/exouser/operations/rsmas_insar/tools/MiaplPy/miaplpy/objects/arg_parser.py__init__   s
   zMiaplPyParser.__init__c                 C   s   | j dkr|  | _nP| j dkr|  | _nE| j dkr!|  | _n:| j dkr,|  | _n/| j dkr7|  | _n$| j dkrB|  | _n| j dkrM|  | _n| j dkr[| 	 \| _| _
}| jj| jd	}| j dkrm| |}| j dkrx| ||}|S )
Nload_slcphase_linkingZgenerate_interferogramsZgenerate_maskZunwrap_miaplpyZgenerate_temporal_coherenceinvert_networkZmiaplpy_app)args)r   load_slc_parserr   phase_linking_parsergenerate_interferograms_parsergenerate_unwrap_mask_parserunwrap_parser"generate_temporal_coherence_parsernetwork_inversion_parsermiaplpy_app_parser	STEP_LIST
parse_argsr   out_load_slcout_miaplpy_app)r   EXAMPLEinpsr   r   r   parse   s,   










zMiaplPyParser.parsec                    s  | d tjtjtjtj} jrn' jrt|| j	
  td tjt td tjt td tj j _tj j _ jd u r\tjtj jd _ntj j _tj jdd tj jd _tj jdd  fd	d
 jD  _ S )Nztemplate:
                    ########## 1. Load Data (--load to exit after this step)
                    {}

                    {}

                    {}

                    {}

                    zI{}: error: one of the following arguments are required: -t/--template, -Hz'{} -H to show the example template file   miaplpyT)exist_okinputsc                    s   g | ]
}t j j|qS r   )ospathjoinout_dir).0ir-   r   r   
<listcomp>^   s    z.MiaplPyParser.out_load_slc.<locals>.<listcomp>)formatr   ZisceTopsAutoPathZisceStripmapAutoPathZroipacAutoPathZgammaAutoPathtemplate_fileprint_example_template
SystemExitr   print_usageprintr3   r4   basename__file__sysexitabspathproject_dirPROJECT_NAMEwork_dirr5   makedirsr6   out_file)r   sinpsZDEFAULT_TEMPLATEr   r9   r   r*   ;   s8   


zMiaplPyParser.out_load_slcc                 C   s  |}t jt jtjd}t jt jtjd}|jr&tt|d	 |j
r/ttj
j|jsYt jt j|sY|jsY| j  t| d}|d7 }|d7 }t| t |jrt j|j|_t j|jspt|jt j|jt j|kr|j|_d |_| |}|S )Nzdefaults/miaplpyApp.cfgz!defaults/miaplpy_mintpy_print.cfgrz+ERROR: no template file found! It requires:z&
  1) input a custom template file, ORzH
  2) there is a default template 'miaplpyApp.cfg' in current directory.)r3   r4   r5   dirnamer0   rB   print_templater>   openreadversionr	   customTemplateFileisfilerA   generate_templater   r?   r@   rE   FileNotFoundErrortemplateFileread_inps2run_steps)r   rK   r,   r-   r<   Ztemplate_file_printmsgr   r   r   r+   b   s8   


zMiaplPyParser.out_miaplpy_appc                 C   s,  dD ]$}t || }|r&|| jvr&|dks&d|}|d| j7 }t|q|jr2|j|_|j|_| j|j}| j|j}||krPd|j|j}t|| j||d  |_|j	r`g |_t
d t|jdkrt|jdkryt
tjj nt
tjj t
d	tj  t
d
t  t
dtjt|j t
d| j|d d  |jdu r|jrtj|j}|d |_ntj|j|_tj|j|_d|_|jrtj|jdkstjtj|jd |_t
d|j ntjtj|j|_tj|jst|j t
d |S )z(read/get run_steps from input arguments.)	startStependStepdoStep	multilookzInput step not found: {}z
Available steps: {}z2input start step "{}" is AFTER input end step "{}"r/   z2--------------------------------------------------r   z--RUN-at-{}--zCurrent directory: {}z+Run routine processing with {} on steps: {}zRemaining steps: {}Nz/miaplpyzmiaplpyApp.cfgzProject name:) varsr(   r;   
ValueErrorr[   rY   rZ   indexZ	run_stepsrT   r@   lenr0   rQ   version_descriptionlogodatetimenowr3   getcwdr4   rA   rB   workDirrR   rM   rV   rE   ZprojectNamesplitextexistsmkdir)r   r-   keyvaluerX   idx0idx1Zpath1r   r   r   rW      sV   

z!MiaplPyParser.read_inps2run_stepsc               	   C   s   d} d}t jdt j| d | d}|jdddd	d
 |jddtdddd |jddtddd |jdddd dd |jddtdh ddd d! |jd"d#d$d%d&d
 |jd'h d(d d)d* |jd+d,dd-d
 |jd.d/td0d1g d2d3d4 |S )5Na  template:
        ########## 1. Load Data
        ## auto - automatic path pattern for Univ of Miami file structure
        ## load_slc.py -H to check more details and example inputs.
        ## compression to save disk usage for slcStack.h5 file:
        ## no   - save   0% disk usage, fast [default]
        ## lzf  - save ~57% disk usage, relative slow
        ## gzip - save ~62% disk usage, very slow [not recommend]
        
        miaplpy.load.processor      = auto  #[isce,snap,gamma,roipac], auto for isceTops
        miaplpy.load.updateMode     = auto  #[yes / no], auto for yes, skip re-loading if HDF5 files are complete
        miaplpy.load.compression    = auto  #[gzip / lzf / no], auto for no.
        miaplpy.load.autoPath       = auto    # [yes, no] auto for no
        
        miaplpy.load.slcFile        = auto  #[path2slc_file]
        miaplpy.load.startDate      = auto  #auto for first date
        miaplpy.load.endDate        = auto  #auto for last date
        ##---------for ISCE only:
        miaplpy.load.metaFile       = auto  #[path2metadata_file], i.e.: ./reference/IW1.xml, ./referenceShelve/data.dat
        miaplpy.load.baselineDir    = auto  #[path2baseline_dir], i.e.: ./baselines
        ##---------geometry datasets:
        miaplpy.load.demFile        = auto  #[path2hgt_file]
        miaplpy.load.lookupYFile    = auto  #[path2lat_file], not required for geocoded data
        miaplpy.load.lookupXFile    = auto  #[path2lon_file], not required for geocoded data
        miaplpy.load.incAngleFile   = auto  #[path2los_file], optional
        miaplpy.load.azAngleFile    = auto  #[path2los_file], optional
        miaplpy.load.shadowMaskFile = auto  #[path2shadow_file], optional
        miaplpy.load.waterMaskFile  = auto  #[path2water_mask_file], optional
        miaplpy.load.bperpFile      = auto  #[path2bperp_file], optional
        
        ##---------subset (optional):
        ## if both yx and lalo are specified, use lalo option unless a) no lookup file AND b) dataset is in radar coord
        miaplpy.subset.yx           = auto    #[y0:y1,x0:x1 / no], auto for no
        miaplpy.subset.lalo         = auto    #[S:N,W:E / no], auto for no
        a  example:
          load_slc.py -t PichinchaSenDT142.txt
          load_slc.py -t miaplpyApp.cfg
          load_slc.py -t PichinchaSenDT142.txt --project_dir $SCRATCH/PichinchaSenDT142
          load_slc.py -H #Show example input template for ISCE/ROI_PAC/GAMMA products
        z0Saving a stack of Interferograms to an HDF5 file
r	   formatter_classepilog-Hr=   r   z1Print/Show the example template file for loading.destr   r   -t
--template+r<   zTemplate file with path info.)typenargsrt   r   z-pjz--project_dirrF   z-Project directory of SLC dataset to read fromrx   rt   r   -d
--work_dirrH   z0Working directory of miaplpy (default ./miaplpy)rt   defaultr   z-prz--processor	processor>   roipaciscegammazFInSAR processor/software of the file (This version only supports isce)r   )rx   rt   choicesr   r~   z	--enforce-f
updateModestore_falsezADisable the update mode, or skip checking dataset already loaded.z--compression>   gzipNlzfz@Compress loaded geometry while writing HDF5 file, default: None.)r   r~   r   z--no_metadata_checkZno_metadata_checkz:Do not check for rsc files, when running via miaplpyApp.py-o--output   rJ   )zslcStack.h5zgeometryRadar.h5zgeometryGeo.h5zOutput HDF5 file)rx   ry   rt   r~   r   )r   r   RawTextHelpFormatterr   str)TEMPLATEr,   r   r   r   r   r       sJ   $


zMiaplPyParser.load_slc_parserc                 C   sB  | j }|d}|jddtddd |jddtd	d
dd |jddtdd
dd |jddtdddd |jddtdddd |jddtdddd |jd d!td"dd#d |jd$d%td&d'dd |jd(d)td*dd+d |jd,d-td.d/d |jd0d1td2d3d4d |jd5d6d7td8d9d: |jd;d<d=td d>d: |jd?d@dAdBdCdD |S )ENzPhase inversion option-wr|   rH   Working directory (miaplpy)rz   -rz--range_windowrange_window   z!Range window size for shp findingrx   rt   r~   r   -az--azimuth_windowazimuth_windowz#Azimuth window size for shp finding-mz--methodZinversion_methodZEMIz5Inversion method (EMI, EVD, PTA, sequential_EMI, ...)z-lz
--time_lagZtime_lag
   zTime lag in case StBAS is usedru   z--testZshp_testksz$Shp statistical test (ks, ad, ttest)z-psnz--ps_num_shpZps_shpz Number of SHPs for PS candidates-pz--patch_sizeZ
patch_size   z-mssz--mini_stack_sizeZministack_sizez#Number of images in each mini stack-sz--slc_stack	slc_stackzSLC stack filez-ms--mask	mask_fileNonezmask file for inversionz-nz--num_worker
num_workerr/   z%Number of parallel tasks (default: 1)rt   rx   r~   r   -iz--index	sub_indexz<The list containing patches of i*num_worker:(i+1)*num_worker-cz--concatenateZdo_concatenater   z&Concatenate all phase inverted patchesrs   )r   r   r   r   int)r   r   patchr   r   r   r!     sN   
z"MiaplPyParser.phase_linking_parserc                  C   sh   t jdd} | jddtdddd | jd	d
tdd dd | jddtdd dd | jddtdddd | S )Nz?Generate unwrap mask based on shadow mask and input custom maskr   -gz
--geometryZgeometry_stackTz3Geometry stack file with shadowMask in the datasetsrx   rt   requiredr   r   r   Zcustom_maskzCustom mask in HDF5 formatr   r   r   Zoutput_maskz-Output binary mask for unwrapping with snaphuru   z
--text_cmdZtext_cmd zGCommand before calling any script. exp: singularity run dockerimage.sifr   r   r   r   r   r   r   r   r#   8  s   z)MiaplPyParser.generate_unwrap_mask_parserc                  C   s   t jdd} | jddtdddd | jd	d
tdddd | jddtdddd | jddtdddd | jddtdddd | jddtdddd | jd d!td"d#d$d | jd%d&d'td(d)d* | S )+NzGenerate interferogramr   r   z--reference	referenceTzReference imager   r   z--secondaryZ	secondaryzSecondary imageru   z--stack
stack_filez$Phase series stack file to read fromr   z--output_dirr6   interferogramsz"Prefix of output int and amp filesr   r   z--azimuth_looksZazlooksr/   zAzimuth looksr   z--range_looksZrglookszRange looksr   z--filter_strengthZfilter_strength      ?zfiltering strengthr   z--stack_prefixprefixtopsz?ISCE stack processor: options= tops, stripmap -- default = topsr   r   r   r   r   r   floatr   r   r   r   r"   H  s4   z,MiaplPyParser.generate_interferograms_parserc                  C   sN  t jdd} | jdddtddd | jd	d
dtddd | jdddtddd | jdddtd dd | jdddtd dd | jdddtd dd | jdddtd d d | jd!d"d#td d$d | jd%d&d'td d(d | jd)d*d+td,d-d | jd.d/d0td1d2d | jd3d4d5td6d7d | jd8d9d:d;d< | jd=d>d:d?d< | jd@dAd:dBd< | S )CNzUnwrap using snaphur   r   z--ifgZ	input_ifgTzInput wrapped interferogram)rt   rx   r   r   r   z--coherenceZ	input_corzInput coherence filez-uz--unwrapped_ifgZunwrapped_ifgzOutput unwrapped interferogramr   r   Zunwrap_maskr   z-swz--widthZ	ref_widthzWidth of Reference .h5 filez-slz--lengthZ
ref_lengthzLength of .h5 filer   z--wavelength
wavelength
Wavelengthz-htz--heightheightzAltitude of satellitez-erz--earth_radiusearth_radiuszEarth Radiusr   z--init_methodZinit_methodMSTz*Unwrap initialization algorithm (MST, MCF)r{   z--max_discontinuityZdefo_maxg333333?z+Maximum abrupt phase discontinuity (cycles)z-ntz--num_tilesZ	num_tilesr/   z*Number of tiles for Unwrapping in parallelz--two-stageZunwrap_2stager   z"Use 2 stage unwrapping (from ISCE)rs   z
--rmfilterZremove_filter_flagzRemove filtering after unwrap--tmpcopy_to_tmpCopy and process on tmpr   r   r   r   r   r$   `  sZ   

zMiaplPyParser.unwrap_parserc                  C   s8   t jdd} | jddtdddd | jd	d
ddd | S )N"Convert phase to range time seriesr   r{   r|   rH   Tr   r   --shadow_maskshadow_maskr   %use shadow mask to mask final resultsrs   r   r   r   r   r   r%     s   
z0MiaplPyParser.generate_temporal_coherence_parserc               
   C   s   t jdd} | jddd | jddtdd	d
d | jdddtd dd | jdddd dd | jdddddtddd | jddd dd! | jd"d#d$d%d! | jd&d'd(d(d)gd*d+ | jd,d-d.d/d | jd0d1d2d3h d4d5d+ | S )6Nr   r   ZifgramStackFilez(interferograms stack file to be inverted)r   r{   r|   rH   Tr   r   ru   rv   r<   z-template file (default: smallbaselineApp.cfg)r   z--tcohz
--temp_cohtemp_cohr   r}   z--mask-thresz--mask-thresholdz--mtZmaskThresholdZNUMr   zIthreshold to generate mask for temporal coherence (default: %(default)s).)rt   metavarrx   r~   r   r   r   r   rs   z--min-norm-phaseZminNormVelocityr   zoEnable inversion with minimum-norm deformation phase, instead of the default minimum-norm deformation velocity.z--normresidualNormL1L2z;Optimization mehtod, L1 or L2 norm. (default: %(default)s).)rt   r~   r   r   z--smooth_factorZL1_alphagMbP?z6Smoothing factor for L1 inversion [0-1] default: 0.01.r   z--weight-funcZ
weightFuncvar>   cohr   Zfimnozfunction used to convert coherence to weight for inversion:
var - inverse of phase variance due to temporal decorrelation (default)
fim - Fisher Information Matrix as weightcoh - spatial coherence
no  - no/uniform weight)r   r   r   r   r   r   r   r   r   r&     s>   


z&MiaplPyParser.network_inversion_parserc               
   C   s\  g d} d | dd | dd  }d}tjdtj|d}|jdd	d
d |jdddd dd |jddddd |jddddd |jddddd |jddd dd |jd d!d d"d |jd#d$dd%d |jd&d'dd(d |jd)d*dd+d |d,|}|jd-d.d/| d d0 | d d1 |jd2d3d4d/| d5 d6 | d5 d1 |jd7d8d/d9d: || |fS );N)		load_datar   Zconcatenate_patchesZgenerate_ifgramZunwrap_ifgramZload_ifgramZifgram_correctionr   Ztimeseries_correctionag  Command line options for steps processing with names are chosen from the following list:
        {}
        {}

        In order to use either --start or --step, it is necessary that a
        previous run was done using one of the steps options to process at least
        through the step immediately preceding the starting step of the current run.
        r      a  example: 
              miaplpyApp.py  <custom_template_file>            # run with default and custom templates
              miaplpyApp.py  -h / --help                       # help 
              miaplpyApp.py  -H                                # print    default template options
              # Run with --start/stop/step options
              miaplpyApp.py PichinchaSenDT142.txt --dostep  load_data       # run the step 'download' only
              miaplpyApp.py PichinchaSenDT142.txt --start load_data         # start from the step 'download' 
              miaplpyApp.py PichinchaSenDT142.txt --stop  unwrap_ifgram    # end after step 'interferogram'
              z(Routine Time Series Analysis for MiaplPyro   rR   ?zUCustom template with option settings.
ignored if the default miaplpyApp.cfg is input.)ry   r   z--dirz
--work-dirrf   z'Work directory, (default: %(default)s).r}   r   rT   r   z:Generate default template (if it does not exist) and exit.rs   rr   rN   z)Print the default template file and exit.r
   r   r   r   z
--walltimeZ	wall_timez+walltime for submitting the script as a jobz--queuequeuez
Queue namez
--jobfilesZ	write_jobz*Do not run the tasks, only write job filesz
--runfilesZrun_flagzCreate run files for all stepsr   r   r   z#steps processing (start/end/dostep)z--startrY   STEPz/Start processing at the named step, default: {})rt   r   r~   r   z--endz--stoprZ   z-End processing at the named step, default: {}z--dostepr[   z%Run processing at the named step only)rt   r   r   )r;   r   r   r   r   r   )r(   Z	STEP_HELPr,   r   stepr   r   r   r'     sT   		





z MiaplPyParser.miaplpy_app_parser)NN)__name__
__module____qualname__r   r.   r*   r+   rW   staticmethodr    r!   r#   r"   r$   r%   r&   r'   r   r   r   r   r      s*    
'(B
K 


"
	
r   )rC   r   r0   miaplpy.defaultsr   r3   rc   ZPathFindZpathObjCLUSTER_LISTr   r   r   r   r   <module>   s   