Skip to content

Instantly share code, notes, and snippets.

@phydev
Last active November 28, 2023 14:09
Show Gist options
  • Save phydev/bd2685e8a2a04e05b3a1331e0218ca1e to your computer and use it in GitHub Desktop.
Save phydev/bd2685e8a2a04e05b3a1331e0218ca1e to your computer and use it in GitHub Desktop.
Integrating a diffusion equation by convolution
"""
In this script we integrate the diffusion equation by applying the stencil matrix through
the convolve function from scipy.ndimage. This function applies a convolution, which means
that for each element in matrix phi it will multiply the weights in the intencil to the
element itself and its 8 nearest neighbors, summing the result subsequently.
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import convolve
dx = 1.0 # space interval between points in the space discretization
stencil = (1/(dx*dx)) * np.array([[0, +1, 0],
[1, -4, 1],
[0, +1, 0]])
# initial condition
condition = 'random'
if condition == 'dirac':
phi = np.zeros((50, 50))
phi[25, 25] = 10.
if condition == 'random':
phi = np.random.rand(50, 50)
tsteps = 100 # total time iterations
dt = 0.01 # time step
diffusion_constant = 1
nshots = 4 # number of screeshots
print_nstep = tsteps/nshots
fig = plt.figure()
ax = []
ishot = 1
for nstep in range(tsteps):
if nstep % print_nstep == 0:
print(nstep)
ax.append(fig.add_subplot(1, nshots, ishot))
im = ax[ishot-1].imshow(phi, interpolation='bicubic', cmap=plt.get_cmap('plasma'), origin='lower', vmin=0, vmax=1)
ax[ishot-1].set_title(r'$t = '+str(nstep)+'$')
ishot+=1
# time integration
phi = phi + dt * diffusion_constant * convolve(phi, stencil, mode='wrap')
for figure in ax:
figure.set_yticklabels([])
fig.colorbar(im, ax=[ax[0], ax[1], ax[2], ax[3]], location='bottom')
plt.savefig('diffusion.png', dpi=100)
plt.show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment