SciPy - interpolate.RBFInterpolator() Function



scipy.interpolate.RBFInterpolator() in SciPy performs radial basis function (RBF) interpolation which is ideal for smoothly interpolating scattered 2D or higher-dimensional data. When passed the points and corresponding values it creates a continuous, differentiable function that estimates values at new points.

RBFs such as Gaussian, linear and cubic can be specified by impacting smoothness and approximation. The key parameters include kernel (choice of RBF type), epsilon (scaling factor), and neighbors (limiting points considered per interpolation which is useful for large datasets. This method excels in situations with irregularly spaced data and offers flexibility in balancing accuracy, smoothness and computational efficiency.

Syntax

Following is the syntax of the function scipy.interpolate.RBFInterpolator() which is used to perform radial basic function −

RBFInterpolator(points, values, fill_value=np.nan, tol=1e-06, maxiter=400, rescale=False)

Parameters

Below are the parameters of the scipy.interpolate.RBFInterpolator() function −

  • y (array-like, shape (n, d)): Coordinates of the data points where interpolation values are known.
  • d (array-like, shape (n,) or (n, m)): Values at each of the data points in y. Each entry in d corresponds to a point defined in y.
  • neighbors (int or None, optional): Limits interpolation to only the nearest neighbors, improving efficiency for large datasets.
  • smoothing (float, optional): Controls the smoothness of the interpolation. A value of 0 enforces exact interpolation, while higher values allow smoothing to account for noisy data.
  • kernel (str, optional): Specifies the type of Radial Basis Function (RBF) to use, e.g., 'linear', 'thin_plate_spline', 'cubic', 'quintic', or 'gaussian'.
  • epsilon (float or None, optional): Scale parameter for the RBF, controlling the width. Smaller values increase locality, while larger values smooth across more distant points.
  • degree (int or None, optional): Degree of the polynomial added to the RBF to handle trends in the data.

Return Value

The scipy.interpolate.RBFInterpolator() function returns an interpolation object that can be used to interpolate values at new points based on scattered data.

Basic RBF Interpolation

Following is the example of scipy.interpolate.RBFInterpolator() function. In this example we create a simple RBF interpolator for a set of known points and values −

import numpy as np
from scipy.interpolate import RBFInterpolator

# Define known points (x, y) and their values
points = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
values = np.array([0, 1, 1, 0])

# Create the RBF interpolator
interpolator = RBFInterpolator(points, values)

# Interpolate at a new point
new_point = np.array([[0.5, 0.5]])
interpolated_value = interpolator(new_point)
print("Interpolated value at (0.5, 0.5):", interpolated_value[0])

Here is the output of the scipy.interpolate.RBFInterpolator() function basic example −

Interpolated value at (0.5, 0.5): 0.5

Using Different Kernels

The RBFInterpolator() function in SciPy allow us to perform Radial Basis Function (RBF) interpolation using different kernels. Heres how to use RBFInterpolator() function with various kernel options showing the differences in interpolation results based on the chosen kernel −

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import RBFInterpolator

# Define known data points (x, y) and their corresponding values (z)
x = np.random.rand(10) * 10  # Random x-coordinates
y = np.random.rand(10) * 10  # Random y-coordinates
z = np.sin(x) * np.cos(y)    # Some values based on a function

# Create a meshgrid for interpolation
grid_x, grid_y = np.mgrid[0:10:100j, 0:10:100j]

# Create a plot to compare the kernels
fig, axs = plt.subplots(2, 3, figsize=(15, 10))
kernels = ['linear', 'cubic', 'quintic', 'gaussian', 'thin_plate_spline']
epsilon_value = 1.0  # Set a value for epsilon for the Gaussian kernel

# Interpolate and plot for each kernel
for ax, kernel in zip(axs.flatten(), kernels):
    # Set epsilon only for Gaussian kernel
    if kernel == 'gaussian':
        rbf = RBFInterpolator(np.column_stack((x, y)), z, kernel=kernel, epsilon=epsilon_value)
    else:
        rbf = RBFInterpolator(np.column_stack((x, y)), z, kernel=kernel)

    # Perform interpolation on the grid (stacking grid_x and grid_y)
    points = np.column_stack((grid_x.ravel(), grid_y.ravel()))  # Combine into (n_points, 2)
    grid_z = rbf(points)  # Perform interpolation

    # Reshape grid_z back to the original grid shape
    grid_z = grid_z.reshape(grid_x.shape)

    # Plot the result
    img = ax.imshow(grid_z.T, extent=(0, 10, 0, 10), origin='lower', cmap='viridis', alpha=0.8)
    ax.scatter(x, y, c=z, edgecolor='k', label='Data Points')
    ax.set_title(f'RBF Interpolation with Kernel: {kernel}')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    plt.colorbar(img, ax=ax, label='Interpolated Values')

# Show the plot
plt.tight_layout()
plt.show()

Here is the output of the scipy.interpolate.RBFInterpolator() function using different kernels −

RBF Different Kernels Example

Visualizing Interpolated Surface

Here's is the example which shows how to create both 2D contour plots and a 3D surface plot for the interpolation results −

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import RBFInterpolator
from mpl_toolkits.mplot3d import Axes3D

# Define known data points (x, y) and their corresponding values (z)
x = np.random.rand(10) * 10  # Random x-coordinates
y = np.random.rand(10) * 10  # Random y-coordinates
z = np.sin(x) * np.cos(y)    # Some values based on a function

# Create a meshgrid for interpolation
grid_x, grid_y = np.mgrid[0:10:100j, 0:10:100j]

# Set epsilon for the Gaussian kernel
epsilon_value = 1.0

# Create RBF interpolator with Gaussian kernel
rbf = RBFInterpolator(np.column_stack((x, y)), z, kernel='gaussian', epsilon=epsilon_value)

# Perform interpolation on the grid (stacking grid_x and grid_y)
points = np.column_stack((grid_x.ravel(), grid_y.ravel()))  # Combine into (n_points, 2)
grid_z = rbf(points)  # Perform interpolation
grid_z = grid_z.reshape(grid_x.shape)  # Reshape grid_z back to the original grid shape

# Create 2D contour plot
plt.figure(figsize=(15, 7))
plt.subplot(1, 2, 1)
contour = plt.contourf(grid_x, grid_y, grid_z, levels=50, cmap='viridis')
plt.colorbar(contour, label='Interpolated Values')
plt.scatter(x, y, c=z, edgecolor='k', label='Data Points')
plt.title('RBF Interpolation - Contour Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()

# Create 3D surface plot
ax = plt.subplot(1, 2, 2, projection='3d')
ax.plot_surface(grid_x, grid_y, grid_z, cmap='viridis', edgecolor='none', alpha=0.8)
ax.scatter(x, y, z, color='r', label='Data Points')
ax.set_title('RBF Interpolation - 3D Surface Plot')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.view_init(elev=30, azim=30)  # Adjust the viewing angle
plt.legend()

# Show the plots
plt.tight_layout()
plt.show()

Here is the output of the scipy.interpolate.RBFInterpolator() function visualising the interpolation −

RBF Visualising Interpolation Example
scipy_interpolate.htm
Advertisements