當前位置: 首頁>>代碼示例>>Python>>正文


Python interpolate.RectBivariateSpline方法代碼示例

本文整理匯總了Python中scipy.interpolate.RectBivariateSpline方法的典型用法代碼示例。如果您正苦於以下問題:Python interpolate.RectBivariateSpline方法的具體用法?Python interpolate.RectBivariateSpline怎麽用?Python interpolate.RectBivariateSpline使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在模塊scipy.interpolate的用法示例。

在下文中一共展示了interpolate.RectBivariateSpline方法的21個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def __init__(self, scale_list, values, extrapolate=False):
        # error checking
        if len(values.shape) != 2:
            raise ValueError('This class only works for 2D data.')
        elif len(scale_list) != 2:
            raise ValueError('input and output dimension mismatch.')

        nx, ny = values.shape
        offset, scale = scale_list[0]
        x = np.linspace(offset, (nx - 1) * scale + offset, nx)  # type: np.multiarray.ndarray
        offset, scale = scale_list[1]
        y = np.linspace(offset, (ny - 1) * scale + offset, ny)  # type: np.multiarray.ndarray

        self._min = x[0], y[0]
        self._max = x[-1], y[-1]

        DiffFunction.__init__(self, [(x[0], x[-1]), (y[0], y[-1])], delta_list=None)

        self.fun = interp.RectBivariateSpline(x, y, values)
        self._extrapolate = extrapolate 
開發者ID:ucb-art,項目名稱:BAG_framework,代碼行數:22,代碼來源:interpolate.py


示例2: _get_above_cloud_profiles

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def _get_above_cloud_profiles(self, P_profile, T_profile, abundances,
                                  planet_mass, planet_radius, star_radius,
                                  above_cloud_cond, T_star=None):
        
        assert(len(P_profile) == len(T_profile))
        # First, get atmospheric weight profile
        mu_profile = np.zeros(len(P_profile))
        atm_abundances = {}
        
        for species_name in abundances:
            interpolator = RectBivariateSpline(
                self.T_grid, np.log10(self.P_grid),
                np.log10(abundances[species_name]), kx=1, ky=1)
            abund = 10**interpolator.ev(T_profile, np.log10(P_profile))
            atm_abundances[species_name] = abund
            mu_profile += abund * self.mass_data[species_name]

        radii, dr = _hydrostatic_solver._solve(
            P_profile, T_profile, self.ref_pressure, mu_profile, planet_mass,
            planet_radius, star_radius, above_cloud_cond, T_star)
        
        for key in atm_abundances:
            atm_abundances[key] = atm_abundances[key][above_cloud_cond]
            
        return radii, dr, atm_abundances, mu_profile 
開發者ID:ideasrule,項目名稱:platon,代碼行數:27,代碼來源:_atmosphere_solver.py


示例3: test_baffle_leakage_Bell_refit

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def test_baffle_leakage_Bell_refit():
    from ht.conv_tube_bank import Bell_baffle_leakage_tck
    # Test refitting the data
    obj = RectBivariateSpline(Bell_baffle_leakage_x, Bell_baffle_leakage_z_values, Bell_baffle_leakage_zs, kx=3, ky=1, s=0.002)
    new_tck = obj.tck + obj.degrees
    [assert_allclose(i, j) for (i, j) in zip(Bell_baffle_leakage_tck, new_tck)]


#import matplotlib.pyplot as plt
#for ys in Bell_baffle_leakage_zs.T:
#    plt.plot(Bell_baffle_leakage_x, ys)
#for z in Bell_baffle_leakage_z_values:
#    xs = np.linspace(min(Bell_baffle_leakage_x), max(Bell_baffle_leakage_x), 1000)
#    ys = np.clip(Bell_baffle_leakage_obj(xs, z), 0, 1)
#    plt.plot(xs, ys, '--')
#
#for z in Bell_baffle_leakage_z_values:
#    xs = np.linspace(min(Bell_baffle_leakage_x), max(Bell_baffle_leakage_x), 1000)
#    rs = z
#    rl = xs
#    ys = 0.44*(1.0 - rs) + (1.0 - 0.44*(1.0 - rs))*np.exp(-2.2*rl)
#    plt.plot(xs, ys, '--') 
開發者ID:CalebBell,項目名稱:ht,代碼行數:24,代碼來源:test_conv_tube_bank.py


示例4: get_elevation

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def get_elevation(self, interpolation='nearest_neighbor'):
        assert interpolation in ('nearest_neighbor', 'bivariate')

        if self._elevation.get(interpolation, None) is None:
            self._log.debug('Getting elevation...')
            # region = llLon, urLon, llLat, urLon
            coords = self.frame.coordinates
            lons = coords[:, 0]
            lats = coords[:, 1]

            region = (lons.min(), lons.max(), lats.min(), lats.max())
            if not srtmgl3.covers(region):
                raise AssertionError(
                    'Region is outside of SRTMGL3 topo dataset')

            tile = srtmgl3.get(region)
            if not tile:
                raise AssertionError('Cannot get SRTMGL3 topo dataset')

            if interpolation == 'nearest_neighbor':
                iy = num.rint((lats - tile.ymin) / tile.dy).astype(num.intp)
                ix = num.rint((lons - tile.xmin) / tile.dx).astype(num.intp)

                elevation = tile.data[(iy, ix)]

            elif interpolation == 'bivariate':
                interp = interpolate.RectBivariateSpline(
                    tile.y(), tile.x(), tile.data)
                elevation = interp(lats, lons, grid=False)

            elevation = elevation.reshape(self.rows, self.cols)
            self._elevation[interpolation] = elevation

        return self._elevation[interpolation] 
開發者ID:pyrocko,項目名稱:kite,代碼行數:36,代碼來源:scene.py


示例5: test_dblint

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def test_dblint():
    # Basic test to see it runs and gives the correct result on a trivial
    # problem.  Note that `dblint` is not exposed in the interpolate namespace.
    x = np.linspace(0, 1)
    y = np.linspace(0, 1)
    xx, yy = np.meshgrid(x, y)
    rect = interpolate.RectBivariateSpline(x, y, 4 * xx * yy)
    tck = list(rect.tck)
    tck.extend(rect.degrees)

    assert_almost_equal(dblint(0, 1, 0, 1, tck), 1)
    assert_almost_equal(dblint(0, 0.5, 0, 1, tck), 0.25)
    assert_almost_equal(dblint(0.5, 1, 0, 1, tck), 0.75)
    assert_almost_equal(dblint(-100, 100, -100, 100, tck), 1) 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:16,代碼來源:test_fitpack.py


示例6: interpolate_2d_features

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def interpolate_2d_features(features):
    out_size = feature_size
    x = np.arange(features.shape[0])
    y = np.arange(features.shape[1])
    z = features
    xx = np.linspace(x.min(), x.max(), out_size)
    yy = np.linspace(y.min(), y.max(), out_size)
    new_kernel = interpolate.RectBivariateSpline(x, y, z, kx=1, ky=1)
    kernel_out = new_kernel(xx, yy)
    return kernel_out


# Interpolation 2d of each channel, so we obtain 3d interpolated feature maps 
開發者ID:imatge-upc,項目名稱:detection-2016-nipsws,代碼行數:15,代碼來源:features.py


示例7: _updatePlasmaPsi

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def _updatePlasmaPsi(self, plasma_psi):
        """
        Sets the plasma psi data, updates spline interpolation coefficients.
        Also updates:

        self.mask        2D (R,Z) array which is 1 in the core, 0 outside
        self.psi_axis    Value of psi on the magnetic axis
        self.psi_bndry   Value of psi on plasma boundary
        """
        self.plasma_psi = plasma_psi

        # Update spline interpolation
        self.psi_func = interpolate.RectBivariateSpline(self.R[:,0], self.Z[0,:], plasma_psi)

        # Update the locations of the X-points, core mask, psi ranges.
        # Note that this may fail if there are no X-points, so it should not raise an error
        # Analyse the equilibrium, finding O- and X-points
        psi = self.psi()
        opt, xpt = critical.find_critical(self.R, self.Z, psi)
        if opt:
            self.psi_axis = opt[0][2]

            if xpt:
                self.psi_bndry = xpt[0][2]
                self.mask = critical.core_mask(self.R, self.Z, psi, opt, xpt)
                
                # Use interpolation to find if a point is in the core.
                self.mask_func = interpolate.RectBivariateSpline(self.R[:,0], self.Z[0,:], self.mask)
            else:
                self.psi_bndry = None
                self.mask = None 
開發者ID:bendudson,項目名稱:freegs,代碼行數:33,代碼來源:equilibrium.py


示例8: test_Nu_Grimison_tube_bank_tcks

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def test_Nu_Grimison_tube_bank_tcks():
    from ht.conv_tube_bank import Grimison_ST_aligned, Grimison_SL_aligned, Grimison_C1_aligned, Grimison_C1_aligned_tck
    Grimison_C1_aligned_interp = RectBivariateSpline(Grimison_ST_aligned, 
                                                     Grimison_SL_aligned,
                                                     np.array(Grimison_C1_aligned))

    tck_recalc = Grimison_C1_aligned_interp.tck
    [assert_allclose(i, j) for i, j in zip(Grimison_C1_aligned_tck, tck_recalc)]
    
    from ht.conv_tube_bank import Grimison_m_aligned_tck, Grimison_m_aligned
    Grimison_m_aligned_interp = RectBivariateSpline(Grimison_ST_aligned, 
                                                    Grimison_SL_aligned, 
                                                    np.array(Grimison_m_aligned))
    tck_recalc = Grimison_m_aligned_interp.tck
    [assert_allclose(i, j) for i, j in zip(Grimison_m_aligned_tck, tck_recalc)] 
開發者ID:CalebBell,項目名稱:ht,代碼行數:17,代碼來源:test_conv_tube_bank.py


示例9: _get_orthrectified_from_array_flat

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def _get_orthrectified_from_array_flat(self, ortho_bounds, row_array, col_array, value_array):
        # setup the result workspace
        value_array, pixel_rows, pixel_cols, ortho_array = self._setup_flat_workspace(
            ortho_bounds, row_array, col_array, value_array)
        value_array = self._apply_radiometric_params(row_array, col_array, value_array)

        # set up our spline
        sp = RectBivariateSpline(row_array, col_array, value_array, kx=self.row_order, ky=self.col_order, s=0)
        # determine the in bounds points
        mask = self._get_mask(pixel_rows, pixel_cols, row_array, col_array)
        result = sp.ev(pixel_rows[mask], pixel_cols[mask])
        # potentially apply the radiometric parameters
        ortho_array[mask] = result
        return ortho_array 
開發者ID:ngageoint,項目名稱:sarpy,代碼行數:16,代碼來源:ortho_rectify.py


示例10: make_cached_spline_builder

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def make_cached_spline_builder(smooth):

    @lru_cache(4)  # 4 means our tests are quick (and should tile a local patch)
    def cached_spline_builder(dir, flat, flon):
        h = cached_file_reader(dir, flat, flon)
        x, y = np.linspace(flat, flat+1, SAMPLES), np.linspace(flon, flon+1, SAMPLES)
        # not 100% sure on the scaling of s but it seems to be related to sum of errors at all points
        # however, a scaling of SAMPLES * SAMPLES means that smooth=1 gives a numerical error, so add 10
        return RectBivariateSpline(x, y, h, s=smooth * SAMPLES * SAMPLES * 10)

    return cached_spline_builder 
開發者ID:andrewcooke,項目名稱:choochoo,代碼行數:13,代碼來源:spline.py


示例11: interpolate_zvals_at_xy

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def interpolate_zvals_at_xy(xy, topography, method='interp2d'):
        """
        Interpolates DEM values on a defined section

        Args:
            xy: x (EW) and y (NS) coordinates of the profile
            topography (:class:`gempy.core.grid_modules.topography.Topography`)
            method: interpolation method, 'interp2d' for cubic scipy.interpolate.interp2d
                                             'spline' for scipy.interpolate.RectBivariateSpline

        Returns:
            numpy.ndarray: z values, i.e. topography along the profile

        """

        xj = topography.values_2d[:, 0, 0]
        yj = topography.values_2d[0, :, 1]
        zj = topography.values_2d[:, :, 2]

        if method == 'interp2d':
            f = interpolate.interp2d(xj, yj, zj.T, kind='cubic')
            zi = f(xy[:, 0], xy[:, 1])
            if xy[:, 0][0] <= xy[:, 0][-1] and xy[:, 1][0] <= xy[:, 1][-1]:
                return np.diag(zi)
            else:
                return np.flipud(zi).diagonal()
        else:
            assert xy[:, 0][0] <= xy[:, 0][-1], 'The xy values of the first point must be smaller than second.' \
                                               'Please use interp2d as method argument. Will be fixed.'
            assert xy[:, 1][0] <= xy[:, 1][-1], 'The xy values of the first point must be smaller than second.' \
                                               'Please use interp2d as method argument. Will be fixed.'
            f = interpolate.RectBivariateSpline(xj, yj, zj)
            zi = f(xy[:, 0], xy[:, 1])
            return np.flipud(zi).diagonal() 
開發者ID:cgre-aachen,項目名稱:gempy,代碼行數:36,代碼來源:grid_types.py


示例12: __init__

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def __init__(self, ttfile, datum):
        with open(ttfile, 'r') as f:
            count = 0
            for line in f:
                if count == 0:
                    count += 1
                    continue
                elif count == 1:
                    n_dist, n_depth = line.split()
                    n_dist = int(n_dist)
                    n_depth = int(n_depth)
                    dists = np.zeros(n_dist)
                    tt = np.zeros((n_depth, n_dist))
                    count += 1
                    continue
                elif count == 2:
                    depths = line.split()
                    depths = np.array([float(x) for x in depths])
                    count += 1
                    continue
                else:
                    temp = line.split()
                    temp = np.array([float(x) for x in temp])
                    dists[count-3] = temp[0]
                    tt[:, count-3] = temp[1:]
                    count += 1
        self.tt = tt
        self.dists = dists
        self.depths = depths
        self.datum = datum

        from scipy.interpolate import RectBivariateSpline
        self.interp_ = RectBivariateSpline(self.depths, self.dists, self.tt) 
開發者ID:interseismic,項目名稱:PhaseLink,代碼行數:35,代碼來源:phaselink_dataset.py


示例13: __init__

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def __init__(self, inp_img):
        self.ndim = 2

        # Load up the image (greyscale) and filter to soften it up
        img = median_filter(imread(inp_img, flatten=True), 5)

        # Convert 'ij' indexing to 'xy' coordinates
        self.img = np.flipud(img).T
        self._lower_left = np.array([0., 0.])
        self._upper_right = self.img.shape

        # Construct a spline interpolant to use as a target
        x = np.arange(self._lower_left[0], self._upper_right[0], 1)
        y = np.arange(self._lower_left[1], self._upper_right[1], 1)
        self._interpolant = RectBivariateSpline(x, y, self.img) 
開發者ID:bfarr,項目名稱:kombine,代碼行數:17,代碼來源:twoD.py


示例14: cartesian_to_polar

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def cartesian_to_polar(
    interpolated_data_cartesian: ndarray,
    extent_cartesian: Tuple[float, float, float, float],
) -> Tuple[ndarray, Tuple[float, float, float, float]]:
    """Convert interpolated Cartesian pixel grid to polar coordinates.

    Parameters
    ----------
    interpolated_data_cartesian
        The interpolated data on a Cartesian grid.
    extent_cartesian
        The extent in Cartesian space as (xmin, xmax, ymin, ymax). It
        must be square.

    Returns
    -------
    interpolated_data_polar
        The interpolated data on a polar grid (R, phi).
    extent_polar
        The extent on a polar grid (0, Rmax, 0, 2π).
    """
    data, extent = interpolated_data_cartesian, extent_cartesian

    if not np.allclose(extent[1] - extent[0], extent[3] - extent[2]):
        raise ValueError('Bad polar plot: x and y have different scales')

    number_of_pixels = data.shape
    radius_pix = 0.5 * data.shape[0]

    data = transform.warp_polar(data, radius=radius_pix)

    radius = 0.5 * (extent[1] - extent[0])
    extent_polar = (0, radius, 0, 2 * np.pi)

    x_grid = np.linspace(*extent[:2], data.shape[0])
    y_grid = np.linspace(*extent[2:], data.shape[1])
    spl = RectBivariateSpline(x_grid, y_grid, data)
    x_regrid = np.linspace(extent[0], extent[1], number_of_pixels[0])
    y_regrid = np.linspace(extent[2], extent[3], number_of_pixels[1])
    interpolated_data_polar = spl(x_regrid, y_regrid)

    return interpolated_data_polar, extent_polar 
開發者ID:dmentipl,項目名稱:plonk,代碼行數:44,代碼來源:geometry.py


示例15: newDomain

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def newDomain(eq,
              Rmin=None, Rmax=None,
              Zmin=None, Zmax=None,
              nx=None, ny=None):
    """Creates a new Equilibrium, solving in a different domain.
    The domain size (Rmin, Rmax, Zmin, Zmax) and resolution (nx,ny)
    are taken from the input equilibrium eq if not specified.
    """
    if Rmin is None:
        Rmin = eq.Rmin
    if Rmax is None:
        Rmax = eq.Rmax
    if Zmin is None:
        Zmin = eq.Zmin
    if Zmax is None:
        Zmax = eq.Zmax
    if nx is None:
        nx = eq.R.shape[0]
    if ny is None:
        ny = eq.R.shape[0]

    # Create a new equilibrium with the new domain
    result = Equilibrium(tokamak=eq.tokamak,
                         Rmin = Rmin,
                         Rmax = Rmax,
                         Zmin = Zmin,
                         Zmax = Zmax,
                         nx=nx, ny=ny)

    # Calculate the current on the old grid
    profiles = eq._profiles
    Jtor = profiles.Jtor(eq.R, eq.Z, eq.psi())

    # Interpolate Jtor onto new grid
    Jtor_func = interpolate.RectBivariateSpline(eq.R[:,0], eq.Z[0,:], Jtor)
    Jtor_new = Jtor_func(result.R, result.Z, grid=False)

    result._applyBoundary(result, Jtor_new, result.plasma_psi)

    # Right hand side of G-S equation
    rhs = -mu0 * result.R * Jtor_new

    # Copy boundary conditions
    rhs[0,:] = result.plasma_psi[0,:]
    rhs[:,0] = result.plasma_psi[:,0]
    rhs[-1,:] = result.plasma_psi[-1,:]
    rhs[:,-1] = result.plasma_psi[:,-1]

    # Call elliptic solver
    plasma_psi = result._solver(result.plasma_psi, rhs)
        
    result._updatePlasmaPsi(plasma_psi)

    # Solve once more, calculating Jtor using new psi
    result.solve(profiles)
    
    return result 
開發者ID:bendudson,項目名稱:freegs,代碼行數:59,代碼來源:equilibrium.py


示例16: find_separatrix

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def find_separatrix(eq, opoint=None, xpoint=None, ntheta=20, psi=None, axis=None, psival=1.0):
    """Find the R, Z coordinates of the separatrix for equilbrium
    eq. Returns a tuple of (R, Z, R_X, Z_X), where R_X, Z_X are the
    coordinates of the X-point on the separatrix. Points are equally
    spaced in geometric poloidal angle.

    If opoint, xpoint or psi are not given, they are calculated from eq

    eq - Equilibrium object
    opoint - List of O-point tuples of (R, Z, psi)
    xpoint - List of X-point tuples of (R, Z, psi)
    ntheta - Number of points to find
    psi - Grid of psi on (R, Z)
    axis - A matplotlib axis object to plot points on
    """
    if psi is None:
        psi = eq.psi()

    if (opoint is None) or (xpoint is None):
        opoint, xpoint = find_critical(eq.R, eq.Z, psi)

    psinorm = (psi - opoint[0][2])/(xpoint[0][2] - opoint[0][2])
    
    psifunc = interpolate.RectBivariateSpline(eq.R[:,0], eq.Z[0,:], psinorm)

    r0, z0 = opoint[0][0:2]

    theta_grid = linspace(0, 2*pi, ntheta, endpoint=False)
    dtheta = theta_grid[1] - theta_grid[0]

    # Avoid putting theta grid points exactly on the X-points
    xpoint_theta = arctan2(xpoint[0][0] - r0, xpoint[0][1] - z0)
    # How close in theta to allow theta grid points to the X-point
    TOLERANCE = 1.e-3
    if any(abs(theta_grid - xpoint_theta) < TOLERANCE):
        warn("Theta grid too close to X-point, shifting by half-step")
        theta_grid += dtheta / 2

    isoflux = []
    for theta in theta_grid:
        r, z = find_psisurface(eq, psifunc,
                               r0, z0,
                               r0 + 10.*sin(theta), z0 + 10.*cos(theta),
                               psival=psival,
                               axis=axis)
        isoflux.append((r, z, xpoint[0][0], xpoint[0][1]))

    return isoflux 
開發者ID:bendudson,項目名稱:freegs,代碼行數:50,代碼來源:critical.py


示例17: zoom_rbs

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def zoom_rbs(array, newSize, order=3):
    """
    A Class to zoom 2-dimensional arrays using RectBivariateSpline interpolation

    Uses the scipy ``RectBivariateSpline`` interpolation routine to zoom into an array. Can cope with real of complex data. May be slower than above ``zoom``, as RBS routine copies data.

    Parameters:
        array (ndarray): 2-dimensional array to zoom
        newSize (tuple): the new size of the required array
        order (int, optional): Order of interpolation to use. default is 3

    Returns:
        ndarray : zoom array of new size.
    """
    try:
        xSize = newSize[0]
        ySize = newSize[1]

    except IndexError:
        xSize = ySize = newSize

    coordsX = numpy.linspace(0, array.shape[0]-1, xSize)
    coordsY = numpy.linspace(0, array.shape[1]-1, ySize)

    #If array is complex must do 2 interpolations
    if array.dtype==numpy.complex64 or array.dtype==numpy.complex128:
        realInterpObj = RectBivariateSpline(   
                numpy.arange(array.shape[0]), numpy.arange(array.shape[1]), 
                array.real, kx=order, ky=order)
        imagInterpObj = RectBivariateSpline(   
                numpy.arange(array.shape[0]), numpy.arange(array.shape[1]), 
                array.imag, kx=order, ky=order)
                         
        return (realInterpObj(coordsY,coordsX)
                            + 1j*imagInterpObj(coordsY,coordsX))
            
    else:

        interpObj = RectBivariateSpline(   numpy.arange(array.shape[0]),
                numpy.arange(array.shape[1]), array, kx=order, ky=order)


        return interpObj(coordsY,coordsX) 
開發者ID:AOtools,項目名稱:aotools,代碼行數:45,代碼來源:interpolation.py


示例18: activation_surface

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def activation_surface(data, target_shape=None, source_shape=None,
        scale_offset=None, deg=1, pad=True):
    """
    Generates an upsampled activation sample.
    Params:
        target_shape Shape of the output array.
        source_shape The centered shape of the output to match with data
            when upscaling.  Defaults to the whole target_shape.
        scale_offset The amount by which to scale, then offset data
            dimensions to end up with target dimensions.  A pair of pairs.
        deg Degree of interpolation to apply (1 = linear, etc).
        pad True to zero-pad the edge instead of doing a funny edge interp.
    """
    # Default is that nothing is resized.
    if target_shape is None:
        target_shape = data.shape
    # Make a default scale_offset to fill the image if there isn't one
    if scale_offset is None:
        scale = tuple(float(ts) / ds
                for ts, ds in zip(target_shape, data.shape))
        offset = tuple(0.5 * s - 0.5 for s in scale)
    else:
        scale, offset = (v for v in zip(*scale_offset))
    # Now we adjust offsets to take into account cropping and so on
    if source_shape is not None:
        offset = tuple(o + (ts - ss) / 2.0
                for o, ss, ts in zip(offset, source_shape, target_shape))
    # Pad the edge with zeros for sensible edge behavior
    if pad:
        zeropad = numpy.zeros(
                (data.shape[0] + 2, data.shape[1] + 2), dtype=data.dtype)
        zeropad[1:-1, 1:-1] = data
        data = zeropad
        offset = tuple((o - s) for o, s in zip(offset, scale))
    # Upsample linearly
    ty, tx = (numpy.arange(ts) for ts in target_shape)
    sy, sx = (numpy.arange(ss) * s + o
            for ss, s, o in zip(data.shape, scale, offset))
    levels = RectBivariateSpline(
            sy, sx, data, kx=deg, ky=deg)(ty, tx, grid=True)
    # Return the mask.
    return levels 
開發者ID:CSAILVision,項目名稱:gandissect,代碼行數:44,代碼來源:actviz.py


示例19: getStraightenWormInt

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def getStraightenWormInt(worm_img, skeleton, half_width, width_resampling):
    '''
        Code to straighten the worm worms.
        worm_image - image containing the worm
        skeleton - worm skeleton
        half_width - half width of the worm, if it is -1 it would try to calculated from cnt_widths
        width_resampling - number of data points used in the intensity map along the worm width
        length_resampling - number of data points used in the intensity map along the worm length
        ang_smooth_win - window used to calculate the skeleton angles.
            A small value will introduce noise, therefore obtaining bad perpendicular segments.
            A large value will over smooth the skeleton, therefore not capturing the correct shape.

    '''

    assert not np.any(np.isnan(skeleton))

    dX = np.diff(skeleton[:, 0])
    dY = np.diff(skeleton[:, 1])

    skel_angles = np.arctan2(dY, dX)
    skel_angles = np.hstack((skel_angles[0], skel_angles))

    #%get the perpendicular angles to define line scans (orientation doesn't
    #%matter here so subtracting pi/2 should always work)
    perp_angles = skel_angles - np.pi / 2

    #%for each skeleton point get the coordinates for two line scans: one in the
    #%positive direction along perpAngles and one in the negative direction (use
    #%two that both start on skeleton so that the intensities are the same in
    #%the line scan)

    r_ind = np.linspace(-half_width, half_width, width_resampling)

    # create the grid of points to be interpolated (make use of numpy implicit
    # broadcasting Nx1 + 1xM = NxM)
    grid_x = skeleton[:, 0] + r_ind[:, np.newaxis] * np.cos(perp_angles)
    grid_y = skeleton[:, 1] + r_ind[:, np.newaxis] * np.sin(perp_angles)

    # interpolated the intensity map
    f = RectBivariateSpline(
        np.arange(
            worm_img.shape[0]), np.arange(
            worm_img.shape[1]), worm_img)
    straighten_worm = f.ev(grid_y, grid_x)

    return straighten_worm, grid_x, grid_y 
開發者ID:ver228,項目名稱:tierpsy-tracker,代碼行數:48,代碼來源:getIntensityProfile.py


示例20: get_dataset

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def get_dataset(self, key, info):
        """Load a dataset."""
        if not info['view'].startswith(self.view):
            return
        logger.debug('Reading %s.', key.name)
        # Check if file_key is specified in the yaml
        file_key = info.get('file_key', key.name)

        variable = self.nc[file_key]
        l_step = self.nc.attrs.get('al_subsampling_factor', 1)
        c_step = self.nc.attrs.get('ac_subsampling_factor', 16)

        if c_step != 1 or l_step != 1:
            logger.debug('Interpolating %s.', key.name)

            # TODO: do it in cartesian coordinates ! pbs at date line and
            # possible
            tie_x = self.cartx['x_tx'].data[0, :][::-1]
            tie_y = self.cartx['y_tx'].data[:, 0]
            full_x = self.cart['x_i' + self.view].data
            full_y = self.cart['y_i' + self.view].data

            variable = variable.fillna(0)

            from scipy.interpolate import RectBivariateSpline
            spl = RectBivariateSpline(
                tie_y, tie_x, variable.data[:, ::-1])

            values = spl.ev(full_y, full_x)

            variable = xr.DataArray(da.from_array(values, chunks=(CHUNK_SIZE, CHUNK_SIZE)),
                                    dims=['y', 'x'], attrs=variable.attrs)

        variable.attrs['platform_name'] = self.platform_name
        variable.attrs['sensor'] = self.sensor

        if 'units' not in variable.attrs:
            variable.attrs['units'] = 'degrees'

        variable.attrs.update(key.to_dict())

        return variable 
開發者ID:pytroll,項目名稱:satpy,代碼行數:44,代碼來源:slstr_l1b.py


示例21: zoom_rbs

# 需要導入模塊: from scipy import interpolate [as 別名]
# 或者: from scipy.interpolate import RectBivariateSpline [as 別名]
def zoom_rbs(array, newSize, order=3):
    """
    A Class to zoom 2-dimensional arrays using RectBivariateSpline interpolation

    Uses the scipy ``RectBivariateSpline`` interpolation routine to zoom into an array. Can cope with real of complex data. May be slower than above ``zoom``, as RBS routine copies data.

    Parameters:
        array (ndarray): 2-dimensional array to zoom
        newSize (tuple): the new size of the required array
        order (int, optional): Order of interpolation to use. default is 3

    Returns:
        ndarray : zoom array of new size.
    """
    try:
        xSize = int(newSize[0])
        ySize = int(newSize[1])

    except IndexError:
        xSize = ySize = int(newSize)

    coordsX = numpy.linspace(0, array.shape[0]-1, xSize)
    coordsY = numpy.linspace(0, array.shape[1]-1, ySize)

    #If array is complex must do 2 interpolations
    if array.dtype==numpy.complex64 or array.dtype==numpy.complex128:
        realInterpObj = RectBivariateSpline(   
                numpy.arange(array.shape[0]), numpy.arange(array.shape[1]), 
                array.real, kx=order, ky=order)
        imagInterpObj = RectBivariateSpline(   
                numpy.arange(array.shape[0]), numpy.arange(array.shape[1]), 
                array.imag, kx=order, ky=order)
                         
        return (realInterpObj(coordsY,coordsX)
                            + 1j*imagInterpObj(coordsY,coordsX))
            
    else:

        interpObj = RectBivariateSpline(   numpy.arange(array.shape[0]),
                numpy.arange(array.shape[1]), array, kx=order, ky=order)


        return interpObj(coordsY,coordsX) 
開發者ID:AOtools,項目名稱:soapy,代碼行數:45,代碼來源:interp.py



注:本文中的scipy.interpolate.RectBivariateSpline方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。