jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def get_interp_slice_posts(x, y, vals, slice_shape):
    
    slice_vals = np.zeros(slice_shape)
    
    # interpolator 
    tck = scipy.interpolate.bisplrep(x, y, vals)

    # evaluate interpolator on the mesh
    xgrid = np.arange(slice_shape[0])
    ygrid = np.arange(slice_shape[1])
    yy,xx = np.meshgrid(ygrid,xgrid)
    xx = np.ravel(xx)
    yy = np.ravel(yy)
    
    for i in range(len(xx)):
        slice_vals[xx[i], yy[i]] = scipy.interpolate.bisplev(xx[i], yy[i], tck)

    return slice_vals
//  [python]
def test_interp2d_bounds(self):
        x = np.linspace(0, 1, 5)
        y = np.linspace(0, 2, 7)
        z = x[:,None]**2 + y[None,:]

        ix = np.linspace(-1, 3, 31)
        iy = np.linspace(-1, 3, 33)

        b = interp2d(x, y, z, bounds_error=True)
        assert_raises(ValueError, b, ix, iy)

        b = interp2d(x, y, z, fill_value=np.nan)
        iz = b(ix, iy)
        mx = (ix < 0) | (ix > 1)
        my = (iy < 0) | (iy > 2)
        assert_(np.isnan(iz[my,:]).all())
        assert_(np.isnan(iz[:,mx]).all())
        assert_(np.isfinite(iz[~my,:][:,~mx]).all())
//  [python]
def test_interp2d_bounds(self):
        x = np.linspace(0, 1, 5)
        y = np.linspace(0, 2, 7)
        z = x[:,None]**2 + y[None,:]

        ix = np.linspace(-1, 3, 31)
        iy = np.linspace(-1, 3, 33)

        b = bisplev(x, y, z, ix, iy, kx=1, ky=1, s=0)
        assert_raises(ValueError, b, ix, iy)

        b = bisplev(x, y, z, ix, iy, kx=1, ky=1, s=0, extrapolate=False)

        iz = b

        mx = (ix < 0) | (ix > 1)
        my = (iy < 0) | (iy > 2)
        assert_(np.isnan(iz[my,:]).all())
        assert_(np.isnan(iz[:,mx]).all())
        assert_(np.isfinite(iz[~my,:][:,~mx]).all())
//  [python]
def mm_to_galvo(self, x, y):
        """ Given one or many points in mm space, map them to galvo space.
            e.g.,
            >>> Printer.mm_to_galvo(0, 0) # -> galvo ticks for middle of build area.
            >>> Printer.mm_to_galvo([[0, 1, 2], [0, 0, 0]]) # -> A three-segment line along the x axis.
            The returned array is 2xN, where N is the number of source points
        """
        xshape = np.shape(x)
        if self._grid_table is None:
            grid = np.array(self.read_grid_table())
            assert grid.shape == (5, 5, 2)

            pts_mm = np.linspace(-64, 64, 5) # Grid positions in mm

            # Interpolators for X and Y values (mm to galvo ticks)
            import scipy.interpolate
            fit_x = scipy.interpolate.interp2d(pts_mm, pts_mm, grid[:,:,0])
            fit_y = scipy.interpolate.interp2d(pts_mm, pts_mm, grid[:,:,1])
            self._grid_table = (fit_x, fit_y)

        if np.shape(x) != np.shape(y):
            raise TypeError('x and y shapes must match. Got x.shape: {}, y.shape: {}'.format(np.shape(x), np.shape(y)))

        x = np.atleast_1d(x)
        y = np.atleast_1d(y)

        x_ = [self._grid_table[0](a, b) for a, b in zip(x, y)]
        y_ = [self._grid_table[1](a, b) for a, b in zip(x, y)]

        result = np.hstack([x_, y_]).T
        if xshape == (): # If it's called with scalars, return a flat result.
            return result.flatten()
        return result
//  [python]
def mm_to_galvo(self, x, y):
        """ Given one or many points in mm space, map them to galvo space.
            e.g.,
            >>> Printer.mm_to_galvo(0, 0) # -> galvo ticks for middle of build area.
            >>> Printer.mm_to_galvo([[0, 1, 2], [0, 0, 0]]) # -> A three-segment line along the x axis.
            The returned array is 2xN, where N is the number of source points
        """
        xshape = np.shape(x)
        if self._grid_table is None:
            grid = np.array(self.read_grid_table())
            assert grid.shape == (5, 5, 2)

            pts_mm = np.linspace(-64, 64, 5) # Grid positions in mm

            # Interpolators for X and Y values (mm to galvo ticks)
            import scipy.interpolate
            kx = ky = 1
            fit_x = scipy.interpolate.bisplev(pts_mm, pts_mm, grid[:,:,0], kx=kx, ky=ky)
            fit_y = scipy.interpolate.bisplev(pts_mm, pts_mm, grid[:,:,1], kx=kx, ky=ky)
            self._grid_table = (fit_x, fit_y)

        if np.shape(x) != np.shape(y):
            raise TypeError('x and y shapes must match. Got x.shape: {}, y.shape: {}'.format(np.shape(x), np.shape(y)))

        x = np.atleast_1d(x)
        y = np.atleast_1d(y)

        x_ = [self._grid_table[0](a, b) for a, b in zip(x, y)]
        y_ = [self._grid_table[1](a, b) for a, b in zip(x, y)]

        result = np.hstack([x_, y_]).T
        if xshape == (): # If it's called with scalars, return a flat result.
            return result.flatten()
        return result
//  [python]
def create_acceptance_function(self):
        """Creates a 2D linear interpolation of the acceptance of the detector
        for the given season, as a function of declination and gamma. Returns
        this interpolation function.

        :return: 2D linear interpolation
        """

        acc_path = acceptance_path(self.season)

        with open(acc_path, "rb") as f:
            [dec_bins, gamma_bins, acc] = pickle.load(f)

        f = scipy.interpolate.interp2d(dec_bins, gamma_bins, acc.T, kind="linear")
        return f
//  [python]
def create_acceptance_function(self):
        """Creates a 2D linear interpolation of the acceptance of the detector
        for the given season, as a function of declination and gamma. Returns
        this interpolation function.

        :return: 2D linear interpolation
        """

        acc_path = acceptance_path(self.season)

        with open(acc_path, "rb") as f:
            [dec_bins, gamma_bins, acc] = pickle.load(f)

        tck = scipy.interpolate.bisplrep(dec_bins, gamma_bins, acc.T)
        f = lambda dec, gamma: scipy.interpolate.bisplev(dec, gamma, tck)
        return f
//  [python]
def add_velocity_streams(ax, ds, fn, nngrid=80, zlev=0):
    # slower than adding quivers, but informative in a different way
    # GET DATA
    G = zrfun.get_basic_info(fn, only_G=True)
    if zlev == 0:
        u = ds['u'][0, -1, :, :].squeeze()
        v = ds['v'][0, -1, :, :].squeeze()
    else:
        zfull_u = get_zfull(ds, fn, 'u')
        zfull_v = get_zfull(ds, fn, 'v')
        u = get_laym(ds, zfull_u, ds['mask_u'][:], 'u', zlev).squeeze()
        v = get_laym(ds, zfull_v, ds['mask_v'][:], 'v', zlev).squeeze()
    # ADD VELOCITY STREAMS
    # set masked values to 0
    ud = u.data; ud[u.mask]=0
    vd = v.data; vd[v.mask]=0
    # create interpolant
    import scipy.interpolate as intp
    ui = intp.interp2d(G['lon_u'][0, :], G['lat_u'][:, 0], ud)
    vi = intp.interp2d(G['lon_v'][0, :], G['lat_v'][:, 0], vd)
    # create regular grid
    aaa = ax.axis()
    daax = aaa[1] - aaa[0]
    daay = aaa[3] - aaa[2]
    axrat = np.cos(np.deg2rad(aaa[2])) * daax / daay
    x = np.linspace(aaa[0], aaa[1], round(nngrid * axrat))
    y = np.linspace(aaa[2], aaa[3], nngrid)
    xx, yy = np.meshgrid(x, y)
    # interpolate to regular grid
    uu = ui(x, y)
    vv = vi(x, y)
    mask = uu != 0
    # plot velocity streams
    spd = np.sqrt(uu**2 + vv**2)
    ax.streamplot(x, y, uu, vv, density = 6,
    color='k', linewidth=spd*3, arrowstyle='-')
//  [python]
def add_velocity_streams(ax, ds, fn, nngrid=80, zlev=0):
    # slower than adding quivers, but informative in a different way
    # GET DATA
    G = zrfun.get_basic_info(fn, only_G=True)
    if zlev == 0:
        u = ds['u'][0, -1, :, :].squeeze()
        v = ds['v'][0, -1, :, :].squeeze()
    else:
        zfull_u = get_zfull(ds, fn, 'u')
        zfull_v = get_zfull(ds, fn, 'v')
        u = get_laym(ds, zfull_u, ds['mask_u'][:], 'u', zlev).squeeze()
        v = get_laym(ds, zfull_v, ds['mask_v'][:], 'v', zlev).squeeze()
    # ADD VELOCITY STREAMS
    # set masked values to 0
    ud = u.data; ud[u.mask]=0
    vd = v.data; vd[v.mask]=0
    # create interpolant
    import scipy.interpolate as intp
    x_u = G['lon_u'][0, :]
    y_u = G['lat_u'][:, 0]
    x_v = G['lon_v'][0, :]
    y_v = G['lat_v'][:, 0]
    tck_u = intp.bisplrep(x_u, y_u, ud)
    tck_v = intp.bisplrep(x_v, y_v, vd)
    # create regular grid
    aaa = ax.axis()
    daax = aaa[1] - aaa[0]
    daay = aaa[3] - aaa[2]
    axrat = np.cos(np.deg2rad(aaa[2])) * daax / daay
    x = np.linspace(aaa[0], aaa[1], round(nngrid * axrat))
    y = np.linspace(aaa[2], aaa[3], nngrid)
    xx, yy = np.meshgrid(x, y)
    # interpolate to regular grid
    uu = intp.bisplev(x, y, tck_u)
    vv = intp.bisplev(x, y, tck_v)
    mask = uu != 0
    # plot velocity streams
    spd = np.sqrt(uu**2 + vv**2)
    ax.streamplot(x, y, uu, vv, density = 6,
    color='k', linewidth=spd*3, arrowstyle='-')
//  [python]
def add_velocity_vectors(ax, ds, fn, v_scl=3, v_leglen=0.5, nngrid=80, zlev='top', center=(.8,.05)):
    # v_scl: scale velocity vector (smaller to get longer arrows)
    # v_leglen: m/s for velocity vector legend
    xc = center[0]
    yc = center[1]
    # GET DATA
    G = zrfun.get_basic_info(fn, only_G=True)
    if zlev == 'top':
        u = ds['u'][0, -1, :, :].squeeze()
        v = ds['v'][0, -1, :, :].squeeze()
    elif zlev == 'bot':
        u = ds['u'][0, 0, :, :].squeeze()
        v = ds['v'][0, 0, :, :].squeeze()
    else:
        zfull_u = get_zfull(ds, fn, 'u')
        zfull_v = get_zfull(ds, fn, 'v')
        u = get_laym(ds, zfull_u, ds['mask_u'][:], 'u', zlev).squeeze()
        v = get_laym(ds, zfull_v, ds['mask_v'][:], 'v', zlev).squeeze()
    # ADD VELOCITY VECTORS
    # set masked values to 0
    ud = u.data; ud[u.mask]=0
    vd = v.data; vd[v.mask]=0
    # create interpolant
    import scipy.interpolate as intp
    ui = intp.interp2d(G['lon_u'][0, :], G['lat_u'][:, 0], ud)
    vi = intp.interp2d(G['lon_v'][0, :], G['lat_v'][:, 0], vd)
    # create regular grid
    aaa = ax.axis()
    daax = aaa[1] - aaa[0]
    daay = aaa[3] - aaa[2]
    axrat = np.cos(np.deg2rad(aaa[2])) * daax / daay
    x = np.linspace(aaa[0], aaa[1], int(round(nngrid * axrat)))
    y = np.linspace(aaa[2], aaa[3], int(nngrid))
    xx, yy = np.meshgrid(x, y)
    # interpolate to regular grid
    uu = ui(x, y)
    vv = vi(x, y)
    mask = uu != 0
    # plot velocity vectors
    ax.quiver(xx[mask], yy[mask], uu[mask], vv[mask],
        units='y', scale=v_scl, scale_units='y', color='k')
    ax.quiver([xc, xc] , [yc, yc], [v_leglen, v_leglen],
              [v_leglen, v_leglen],
        units='y', scale=v_scl, scale_units='y', color='k',
        transform=ax.transAxes)
    ax.text(xc+.05, yc, str(v_leglen) + ' m/s',
        horizontalalignment='left', transform=ax.transAxes)
//  [python]
def add_velocity_vectors(ax, ds, fn, v_scl=3, v_leglen=0.5, nngrid=80, zlev='top', center=(.8,.05)):
    # v_scl: scale velocity vector (smaller to get longer arrows)
    # v_leglen: m/s for velocity vector legend
    xc = center[0]
    yc = center[1]
    # GET DATA
    G = zrfun.get_basic_info(fn, only_G=True)
    if zlev == 'top':
        u = ds['u'][0, -1, :, :].squeeze()
        v = ds['v'][0, -1, :, :].squeeze()
    elif zlev == 'bot':
        u = ds['u'][0, 0, :, :].squeeze()
        v = ds['v'][0, 0, :, :].squeeze()
    else:
        zfull_u = get_zfull(ds, fn, 'u')
        zfull_v = get_zfull(ds, fn, 'v')
        u = get_laym(ds, zfull_u, ds['mask_u'][:], 'u', zlev).squeeze()
        v = get_laym(ds, zfull_v, ds['mask_v'][:], 'v', zlev).squeeze()
    # ADD VELOCITY VECTORS
    # set masked values to 0
    ud = u.data; ud[u.mask]=0
    vd = v.data; vd[v.mask]=0
    # create interpolant
    import scipy.interpolate as intp
    ui = intp.bisplev(G['lon_u'][0, :], G['lat_u'][:, 0], ud)
    vi = intp.bisplev(G['lon_v'][0, :], G['lat_v'][:, 0], vd)
    # create regular grid
    aaa = ax.axis()
    daax = aaa[1] - aaa[0]
    daay = aaa[3] - aaa[2]
    axrat = np.cos(np.deg2rad(aaa[2])) * daax / daay
    x = np.linspace(aaa[0], aaa[1], int(round(nngrid * axrat)))
    y = np.linspace(aaa[2], aaa[3], int(nngrid))
    xx, yy = np.meshgrid(x, y)
    # interpolate to regular grid
    uu = ui(x, y)
    vv = vi(x, y)
    mask = uu != 0
    # plot velocity vectors
    ax.quiver(xx[mask], yy[mask], uu[mask], vv[mask],
        units='y', scale=v_scl, scale_units='y', color='k')
    ax.quiver([xc, xc] , [yc, yc], [v_leglen, v_leglen],
              [v_leglen, v_leglen],
        units='y', scale=v_scl, scale_units='y', color='k',
        transform=ax.transAxes)
    ax.text(xc+.05, yc, str(v_leglen) + ' m/s',
        horizontalalignment='left', transform=ax.transAxes)
//  [python]
def cubic_interpolate(yr, xr, image):
    try:
        z1 = cv2.imread(image)[:,:,2]
        z2 = cv2.imread(image)[:,:,1]
        z3 = cv2.imread(image)[:,:,0]
    except:
        try:
            z1 = image[0, :, :, 2]
            z2 = image[0, : ,: , 1]
            z3 = image[0, :, :, 3]
        except:
            z1 = image[:, :, 2]
            z2 = image[:, :, 1]
            z3 = image[:, :, 0]
    try:
        cubic1 = scipy.interpolate.interp2d(yr, xr, z1.T)
        cubic2 = scipy.interpolate.interp2d(yr, xr, z2.T)
        cubic3 = scipy.interpolate.interp2d(yr, xr, z3.T)
    except:
        cubic1 = scipy.interpolate.interp2d(yr, xr, z1)
        cubic2 = scipy.interpolate.interp2d(yr, xr, z2)
        cubic3 = scipy.interpolate.interp2d(yr, xr, z3)
    return cubic1, cubic2, cubic3
//  [python]
def cubic_interpolate(yr, xr, image):
    try:
        z1 = cv2.imread(image)[:,:,2]
        z2 = cv2.imread(image)[:,:,1]
        z3 = cv2.imread(image)[:,:,0]
    except:
        try:
            z1 = image[0, :, :, 2]
            z2 = image[0, : ,: , 1]
            z3 = image[0, :, :, 3]
        except:
            z1 = image[:, :, 2]
            z2 = image[:, :, 1]
            z3 = image[:, :, 0]
    try:
        cubic1 = scipy.interpolate.bisplev(yr, xr, scipy.interpolate.bisplrep(yr, xr, z1.T))
        cubic2 = scipy.interpolate.bisplev(yr, xr, scipy.interpolate.bisplrep(yr, xr, z2.T))
        cubic3 = scipy.interpolate.bisplev(yr, xr, scipy.interpolate.bisplrep(yr, xr, z3.T))
    except:
        cubic1 = scipy.interpolate.bisplev(yr, xr, scipy.interpolate.bisplrep(yr, xr, z1))
        cubic2 = scipy.interpolate.bisplev(yr, xr, scipy.interpolate.bisplrep(yr, xr, z2))
        cubic3 = scipy.interpolate.bisplev(yr, xr, scipy.interpolate.bisplrep(yr, xr, z3))
    return cubic1, cubic2, cubic3
//  [python]
def time_interpolate(self, n_samples, method):
        interpolate.interp2d(self.x, self.y, self.z, kind=method)
//  [python]
def time_interpolate(self, n_samples, method):
        interpolate.bisplev(self.x, self.y, self.z, kind=method)
//  [python]
def load_data_to_array(path_to_data):
    # Need customization
    # data: [N,1,121,T_MAX]
    # label: [N,]
    global T_MAX
    print('Loading data from ' + str(path_to_data))

    # Load data
    data = []
    label = []
    domain = []
    for data_root, data_dirs, data_files in os.walk(path_to_data):
        for data_file_name in data_files:

            file_path = os.path.join(data_root,data_file_name)
            try:
                # Label embedding
                label_1_str = data_file_name.split('_')[0]
                if label_1_str == 'fall':
                    label_1 = 1
                elif label_1_str == 'nonfall':
                    label_1 = 0
                else:
                    print('Wrong fall/nonfall prefix, skiping...')
                    continue
                domain_1_name = data_file_name.split('_')[2]
                domain_1 = ID_LIST.index(domain_1_name)

                data_1 = np.abs(scio.loadmat(file_path)[mat_file_key])  # [T,61]
                # Interpolation
                f = scipy.interpolate.interp2d(np.arange(0,data_1.shape[1]), np.arange(0,data_1.shape[0]), data_1)
                data_1 = f(np.linspace(0,data_1.shape[1],121), np.arange(0,data_1.shape[0]))    # [T,61] => [T,121]
                data_1 = np.expand_dims(data_1.transpose(), axis=0) # [T,121]=>[1,121,T]
                
                # Downsample
                data_1 = data_1[:,:,0::downsamp_ratio_for_stft]     # [1,121,T]=>[1,121,t]

                # Skip nan
                if np.sum(np.isnan(data_1)):
                    print('Skipping ' + str(data_file_name))
                    continue

                # Normalization
                data_normed_1 = normalize_data(data_1)  # [6,121,t]

                # Update T_MAX
                if T_MAX < np.array(data_1).shape[2]:
                    T_MAX = np.array(data_1).shape[2]                
            except Exception as e:
                print(str(e))
                continue

            # Save List
            data.append(data_normed_1.tolist())
            label.append(label_1)
            domain.append(domain_1)

    # Zero-padding
    data = zero_padding(data, T_MAX)    # ([6,121,t1],...)=>[N,1,121,T]

    # Convert from complex128 to 2_channel_float32
    data = complex_array_to_2_channel_float_array(data)    # [N,1,121,T]=>[N,2,1,121,T]

    # Convert label to ndarray
    label = np.array(label)
    domain = np.array(domain)

    # data(ndarray): [N,2,1,121,T_MAX], label(ndarray): [N,], domain(ndarray): [N,]
    return data, label, domain
//  [python]
def load_data_to_array(path_to_data):
    # Need customization
    # data: [N,1,121,T_MAX]
    # label: [N,]
    global T_MAX
    print('Loading data from ' + str(path_to_data))

    # Load data
    data = []
    label = []
    domain = []
    for data_root, data_dirs, data_files in os.walk(path_to_data):
        for data_file_name in data_files:

            file_path = os.path.join(data_root,data_file_name)
            try:
                # Label embedding
                label_1_str = data_file_name.split('_')[0]
                if label_1_str == 'fall':
                    label_1 = 1
                elif label_1_str == 'nonfall':
                    label_1 = 0
                else:
                    print('Wrong fall/nonfall prefix, skiping...')
                    continue
                domain_1_name = data_file_name.split('_')[2]
                domain_1 = ID_LIST.index(domain_1_name)

                data_1 = np.abs(scio.loadmat(file_path)[mat_file_key])  # [T,61]
                # Interpolation
                x = np.arange(0,data_1.shape[1])
                y = np.arange(0,data_1.shape[0])
                tck = scipy.interpolate.bisplrep(x, y, data_1)
                data_1 = scipy.interpolate.bisplev(np.linspace(0,data_1.shape[1],121), y, tck)    # [T,61] => [T,121]
                data_1 = np.expand_dims(data_1.transpose(), axis=0) # [T,121]=>[1,121,T]
                
                # Downsample
                data_1 = data_1[:,:,0::downsamp_ratio_for_stft]     # [1,121,T]=>[1,121,t]

                # Skip nan
                if np.sum(np.isnan(data_1)):
                    print('Skipping ' + str(data_file_name))
                    continue

                # Normalization
                data_normed_1 = normalize_data(data_1)  # [6,121,t]

                # Update T_MAX
                if T_MAX < np.array(data_1).shape[2]:
                    T_MAX = np.array(data_1).shape[2]                
            except Exception as e:
                print(str(e))
                continue

            # Save List
            data.append(data_normed_1.tolist())
            label.append(label_1)
            domain.append(domain_1)

    # Zero-padding
    data = zero_padding(data, T_MAX)    # ([6,121,t1],...)=>[N,1,121,T]

    # Convert from complex128 to 2_channel_float32
    data = complex_array_to_2_channel_float_array(data)    # [N,1,121,T]=>[N,2,1,121,T]

    # Convert label to ndarray
    label = np.array(label)
    domain = np.array(domain)

    # data(ndarray): [N,2,1,121,T_MAX], label(ndarray): [N,], domain(ndarray): [N,]
    return data, label, domain
//  [python]
def findpeak3(f,subpixel):
    stdx=1e-4
    stdy=1e-4

    kernelsize=3

    # get absolute peak pixel
    max_f = np.amax(f)
    [xpeak,ypeak] = np.unravel_index(f.argmax(), f.shape)

    if subpixel==False or xpeak < kernelsize or xpeak > np.shape(f)[0]-kernelsize or ypeak < kernelsize or ypeak > np.shape(f)[1]-kernelsize: # on edge
        return xpeak, ypeak, stdx, stdy, max_f # return absolute peak
    else:
        # determine sub pixel accuracy by centroid
        fextracted=f[xpeak-kernelsize:xpeak+kernelsize+1,ypeak-kernelsize:ypeak+kernelsize+1]
        fextractedx=np.mean(fextracted,0)
        fextractedy=np.mean(fextracted,1)
        x=np.arange(-kernelsize,kernelsize+1,1)
        y=np.transpose(x)

        xoffset=np.dot(x,fextractedx)
        yoffset=np.dot(y,fextractedy)

        # return only one-thousandths of a pixel precision
        xoffset = np.round(1000*xoffset)/1000
        yoffset = np.round(1000*yoffset)/1000
        xpeak=xpeak+xoffset
        ypeak=ypeak+yoffset

        # 2D linear interpolation
        bilinterp = scipy.interpolate.interp2d(x, x, fextracted, kind='linear')
        max_f = bilinterp(xoffset,yoffset)

        # peak width (full width at half maximum)
        scalehalfwidth=1.1774
        stdx=scalehalfwidth*np.std(fextractedx)
        stdy=scalehalfwidth*np.std(fextractedy)

    return xpeak, ypeak, stdx, stdy, max_f
//  [python]
def findpeak3(f,subpixel):
    stdx=1e-4
    stdy=1e-4

    kernelsize=3

    # get absolute peak pixel
    max_f = np.amax(f)
    [xpeak,ypeak] = np.unravel_index(f.argmax(), f.shape)

    if subpixel==False or xpeak < kernelsize or xpeak > np.shape(f)[0]-kernelsize or ypeak < kernelsize or ypeak > np.shape(f)[1]-kernelsize: # on edge
        return xpeak, ypeak, stdx, stdy, max_f # return absolute peak
    else:
        # determine sub pixel accuracy by centroid
        fextracted=f[xpeak-kernelsize:xpeak+kernelsize+1,ypeak-kernelsize:ypeak+kernelsize+1]
        fextractedx=np.mean(fextracted,0)
        fextractedy=np.mean(fextracted,1)
        x=np.arange(-kernelsize,kernelsize+1,1)
        y=np.transpose(x)

        xoffset=np.dot(x,fextractedx)
        yoffset=np.dot(y,fextractedy)

        # return only one-thousandths of a pixel precision
        xoffset = np.round(1000*xoffset)/1000
        yoffset = np.round(1000*yoffset)/1000
        xpeak=xpeak+xoffset
        ypeak=ypeak+yoffset

        # 2D linear interpolation
        tck = scipy.interpolate.bisplrep(x, x, fextracted, kx=1, ky=1)
        max_f = scipy.interpolate.bisplev(xoffset,yoffset,tck)

        # peak width (full width at half maximum)
        scalehalfwidth=1.1774
        stdx=scalehalfwidth*np.std(fextractedx)
        stdy=scalehalfwidth*np.std(fextractedy)

    return xpeak, ypeak, stdx, stdy, max_f
//  [python]
def findpeak2(f,subpixel):
    stdx=1e-4
    stdy=1e-4

    kernelsize=3

    # get absolute peak pixel
    max_f = np.amax(f)
    [xpeak,ypeak] = np.unravel_index(f.argmax(), f.shape)

    if subpixel==False or xpeak < kernelsize or xpeak > np.shape(f)[0]-kernelsize or ypeak < kernelsize or ypeak > np.shape(f)[1]-kernelsize: # on edge
        return xpeak, ypeak, stdx, stdy, max_f # return absolute peak
    else:
        # determine sub pixel accuracy by upsampling and interpolation
        fextracted=f[xpeak-kernelsize:xpeak+kernelsize+1,ypeak-kernelsize:ypeak+kernelsize+1]
        totalsize=2*kernelsize+1
        upsampling=totalsize*10+1
        #step=2/upsampling
        x=np.linspace(-kernelsize,kernelsize,totalsize)
        #[X,Y]=np.meshgrid(x,x)
        xq=np.linspace(-kernelsize,kernelsize,upsampling)
        #[Xq,Yq]=np.meshgrid(xq,xq)

        bilinterp = scipy.interpolate.interp2d(x, x, fextracted, kind='cubic')
        fq = bilinterp(xq, xq)
        #splineint = RectBivariateSpline(x, x, fextracted, kx=3, ky=3, s=0)
        #fq=splineint(xq,xq)
        #fq=griddata((x, x), fextracted, (Xq, Yq), method='cubic')

        max_f = np.amax(fq)
        [xpeaknew,ypeaknew] = np.unravel_index(fq.argmax(), fq.shape)

        #xoffset=Xq[0,xpeaknew]
        #yoffset=Yq[ypeaknew,0]
        xoffset=xq[xpeaknew]
        yoffset=xq[ypeaknew]

        # return only one-thousandths of a pixel precision
        xoffset = np.round(1000*xoffset)/1000
        yoffset = np.round(1000*yoffset)/1000
        xpeak=xpeak+xoffset
        ypeak=ypeak+yoffset

        # peak width (full width at half maximum)
        scalehalfwidth=1.1774;
        fextractedx=np.mean(fextracted,0)
        fextractedy=np.mean(fextracted,1)
        stdx=scalehalfwidth*np.std(fextractedx)
        stdy=scalehalfwidth*np.std(fextractedy)

    return xpeak, ypeak, stdx, stdy, max_f
//  [python]
def findpeak2(f,subpixel):
    stdx=1e-4
    stdy=1e-4

    kernelsize=3

    # get absolute peak pixel
    max_f = np.amax(f)
    [xpeak,ypeak] = np.unravel_index(f.argmax(), f.shape)

    if subpixel==False or xpeak < kernelsize or xpeak > np.shape(f)[0]-kernelsize or ypeak < kernelsize or ypeak > np.shape(f)[1]-kernelsize: # on edge
        return xpeak, ypeak, stdx, stdy, max_f # return absolute peak
    else:
        # determine sub pixel accuracy by upsampling and interpolation
        fextracted=f[xpeak-kernelsize:xpeak+kernelsize+1,ypeak-kernelsize:ypeak+kernelsize+1]
        totalsize=2*kernelsize+1
        upsampling=totalsize*10+1
        #step=2/upsampling
        x=np.linspace(-kernelsize,kernelsize,totalsize)
        #[X,Y]=np.meshgrid(x,x)
        xq=np.linspace(-kernelsize,kernelsize,upsampling)
        #[Xq,Yq]=np.meshgrid(xq,xq)

        bilinterp = scipy.interpolate.bisplev(x,xq,scipy.interpolate.bisplrep(x,x,fextracted,kx=3,ky=3,s=0))
        fq = bilinterp
        #splineint = RectBivariateSpline(x, x, fextracted, kx=3, ky=3, s=0)
        #fq=splineint(xq,xq)
        #fq=griddata((x, x), fextracted, (Xq, Yq), method='cubic')

        max_f = np.amax(fq)
        [xpeaknew,ypeaknew] = np.unravel_index(fq.argmax(), fq.shape)

        #xoffset=Xq[0,xpeaknew]
        #yoffset=Yq[ypeaknew,0]
        xoffset=xq[xpeaknew]
        yoffset=xq[ypeaknew]

        # return only one-thousandths of a pixel precision
        xoffset = np.round(1000*xoffset)/1000
        yoffset = np.round(1000*yoffset)/1000
        xpeak=xpeak+xoffset
        ypeak=ypeak+yoffset

        # peak width (full width at half maximum)
        scalehalfwidth=1.1774;
        fextractedx=np.mean(fextracted,0)
        fextractedy=np.mean(fextracted,1)
        stdx=scalehalfwidth*np.std(fextractedx)
        stdy=scalehalfwidth*np.std(fextractedy)

    return xpeak, ypeak, stdx, stdy, max_f
//  [python]
def __init__(self, data):
        """Checks if the continous flow should be created from a set of data points if so it interpolates them for a
        continuous flow field
        """
        self.f_U = scipy.interpolate.interp2d(data[0, :, 0], data[:, 0, 1], data[:, :, 2])
        self.f_V = scipy.interpolate.interp2d(data[0, :, 0], data[:, 0, 1], data[:, :, 3])
//  [python]
def __init__(self, data):
        """Checks if the continous flow should be created from a set of data points if so it interpolates them for a
        continuous flow field
        """
        self.f_U = scipy.interpolate.bisplev(data[0, :, 0], data[:, 0, 1], data[:, :, 2])
        self.f_V = scipy.interpolate.bisplev(data[0, :, 0], data[:, 0, 1], data[:, :, 3])
//  [python]
def like_interp_2d(inputs: list, int_type: str = 'cubic') -> object:
    '''
    We want to predict the function for any new point of k and z (example)

    :param: inputs (list) - a list containing x, y, f(x,y)

    :param: int_type (str) - interpolation type (default: 'cubic')

    :return: f (object) - the interpolator
    '''

    k, z, f_kz = np.log(inputs[0]), inputs[1], inputs[2]

    inputs_trans = [k, z, f_kz]

    f = itp.interp2d(*inputs_trans)

    return f
//  [python]
def like_interp_2d(inputs: list, int_type: str = 'cubic') -> object:
    '''
    We want to predict the function for any new point of k and z (example)

    :param: inputs (list) - a list containing x, y, f(x,y)

    :param: int_type (str) - interpolation type (default: 'cubic')

    :return: f (object) - the interpolator
    '''

    k, z, f_kz = np.log(inputs[0]), inputs[1], inputs[2]

    inputs_trans = [k, z, f_kz]

    f = itp.bisplev(*inputs_trans)

    return f
//  [python]
def get_rockingcurve_func(self, lamb=None, n=None):
        """ Return the rocking curve function

        Also return the wavelength (lamb) (in meters) for which it was computed
            and the associated reference bragg angle (in rad)

        """
        drock = self.rockingcurve
        if drock['type'] == 'tabulated-1d':
            if lamb is not None and lamb != drock['lamb']:
                msg = ("rocking curve was tabulated only for:\n"
                       + "\tlamb = {} m\n".format(lamb)
                       + "  => Please let lamb=None")
                raise Exception(msg)
            lamb = drock['lamb']
            bragg = self._checkformat_bragglamb(lamb=lamb, n=n)
            func = scpinterp.interp1d(drock['dangle'] + bragg, drock['value'],
                                      kind='linear', bounds_error=False,
                                      fill_value=0, assume_sorted=True)

        elif drock['type'] == 'tabulated-2d':
            lmin, lmax = drock['lamb'].min(), drock['lamb'].max()
            if lamb is None:
                lamb = drock['lamb']
            if lamb < lmin or lamb > lmax:
                msg = ("rocking curve was tabulated only in interval:\n"
                       + "\tlamb in [{}; {}] m\n".format(lmin, lmax)
                       + "  => Please set lamb accordingly")
                raise Exception(msg)
            bragg = self._checkformat_bragglamb(lamb=lamb, n=n)

            def func(angle, lamb=lamb, bragg=bragg, drock=drock):
                return scpinterp.interp2d(drock['dangle']+bragg, drock['lamb'],
                                          drock['value'], kind='linear',
                                          bounds_error=False, fill_value=0,
                                          assume_sorted=True)(angle, lamb)

        else:
            # TBC
            raise NotImplementedError
            def func(angle, d=d, delta_bragg=delta_bragg,
                     Rmax=drock['Rmax'], sigma=drock['sigma']):
                core = sigma**2/((angle - (bragg+delta_bragg))**2 + sigma**2)
                if Rmax is None:
                    return core/(sigma*np.pi)
                else:
                    return Rmax*core
        return func, lamb, bragg
//  [python]
def get_rockingcurve_func(self, lamb=None, n=None):
        """ Return the rocking curve function

        Also return the wavelength (lamb) (in meters) for which it was computed
            and the associated reference bragg angle (in rad)

        """
        drock = self.rockingcurve
        if drock['type'] == 'tabulated-1d':
            if lamb is not None and lamb != drock['lamb']:
                msg = ("rocking curve was tabulated only for:\n"
                       + "\tlamb = {} m\n".format(lamb)
                       + "  => Please let lamb=None")
                raise Exception(msg)
            lamb = drock['lamb']
            bragg = self._checkformat_bragglamb(lamb=lamb, n=n)
            func = scpinterp.interp1d(drock['dangle'] + bragg, drock['value'],
                                      kind='linear', bounds_error=False,
                                      fill_value=0, assume_sorted=True)

        elif drock['type'] == 'tabulated-2d':
            lmin, lmax = drock['lamb'].min(), drock['lamb'].max()
            if lamb is None:
                lamb = drock['lamb']
            if lamb < lmin or lamb > lmax:
                msg = ("rocking curve was tabulated only in interval:\n"
                       + "\tlamb in [{}; {}] m\n".format(lmin, lmax)
                       + "  => Please set lamb accordingly")
                raise Exception(msg)
            bragg = self._checkformat_bragglamb(lamb=lamb, n=n)

            tck = scpinterp.bisplrep(drock['dangle']+bragg, drock['lamb'], drock['value'], kx=1, ky=1)
            def func(angle, lamb=lamb, bragg=bragg, drock=drock, tck=tck):
                return scpinterp.bisplev(angle, lamb, tck)

        else:
            # TBC
            raise NotImplementedError
            def func(angle, d=d, delta_bragg=delta_bragg,
                     Rmax=drock['Rmax'], sigma=drock['sigma']):
                core = sigma**2/((angle - (bragg+delta_bragg))**2 + sigma**2)
                if Rmax is None:
                    return core/(sigma*np.pi)
                else:
                    return Rmax*core
        return func, lamb, bragg
//  [python]
def plot_interpolated(grid, v, fine_num_lats, fine_num_lons, path_density, inset_region,
                      v_type):

    xmin, xmax, ymin, ymax = grid.bbox()
    # Interpolate the data onto a finer grid
    # --------------------------------------------------------------------------------------------------------------- #
    lats = np.linspace(ymin, ymax, fine_num_lats)
    lons = np.linspace(xmin, xmax, fine_num_lons)

    x = np.digitize(lats, grid.yarray(), right=True)
    y = np.digitize(lons, grid.xarray(), right=True)

    fv = scipy.interpolate.interp2d(grid.yarray(), grid.xarray(), v, kind="cubic")
    v_interp = fv(lats, lons)
    # ----------------------------------------------------------------------- #

    # Mask areas with no raypaths
    # ----------------------------------------------------------------------- #
    for i in range(len(x)):
        for j in range(len(y)):
            dens = path_density[y[j], x[i]]
            if dens < 1.0:
                v_interp[j, i] = v_interp[j, i] * np.nan
    # ----------------------------------------------------------------------- #

    grd = xr.DataArray(v_interp.T, coords=(lats, lons)) # Get the data in a format that pygmt can use

    fig = pygmt.Figure()
    fig.basemap(
        region=f"{xmin-1}/{xmax+1}/{ymin-1}/{ymax+1}", # Plot a slightly expanded region around the study area
        frame=True, # Plot a nice frame
        projection="M15c" # Use Mercator projection with a plot width of 15cm
    )
    fig.coast(
        land="lightgray", # Color the land light gray
        water="white", # color the water white
        borders=1, # Plot national boundaries
        shorelines=True # Show shorelines
    )

    # Make a colormap
    pygmt.makecpt(
          cmap="inferno", reverse=True,
          series=[np.nanmin(v_interp), np.nanmax(v_interp)]
    )

    # Show the tomography data
    fig.grdimage(
                 grd,
                 frame=True,
                 cmap=True,
                 nan_transparent=True,
                 transparency=20
    )

    # Make an inset plot, with the study area depicted
    with fig.inset(position="jTL+w5c/4.8c", box="+gblack+p2p"):
        fig.coast(
            region=inset_region,
            land="green",
            water="cornflowerblue"
        )
        rectangle=[[xmin-1, ymin-1, xmax+1,ymax+1]]
        fig.plot(data=rectangle, style="r+s", pen="2p,blue")
    fig.colorbar(frame=f'+l"{v_type} [km/s]"')
    fig.show()
//  [python]
def plot_interpolated(grid, v, fine_num_lats, fine_num_lons, path_density, inset_region,
                      v_type):

    xmin, xmax, ymin, ymax = grid.bbox()
    # Interpolate the data onto a finer grid
    # --------------------------------------------------------------------------------------------------------------- #
    lats = np.linspace(ymin, ymax, fine_num_lats)
    lons = np.linspace(xmin, xmax, fine_num_lons)

    x = np.digitize(lats, grid.yarray(), right=True)
    y = np.digitize(lons, grid.xarray(), right=True)

    tck = scipy.interpolate.bisplrep(grid.yarray(), grid.xarray(), v, kx=3, ky=3)
    v_interp = scipy.interpolate.bisplev(lats, lons, tck)
    # ----------------------------------------------------------------------- #

    # Mask areas with no raypaths
    # ----------------------------------------------------------------------- #
    for i in range(len(x)):
        for j in range(len(y)):
            dens = path_density[y[j], x[i]]
            if dens < 1.0:
                v_interp[j, i] = v_interp[j, i] * np.nan
    # ----------------------------------------------------------------------- #

    grd = xr.DataArray(v_interp.T, coords=(lats, lons)) # Get the data in a format that pygmt can use

    fig = pygmt.Figure()
    fig.basemap(
        region=f"{xmin-1}/{xmax+1}/{ymin-1}/{ymax+1}", # Plot a slightly expanded region around the study area
        frame=True, # Plot a nice frame
        projection="M15c" # Use Mercator projection with a plot width of 15cm
    )
    fig.coast(
        land="lightgray", # Color the land light gray
        water="white", # color the water white
        borders=1, # Plot national boundaries
        shorelines=True # Show shorelines
    )

    # Make a colormap
    pygmt.makecpt(
          cmap="inferno", reverse=True,
          series=[np.nanmin(v_interp), np.nanmax(v_interp)]
    )

    # Show the tomography data
    fig.grdimage(
                 grd,
                 frame=True,
                 cmap=True,
                 nan_transparent=True,
                 transparency=20
    )

    # Make an inset plot, with the study area depicted
    with fig.inset(position="jTL+w5c/4.8c", box="+gblack+p2p"):
        fig.coast(
            region=inset_region,
            land="green",
            water="cornflowerblue"
        )
        rectangle=[[xmin-1, ymin-1, xmax+1,ymax+1]]
        fig.plot(data=rectangle, style="r+s", pen="2p,blue")
    fig.colorbar(frame=f'+l"{v_type} [km/s]"')
    fig.show()
//  [python]
def two_dims_interpolate(inputs: list, grid: list) -> np.ndarray:
    '''
    Function to perform 2D interpolation using interpolate.interp2d

    :param: inputs (list) : inputs to the interpolation module, that is, we need to specify the following:
        - x
        - y
        - f(x,y)
        - 'linear', 'cubic', 'quintic'

    :param: grid (list) : a list containing xnew and ynew

    :return: pred_new (np.ndarray) : the predicted values on the 2D grid
    '''

    # check that all elements are greater than 0 for log-transformation to be used
    condition = np.all(inputs[2] > 0)

    if condition:
        # transform k and f to log
        k, z, f_kz, int_type = np.log(inputs[0]), inputs[1], np.log(inputs[2]), inputs[3]

    else:
        # transform in k to log
        k, z, f_kz, int_type = np.log(inputs[0]), inputs[1], inputs[2], inputs[3]

    inputs_trans = [k, z, f_kz, int_type]

    # tranform the grid to log
    knew, znew = np.log(grid[0]), grid[1]

    grid_trans = [knew, znew]

    f = itp.interp2d(*inputs_trans)

    if condition:
        pred_new = np.exp(f(*grid_trans))

    else:
        pred_new = f(*grid_trans)

    return pred_new
//  [python]
def two_dims_interpolate(inputs: list, grid: list) -> np.ndarray:
    '''
    Function to perform 2D interpolation using interpolate.interp2d

    :param: inputs (list) : inputs to the interpolation module, that is, we need to specify the following:
        - x
        - y
        - f(x,y)
        - 'linear', 'cubic', 'quintic'

    :param: grid (list) : a list containing xnew and ynew

    :return: pred_new (np.ndarray) : the predicted values on the 2D grid
    '''

    # check that all elements are greater than 0 for log-transformation to be used
    condition = np.all(inputs[2] > 0)

    if condition:
        # transform k and f to log
        k, z, f_kz, int_type = np.log(inputs[0]), inputs[1], np.log(inputs[2]), inputs[3]

    else:
        # transform in k to log
        k, z, f_kz, int_type = np.log(inputs[0]), inputs[1], inputs[2], inputs[3]

    inputs_trans = [k, z, f_kz, int_type]

    # tranform the grid to log
    knew, znew = np.log(grid[0]), grid[1]

    grid_trans = [knew, znew]

    tck = itp.bisplrep(inputs_trans[0], inputs_trans[1], inputs_trans[2], s=0)
    if condition:
        pred_new = np.exp(itp.bisplev(grid_trans[0], grid_trans[1], tck))
    else:
        pred_new = itp.bisplev(grid_trans[0], grid_trans[1], tck)


    return pred_new
//  [python]
def interp2d_pairs(*args,**kwargs):
    """ Same interface as interp2d but the returned interpolant will evaluate its inputs as pairs of values.
    Inputs can therefore be arrays

    example:
       f = interp2d_pairs(vx, vy, M, kind='cubic')

    vx: array of length nx
    vy: array of length ny
    M : array of shape nx x ny
    f : interpolant function
          v = f(x,y) : if x,y are array of length n, v is of length n
                       with  v_i = f(x_i, y_i)
    author: E. Branlard
    """
    import scipy.interpolate as si
    # Internal function, that evaluates pairs of values, output has the same shape as input
    def interpolant(x,y,f):
        x,y = np.asarray(x), np.asarray(y)
        return (si.dfitpack.bispeu(f.tck[0], f.tck[1], f.tck[2], f.tck[3], f.tck[4], x.ravel(), y.ravel())[0]).reshape(x.shape)
    # Wrapping the scipy interp2 function to call out interpolant instead
    return lambda x,y: interpolant(x,y,si.interp2d(*args,**kwargs))
//  [python]
def interp2d_pairs(*args,**kwargs):
    """ Same interface as interp2d but the returned interpolant will evaluate its inputs as pairs of values.
    Inputs can therefore be arrays

    example:
       f = interp2d_pairs(vx, vy, M, kind='cubic')

    vx: array of length nx
    vy: array of length ny
    M : array of shape nx x ny
    f : interpolant function
          v = f(x,y) : if x,y are array of length n, v is of length n
                       with  v_i = f(x_i, y_i)
    author: E. Branlard
    """
    import scipy.interpolate as si
    import numpy as np
    # Internal function, that evaluates pairs of values, output has the same shape as input
    def interpolant(x,y,f):
        x,y = np.asarray(x), np.asarray(y)
        return (si.bisplev(x.ravel(), y.ravel(), f)[0]).reshape(x.shape)
    # Wrapping the scipy interp2 function to call out interpolant instead
    return lambda x,y: interpolant(x,y,si.bisplrep(*args,**kwargs))
//  [python]
def contourplotly(ay_table, ym_table, z_table, clean_table, ax_range, v_range, beta_range, delta_range, plot_config,
                  ia):

    sz = ay_table.shape
    ay_table = ay_table[0, 0, 15, :]
    ym_table = ym_table[0, 0, 15, :]
    z_table = z_table[0, 0, 15, :]

    ay_table_flat = ay_table.flatten()
    ym_table_flat = ym_table.flatten()
    z_table_flat = z_table.flatten()

    # z_table = np.nan_to_num(z_table)
    f = interpolate.interp2d(ay_table_flat, ym_table_flat, z_table_flat)
    x2 = np.linspace(-40, 40, 30)
    y2 = np.linspace(-40000, 40000, 30)
    z2 = f(x2, y2)
    """""
    def pointValue(x, y, power, smoothing, x2, y2, values):
        nominator = 0
        denominator = 0
        for i in range(0, len(values)):
            dist = sqrt((x - x2[i]) * (x - x2[i]) + (y - y2[i]) * (y - y2[i]) + smoothing * smoothing)
            # If the point is really close to one of the data points, return the data point value to avoid singularities
            if (dist < 0.0000000001):
                return values[i]
            nominator = nominator + (values[i] / pow(dist, power))
            denominator = denominator + (1 / pow(dist, power))
        # Return NODATA if the denominator is zero
        if denominator > 0:
            value = nominator / denominator
        else:
            value = -9999
        return value

    def invDist(x2, y2, values, xsize, ysize, power, smoothing):
        valuesGrid = np.zeros((ysize, xsize))
        for x in range(xsize):
            for y in range(ysize):
                valuesGrid[y][x] = pointValue(x, y, power, smoothing, x2, y2, values)
        return valuesGrid


    power = 1
    smoothing = 20

    # Creating the interpolation function and populating the output matrix value
    z4 = invDist(x2, y2, z_table, 500, 500, power, smoothing)
    """

    z3 = griddata((ay_table_flat, ym_table_flat), z_table_flat, (x2, y2), method='cubic')

    # z_table = np.ones((sz[2], sz[3]))
    fig = go.Figure(data=
    go.Contour(
        z=z2,
        x=x2,  # horizontal axis
        y=y2  # vertical axis
    ))
    fig.show()
    return fig
//  [python]
def contourplotly(ay_table, ym_table, z_table, clean_table, ax_range, v_range, beta_range, delta_range, plot_config,
                  ia):

    sz = ay_table.shape
    ay_table = ay_table[0, 0, 15, :]
    ym_table = ym_table[0, 0, 15, :]
    z_table = z_table[0, 0, 15, :]

    ay_table_flat = ay_table.flatten()
    ym_table_flat = ym_table.flatten()
    z_table_flat = z_table.flatten()

    # z_table = np.nan_to_num(z_table)
    tck = interpolate.bisplrep(ay_table_flat, ym_table_flat, z_table_flat)
    x2 = np.linspace(-40, 40, 30)
    y2 = np.linspace(-40000, 40000, 30)
    z2 = interpolate.bisplev(x2, y2, tck)
    """""
    def pointValue(x, y, power, smoothing, x2, y2, values):
        nominator = 0
        denominator = 0
        for i in range(0, len(values)):
            dist = sqrt((x - x2[i]) * (x - x2[i]) + (y - y2[i]) * (y - y2[i]) + smoothing * smoothing)
            # If the point is really close to one of the data points, return the data point value to avoid singularities
            if (dist < 0.0000000001):
                return values[i]
            nominator = nominator + (values[i] / pow(dist, power))
            denominator = denominator + (1 / pow(dist, power))
        # Return NODATA if the denominator is zero
        if denominator > 0:
            value = nominator / denominator
        else:
            value = -9999
        return value

    def invDist(x2, y2, values, xsize, ysize, power, smoothing):
        valuesGrid = np.zeros((ysize, xsize))
        for x in range(xsize):
            for y in range(ysize):
                valuesGrid[y][x] = pointValue(x, y, power, smoothing, x2, y2, values)
        return valuesGrid


    power = 1
    smoothing = 20

    # Creating the interpolation function and populating the output matrix value
    z4 = invDist(x2, y2, z_table, 500, 500, power, smoothing)
    """

    z3 = griddata((ay_table_flat, ym_table_flat), z_table_flat, (x2, y2), method='cubic')

    # z_table = np.ones((sz[2], sz[3]))
    fig = go.Figure(data=
    go.Contour(
        z=z2,
        x=x2,  # horizontal axis
        y=y2  # vertical axis
    ))
    fig.show()
    return fig
//  [python]
def get_interpolation_function(x, y, z, num_x=10, num_y=360):
    """

    :param x:
    :param y:
    :param z:
    :param num_x:
    :param num_y:
    :return:
    """
    x, y, z = np.array(x), np.array(y), np.array(z)
    xi, yi = np.linspace(x.min(), x.max(), num_x), np.linspace(
        y.min(), y.max(), num_y)
    xi, yi = np.meshgrid(xi, yi)
    zi = interp_at(x, y, z, xi.ravel(), yi.ravel(),
                   algorithm="linear", extrapolate=True)
    fun = scipy.interpolate.interp2d(xi, yi, zi, kind='linear')
    return fun
//  [python]
def get_interpolation_function(x, y, z, num_x=10, num_y=360):
    """

    :param x:
    :param y:
    :param z:
    :param num_x:
    :param num_y:
    :return:
    """
    x, y, z = np.array(x), np.array(y), np.array(z)
    xi, yi = np.linspace(x.min(), x.max(), num_x), np.linspace(
        y.min(), y.max(), num_y)
    xi, yi = np.meshgrid(xi, yi)
    zi = interp_at(x, y, z, xi.ravel(), yi.ravel(),
                   algorithm="linear", extrapolate=True)
    tck = scipy.interpolate.bisplev(xi, yi, (xi,yi,zi))
    fun = lambda x,y: scipy.interpolate.bisplev(x, y, tck)
    return fun
//  [python]
def __init__(self, knots, name=NN, **wrap):
        '''New L{HeightCubic} interpolator.

           @arg knots: The points with known height (C{LatLon}s).
           @kwarg name: Optional name for this height interpolator (C{str}).
           @kwarg wrap: If C{True}, wrap or I{normalize} all B{C{knots}}
                        and B{C{llis}} locations (C{bool}).

           @raise HeightError: Insufficient number of B{C{knots}} or
                               invalid B{C{knot}}.

           @raise ImportError: Package C{numpy} or C{scipy} not found
                               or not installed.

           @raise SciPyError: A C{scipy.interpolate.interp2d} issue.

           @raise SciPyWarning: A C{scipy.interpolate.interp2d} warning
                                as exception.
        '''
        spi = self.scipy_interpolate

        xs, ys, hs = self._xyhs3(knots, **wrap)
        try:  # SciPy.interpolate.interp2d kind 'linear' or 'cubic'
            self._interp2d = spi.interp2d(xs, ys, hs, kind=self._kind)
        except Exception as x:
            raise _SciPyIssue(x)

        if name:
            self.name = name