simulate a 2d gaussian function and fit it to a 2d gaussian function in python

To simulate a 2D Gaussian function and fit it to a 2D Gaussian function in Python, you can use the following steps:

Simulating a 2D Gaussian Function

main.py
import numpy as np
import matplotlib.pyplot as plt

# Define the 2D Gaussian function
def gaussian_2d(x, y, amplitude, x0, y0, sigma_x, sigma_y):
    return amplitude * np.exp(-((x - x0) ** 2 / (2 * sigma_x ** 2) + (y - y0) ** 2 / (2 * sigma_y ** 2)))

# Generate x and y values
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
x, y = np.meshgrid(x, y)

# Simulate the 2D Gaussian function
amplitude = 1.0
x0 = 0.0
y0 = 0.0
sigma_x = 2.0
sigma_y = 3.0
z = gaussian_2d(x, y, amplitude, x0, y0, sigma_x, sigma_y)

# Add some noise to the simulated data
z += np.random.normal(0, 0.1, size=z.shape)

# Plot the simulated data
plt.imshow(z, cmap='viridis', extent=[-10, 10, -10, 10])
plt.show()
701 chars
27 lines

Fitting the 2D Gaussian Function

main.py
from scipy.optimize import curve_fit

# Define the 2D Gaussian function to fit
def gaussian_2d_fit(x, y, amplitude, x0, y0, sigma_x, sigma_y):
    return gaussian_2d(x, y, amplitude, x0, y0, sigma_x, sigma_y)

# Flatten the x, y, and z values for fitting
x_flat = x.flatten()
y_flat = y.flatten()
z_flat = z.flatten()

# Initial guess for the fitting parameters
initial_guess = [amplitude, x0, y0, sigma_x, sigma_y]

# Fit the 2D Gaussian function
popt, pcov = curve_fit(gaussian_2d_fit, (x_flat, y_flat), z_flat, p0=initial_guess)

# Print the fitted parameters
print("Fitted parameters:")
print("Amplitude:", popt[0])
print("x0:", popt[1])
print("y0:", popt[2])
print("sigma_x:", popt[3])
print("sigma_y:", popt[4])

# Plot the fitted function
z_fit = gaussian_2d(x, y, *popt)
plt.imshow(z_fit, cmap='viridis', extent=[-10, 10, -10, 10])
plt.show()
851 chars
30 lines

Note that the curve_fit function from scipy.optimize is used to fit the 2D Gaussian function to the simulated data. The initial guess for the fitting parameters is set to the original values used to simulate the data. The fitted parameters are then printed and used to plot the fitted function.

related categories

gistlibby LogSnag