Wednesday, 8 January 2025

CFD Wizardry: A 50-Line Python Marvel

     In abundant spare time ⏳, yours truly has implemented the non-conservative and non-dimensional form of the discretized Navier-Stokes 🍃 equations. The code 🖳 in it's simplest form is less than 50 lines including importing libraries and plotting! 😲 For validation, refer here. More examples and free code is available here, here and here. Happy codding!

Code

# Copyright <2024> <FAHAD BUTT>
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import numpy as np
import matplotlib.pyplot as plt
l_square = 1 # length of square
h = l_square / 50 # grid spacing
dt = 0.001 # time step
L = 1 # domain length
D = 1 # domain depth
Nx = round(L / h) + 1 # grid points in x-axis
Ny = round(D / h) + 1 # grid points in y-axis
nu = 1 / 100 # kinematic viscosity
Uinf = 1 # free stream velocity / inlet velocity / lid velocity
cfl = dt * Uinf / h # cfl number
travel = 20 # times the disturbance travels entire length of computational domain
TT = travel * L / Uinf # total time
ns = int(TT / dt) # number of time steps
Re = round(l_square * Uinf / nu) # Reynolds number
u = np.zeros((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure
for nt in range(ns): # solve 2D Navier-Stokes equations
    pn = p.copy()
    p[1:-1, 1:-1] = (pn[2:, 1:-1] + pn[:-2, 1:-1] + pn[1:-1, 2:] + pn[1:-1, :-2]) / 4 - h / (8 * dt) * (u[2:, 1:-1] - u[:-2, 1:-1] + v[1:-1, 2:] - v[1:-1, :-2]) # pressure
    p[0, :] = p[1, :] # dp/dx = 0 at x = 0
    p[-1, :] = p[-2, :] # dp/dx = 0 at x = L
    p[:, 0] = p[:, 1] # dp/dy = 0 at y = 0
    p[:, -1] = 0 # p = 0 at y = D
    un = u.copy()
    vn = v.copy()
    u[1:-1, 1:-1] = (un[1:-1, 1:-1] - dt / (2 * h) * (un[1:-1, 1:-1] * (un[2:, 1:-1] - un[:-2, 1:-1]) + vn[1:-1, 1:-1] * (un[1:-1, 2:] - un[1:-1, :-2])) - dt / (2 * h) * (p[2:, 1:-1] - p[:-2, 1:-1]) + (1 / Re) * dt / h**2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2] - 4 * un[1:-1, 1:-1])) # x momentum
    u[0, :] = 0 # u = 0 at x = 0
    u[-1, :] = 0 # u = 0 at x = L
    u[:, 0] = 0 # u = 0 at y = 0
    u[:, -1] = Uinf # u = Uinf at y = D
    v[1:-1, 1:-1] = (vn[1:-1, 1:-1] - dt / (2 * h) * (un[1:-1, 1:-1] * (vn[2:, 1:-1] - vn[:-2, 1:-1]) + vn[1:-1, 1:-1] * (vn[1:-1, 2:] - vn[1:-1, :-2])) - dt / (2 * h) * (p[1:-1, 2:] - p[1:-1, :-2]) + (1 / Re) * dt / h**2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2] - 4 * vn[1:-1, 1:-1])) # y momentum
    v[0, :] = 0 # v = 0 at x = 0
    v[-1, :] = 0 # v = 0 at x = L
    v[:, 0] = 0 # v = 0 at y = 0
    v[:, -1] = 0 # v = 0 at y = D
X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
plt.figure(dpi = 200)
plt.contourf(X, Y, v.T, 128, cmap = 'jet') # plot contours
plt.colorbar()
plt.streamplot(X, Y, u.T, v.T, color = 'black', cmap = 'jet', density = 2, linewidth = 0.5, arrowstyle='->', arrowsize = 1) # plot streamlines
plt.gca().set_aspect('equal', adjustable='box')
plt.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.show()

     Thank you for reading! If you want to hire me as your next shinning post-doc, do let reach out!

Sunday, 5 January 2025

16th Step of the 12 steps to Navier-Stokes 😑

      FOANSS, i.e. Fadoobaba's Open Advanced Navier-Stokes 🌬 Solver is now capable to simulate flow with species with / without obstacles of course 🤓. In this example, the species is temperature. Gravity is not considered so the momentum equations are unchanged from Step 14. The non dimensional version of energy equation has been used. Mach number term is removed as Reynolds number is very low 😱. These blog posts are written for educational purposes, hence the over simplifications! A remainder that you are reading a blog, not a Q1 journal 😃.

     The simulated case is called the case of flow around an obstacle. Like a heat sink fin ⬜. The fin / box is heated in the example shown in Fig. 1. For validation, read hereThis code and blog post is not endorsed or approved by Dr. Barba, I just continue the open-source work of her. The 13th and 15th Steps are available for reading along with code.

Fig. 1, Temperature contours with streamlines


Code

# Copyright <2024> <FAHAD BUTT>

# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#%% import libraries

import numpy as np

import matplotlib.pyplot as plt

#%% define spatial and temporal grids

l_square = 1 # length of square

h = l_square / 50 # grid spacing

dt = 0.002 # time step

L = 35 # domain length

D = 21 # domain depth

Nx = round(L / h) + 1 # grid points in x-axis

Ny = round(D / h) + 1 # grid points in y-axis

nu = 1 / 100 # kinematic viscosity

Uinf = 1 # free stream velocity / inlet velocity / lid velocity

cfl = dt * Uinf / h # cfl number

travel = 2 # times the disturbance travels entire length of computational domain

TT = travel * L / Uinf # total time

ns = int(TT / dt) # number of time steps

Re = round(l_square * Uinf / nu) # Reynolds number

Pr = 0.7 # Prandtl number

rho = 1 # fluid density

#%% initialize flowfield

u = Uinf * np.ones((Nx, Ny)) # x-velocity

v = np.zeros((Nx, Ny)) # y-velocity

p = np.zeros((Nx, Ny)) # pressure

T = np.ones((Nx, Ny)) # temperature

X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid

#%% solve 2D Navier-Stokes equations

for nt in range(ns):

    pn = p.copy()

    p[1:-1, 1:-1] = (pn[2:, 1:-1] + pn[:-2, 1:-1] + pn[1:-1, 2:] + pn[1:-1, :-2]) / 4 - h * rho / (8 * dt) * (u[2:, 1:-1] - u[:-2, 1:-1] + v[1:-1, 2:] - v[1:-1, :-2]) # pressure

    # boundary conditions for pressure

    p[0, :] = p[1, :] # dp/dx = 0 at x = 0

    p[-1, :] = 0 # p = 0 at x = L

    p[:, 0] = p[:, 1] # dp/dy = 0 at y = 0

    p[:, -1] = p[:, -2] # dp/dy = 0 at y = D

    p[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box geometry

    p[round(10 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = p[round(10 * Nx / L) - 1, round(10 * Ny / D):round(11 * Ny / D)] # box left

    p[round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = p[round(11 * Nx / L) + 1, round(10 * Ny / D):round(11 * Ny / D)] # box right

    p[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D)] = p[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D) - 1] # box bottom

    p[round(10 * Nx / L):round(11 * Nx / L), round(11 * Ny / D)] = p[round(10 * Nx / L):round(11 * Nx / L), round(11 * Ny / D) + 1] # box top

    un = u.copy()

    vn = v.copy()

    u[1:-1, 1:-1] = (un[1:-1, 1:-1] - dt / (2 * h) * (un[1:-1, 1:-1] * (un[2:, 1:-1] - un[:-2, 1:-1]) + vn[1:-1, 1:-1] * (un[1:-1, 2:] - un[1:-1, :-2])) - dt / (2 * rho * h) * (p[2:, 1:-1] - p[:-2, 1:-1]) + nu * dt / h**2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2] - 4 * un[1:-1, 1:-1])) # x momentum

    # boundary conditions for x-velocity

    u[0, :] = Uinf # u = Uinf at x = 0

    u[-1, :] = u[-2, :] # du/dx = 0 at x = L

    u[:, 0] = Uinf # u = 0 at y = 0

    u[:, -1] = Uinf # u = 0 at y = D

    u[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box geometry

    u[round(10 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box left

    u[round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box right

    u[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D)] = 0 # box bottom

    u[round(11 * Nx / L):round(11 * Nx / L), round(11 * Ny / D)] = 0 # box top

    v[1:-1, 1:-1] = (vn[1:-1, 1:-1] - dt / (2 * h) * (un[1:-1, 1:-1] * (vn[2:, 1:-1] - vn[:-2, 1:-1]) + vn[1:-1, 1:-1] * (vn[1:-1, 2:] - vn[1:-1, :-2])) - dt / (2 * rho * h) * (p[1:-1, 2:] - p[1:-1, :-2]) + nu * dt / h**2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2] - 4 * vn[1:-1, 1:-1])) # y momentum

    # boundary conditions for y-velocity

    v[0, :] = 0 # v = 0 at x = 0

    v[-1, :] = v[-2, :] # dv/dx = 0 at x = L

    v[:, 0] = 0 # v = 0 at y = 0

    v[:, -1] = 0 # v = 0 at y = D

    v[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box geometry

    v[round(10 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box left

    v[round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box right

    v[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D)] = 0 # box bottom

    v[round(11 * Nx / L):round(11 * Nx / L), round(11 * Ny / D)] = 0 # box top

    Tn = T.copy()

    T[1:-1, 1:-1] = Tn[1:-1, 1:-1] - (dt / (2 * h)) * (u[1:-1, 1:-1] * (Tn[2:, 1:-1] - Tn[:-2, 1:-1]) + v[1:-1, 1:-1] * (Tn[1:-1, 2:] - Tn[1:-1, :-2])) + (dt / (h**2 * Re * Pr)) * ((Tn[2:, 1:-1] - 2 * Tn[1:-1, 1:-1] + Tn[:-2, 1:-1]) + (Tn[1:-1, 2:] - 2 * Tn[1:-1, 1:-1] + Tn[1:-1, :-2])) # energy

    T[0, :] = 1 # T = 0 at x = 0

    T[-1, :] = T[-2, :] # dT/dx = 0 at x = L

    T[:, 0] = 1 # T = 0 at y = 0

    T[:, -1] = 1 # T = 0 at y = D

    T[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box geometry

    T[round(10 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box left

    T[round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = 0 # box right

    T[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D)] = 0 # box bottom

    T[round(11 * Nx / L):round(11 * Nx / L), round(11 * Ny / D)] = 0 # box top

#%% post-processing

velocity_magnitude = np.sqrt(u**2 + v**2)  # velocity magnitude

u1 = u.copy() # u-velocity for plotting with box

v1 = v.copy() # v-velocity for plotting with box

p1 = p.copy() # pressure for plotting with box

T1 = T.copy() # temperature for plotting with box

# box geometry for plotting

u1[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)] = np.nan

v1[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)]  = np.nan

p1[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)]  = np.nan

T1[round(10 * Nx / L):round(11 * Nx / L), round(10 * Ny / D):round(11 * Ny / D)]  = np.nan

velocity_magnitude1 = np.sqrt(u1**2 + v1**2) # velocity magnitude with box

# visualize velocity vectors and pressure contours

plt.figure(dpi = 500)

plt.contourf(X, Y, u1.T, 128, cmap = 'hsv')

# plt.colorbar()

plt.gca().set_aspect('equal', adjustable='box')

plt.xticks([0, L])

plt.yticks([0, D])

plt.xlabel('x [m]')

plt.ylabel('y [m]')

plt.show()

plt.figure(dpi = 500)

plt.contourf(X, Y, v1.T, 128, cmap = 'turbo')

# plt.colorbar()

plt.gca().set_aspect('equal', adjustable='box')

plt.xticks([0, L])

plt.yticks([0, D])

plt.xlabel('x [m]')

plt.ylabel('y [m]')

plt.show()

plt.figure(dpi = 500)

plt.contourf(X, Y, p1.T, 128, cmap = 'gist_rainbow')

# plt.colorbar()

plt.gca().set_aspect('equal', adjustable='box')

plt.xticks([0, L])

plt.yticks([0, D])

plt.xlabel('x [m]')

plt.ylabel('y [m]')

plt.show()

plt.figure(dpi = 500)

plt.contourf(X, Y, T1.T, 128, cmap = 'jet')

# plt.colorbar()

plt.gca().set_aspect('equal', adjustable='box')

plt.xticks([0, L])

plt.yticks([0, D])

plt.xlabel('x [m]')

plt.ylabel('y [m]')

plt.show()

plt.figure(dpi = 500)

plt.streamplot(X, Y, u1.T, v1.T, color = 'black', cmap = 'jet', density = 2, linewidth = 0.5,\

                    arrowstyle='->', arrowsize = 1)  # plot streamlines

plt.gca().set_aspect('equal', adjustable = 'box')

plt.axis('off')

plt.show()

     Thank you very much for reading! If you want to hire me as your new shinning post-doc or want to collaborate on the research, please reach out!

Wednesday, 25 December 2024

15th Step of the 12 steps to Navier-Stokes 😑

     FOANSS, i.e. Fadoobaba's Open Advanced Navier-Stokes 🌬 Solver is now capable to simulate flow around curved geometries. In this example, flow around a circular cylinder ⭕ is presented. The main challenge in handling the curved boundaries 🗻 in discrete world is application of the Neumann boundary condition for pressure. The method employed in FOANSS is to use polar ⭗ coordinate system for normal derivative calculation. The idea came while yours's truly was developing FOAMNE i.e. Fadoobaba's Open Advanced 🔨 Mechanics 🧠 Neural Engine. More details can be read here.

     In the CFD code, ∂p/dn is replaced by ∂p/dx * cos(θ) + ∂p/dy * sin(θ). After some trickery, the pressure on the curved surface can be represented by equation 1. Within equation 1, p is the pressure at current time-step. i and j are nodes in the x and y axis, respectively. cos_theta and sin_theta represent radial angles of the polar coordinate system (r θ).

((p[i + 1, j] + p[i - 1, j]) * cos_theta + (p[i, j + 1] + p[i, j - 1] * sin_theta)) / (2 * (cos_theta + sin_theta)) (1)

     At first, flow around a circular cylinder at Reynolds number 100 is simulated. The accuracy of the results is measured using the Strouhal number. For Reynolds number 100, Strouhal number for flow around a circular cylinder is 0.16. The Strouhal number obtained from the code on a coarse mesh, i.e. only 50 cells per cylinder diameter, is 0.17. This is within 8% of the published data. The Strouhal number will never reach 0.16 as the mesh is cartesian and the cylinder surface is represented as a stairstep. Still, very good for teaching purposes! The results are shown in Fig. 1. It can be seen that the vortex shedding phenomenon is calculated relatively accurately. A remainder that you are reading a blog, not a Q1 journal 😃. The vorticity plot is shown in Fig. 2.

     This code and blog post is not endorsed or approved by Dr. Barba, I just continue the open-source work of her.

Fig. 1, The results from the code

Code

#%% import libraries
import numpy as np
import matplotlib.pyplot as plt
#%% define spatial and temporal grids
l_square = 1 # length of square or diamater of circle
h = l_square / 50 # grid spacing
dt = 0.0001 # time step
L = 15 # domain length
D = 10 # domain depth
Nx = round(L / h) + 1 # grid points in x-axis
Ny = round(D / h) + 1 # grid points in y-axis
nu = 1 / 100 # kinematic viscosity
Uinf = 1 # free stream velocity / inlet velocity / lid velocity
cfl = dt * Uinf / h # cfl number
travel = 2 # times the disturbance travels entire length of computational domain
TT = travel * L / Uinf # total time
ns = int(TT / dt) # number of time steps
Re = round(l_square * Uinf / nu) # Reynolds number
rho = 1 # fluid density
#%% initialize flowfield
u = np.ones((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure
x = np.linspace(0, L, Nx) # x-axis vector
y = np.linspace(0, D, Ny) # y-axis vector
XX, YY = np.meshgrid(x, y, indexing="ij") # grid for circle boundary
#%% create circle
x_c = 5 # circle center y
y_c = 5 # circle center y
radius = 0.5 # circle radius
mask = (XX - x_c)**2 + (YY - y_c)**2 <= radius**2 # circular region
tol = 0.125 * h # tolerance for boundary points
circle_boundary = np.abs(np.sqrt((XX - x_c)**2 + (YY - y_c)**2) - radius) <= tol # boundary mask
boundary_indices = np.argwhere(circle_boundary) # circle boundary
# compute radial distances and angles (polar coordinates)
r_values = []
cos_theta_values = []
sin_theta_values = []
for idx in boundary_indices:
    i, j = idx
    r = np.sqrt((XX[i, j] - x_c)**2 + (YY[i, j] - y_c)**2)
    cos_theta = (XX[i, j] - x_c) / r
    sin_theta = (YY[i, j] - y_c) / r
    r_values.append(r)
    cos_theta_values.append(cos_theta)
    sin_theta_values.append(sin_theta)
# define quadrant masks (circle is divided in 4 parts) and corner points
quadrant1 = (XX > x_c) & (YY > y_c) & circle_boundary
quadrant2 = (XX > x_c) & (YY < y_c) & circle_boundary
quadrant3 = (XX < x_c) & (YY < y_c) & circle_boundary
quadrant4 = (XX < x_c) & (YY > y_c) & circle_boundary
top_pt= (XX == x_c) & (YY > y_c) & circle_boundary
bottom_pt = (XX == x_c) & (YY < y_c) & circle_boundary
left_pt = (XX < x_c) & (YY == y_c) & circle_boundary
right_pt = (XX > x_c) & (YY == y_c) & circle_boundary
#%% Solve 2D Navier-Stokes equations
for nt in range(ns):
    pn = p.copy()
    p[1:-1, 1:-1] = (pn[2:, 1:-1] + pn[:-2, 1:-1] + pn[1:-1, 2:] + pn[1:-1, :-2]) / 4 - h * rho / (8 * dt) * (u[2:, 1:-1] - u[:-2, 1:-1] + v[1:-1, 2:] - v[1:-1, :-2]) # pressure
    # boundary conditions for pressure
    p[0, :] = p[1, :] # dp/dx = 0 at x = 0
    p[-1, :] = 0 # p = 0 at x = L
    p[:, 0] = p[:, 1] # dp/dy = 0 at y = 0
    p[:, -1] = p[:, -2] # dp/dy = 0 at y = D
    p[mask] = 0 # circle
    # apply Neumann boundary condition for pressure in polar coordinates
    p[quadrant1] = (((p[i + 1, j] + p[i - 1, j]) * cos_theta) + ((p[i, j + 1] + p[i, j - 1]) * sin_theta)) / (2 * (cos_theta + sin_theta))
    p[quadrant2] = (((p[i + 1, j] + p[i - 1, j]) * cos_theta) + ((p[i, j + 1] + p[i, j - 1]) * sin_theta)) / (2 * (cos_theta + sin_theta))
    p[quadrant3] = (((p[i + 1, j] + p[i - 1, j]) * cos_theta) + ((p[i, j + 1] + p[i, j - 1]) * sin_theta)) / (2 * (cos_theta + sin_theta))
    p[quadrant4] = (((p[i + 1, j] + p[i - 1, j]) * cos_theta) + ((p[i, j + 1] + p[i, j - 1]) * sin_theta)) / (2 * (cos_theta + sin_theta))
    p[top_pt] = p[i, j + 1]
    p[bottom_pt] = p[i, j - 1]
    p[left_pt] = p[i - 1, j]
    p[right_pt] = p[i + 1, j]
    un = u.copy()
    vn = v.copy()
    u[1:-1, 1:-1] = (un[1:-1, 1:-1] - dt / (2 * h) * (un[1:-1, 1:-1] * (un[2:, 1:-1] - un[:-2, 1:-1]) + vn[1:-1, 1:-1] * (un[1:-1, 2:] - un[1:-1, :-2])) - dt / (2 * rho * h) * (p[2:, 1:-1] - p[:-2, 1:-1]) + nu * dt / h**2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2] - 4 * un[1:-1, 1:-1])) # x momentum
    # boundary conditions for x-velocity
    u[0, :] = Uinf # u = Uinf at x = 0
    u[-1, :] = u[-2, :] # du/dx = 0 at x = L
    u[:, 0] = Uinf # u = 0 at y = 0
    u[:, -1] = Uinf # u = 0 at y = D
    u[mask] = 0 # circle
    u[circle_boundary] = 0 # circle
    v[1:-1, 1:-1] = (vn[1:-1, 1:-1] - dt / (2 * h) * (un[1:-1, 1:-1] * (vn[2:, 1:-1] - vn[:-2, 1:-1]) + vn[1:-1, 1:-1] * (vn[1:-1, 2:] - vn[1:-1, :-2])) - dt / (2 * rho * h) * (p[1:-1, 2:] - p[1:-1, :-2]) + nu * dt / h**2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2] - 4 * vn[1:-1, 1:-1])) # y momentum
    # boundary conditions for y-velocity
    v[0, :] = 0 # v = 0 at x = 0
    v[-1, :] = v[-2, :] # dv/dx = 0 at x = L
    v[:, 0] = 0 # v = 0 at y = 0
    v[:, -1] = 0 # v = 0 at y = D
    v[mask] = 0 # circle
    v[circle_boundary] = 0 # circle
#%% post-processing
velocity_magnitude = np.sqrt(u**2 + v**2) # velocity magnitude
X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
# visualize velocity vectors and pressure contours
plt.figure(dpi = 500)
plt.contourf(X, Y, u.T, 128, cmap = 'jet')
# plt.colorbar()
plt.gca().set_aspect('equal', adjustable='box')
plt.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.colorbar(orientation='vertical')
plt.show()
plt.figure(dpi = 500)
plt.contourf(X, Y, v.T, 128, cmap = 'jet')
# plt.colorbar()
plt.gca().set_aspect('equal', adjustable='box')
plt.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.colorbar(orientation='vertical')
plt.show()
plt.figure(dpi = 500)
plt.contourf(X, Y, p.T, 128, cmap = 'jet')
# plt.colorbar()
plt.gca().set_aspect('equal', adjustable='box')
plt.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.colorbar(orientation='vertical')
plt.show()
plt.figure(dpi = 500)  # make a nice crisp image :)
plt.streamplot(X, Y, u.T, v.T, color = 'black', cmap = 'jet', density = 2, linewidth = 0.5,\
                    arrowstyle='->', arrowsize = 1)  # plot streamlines
plt.gca().set_aspect('equal', adjustable = 'box')
plt.axis('off')
plt.show()

Fig. 2, Vorticity with streamlines

     Thank you very much for reading! If you want to hire me as your new shinning post-doc or want to collaborate on the research, please reach out!

Saturday, 21 December 2024

2D Heat Equation Code (Finite Difference Method)

     After 🎉 successfully teaching 👨‍🏫 the neural network about the 🔥 heat / diffusion 💉 equation, yours truly thought it is the time ⏱️ to write a simple code 🖥️ for discretized domain as well. A code yours truly created in abundant spare time is mentioned in this blog 📖.

     A complex (sinusoidal) 🌊 boundary condition is implemented. Dirichlet and Neumann boundary conditions are also implemented. The code is vectorized ↗ so there is only one loop 😁.  CFL condition is implemented in the time-step calculation so time-step ⏳ is adjusted based on the mesh size automatically 😇.

     For simple geometries, traditional numerical methods are is still better than PINNs. 🧠

Code

#Copyright <2024> <FAHAD BUTT>
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import numpy as np
import matplotlib.pyplot as plt
# mesh parameters
L = 1 # length of plate
D = np.pi # width of plate
h = 1 / 50 # grid size
Nx = int((L / h) + 1) # grid points in x-axis
Ny = int((D / h) + 1) # grid points in y-axis
alpha = 1 # thermal diffusivity
dt = h**2 / (4 * alpha) # time step (based on CFL condition)
total_time = 1 # total time
nt = int(total_time / dt) # total time steps
# initialization
T = np.zeros((Nx, Ny)) # initial condition
T_new = np.zeros_like(T)
x = np.linspace(0, L, Nx)
y = np.linspace(0, D, Ny)
# solve 2D-transient heat equation
for n in range(nt):
    T_new[1:-1, 1:-1] = T[1:-1, 1:-1] + ((alpha * dt) / h**2) * (T[2:, 1:-1] + T[:-2, 1:-1] + T[1:-1, 2:] + T[1:-1, :-2] - 4 * T[1:-1, 1:-1])
    T[:, :] = T_new
    # apply boundary conditions
    T[0, :] = np.sin(2 * np.pi * y / D) # T = sin(y) at x = 0
    T[-1, :] = T[-2, :] # dT/dx = 0 at x = L
    T[:, 0] = 0 # T = 0 at y = 0
    T[:, -1] = 0 # T = 0 at y = D
# plotting
X, Y = np.meshgrid(x, y, indexing="ij")
plt.figure(dpi = 500)
plt.contourf(X, Y, T, levels = 64, cmap = "jet")
plt.gca().set_aspect('equal', adjustable = 'box')
plt.colorbar(label = "Temperature")
plt.title("Temperature Distribution")
plt.xlabel("x")
plt.ylabel("y")
plt.show()

     The code creates the output as shown in Fig. 1.



Fig. 1, Temperature distribution

     Thank you for reading! If you want to hire me as a post-doc researcher in the fields of thermo-fluids and / or fracture mechanics, do reach out!