
    Zf                         d 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	  ej                         5   ej                  de       ddlZddd       ddlmZ ddlmZ ddlmZmZmZ  G d	 d
      Zy# 1 sw Y   *xY w)z5Class wrapped around pyresample/scipy for resampling.    N)ndimage)RegularGridInterpolatorignore)EARTH_RADIUS)split_box2sub_boxes)ptimereadfileutils0c                       e Zd ZdZddddej
                  ddddddfdZd	 Zd
 ZddZ	e
dd       Ze
dd       Zd Zd Zd Ze
dej
                  ddfd       Zd Zdej
                  dfdZy)resamplea|	  
    Geometry Definition objects for geocoding using:
    1) pyresample (http://pyresample.readthedocs.org)
    2) scipy.interpolate.RegularGridInterpolator:
       (https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html)

    Example:
        from mintpy.objects.resample import resample
        from mintpy.utils import readfile, attribute as attr

        ##### opt 1 - entire matrix (by not changing max_memory=0)
        res_obj = resample(lut_file='./inputs/geometryRadar.h5', src_file='velocity.h5')
        # OR use ISCE-2 lookup table files instead of MintPy geometry file in HDF5 format
        res_obj = resample(lut_file='../merged/geom_reference/lat.rdr', src_file='velocity.h5',
                           lat_file='../merged/geom_reference/lat.rdr',
                           lon_file='../merged/geom_reference/lon.rdr')

        res_obj.open()
        res_obj.prepare()

        # read data / attribute
        rdr_data, atr = readfile.read(src_file)
        # resample data
        box = res_obj.src_box_list[0]
        geo_data = res_obj.run_resample(src_data=rdr_data[box[1]:box[3], box[0]:box[2]])
        # update attribute
        atr = attr.update_attribute4radar2geo(atr, res_obj=res_obj)

        ##### opt 2 - block-by-block IO (by setting max_memory=4)
        res_obj = resample(lut_file='./inputs/geometryRadar.h5', src_file='timeseries.h5', max_memory=4)
        res_obj.open()
        res_obj.prepare()

        # prepare output: metadata and initial file
        atr = readfile.read_attribute(src_file)
        atr = attr.update_attribute4radar2geo(atr, res_obj=res_obj)
        writefile.layout_hdf5(outfile, metadata=atr, ref_file=src_file)

        # block-by-block IO
        for i in range(res_obj.num_bix):
            src_box = res_obj.src_box_list[i]
            dest_box = res_obj.dest_box_list[i]
            # read
            data = readfile.read(src_file, box=src_box)[0]
            # resample
            data = res_obj.run_resample(src_data=rdr_data, box_ind=i)
            # write
            block = [0, data.shape[0],
                     dest_box[1], dest_box[3],
                     dest_box[0], dest_box[2]]
            writefile.write_hdf5_block(outfile,
                                       data=data,
                                       datasetName='timeseries',
                                       block=block)
    Nnearest   r   
pyresampleTc                     || _         || _        || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        d| _        d| _        y)a  
        Parameters: lut_file      - str, path of lookup table file, containing datasets:
                                    latitude / longitude      for lut_file in radar-coord
                                    azimuthCoord / rangeCoord for lut_file in geo-coord
                    src_file      - str, path of data file to be resampled.
                    SNWE          - tuple of 4 float, indicating south/north/west/east
                                    coordinates at pixel outer boundary (consistent with Y/X_FIRST; not pixel center)
                    lalo_step     - list of 2 float, output step in lat/lon direction in degree / meter
                                    input lalo_step is used ONLY IF 1) radar2geo = True AND 2) lut_file is in radar-coord
                    interp_method - str, interpolation / resampling method, nearest / linear
                    fill_value    - number, fill value for extrapolation pixels
                    nprocs        - int, number of processors used in parallel
                    max_memory    - float, maximum memory to use
                                    set to 0 or negative value to disable block-by-block IO (default)
                    software      - str, interpolation software, pyresample / scipy
                    lat/lon_file  - str, path of the ISCE-2 lat/lon.rdr file
                                    To geocode file with ISCE-2 lookup table files directly,
                                    without using/loading geometry files in HDF5/MintPy format.
        r   N)lut_filelat_filelon_filesrc_fileSNWE	lalo_stepinterp_method
fill_valuenprocs
max_memorysoftware	print_msgnum_boxradius)selfr   r   r   r   r   r   r   r   r   r   r   r   s                P/home/exouser/operations/rsmas_insar/tools/MintPy/src/mintpy/objects/resample.py__init__zresample.__init__U   si    , !   	"*$$ "     c                 Z   | j                   r%t        j                  | j                         | _        nd| _        | j                  r%t        j                  | j                        | _        nd| _        | j                  dk(  r,| j                  | j                  | j                        | _	        yy)zRead metadata

        Note: separate open() from prepare() to handle numpy matrix directly w/o src_file
        by assigning src_meta after open() and before prepare()
        Nr   )
r   r	   read_attributelut_metar   src_metar   get_num_boxr   r   r   s    r    openzresample.open   s{     ==$33DMMBDM DM==$33DMMBDM DM ==L(++DMM4??KDL )r"   c                    | j                   | j                  t        d      t        d| j                          | j                  dk(  r8d| j                   j                         v r| j                          yt        d      | j                  dk(  rid| j                   j                         v r| j                          n| j                          | j                  | j                  | j                        | _        yy)z/Prepare aux data before interpolation operationNz-lookup table or source data metadata is None!zresampling software: scipyY_FIRSTzXresampling using scipy with lookup table in radar-coord (ISCE / DORIS) is NOT supported!r   )r%   r&   
ValueErrorprintr   keys!prepare_regular_grid_interpolatorprepare_geometry_definition_geo!prepare_geometry_definition_radarget_radius_of_influencer   r   r(   s    r    preparezresample.prepare   s     == DMM$9LMM 	%dmm_56==G#DMM..00668 !{||]]l*DMM..00446 668 66t~~t}}UDK +r"   c           
      X   |rt         nd }| j                  }t        j                  t        j                  t        j
                  t        j                  t        j                  t        j                  g}|j                  t        j                  k(  rd} |d       n-|j                  |vrt        j                  |      r
d} |d       t        | j                  ||      }| j                  dk(  rt        |j                         dk(  rt        j"                  |dd	      } | j$                  d|| j&                  |   | j(                  |   | j*                  | j,                  d
|}t        |j                         dk(  rt        j"                  |d	d      }|S  || j                   d       t        |j                         dk(  rt        j.                  |j                   d   | j0                  | j2                  f|j                        }t5        j6                  |j                   d   |      }	t9        |j                   d         D ]>  }
|	j;                  |
dz           | j<                  dd||
ddddf   i|||
ddddf<   @ |	j?                          |S  | j<                  dd|i|}|S )a  Run interpolation operation for input 2D/3D data
        Parameters: src_data   - 2D/3D np.array, source data to be resampled
                    box_ind    - int, index of the current box of interest
                                 for multiple boxes with pyresample only
                    print_msg  - bool
        Returns:    dest_data  - 2D/3D np.array, resampled data
        c                       y N )argskwargss     r    <lambda>z'resample.run_resample.<locals>.<lambda>   s    r"   Fz=input source data is bool type, restrict fill_value to False.r   z@input source data is NOT float, change fill_value from NaN to 0.)r   r   r   r      )src_datasrc_defdest_defr   r   z? resampling using scipy.interpolate.RegularGridInterpolator ...)maxValuer   r   r>   Nr8   ) r.   r   npsingledouble
longdoublecsinglecdoubleclongdoubledtypebool_isnandictr   r   lenshapemoveaxisrun_pyresamplesrc_def_listdest_def_listr   r   emptylengthwidthr   progressBarrangeupdaterun_regular_grid_interpolatorclose)r   r>   box_indr   vprintr   float_typesr:   	dest_dataprog_baris              r    run_resamplezresample.run_resample   se    $)E __
yy"))R]]BJJ

TVTbTbc>>RXX%JRS^^;.288J3GJUV ,,!
 ==L( 8>>"a';;xB7 ,++ !))'2++G4{{{{ I 9??#q(KK	2q9	  d(())hij8>>"a'HHhnnQ&7djj%QS[SaSab	 ,,hnnQ6GS\]x~~a01 rAOOAaC()K)K)K)qU]^_abde^eUf)qjp)qIaAg&r    ?D>>[[TZ[	r"   c                    d}| r]t         j                  j                  |       r=|dkD  r7t        j                  |       }t         j                  j                  |       d   }|dv ryt        j                  | d      5 }|j                         D cg c].  }t        ||   t        j                        r||   j                  0 }}t        d |D              }	ddd       nt        |d         t        |d         z  }	|j                  d	d
      j                  d      r	|d	   j!                  d      rdndz  }	t        t#        j$                  	dz  dz  |dz  z              }|S c c}w # 1 sw Y   vxY w)a  Get the number of boxes to split to not exceed the max memory
        Parameters: src_file   - str, path of source data file (largest one if multiple)
                    max_memory - float, memory size in GB
                    scale_fac  - float, scale factor from data size to memory used
                                 empirically estimated.
        Returns:    num_box    - int, number of boxes to be split
        r   r   )z.h5z.he5rc              3   F   K   | ]  }t        j                  |        y wr7   )rB   prod).0r`   s     r    	<genexpr>z'resample.get_num_box.<locals>.<genexpr>  s     %DQbggaj%Ds   !NLENGTHWIDTH	DATA_TYPEfloat32complex128   r<      i   @)ospathisfiler	   r$   splitexth5pyFiler/   
isinstanceDatasetrN   maxintget
startswithendswithrB   ceil)
r   r   	scale_facr   atrfextfr`   	ds_shapesmax_ds_sizes
             r    r'   zresample.get_num_box   s\     x0Z!^))(3C77##H-a0D&YYx- E56VVX !D$.qtT\\$B "#1 !DI !D"%%D)%D"DKE E
 "#h-03s7|3DD ww{I.99)DC$4$=$=e$Dq!K "'';?Q#6:;O"PQRG!DE Es   =E*3E%E*%E**E3c                     d|j                         v rd}|S t        t        j                  |             }|t        j                  z  dz  t
        z  }||z  }|S )zQGet radius of influence based on the lookup table resolution in lat/lon directionr,   g     j@g     f@)r/   rx   rB   abspir   )r   r&   ratior   step_degstep_ms         r    r3   z resample.get_radius_of_influence  sY     'F  266),-H%-<Fe^Fr"   c           
         | j                   | j                   \  }}nBt        d       i | j                  | j                  }g d}|D 	cg c]  }	|	|j	                         vs|	 }
}	t        |
      dk(  rt        j                  t        t        j                  t        |d                           }t        j                  |      }t        j                  |      }|t        t        j                  |            z  |t        t        j                  |            z  z   }|t        t        j                  |            z  |t        t        j                  |            z  z   }t        j                   ||z  ||z  z        }||z  }||z  }||z   dz  }t        j"                  |t$        t        j                  t        j                  |            z  z        }t        j"                  |t$        z        dz  }nfd}|d|
 d	z  }|d
z  }|dz  }t        |       t'        | j                  d         }t'        | j                  d         }||z
  |dz
  z  }||z
  |dz
  z  }t        |      dz  }t        |      }||fS c c}	w )a  Get/check the lat/lon step size for geocoding.

        Approach 1: ensure the same pixel area before / after resampling
            Treat the pixel in radar coordinates as an rotated rectangle. Use the bounding
                box of the rotated rectangle for the ratio between lat and lon steps. Then
                scale the lat and lon step size to ensure the same area between the pixels
                in radar and geo coordinates.
            This is recommended, but it requires metadata on the pixel size info.
            Link: https://math.stackexchange.com/questions/4001034

        Approach 2: ensure the same matrix shape before / after resampling
            This is the backup approach if approach 1 does not work.

        Parameters: src_lat0/1   - float, max/min latitude  in degree of the input data file
                    src_lon0/1   - float, min/max longitude in degree of the input data file
        Returns:    lat/lon_step - float, output step size in latitude/longitude in degree
        zVcalculate output pixel size using approach 1 (same pixel area before/after resampling))AZIMUTH_PIXEL_SIZEHEADINGHEIGHTRANGE_PIXEL_SIZESTARTING_RANGEri   r   r          @g      z.WARNING: NOT all required metadata are found. zMissing metadata: z. Switch to approach 2.
z-calculate output pixel size using approach 2 z+(same matrix shape before/after resampling)rh   ri   r   )r   r.   r%   r&   r/   rM   rB   deg2radr   utheading2azimuth_anglefloatazimuth_ground_resolutionrange_ground_resolutioncossinsqrtrad2degr   ry   )r   src_lat0src_lat1src_lon0src_lon1lat_steplon_stepmetakey_listxkey_not_foundaz_angleaz_steprg_stepx_stepy_stepscale_factorlat_cmsglut_lenlut_wids                        r    get_lat_lon_stepzresample.get_lat_lon_step"  s`   & >>%!%Hh
  > ? 6dmm5t}}5DH )1I1ATYY[4HQIMI=!Q& ::c"*B*B5iCY*Z&[\ 66t<44T: !3rvvh'7#887SPXIYEZ;ZZ 3rvvh'7#887SPXIYEZ;ZZ!ww'(9fvo'NO,&,& "H,2::frvvbjjQVFW?X0X&YZ::f|&;<sB G+M?:STTFFDDc
 dmmH56dmmG45$x/GaK@$x/GaK@ x=3&x=!!S Js   I=#I=c           
      4   d }t        d| j                          | j                  r| j                  n| j                  }| j                  r| j                  n| j                  }t	        j
                  |d      d   j                  t        j                        }t	        j
                  |d      d   j                  t        j                        } |||      \  }}}d| j                  j                         vrt        j                  ||         }t        j                  ||         }t        j                  ||         }	t        j                  ||         }
| j                  |||	|
      | _        t        d| j                          | j                  W|| j                  d   d
z  z   || j                  d   d
z  z
  |	| j                  d   d
z  z
  |
| j                  d   d
z  z   f| _        t!        t        j"                  | j                  d   | j                  d   z
  | j                  d   z              | _        t!        t        j"                  | j                  d   | j                  d   z
  | j                  d   z              | _        | j                  d   | j                  d   | j$                  z  z   | j                  d   | j                  d   | j                  d   | j                  d   | j&                  z  z   f| _        t        d| j                          t        d| j$                   d| j&                   d       g | _        g | _        g | _        g | _        t1        dd| j&                  | j$                  f| j2                  dd      \  | _        | _        t5        | j,                        D ]  \  }}d|dz    d| j2                   d| }|d   |d   z
  }|d   |d   z
  }| j                  d   | j                  d   |d   dz   z  z   }| j                  d   | j                  d   |d   dz
  z  z   }| j                  d   | j                  d   |d   dz   z  z   }| j                  d   | j                  d   |d   dz
  z  z   }t        j6                  |||dz  |||dz  f   \  }}t9        ||z
        t9        |
|	z
        z  }t9        ||z
        t9        ||z
        z  }||dz  k  rt:        j<                  j?                  ||||d      }t        j@                  |      \  }}t        jB                  |      t        jB                  |      t        jD                  |      t        jD                  |      f}|d| z  }n(dd|jF                  d   |jF                  d   f}|d| z  }t        |       t:        jH                  jK                  ||d   |d   |d   |d   f   ||d   |d   |d   |d   f         }t:        jH                  jM                  ||      }| j(                  jO                  |       | j*                  jO                  |       | j.                  jO                  |        y	tQ        | j                  d         tQ        | j                  d          g| _        t        d!| j                          tQ        | j                  d         }tQ        | j                  d"         }| j                  s3ddt!        | j                  d#         t!        | j                  d$         f}nt!        t        j"                  | j                  d   |z
  | j                  d   z              t!        t        j"                  | j                  d   |z
  | j                  d   z              t!        t        j"                  | j                  d   |z
  | j                  d   z              t!        t        j"                  | j                  d   |z
  | j                  d   z              f}|| j                  d   |d   z  z   || j                  d   |d   z  z   || j                  d   |d   z  z   || j                  d   |d   z  z   f| _        t        d%| j                          |jF                  \  | _        | _        |d   |d   z
  }|d   |d   z
  }| j                  d   | j                  d   |d   dz   z  z   }| j                  d   | j                  d   |d   dz
  z  z   }| j                  d   | j                  d   |d   dz   z  z   }	| j                  d   | j                  d   |d   dz
  z  z   }
t        j6                  |||dz  |	|
|dz  f   \  } }!|g| _        t:        jH                  jM                  |!|       g| _        dd| j&                  | j$                  fg| _        t:        jH                  jK                  ||      g| _        d| _        y	)&zKGet src_def and dest_def for lookup table in radar-coord (from ISCE, DORIS)c                 J   t        j                  | dk7  |dk7        }t        j                  |t         j                        }| |fD ]G  }t        j                  ||   d      \  }}t        j
                  |      t        j                  |      dz  kD  sPt        j                  |d      }t        j                  ||kD        d   }t        j                  ||t        j                  |         k(        d   }	|d   |d   z
  }
||	d      |
d	z  z
  }||	d
   dz      |
d	z  z   }|t        j                  ||k\  ||k        z  }t        j                  ||   d      \  }}t        j
                  |      t        j                  |      dz  kD  rJ d| |dk(  <   d||dk(  <   | ||fS )a  mask pixels with abnormal values (0, etc.)
            This is found on sentinelStack multiple swath lookup table file.

            Parameters: lat/lon - 2D np.ndarray in float32, latitude/longitude in degrees.
            Returns:    lat/lon - 2D np.ndarray in float32, latitude/longitude in degrees.
                        mask    - 2D np.ndarray in bool, 1/0 for valid/invalid pixels.
                    
   )binsg333333?r<   )cutoffr   r   r   r=        V@)rB   multiplyarrayrJ   	histogramrx   sumr   median_abs_deviation_thresholdr   labelwhereargmax)latlon	zero_maskmaskdata	bin_valuebin_edgebin_value_thres	bin_labelidxbin_stepd_mind_maxs                r    find_valid_lat_lonzFresample.prepare_geometry_definition_radar.<locals>.find_valid_lat_lonz  s    C2Isby9I 88Irxx0Dc
 L&(ll4:B&G#	8ffY'"&&*;c*AA&(&G&G	Z[&\O 'i/.I J1 MI((9	"))I:N0O#OPQRSC'{Xa[8H$SV,x"}<E$SWQY/(R-?EBKKtu}EED*,,,tDz*K'Ix ffY'"&&*;c*AAL  !C	NC	NT>!r"   z2read latitude / longitude from lookup table file: latitudedatasetNamer   	longituder,   +output pixel size in (lat, lon) in degree: Nr   r   r<      .output area extent in (S, N, W, E) in degree: z"output file row / column number: (z, )yT)box	num_split	dimensionr   [/z#] preparing geometry for dest_box:       ?              ?i  )radius_of_influencez --> reduced src_box: z --> full src_box: lonslatsY_STEPX_STEPz*input pixel size in (lat, lon) in degree: X_FIRSTri   rh   z-input area extent in (S, N, W, E) in degree: ))r.   r   r   r   r	   readastyperB   rk   r&   r/   nanmaxnanminr   r   r   ry   rintrT   rU   src_box_listrQ   dest_box_listrR   r   r   	enumeratemgridr   prdata_reduce get_valid_index_from_lonlat_gridr   minrx   rN   geometrySwathDefinitionGridDefinitionappendr   )"r   r   r   r   lut_latlut_lonr   r   r   r   r   r`   dest_boxr   lat_numlon_numlat0lat1lon0lon1dest_latdest_lonsrc_area	dest_areaflagidx_rowidx_colsrc_boxr?   r@   src_lensrc_widsrc_latsrc_lons"                                     r    r2   z*resample.prepare_geometry_definition_radarw  s	    	"L 	B4==/RS$(MM4==t}}$(MM4==t}}--jA!DKKBJJW--kB1ELLRZZX!3GW!E$ DMM..00 yy/Hyy/Hyy/Hyy/H "228XxQYZDN??OPQ yy %q(9C(??%q(9C(??%q(9C(??%q(9C(??A	 bggtyy|diil'BdnnUVFW&WXYDKbggtyy|diil'BdnnUVFW&WXYDJ1q(9DKK(GG111q(9DJJ(FFHDI B499+NO6t{{m2djj\QRST !#D "D!#D!#D 0C4::t{{3,,	0,D  )););< .48!A#a~-PQYPZ[ #1+3"1+3yy|dnnQ&78A;;L&MMyy|dnnQ&78A;;L&MMyy|dnnQ&78A;;L&MMyy|dnnQ&78A;;L&MM%'XXd4
.B.24
.B/C &D"( x(23c(X:M6NNt,s4$;/??	x#~- >>JJ  ,0 K D (*xx~$GW!vvgw!vvgwAG3G9==C  !!W]]1%5w}}Q7GHG0	::Cc
 ++55 GAJ!6
71:8M!MN GAJ!6
71:8M!MN 6  ;;558(5S!!((1!!((1""))(3].4@ 	Y $DMM($;<#DMM($;<>DN>t~~>NOP y12Dy12D99aT]]7%;!<c$--PXBY>Z[ rww		!t(;t~~a?P'PQRrww		!t(;t~~a?P'PQRrww		!t(;t~~a?P'PQRrww		!t(;t~~a?P'PQRT
 q 1GAJ >>q 1GAJ >>q 1GAJ >>q 1GAJ >>@DI A$))MN '.mm#DK aj71:-Gaj71:-Gyy|dnnQ&771:;K&LLHyy|dnnQ&771:;K&LLHyy|dnnQ&771:;K&LLHyy|dnnQ&771:;K&LLH!xx'"*(D(0'"*(D)E  FGW ")	D!#!;!;w!;!W XD#$aT[["A!BD"$++"="=7QX"="Y!ZDDLr"   c           
         d }d| j                   j                         vrt        | j                  d         t        | j                  d         f| _        t        d| j                          t        | j                  d         }t        | j                  d         }| j                  s4ddt        | j                  d         t        | j                  d	         f}n\t        t        j                  | j                  d
   |z
  | j                  d   z              t        t        j                  | j                  d   |z
  | j                  d   z              t        t        j                  | j                  d   |z
  | j                  d   z              t        t        j                  | j                  d   |z
  | j                  d   z              f}t        |d   d      t        |d   d      t        |d
   t        | j                  d               t        |d   t        | j                  d	               f}|| j                  d   |d   z  z   || j                  d   |d   z  z   || j                  d   |d   z  z   || j                  d   |d
   z  z   f| _        t        d| j                          |d   |d
   c| _        | _        t        | j                   d	         }t        | j                   d         }t        j                  d|dz
  |dz  d|dz
  |dz  f   \  }}t        j                   | j"                  d|      d   }	t        j                   | j"                  d|      d   }
d| j                   j                         v rWt        d       |	|	dk7  xx   t        | j                   d         z  cc<   |
|
dk7  xx   t        | j                   d         z  cc<   t        j$                  t        j$                  |	dkD  |	|k        t        j$                  |
dkD  |
|k              }t        j&                  |      \  }}| j                  d   | j                  d   t        j                  |      z  z   | j                  d   | j                  d   t        j                  |      z  z   | j                  d
   | j                  d   t        j                  |      z  z   | j                  d
   | j                  d   t        j                  |      z  z   f}|d   |d   z
  |z  |d   |d
   z
  |z  f} |||||      \  }}t        j(                  |	|	dk(  <   t        j(                  |
|
dk(  <    ||	|
||      \  }}dd||fg| _        t,        j.                  j1                  ||      g| _        |g| _        t,        j.                  j7                  ||      g| _        d| _        yt=        d      )zAGet src_def and dest_def for lookup table from Gamma and ROI_PAC.c                     |d   | |d   z  z   }|d   ||d   z  z   }d|t        j                  |      <   d|t        j                  |      <   d||dk(  <   ||fS )zfscale/project coordinates in pixel number into lat/lon
            based on bbox and step
            r   r   r   r   )rB   rK   )yyxxr   	laloScaler   r   s         r    project_yx2lalozAresample.prepare_geometry_definition_geo.<locals>.project_yx2lalo:  sn     7R)A,..D7R)A,..D#&D$ #&D$  !D:r"   r,   r   r   r   r   r   ri   rh   r   r   r<   r   r   r   azimuthCoord)r   r   
rangeCoordSUBSET_XMIN#input data file was cropped before.r   SUBSET_YMINr   >geo2radar with lookup table in geo-coord it NOT supported yet!N)"r&   r/   r   r%   r   r.   r   ry   rB   r   rx   r   rT   rU   r   r	   r   r   r   r   nanr   r   r   r   rQ   r   r   rR   r   r-   rN   flattenreshape)r   r  r   r   r   r  r  src_ysrc_xdest_ydest_xcommMaskr  r  commSNWEr  r  r	  r   r   	dest_y_lt	dest_x_ltr   r   r  r  rowcols                               r    r1   z(resample.prepare_geometry_definition_geo7  sf   		  DMM..00 $DMM($;<#DMM($;<>DN??OPQ y12Dy12D99q#dmmG&<"=s4==QYCZ?[\  1)<q@Q(Q RS1)<q@Q(Q RS1)<q@Q(Q RS1)<q@Q(Q RSU
  Q/Q/Sw1G-HISx1H-IJL
 q 1HQK ??q 1HQK ??q 1HQK ??q 1HQK ??ADI B499+NO '/qk8A;#DK
 $--12G$--01G88CGBJ$>$'GBJ$>%? @LE5 ]]4==nRZ[\]^F]]4==lPXYZ[\F 2 2 44;<v|$dmmM.J(KK$v|$dmmM.J(KK$ {{2;;vz6G;K#L#%;;vz6G;K#LNH!xx1GW		!t~~a'8266'?'JJ		!t~~a'8266'?'JJ		!t~~a'8266'?'JJ		!t~~a'8266'?'JJLH #1+3w>"1+3w>@I  /ueXyQGW#%66F6R< #%66F6R< !09!UHh #$Q!9 :D!#!;!;w!;!W XD"*D"$++"="=8RZ"="[!\DDLB 	9 ]^^r"   c                    t        t        j                  |j                  dz  dz               }|j	                  d      rF|r| d}	|	d| d| dz  }	t        |	       t        j                  j                  || |||||d      }
nT|j                  d	      rC|r| d
}	|	d| dz  }	t        |	       t        j                  j                  | ||||d||d	      }
d}|rddlm} |j                  ddd      \  }\  \  }}}\  }}}t        j                  |j                         }t        j"                  ||dk(  <   t        j                  |j$                        }t        j"                  ||dk(  <   |j'                  |j                         }|j)                  ||       |j+                  d       |j'                  |j$                        }|j)                  ||       |j+                  d       |j'                  |       }|j)                  ||       |j+                  d       |j'                  |      }|j)                  ||       |j+                  d       |j'                  |      }|j)                  ||       |j+                  d       |j'                  
      }|j)                  ||       |j+                  d       |j-                          
S )a  Resample input src_data into dest_data

        Parameters: src_data      - 2/3D np.ndarray, source data to be resampled
                    src_def       - pyresample geometry definition for source data
                    dest_def      - pyresample geometry definition for destination data
                    radius        - float, radius of influence
                    interp_method - str, interpolation method, nearest / linear
                    fill_value    - number, fill value for extrapolation
                    nprocs        - int, number of processors
        Returns:    dest_data     - 2/3D np.ndarray, source data to be resampled
        Example:    dest_data = reObj.run_pyresample(src_data, src_def, dest_def, radius,
                                                     interp_method=inps.interpMethod,
                                                     fill_value=inps.fillValue)
        g    .Ar   nearz$ resampling with pyresample.kd_tree zusing z CPU cores in z segments ...)r   r   r   segmentsepsilonlinearz% resampling with pyresample.bilinear z CPU cores ...    r   )r   r   
neighboursr   r%  r&  FNr   r<   )      )nrowsncolsfigsizer   r   )axsrc_latssrc_lonsr>   	dest_lats	dest_lonsr^   )ry   rB   r}   sizer{   r.   r   kd_treeresample_nearestr|   bilinearresample_bilinearmatplotlib.pyplotpyplotsubplotsr   r   r  r   imshowcolorbar	set_titleshow)r>   r?   r@   r   r   r   r   r   num_segmentr   r^   
debug_modepltfigax11ax12ax13ax21ax22ax23r2  r3  ims                          r    rP   zresample.run_pyresample  s   $ "''(--#"5";<= ##F+&'KLx~k]-PPc


33$*%$ 4 	I ##H-&'LMx~66c
55%$ 6 
I 
+<?LLqXYcjL<k9C9$4t&8tT4/IRTRXRXIi3>N4O/IQSQWQWIi2o4NW\\*BCLLL4MQUQ_Q_`jQkW\\*BCLLL4MQUQ_Q_`jQkX&BCLLL4MQUQ_Q_`jQkY'BCLLL4MQUQ_Q_`kQlY'BCLLL4MQUQ_Q_`kQlY'BCLLL4MQUQ_Q_`kQlHHJr"   c                    d| j                   j                         vrt        | j                   d         }t        | j                   d         }t        j                  |      dz   t        j                  |      dz   f| _        t        j                  | j                  d      d   }t        j                  | j                  d      d   }d	| j                   j                         v rWt        d
       ||dk7  xx   t        | j                   d         z  cc<   ||dk7  xx   t        | j                   d	         z  cc<   t        j                  t        j                  |dkD  ||k        t        j                  |dkD  ||k              | _        t        j                  || j                     j                  dd      || j                     j                  dd      f      | _        t        | j                   d         }t        | j                   d         }t        | j                   d         }t        | j                   d         }t        | j                   d         }	t        | j                   d         }
||f| _        |	||z  z   |	|
|
||z  z   f| _        || _        || _        dd||fg| _        dd||fg| _        yt/        d      )z3Prepare aux data for RegularGridInterpolator moduler,   rh   ri   r   r  r   r   r  r  r  r   r  r=   r   r   r   r   r  N)r&   r/   ry   rB   arangesrc_ptsr	   r   r   r.   r   r   interp_maskhstackr  dest_ptsr%   r   r   rT   rU   r   r   r-   )r   r  r  r  r  r   r   r   r   r   r   s              r    r0   z*resample.prepare_regular_grid_interpolator  s|    DMM..00$--12G$--01GIIg.4IIg.46DL ]]4==nMaPF]]4==lKANF 2 2 44;<v|$dmmM.J(KK$v|$dmmM.J(KK$!{{2;;vz6GCS+T+-;;vz6GCS+T VDIIvd.>.>'?'G'GA'N'-d.>.>'?'G'GA'N'P QDM $--12G$--01GT]]845HT]]845Hy12Dy12D&1DN7 227 224DI "DK DJ #$Q!9 :D#$a'":!;D ]^^r"   c                    t        | j                  ||d|      }t        j                  | j                  | j
                  f|j                        }|j                  |        || j                        || j                  <   |S )zInterpolate 2D matrixF)methodbounds_errorr   )
r   rM  rB   rS   rT   rU   rI   fillrP  rN  )r   r>   r   r   r   interp_funcgeo_datas          r    rY   z&resample.run_regular_grid_interpolator8  sp     .LL !
 88T[[$**5x~~Fj! &1%?!!"r"   )r   T)Nr   g      @)r<   )__name__
__module____qualname____doc__rB   r  r!   r)   r4   ra   staticmethodr'   r3   r   r2   r1   rP   r0   rY   r8   r"   r    r   r      s    6p +/TTYboqououa,$Y]hl(VL,V:<~  B 
 
P"j}@@F JS`b`f`f4D DR1_h ENZ\Z`Z`lp r"   r   )rZ  rp   warningsrt   numpyrB   r+   r   scipy.interpolater   catch_warningssimplefilterUserWarningr   r   mintpy.constantsr   mintpy.objects.clusterr   mintpy.utilsr   r	   r
   r   r   r8   r"   r    <module>re     sn    ; 
     5X H(K0 * 6 6 6n n s   A11A: