Simulation of the 2D diffusion equation of heat
In the first step, the aim is to numerically determine a solution of the one-dimensional Fourier heat equation using Fourier series with some approximations, and then we want to numerically solve this equation in 2D.
We have a 1D rod of length
We make the assumption regarding the boundary conditions:
Fourier hypothesized that heat could be interpreted as small waves of heat. Building on this, we assume that the temperature
But we recall that
that we will inject into the equation
For a fixed
So, we have as a solution :
We can then determine
Since we are dealing with a Fourier series, we can calculate the coefficients
First thing first, we define our parameters for the equation :
D = 150 #Thermal diffusion coefficient
Lx = 100 #length
Ly = 100 #length
time = 60
Nx = 120 #space nodes
Ny = 120 #space nodes
dx, dy = Lx / Nx, Ly / Ny #space steps
dt = min(dx**2 / (4 * D), dy**2 / (4 * D)) #time step
Nt = int(time / dt) #time nodes
T_max, T_min = 100, 0
center_x, center_y = Nx // 2, Ny // 2
R = 10 # Radius of the circle
I initialize my temperature by creating a matrix for T that will by update for each time step.
T = np.zeros((Nx, Ny)) + 20 # Initial temperature of the plate : 15°C
Next, my goal is to fixed the initial conditions and boundary conditions. All the map is at 15K (because it's impossible to reach 0K). Thus, I want to create a circle at 100K at the center of the map and few elements at 100K too at the edge of the map :
T[(np.arange(Nx)[:, np.newaxis] - center_x)**2 + (np.arange(Ny) - center_y)**2 == R**2] = 100
# Boundary conditions
T[0, :] = np.linspace(T_min, T_max, Ny)
T[-1, :] = np.linspace(T_min, T_max, Ny)
T[:, 0] = np.linspace(T_min, T_max, Nx)
T[:, -1] = np.linspace(T_min, T_max, Nx)
We now come to the heart of the work. We aim to simulate the heat equation using the finite difference method. Therefore, we will discretize this equation as follows: :
Let's discretize
So, we find :
This means that for each time step
counter = 0
while counter < time:
for i in range(1, Nx - 1):
for j in range(1, Ny - 1):
d2x = (T[i - 1, j] - 2 * T[i, j] + T[i + 1, j]) / dx**2
d2y = (T[i, j - 1] - 2 * T[i, j] + T[i, j + 1]) / dy**2
T[i, j] = dt * D * (d2x + d2y) + T[i, j]
counter += dt
T[(np.arange(Nx)[:, np.newaxis] - center_x)**2 + (np.arange(Ny) - center_y)**2 == R**2] = 100
pcm.set_array(T)
ax.set_title("Time: {:.3f} s, Avg Temperature: {:.2f}".format(counter, np.average(T)))
plt.pause(0.01)
plt.show()
It's a relatively short but efficient code. We can have fun changing the initial conditions, the colormap style, or the boundary conditions, the temperatures of certain points to create patterns and figures that are more or less beautiful or symmetrical. Your only limit is your imagination.