
    Zf                        d Z ddlZddlZddlZ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 ddlmZmZmZ ddl ddZddZddZdd	Z	 	 ddZddZddZddZddZddZ e       d
fdZd dZ d!dZ!d"dZ"d#dZ#	 	 d$dZ$y)%z.Miscellaneous utilities - dependent on utils0.    N)GEOMETRY_DSET_NAMESderampifgramStack
timeseries)ptimereadfile	writefile)*c                 4   t        j                  |       }|ddt        |d         t        |d         f}t        |d   |d   z   dz        }t        |d   |d   z   dz        }d|j                         v rLt	        |d         }t	        |d         }t	        |d	         }t	        |d
         }|||z  z   }	|||z  z   }
|	|
fS |||dz   |dz   f}t	        t        j
                  | d|      d         }	t	        t        j
                  | d|      d         }
|	|
fS )z#Get the lat/lon of the scene centerr   WIDTHLENGTH         Y_FIRSTX_FIRSTY_STEPX_STEPlatitudedatasetNamebox	longitude)r   read_attributeintkeysfloatread)	geom_filer   metacol_crow_clat0lon0lat_steplon_steplat_clon_cbox_cs               L/home/exouser/operations/rsmas_insar/tools/MintPy/src/mintpy/utils/utils1.pyget_center_lat_lonr+      s9   ""9-D
{!Sg'T(^)<=Q#a&A%&EQ#a&A%&EDIIKT)_%T)_%h(h(x%''x%''
 %< uQwa0hmmI:5QRSTUhmmI;ERSTUV%<    c                    |r|dk(  rt        d       | }n%t        j                  j                  |       d    d}t        j                  j                  |      d   dz   }t	        || |gd      dk(  r}t	        || 	      dk(  rCt        j                  j                  |       sd
| z   }|dz  }t        |      t        | |||      }t        d|z          t        |      j                  ||      }t        d|z          t        j                  |t              j                  t              }|dddf   j                  t        j                        j!                         }t#        |dddf         }|||fS )aY  Calculate deramped standard deviation in space for each epoch of input timeseries file.
    Parameters: timeseries_resid_file - string, timeseries HDF5 file,
                    e.g. timeseries_ERA5_demErrInvResid.h5
                mask_file - string, mask file, e.g. maskTempCoh.h5
                ramp_type - string, ramp type, e.g. linear, quadratic, no for do not remove ramp
    Returns:    std_list  - list of float, standard deviation of deramped input timeseries file
                date_list - list of string in YYYYMMDD format, corresponding dates
                std_file  - string, text file with std and date info.
    Example:    import mintpy.utils.utils as ut
                std_list, date_list = ut.get_residual_std('timeseries_ERA5_demErrInvResid.h5',
                                                          'maskTempCoh.h5')[:2]
    noNo ramp removalr   _ramp.h5z_std.txtFout_filein_filereadablerunr2   r3   -Can not find input timeseries residual file: $
Re-run dem_error.py to generate it.	ramp_type	mask_filer2   zBcalculating residual standard deviation for each epoch from file: maskFileoutFilezread timeseries RMS from file: dtypeNr   )printospathsplitextrun_or_skipisfile	Exception
run_derampr   timeseries_stdnploadtxtbytesastypestrfloat32tolistlist)	timeseries_resid_filer;   r:   deramped_filestd_filemsgfcstd_list	date_lists	            r*   get_residual_stdrY   2   si    	T) -77++,AB1EFhOww.q1*<H H/Di.P[`aejj7LMQVV77>>"78EF[[>>n$ !+)''*	! 	RS``am,;;YX`;a 

+H
45	HE	*	1	1#	6B!Q$xrzz*113HR1XIY((r,   c                    |r|dk(  rt        d       | }n%t        j                  j                  |       d    d}t        j                  j	                  t        j                  j                  |            }t        j                  j                  t        j                  j                  |            d   }t        j                  j                  |d| d      }t        || |gd      d	k(  r}t        || 
      d	k(  rCt        j                  j                  |       sd| z   }|dz  }t        |      t        | |||      }t        d|z          t        |      j                  ||      }t        d|z          t        j                  |t               j#                  t$              }|dddf   j#                  t        j&                        j)                         }	t+        |dddf         }
|	|
|fS )aV  Calculate deramped Root Mean Square in space for each epoch of input timeseries file.
    Parameters: timeseries_resid_file : string,
                    timeseries HDF5 file, e.g. timeseries_ERA5_demErrInvResid.h5
                mask_file : string,
                    mask file, e.g. maskTempCoh.h5
                ramp_type : string,
                    ramp type, e.g. linear, quadratic, no for do not remove ramp
    Returns:    rms_list : list of float,
                    Root Mean Square of deramped input timeseries file
                date_list : list of string in YYYYMMDD format,
                    corresponding dates
                rms_file : string, text file with rms and date info.
    Example:
        import mintpy.utils.utils as ut
        rms_list, date_list = ut.get_residual_rms('timeseriesResidual.h5', 'maskTempCoh.h5')
    r.   r/   r   r0   rms_.txtFr1   r5   r6   r7   r8   r9   z4
calculating residual RMS for each epoch from file: r<   z(read timeseries residual RMS from file: r?   Nr   )rA   rB   rC   rD   dirnameabspathbasenamejoinrE   rF   rG   rH   r   timeseries_rmsrJ   rK   rL   rM   rN   rO   rP   rQ   )rR   r;   r:   rS   fdirfbaserms_filerU   rV   rms_listrX   s              r*   get_residual_rmsrf   b   s   & 	T) -77++,AB1EFhO77??277??=9:DGGRWW--m<=a@Eww||DDt"45H H/Di.P[`aejj7LMQVV77>>"78EF[[>>n$ !+)''*	! 	EmSTm,;; < 
 

4X
=>	HE	*	1	1#	6B!Q$xrzz*113HR1XIY((r,   c                     t        j                  |       }|d   }|dk(  rt        |       j                  |      }nt	        d|z          yd|d<   t        j                  |||       |S )zDGenerate mask file for non-zero value of input multi-group hdf5 file	FILE_TYPEr   r   z5Only ifgramStack file is supported for now, input is Nmaskr2   metadata)r   r   r   nonzero_maskrA   r	   write)Filer2   r   atrkrj   s         r*   rm   rm      sl    

!
!$
'CKAM4 --+-FEaGHCOOD8c:Or,   Fc           	      	   d }t        j                  |       }	|	d   }
|sddt        |	d         t        |	d         f}|
dk(  r|n>t        j                  j                  t        j                  j                  |             d   }|dnd	}||rd
ndz  }||z   dz   }| j                  |      rt        d        ||       \  }}||fS dt        j                  j                  |        d}d| d}d| d}d| d}	 t        |      }|j                         }|j                          |r	 |D cg c]	  }d|v s| c}d   }n|}	 |D cg c]	  }d|v s| c}d   }t        ||gd      }|
dk(  ret        j                  | d      5 }t        ||   j                   j#                  dt        j                  j%                  |                   }ddd       nt        j                  j%                  |       }t        j                  j%                  |      }||k(  r,||k(  r'|dk(  r"|k  rt        |dz           ||      \  }}||fS |rd|v rd}nd}|
dk(  r`t'        |       }|j                  d       |j)                  ||||||      \  }}|j*                  }|j,                  } |j                          n|
dk(  r"t/        |       j)                  ||||       \  }}nt        j0                  | |!      d   }!|rgt        j                  j3                  |      rHt        d"|z          t        j0                  |d#|$      d   }"t4        j6                  |!|"t        |      k(  <   |d%|!|!|kD  <   d|!|!|k  <   t5        j8                  |!      }t        j                  j                  |       g}|rt        d&|z          t        |d'      }|j;                  ||z   |z   |z          t=        |      }#|
dk(  rG|j;                  d(       t?        |#      D ]'  }|j;                  d)||   ||    |   |   |fz         ) n?|j;                  d*       t?        |#      D ]   }|j;                  ||    d+||   d,d       " |j                           ||      \  }}t=        |      d%k(  r
|d   }|d   }||fS c c}w #  d}Y qxY wc c}w #  d}Y gxY w# 1 sw Y   xY w#  Y xY w)-a  Read/Calculate Spatial Average of input file.

    If input file is text file, read it directly;
    If input file is data matrix file:
        If corresponding text file exists with the same mask file/AOI info, read it directly;
        Otherwise, calculate it from data file.

        Only non-nan pixel is considered.
    Parameters: fname       - string, path of input file
                maskFile    - string, path of mask file, e.g. maskTempCoh.h5
                box         - 4-tuple defining the left, upper, right, and lower pixel coordinate
                saveList    - bool, save (list of) mean value into text file
                reverseMask - bool, perform analysis within masked regions instead of outside of them
                threshold   - float, calculate area ratio above threshold instead of spatial average
    Returns:    meanList    - list(float) or float, average value in space for each epoch of input file
                dateList    - list(str) or str, for date info
                              date12_list, e.g. 101120-110220, for interferograms/coherence
                              date8_list, e.g. 20101120, for timeseries
                              file name, e.g. velocity.h5, for all the other file types
    Example:    meanList = spatial_average('inputs/ifgramStack.h5')[0]
                meanList, date12_list = spatial_average('inputs/ifgramStack.h5',
                                                        maskFile='maskTempCoh.h5',
                                                        saveList=True)
    c                     t        j                  | t              j                  t              }|d d df   D cg c]  }t        |       }}|d d df   D cg c]  }| }}||fS c c}w c c}w )Nr?   r   r   )rJ   rK   rL   rM   rN   r   )fname
txtContentimeanListdateLists        r*   read_text_filez'spatial_average.<locals>.read_text_file   sl    ZZU3::3?
&0A&67E!H77)!Q$/0!A00!! 80s   A(	A-rh   r   r   r   r   N
SpatialAvg	AreaRatioRevMsk r\   z;Input file is spatial average txt already, read it directlyz# Data file: 
z# Mask file: z# AOI box: z# Threshold: z
# AOI box:z# Mask file:Fr1   rMODIFICATION_TIMEskipz! already exists, read it directlyoffsetT	print_msg)r   r=   r   	useMedianreverseMask	thresholdr   )r=   r   r   r   )r   zmask from file: rj   r   r   z-write average value in space into text file: wz'#	DATE12		Mean	Btemp/days	Bperp/m		Num
z%s	%.4f	%8.0f	%8.1f	%d
z#	DATE12		Mean
	z.4f) r   r   r   rB   rC   rD   r_   endswithrA   open	readlinescloserE   h5pyro   r   attrsgetgetmtimer   spatial_averagepbaseIfgramtbaseIfgramr   r   rF   rJ   nannanmeanrn   lenrange)$rt   r   r=   r   saveListcheckAoir   r   ry   rp   rq   prefixsuffixtxtFilerw   rx   	file_line	mask_lineaoi_line
thres_linefllinesrv   aoi_line_origmask_line_origupdate_mask_fileftitor   objpbasetbasedatarj   numLines$                                       r*   r   r      s8   4" 
!
!%
(CKA!SW&CM(:; .[BGG4D4DRWWEUEUV[E\4]^_4`F&.\KF
+h2-Fvo&G ~~fKL+E2(!! !!1!1%!8 9<I 
"-Ise2&H 2.J$']

#,1 Gq\Q5F G J %M	 ).FA.A2EaFqIN '(V[\5#& c!1[>//334GIYIYZ_I`abc c !!%(BWWg&X%"i/$."H'==>!/!8HhX%%
 x;.		 	M% 5! 00## 1 
( 			
l	'.>>#	 ? 
( }}U,Q/x0$X-.==v3GJD-/VVD[))*  %&D	!"&'D"#::d#GG$$U+, =gEF'3
9$X-j89h-HHFG7^ L7"1+x{E!HeAhJK LL HH*+7^ @HQK=8A;s*;2>?@

 (0Hh
8}A;A;XO !H# "
 G	 N
c cs   <-S *R/ .	R*8R*<R/ S R> 
	R9R9R> *S ASA7S *R/ /R63S 9R> >SS SS Sc                 2   t        j                  | |      }|d   }|dvr+t        d|  d       t        j                  |       d   }|| fS |t        j
                  j                  |       d   }|st|dk(  r|d	k(  rd
}ngd|v rd}n`d| d}nY|dk(  rN|| v rPt        j
                  j                  |       j                  d      d   j                  |      d   }d| d}nd|  d}|r;t        j
                  j                  |      rt        j                  |      d   }	|	|fS |dk(  r0t        |       j                  |      }	d|v rd|d<   d|d<   n)||d<   n#|dk(  rt        |       j                         }	d|d<   |rt        j                  	||       	|fS )a  Calculate temporal average of multi-temporal dataset, equivalent to stacking
    For ifgramStack/unwrapPhase, return average phase velocity

    Parameters: fname       - str, file to be averaged in time
                datasetName - str, dataset to be read from input file, for multiple
                              datasets file - ifgramStack - only
                              e.g.: coherence, unwrapPhase
                updateMode  - bool
                outFile     - str, output filename
                              None for auto output filename
                              False for do not save as output file
    Returns:    dataMean    - 2D np.ndarray
                outFile     - str, output file name
    Examples:   avgPhaseVel = ut.temporal_average('ifgramStack.h5', datasetName='unwrapPhase')[0]
                ut.temporal_average('ifgramStack.h5', datasetName='coherence',
                                    outFile='avgSpatialCoh.h5', updateMode=True)
    ri   rh   )r   r   z0WARNING: input file is not multi-temporal file: z, return itself.r   r   r   	coherencezavgSpatialCoh.h5unwrapPhasezavgPhaseVelocity.h5avg.h5r   avgDisplacementvelocityzm/yearUNITdisplacementrk   )r   r   rA   r   rB   rC   rD   r_   splitrF   r   temporal_averager   r	   rn   )
rt   r   
updateModer>   rp   rq   r   extprocessMarkdataMeans
             r*   r   r   U  s   $ 
!
!%[
ACKA--@GWXY}}U#A&U{ ggu%a(M!+-0G"k13G #K=4Gl":"$''"2"25"9"?"?"Ma"P"V"VWZ"[\]"^K /}C@Gwc*bggnnW-==)!,   	Mu%66;6OK')C"CK*C	
l	e$557)K7SAWr,   c           
      l   | sg S t        | t              r| g} | D cg c]  }||	 } }g }| D ]C  }t        j                  |      }|t        t	        t        |      t        |      z
              z  }E |r,|D cg c]!  }t        j                  j                  |      # }}|t	        |      D ]x  }t        j                  |      }|dv r%d|j                         vs/|j                  |       A|dv r%d|j                         v sX|j                  |       jd| }	t        |	       |S c c}w c c}w )aR  Get all existed files matching the input list of file pattern
    Parameters: file_list - string or list of string, input file/directory pattern
                abspath - bool, return absolute path or not
                coord - string, return files with specific coordinate type: geo or radar
                    if none, skip the checking and return all files
    Returns:    file_list_out - list of string, existed file path/name, [] if not existed
    Example:    file_list = get_file_list(['*velocity*.h5','timeseries*.h5'])
                file_list = get_file_list('timeseries*.h5')
    )geor   )radarrdrrdcz un-recognized input coord type: )
isinstancerN   globsortedrQ   setrB   rC   r^   r   r   r   remove
ValueError)
	file_listr^   coordxfile_list_outrt   fnamesrv   rp   rU   s
             r*   get_file_listr     s=    	)S!K	 &7q7I7M H5!S[3}3E%E FGGH 5BC+CC-( 
	&E))%0CCHHJ.!((/11
*!((/8@ o%
	& + 8 Ds   D,D,:&D1c           	         | sBg d}g d}g } |D ]3  }| |D cg c]"  }t         j                  j                  ||      $ c}z  } 5 g }	 t        |       }d}|D ]:  }t        j                  |       dD ]  }		 t        j                  ||	d       |} : < |s|rt	        d	       y|rt         j                  j                  |      }|S c c}w #  |r!t	        d       t	        d       t	        |        Y yxY w#  Y xY w)
a  Find lookup table file with/without input file pattern
    Parameters: filePattern - list of str
                abspath     - bool, return absolute path or not
                print_msg   - bool, printout message or not
    Returns:    outFile     - str, path of the lookup file
    )zgeometryRadar.h5zgeometryGeo_tight.h5zgeometryGeo.h5zgeomap*lks_tight.transzgeomap*lks.transzsim*_tight.UTM_TO_RDCzsim*.UTM_TO_RDC)inputsr}   z	../inputsz-ERROR: No geometry / lookup table file found!zIt should be like:N)r   
rangeCoordF)r   r   z9No lookup table (longitude or rangeCoord) found in files.)	rB   rC   r`   r   rA   r   r   r   r^   )
filePatternr^   r   fileListdirListr]   rt   
existFilesr>   dsNames
             r*   get_lookup_filer     s    @ .  	PGhOUBGGLL%8OOK	P J";/
 G &1 	Fe5I		 MN ''//'*NA P
AB&'+s   'CC 5C6%C36C:c                 B  	 t        | t              r| g} | D ]  }|t        vst        d|        |st	        j
                         }dD cg c]"  }t        j                  j                  ||      $ }}t        ||      }t        |      dk(  r|rt        d       yt        |      D ](  	t        	fd| D              s|j                  	       * t        |      dk(  r|rt        d|  d	       y|d   }|rt        j                  j                  |      }|S c c}w )
z4Find geometry file containing input specific datasetz$unrecognized geometry dataset name: )z*geometry*.h5z*/*geometry*.h5z../*/geometry*.h5)r   r   zNo geometry file found.Nc              3   L   K   | ]  }|t        j                        v  y wN)r   get_dataset_list).0dsetrt   s     r*   	<genexpr>z$get_geometry_file.<locals>.<genexpr>
  s!     Rt844U;;Rs   !$zNo geometry file with dataset z found)r   rN   r   r   rB   getcwdrC   r`   r   r   rA   rQ   anyr   r^   )
	dset_listwork_dirr   r^   r   r   rv   
fname_listr   rt   s
            @r*   get_geometry_filer     s   )S!K	 L**CD6JKKL 99; 6oo"'',,x+oJoz7J
:!+, j! %R	RRe$% :!29+VDE1IGGOOI.	' ps   'Dc           
         d}t        j                  |       }|j                         D ]#  \  }}||j                         v s||   |k7  s"d}% |st	        d| z          | S | dz   }t        |d      }t        |       D ]E  }	|	j                         j                  |d      D 
cg c]  }
|
j                          }}
|	j                  d      st        |      dkD  r|d   }t        j                  |d   d	d
      j                  d      d   j                         }||j                         v r||   |k7  r~|}dD ]  }|j                  |d|       } |dz   |z   }t        j                  ||	      d   }|j                  |||         }|	j                  ||d      }	t	        d| d| d||           |j                  |	       H |j                          t!        j"                  ||        | S c c}
w )zEUpdate option value in template_file with value from input extra_dictFTz)No new option value found, skip updating z.tmpr   r   )%#r   r~   r}   r   )r
   []()\z[\s]*    z: z --> )r   read_templateitemsr   rA   r   stripr   
startswithr   rN   replacerefindallrn   r   shutilmove)template_file
extra_dict	delimiterupdate	orig_dictkeyvaluetmp_filef_tmplinerv   cvalue2searchsymbolold_value_strnew_value_strs                   r*   update_template_filer    s    F&&}5Ioo' 
U*//##
35(@F 9-GH V#H3E]#  $

 2 29a @A1QWWYAAz*s1vzA$CKK!dB/55c:1=CCEEjoo''JsOu,D  %7 OF#/#7#71VH#NLO
  )1,> "

< >q A - 5 5eZ_ M||M=!DSEE7%
3/@ABD/0 
KKM KK-(7 Bs   "G-c           
      l   |rt         nd }t        j                  |       }t        |j	                               }t        ||      }|s
 |d       | S t        j                  j                  |       d   }|dv rt        j                  | d      5 }t        |j                               D ]g  \  }	}
|
dk(  s|
,|	|v s|j                  j                  |	        |d|	        9t        |
      |j                  |	<    |d	|	 d
t        |
              i 	 ddd       | S t        |j                               D ]S  \  }	}
|
dk(  s|
"|	|v s|j                  |	        |d|	        /t        |
      ||	<    |d	|	 d
t        |
              U t!        j"                  || dz   |       | S # 1 sw Y   | S xY w)a8  Add/update input attribute of the give file.

    Parameters: fname   - string, path/name of file
                atr_new - dict, attributes to be added/updated
                          if value is None, delete the item from input file attributes
    Returns:    fname   - string, path/name of updated file
    c                       y r    )argskwargss     r*   <lambda>zadd_attribute.<locals>.<lambda>M  s    r,   zeAll updated (removed) attributes already exists (do not exists) and have the same value, skip update.r   )r   z.he5zr+NoneNremove zadd/update z = z.rscr   )rA   r   r   rQ   r   update_attribute_or_notrB   rC   rD   r   ro   iterr   r   poprN   r	   write_roipac_rsc)rt   atr_newr   vprintrp   key_listr   fextr   r   r   s              r*   add_attributer  E  s     U%AF 
!
!%
(CCHHJH %Wc2F 8 	9 77E"1%DYYud# 	?q"7==?3 
?
UF?emhC(/ $'u:AGGCL[SU=>
?	?: L w}}/ 
	;JC%-(?GGCLWSE?+ u:CSESZL9:
	; 	""3f	JL;	?: Ls   +F):AF))F3c                    | s| ddfS g }g }| D ]?  }t        j                  |      }|j                  |d          |j                  |d          A |r|n
t        |      }|r|n
t        |      }t	        |       }|j                  |      t        |      k7  s|j                  |      t        |      k7  rt        d       t        d       t        d       t        d|d|       t        d	       t        | ||      D ]5  \  }}}	|	|k7  s||k7  st        | d
|	 d|        |j                  |       7 t        dt        t        |            z          t        d       |||fS )zXCheck file size in the list of files, and drop those not in the same size with majority.Nr   r   z-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%z2WARNING: Some files may have the wrong dimensions!z$All files should have the same size.z3The width and length of the majority of files are: z, zNBut the following files have different dimensions and thus will not be loaded:z    width: z
  length: z
Number of files left: z,%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%)r   r   appendmost_commonrQ   countr   rA   zipr   rN   )
r   
mode_widthmode_length
width_listlength_listrt   rp   fname_list_outlengthwidths
             r*   check_file_sizer$  }  sw    4%% JK *%%e,#g,'3x=)*  *{:/FJ!,++k2JK *%N$J7  -[1AA=>BC45;( 	)^_$'
K$L 	- E65
"f&;{5'F8DE%%e,	- 	(S-@)AAB<=:{22r,   c                 f    	 t        | |      d   }t        j                  |       |S #  d}Y |S xY w)a  Check if any file in the file list 1) exists and 2) readable
    Parameters: file_list : str or list(str), file name with/without wildcards
                abspath   : bool, return absolute file name/path or not
    Returns:    file_path : string, found file name/path; None if not.
    )r^   r   N)r   r   r   )r   r^   files      r*   is_file_existr'    s>    Y8;% KKs   %) 0c                    | syt        | t              r| g} t        d | D              sy|r	 t        j                  | d         d    |rJt        |      }|r=t        d |D              }t        d | D              }||kD  ry|rt        |  d| d	       y
#  |rt        | d    d       t        j                  | d          Y yxY w)a  Check whether to update out_file or not.
    return run if any of the following meets:
        1. out_file is empty, e.g. None, []
        2. out_file is not existed
        3. out_file is not readable by readfile.read_attribute() when readable=True
        4. out_file is older than in_file, if in_file is not None
    Otherwise, return skip.

    If in_file=None and out_file exists and readable, return skip

    Parameters: out_file  - string or list of string, output file(s)
                in_file   - string or list of string, input file(s)
                readable  - bool, check if the 1st output file has attribute 'WIDTH'
                print_msg - bool, print message
    Returns:    run/skip  - str, whether to update output file or not
    Example:    if ut.run_or_skip(out_file='timeseries_ERA5_demErr.h5', in_file='timeseries_ERA5.h5'):
                if ut.run_or_skip(out_file='exclude_date.txt',
                                  in_file=['timeseries_ERA5_demErrInvResid.h5',
                                           'maskTempCoh.h5',
                                           'smallbaselineApp.cfg'],
                                  readable=False):
    r5   c              3   Z   K   | ]#  }t         j                  j                  |       % y wr   )rB   rC   rF   r   rv   s     r*   r   zrun_or_skip.<locals>.<genexpr>  s     7277>>!$7   )+r   r   z% exists, but can not read, remove it.c              3   Z   K   | ]#  }t         j                  j                  |       % y wr   rB   rC   r   r*  s     r*   r   zrun_or_skip.<locals>.<genexpr>  s     =((+=r+  c              3   Z   K   | ]#  }t         j                  j                  |       % y wr   r-  r*  s     r*   r   zrun_or_skip.<locals>.<genexpr>  s     >((+>r+  z exists and is newer than z
 --> skip.r   )r   rN   allr   r   rA   rB   r   r   maxmin)r2   r3   r4   r   t_int_outs         r*   rE   rE     s    0 h$ zH7h77 	##HQK09 (=W==D>X>>Ee|
"<WIZPQ#	!%JKLIIhqk"s   B -Cc                 :   t         j                  j                  t         j                  j                  t        j
                        |      }t        j                  |      }d}| j                  |d      j                         }|dk(  r||   }|dk7  rd|d<   | j                         D ]&  \  }}|dk(  s||j                         v s||   | |<   ( dddddd	}| j                         D ]0  \  }}|j                         }||j                         v s)||   | |<   2 | S )
z7Replace auto value based on the input auto config file.zmintpy.compute.clusterautolocal40zmintpy.compute.numWorkerTFN)yestruer.   falsenone)rB   rC   r`   r]   mintpy__file__r   r   r   lowerr   r   )	templateDict	auto_filetemplateAutoFiletemplateAutoDictcluster_keyclusterr   r   special_valuess	            r*   check_template_auto_valuerF    s2    ww||BGGOOFOO$DiP--.>? +K{F399;G&";/'7;34 #((* 6
UF?s&6&;&;&== 0 5L6 N #((* 6
UN'')) .u 5L6
 r,   c                    t        j                          }t        j                  j                  |       }t        j                  j	                  t        j                  j                  |             \  }	}
t        j                  |       }|d   }t        |d         }t        |d         }t        d| d|         |r|n$t        j                  j                  ||	 d|
       }|dk(  r| }t        j                  j                  |      r't        j                  |      d   }t        d	|z          n2t        j                  ||ft        j                  
      }t        d       d}|rxt        j                  j                  |d|	 d      }t!        |d      5 }|j#                  d|  d       |j#                  d| d       |j#                  d| d       ddd       |dk(  r,t%        j&                  || d       t        d       t)        |       j+                         }t-        |      }t/        j0                  |      }t3        |      D ]  }|r,t!        |d      5 }|j#                  ||    d       ddd       t        j                  | ||         d   }t5        |||||      d   }t%        j6                  ||d||dz   d|d|gd       |j9                  |dz   |dz    d | !        |j;                          t        d"|        n8|dk(  rt=        |       }|j!                  d#       |sd$}t?        j@                  | d      5 }||   }| d}||jC                         v r||   }t        d%|        n?|jE                  ||jF                  ||ft        jH                  dd&      }t        d'|        t/        j0                  |jF                        }t3        |jF                        D ]  }|r?t!        |d      5 }|j#                  tK        |jL                  |          d       ddd       ||ddddf   }t5        |||||      d   }|||ddddf<   |j9                  |dz   |dz    d |jF                   !        |j;                          t        d"|         ddd       n|r8t!        |d      5 }|j#                  d(jO                  |d                ddd       |s|d)k(  rd)}t        j                  | |      d   }t5        |||||      d   }t        d*|        t%        j"                  ||| +       |rt        d,       tQ        ||d#       tS        t        j                          |z
  d-      \  }}t        d.|d/d0|d1d2       |S # 1 sw Y   xY w# 1 sw Y   7xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)3a   Remove ramp from each 2D matrix of input file
    Parameters: fname           - str, data file to be deramped
                ramp_type       - str, name of ramp to be estimated.
                mask_file       - str, file of mask of pixels used for ramp estimation
                out_file        - str, output file name
                datasetName     - str, output dataset name, for ifgramStack file type only
                save_ramp_coeff - bool, save the estimated ramp coefficients to text file
                extra_meta      - dict, extra metadata to add to the output file
    Returns:    out_file        - str, output file name
    rh   r   r   r  z ramp from file: _rampr   r   zread mask file: r?   zuse mask of the whole areaN
rampCoeff_r\   r   z# input  file: r~   z# output file: z# ramp type: r   T)ref_filer   z,estimating phase ramp one date at a time ...)maxValuear   ri   )r:   rl   
coeff_filer   F)r   r   blockr   /)r   zfinished writing to file: r   r   zaccess HDF5 dataset /)shaper@   chunkscompressionzcreate HDF5 dataset /z{}    r   zwriting >>> )r2   rJ  z*add/update the following metadata to file:<   ztime used: z02.0fz mins z02.1fz secs.)*timerB   rC   r]   rD   r_   r   r   r   rA   r`   rF   r   rJ   onesbool_r   rn   r	   layout_hdf5r   get_date_listr   r   progressBarr   r   write_hdf5_blockr   r   r   r   ro   r   create_dataset	numIfgramrO   rN   
date12Listformatr  divmod)rt   r:   r;   r2   r   save_ramp_coeff
extra_meta
start_timerb   rc   r  rp   ftyper"  r#  rj   rM  r   rX   num_dateprog_barrv   r   r   ds	dsNameOutdsOutmss                                r*   rH   rH     s    J 77??5!D''""277#3#3E#:;KE4 
!
!%
(CEXFGE	GI;/w
78#xdugU4&<Q)RH 
ww~~i }}Y'* *+wwbhh7*+ JWW\\$*UG4(@A
*c" 	3aGGoeWB/0GGohZr23GGmI;b12	3 h$G<=u%335	y>$$h7x 	=A*c* 5aGG	!.d345 ==IaLA!DD #% D &&(!A#q&!U3 OOAaC1Q3%q
(;O<7	=8 	*8*56	-	% 5!'KYYuc" '	8a;B&-u-IAFFH$)-i[9:((==&%8** $ ) & -i[9:((#--@H3==) Fj#. A!3s~~a'8#9":$ ?@A !Q'{ ' )  "&aAg!qse1S]]O,DE+F, NN.ug67O'	8 '	8V j#& ;!K(89:; u
2$K}}U<Q? !
  	XJ'(x%@ :;h
d; $))+j("-DAq	K%yqiv
67O}	3 	3"5 5jA A''	8 '	8Z; ;sK   A VV*B6W+V7.A;W $WV'*V4	7W<WWWr   )zmaskTempCoh.h5	quadratic)zmaskConnComp.h5N)r   NNFTFN)r   FN)FN)NFT)Nr   TT)=)NN)T)NTT)z"defaults/smallbaselineApp_auto.cfg)NNNFN)%__doc__r   rB   r   r   rT  r   numpyrJ   r<  mintpy.objectsr   r   r   r   mintpy.utilsr   r   r	   mintpy.utils.utils0r+   rY   rf   rm   r   r   r   r   r   r  dictr  r$  r'  rE   rF  rH   r	  r,   r*   <module>rs     s    4  	 	      O O 3 3 !.-)`7)t HLPTgT=D&R2jD+\ "&5 5p#3P5p!H MQ15ir,   