Below is the Python code that fulfills the requirements of the Surface Reconstruction Challenge. The code generates noisy scattered data points, reconstructs the smooth surface using interpolation, and visualizes the reconstructed surface in a 3D plot.
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
# Step 1: Define the mathematical function
def f(x, y):
return np.sin(np.sqrt(x**2 + y**2)) + np.cos(x / 2) * np.sin(y / 2) + (x + y) / 20
# Step 2: Generate noisy, scattered data points
np.random.seed(42) # For reproducibility
num_points = 500
x_scattered = np.random.uniform(-8, 8, num_points)
y_scattered = np.random.uniform(-8, 8, num_points)
z_true = f(x_scattered, y_scattered)
noise = np.random.normal(0, 0.5, num_points) # Add significant noise
z_noisy = z_true + noise
# Step 3: Reconstruct the smooth surface using interpolation
# Create a regular grid over the domain
grid_x, grid_y = np.meshgrid(np.linspace(-8, 8, 100), np.linspace(-8, 8, 100))
# Interpolate the noisy scattered data onto the grid
grid_z = griddata((x_scattered, y_scattered), z_noisy, (grid_x, grid_y), method='cubic')
# Step 4: Visualize the reconstructed surface
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
# Plot the reconstructed surface
surf = ax.plot_surface(grid_x, grid_y, grid_z, cmap='viridis', edgecolor='none', alpha=0.9)
# Add labels, title, and color bar
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Reconstructed Surface')
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=10)
# Show the plot
plt.show()
Explanation of the Code:
-
Function Definition (f(x, y)):
- The mathematical function
f(x, y) is defined as per the problem statement.
-
Data Simulation:
- 500 random
(x, y) points are generated within the range [-8, 8].
- The true
z values are computed using the function f(x, y).
- Substantial random noise is added to the
z values to create z_noisy.
-
Surface Reconstruction:
- A regular grid (
grid_x, grid_y) is created over the domain [-8, 8].
- The
scipy.interpolate.griddata function is used to interpolate the noisy scattered data (x_scattered, y_scattered, z_noisy) onto the regular grid. The method='cubic' ensures smooth interpolation.
-