Monday, 26 May 2025

A Simplified Immersed Boundary Method (S-IBM)

     In this post, details will be shared about a simplified version of the Immersed 🤿 Boundary Method for fluid dynamics 💨 simulations which yours truly has developed in abundant spare time ⏲, referred to as S-IBM 🤓. The purpose of this code is for teaching 🎓 purposes only. The mesh is Cartesian and the method used has no measures in place to resolve the stairstep 𓊍 mesh. The syntax share in this post is for Python 🐍, but this code can be translated to other languages such as C or MATLAB, easily.

     The process starts with creating a polygon, a circular cylinder ⭕ for this post. A polygon is created using parametric equations for the circle. NOTE: Before writing these lines, several parameters such as domain size, mesh size, number of points in each coordinate direction etc. have been already defined and calculated. For more information, read here.

theta = np.linspace(0, 2 * np.pi, 100) # create equally spaced angles from 0 to 2 * pi

radius = 0.5; # radius of circle

circle_center_x = 3.3 # circle center x

circle_center_y = D / 2 # circle center x

x1 = circle_center_x + (radius * np.sin(theta)) # x-coordinates

y1 = circle_center_y + (radius * np.cos(theta)) # y-coordinates

     Path from matplotlib is used to create a polygon approximation of a circle or an airfoil by using the x and y co-ordinates of the circle (x1, y1) or any shape. Next, coordinate pairs of the grid points are created using vstack and ravel commands. A check is performed to verify if a grid point falls inside the polygon. custom_curve is a boolean array. The values inside this array are True only for the points inside the polygon. Transpose is used to keep the curve orientation consistent with the Navier-Stokes equations.

circle_path = Path(np.column_stack((x1, y1)))

points = np.vstack((X.ravel(), Y.ravel())).T

custom_curve = circle_path.contains_points(points).reshape(X.shape)

curve = custom_curve.T

     Another boolean mask is created for boundary points using the boundary_mask statement. Points that are inside the polygon (circle) are marked using using the interior statement.

boundary_mask = np.zeros_like(curve, dtype=bool)

interior = curve[1:-1, 1:-1]

     Next a check is performed to mark each interior point's immediate neighbor. right means point to the right of each interior point, bottom means point to the bottom of each interior point etc. boundary statement is used to identify the boundary points (fluid-solid interface) according to the following logic. The point itself is inside the circle (interior = True) and at least one neighbor is outside. boundary_mask[1:-1, 1:-1] is used to fill the boolean with boundary. Consider a 5×5 a grid (zoomed near the polygon boundary). X marks solid points (inside circle), O marks fluid points, as shown in Fig. 1. For example, if interior = True, right = True, left = True, top = True and bottom = True → boundary = True & ~(True) = False i.e. an interior point. And for example, interior = True, right = False, left = True, top = True, bottom = True → boundary = True & ~(False) = True, i.e. a point on the right boundary. For points outside the polygon, interior = False → boundary = False (regardless of neighbors).


Fig. 1, A grid example

right = curve[2:, 1:-1]

left = curve[:-2, 1:-1]

top = curve[1:-1, 2:]

bottom = curve[1:-1, :-2]

boundary = interior & ~(right & left & top & bottom)

boundary_mask[1:-1, 1:-1] = boundary

custom_curve_boundary = boundary_mask

     In the next step, boundary_indices obtains indices of all boundary points. right_neighbors, left_neighbors etc. calculates indices of neighboring points in all directions. valid_right, valid_left etc. checks if the neighbor is within domain bounds (not at edge) and is outside the circle (fluid point). This allows proper application of no-slip boundary conditions. If for example, valid_right is True, pressure is taken from the right neighbor to be applied to the corresponding boundary index. A visualization of the points is shown in Fig. 2.

boundary_indices = np.where(custom_curve_boundary)

right_neighbors = (boundary_indices[0] + 1, boundary_indices[1])

left_neighbors = (boundary_indices[0] - 1, boundary_indices[1])

top_neighbors = (boundary_indices[0], boundary_indices[1] + 1)

bottom_neighbors = (boundary_indices[0], boundary_indices[1] - 1)

valid_right = (boundary_indices[0] + 1 < X.shape[0]) & (~curve[right_neighbors])

valid_left = (boundary_indices[0] - 1 >= 0) & (~curve[left_neighbors])

valid_top = (boundary_indices[1] + 1 < X.shape[1]) & (~curve[top_neighbors])

valid_bottom = (boundary_indices[1] - 1 >= 0) & (~curve[bottom_neighbors])


Fig. 2, Depiction of grid points in various regimes


     While plotting Fig. 2, several points are skipped. This is done to make plot clearer. This code can be easily implemented in other languages such as MATLAB (inpolygon), C (ray-casting) etc. At Re 200, this code predicts a Drag coefficient of 1.395 and a Lift coefficient of 0.053. These values are well within rage of the values reported by [1]. In this code, there is no interpolation of scheme or smoothing employed. The lift and drag force coefficients for one shedding cycle are shown in Fig. 3. Within Fig. 4, u and v velocities (top left and right), pressure and streamlines (bottom left and right) are shown. 


Fig. 3, red = Cd and black = Cl

Fig. 4, Post processing from the simulations.

References

[1] Braza M, Chassaing P, Minh HH. Numerical study and physical analysis of the pressure and velocity fields in the near wake of a circular cylinder. Journal of Fluid Mechanics. 1986;165:79-130. doi:10.1017/S0022112086003014

     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!

Thursday, 1 May 2025

18th Step of the 12 Steps to Navier-Stokes 😑 (Morphing Airfoil / Swimming Fish)

     This is probably the final step in the series. Unless, one fine morning yours truly randomly decides to write about moving and morphing airfoils 😑 i.e. a true virtual wind tunnel 🤓.

     This whole series is a continuation of a series created by Dr. Barbra 👩‍🏫 to teach about coding 🖳 of the Navier-Stokes 🌬 equations. The code made available this blog is an independent continuation of her open-source work. Yours truly has coded the scaled version of the equations with a modified pressure Poisson equation. The original series ends with the example of the channel flow 🔚. So far, yours truly has added flow around obstacles both curved and non-curved; flow around moving obstacles and species transport to the series. The Fluid-Structure Interaction (FSI) version of the code 💻 is available here.

     This post is about flow around shape changing 🪱 obstacles i.e. morphing wings. The development of these codes shared here, including the one mentioned in this post, started in the year 2020 and continued till the fall of 2023. All this effort was to create a digital CV so that yours truly can get himself accepted in to a funded PhD program. That happened in fall 2023 😌.

     The frequency of oscillations, the equations for amplitude and lateral oscillations 〰️ are all taken from the published literature about swimming fish 🐟. As a starting point, the NACA 0012 airfoil is used. A polygon is then created. Each grid index is then tested for presence inside or outside the polygon. An index is marked as the boundary of the polygon if one index has anyone neighboring index outside the polygon. The neighboring boundary indices are used to apply Neumann boundary conditions for pressure. The boundary indices are used to apply no-slip Dirichlet boundary conditions on the polygon boundary. More details can be read here.

     Because the camber of airfoil changes at each time-step, approximately 400 points are required on the airfoil boundary to properly capture the time-varying camber of the airfoil i.e. the fish 🐋. The output from the code is shown in Fig. 1. Within Fig. 1, top row has u and v components of velocity. Meanwhile, the bottom row shows the pressure and streamlines. The animation is shown in Fig. 2.

     If you plan to use these codes in your scholarly work, do cite this blog as:

     Fahad Butt (2025). 18th Step of the 12 Steps to Navier-Stokes (https://fluiddynamicscomputer.blogspot.com/2025/05/18th-step-of-12-steps-to-navier-stokes.html), Blogger. Retrieved Month Date, Year

Fig. 1, The result from code

 

Fig. 2, Animation


Code

#Copyright <2025> <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
from matplotlib.path import Path

#%% define parameters
l_cr = 1 # characteristic length
h = l_cr / 400 # grid spacing
dt = 0.00001 # time step
L = 8 # domain length
D = 4 # domain depth
Nx = round(L / h) + 1 # grid points in x-axis
Ny = round(D / h) + 1 # grid points in y-axis
nu = 1 / 500 # kinematic viscosity
Uinf = 1 # free stream velocity / inlet velocity / lid velocity
cfl = dt * Uinf / h # cfl number
Re = round(l_cr * Uinf / nu) # Reynolds number

#%% intialization
u = Uinf * np.ones((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure
X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid

#%% pre calculate for speed
P1 = h / (16 * dt)
P2 = (2 / Re) * dt / h**2
P3 = dt / h
P4 = 1 - (4 * P2)

#%% motion parameters
freq = 0.8 # frequency of oscillation (from litrature)
factor = 2 * np.pi * freq # 2 * pi * f
TP = 1 / freq # time period
ns = int(6 * TP / dt) # number of time steps
t = 0.12 # airfoil thickness
c = 1 # airfoil chord length
num_points = 150 # points along chord
alpha = np.linspace(0, np.pi, num_points) # angle values
x_airfoil = 0.5 * (1 - np.cos(alpha)) * c # cosine spacing on x coordinates
x_frac = x_airfoil / c # normalized airfoil x coordinates
a0 = 0.02 # amplitude co efficient a0 (from litrature)
a1 = 0.01 # amplitude co efficient a1
a2 = 0.1 # amplitude co efficient a2
a_x = a0 + a1 * x_frac + a2 * x_frac**2 # amplitude of oscillation (from litrature)
yt = 5 * t * (0.2969 * np.sqrt(x_airfoil) - 0.1260 * x_airfoil - 0.3516 * x_airfoil**2 + 0.2843 * x_airfoil**3 - 0.1036 * x_airfoil**4) # airfoil co ordinates
foil_center_x = L / 3 # foil center x
foil_center_y = D / 2 # foil center y
x1 = foil_center_x + np.concatenate([x_airfoil, x_airfoil[::-1]]) # foil x

#%% solve 2D Navier-Stokes equations
for nt in range(ns):
    y_oscillation = a_x * np.cos(2 * np.pi * x_frac - factor * nt * dt) # lateral oscillation (from litrature)
    y_top = y_oscillation + yt # airfoil top
    y_bottom = y_oscillation - yt # airfoil bottom
    y1 = foil_center_y + np.concatenate([y_top, y_bottom[::-1]]) # foil y
    foil_path = Path(np.column_stack((x1, y1))) # foil region (polygon)
    points = np.vstack((X.ravel(), Y.ravel())).T # check if inside region
    custom_curve = foil_path.contains_points(points).reshape(X.shape) # test all grid points for inclusion in airfoil, contains_points returns True for each point inside the airfoil (polygon)
    curve = custom_curve.T # transpose to match grid orientation
    boundary_mask = np.zeros_like(curve, dtype = bool) # create boolean mask
    interior = curve[1:-1, 1:-1] # interior of foil
    right = curve[2:, 1:-1] # boolean arrays indicating if neighbors of each interior point are inside airfoil (polygon)
    left = curve[:-2, 1:-1]
    top = curve[1:-1, 2:]
    bottom = curve[1:-1, :-2]
    boundary = interior & ~(right & left & top & bottom) # mark if point is inside foil and at least one neighbor is outside foil (mark interface between solid and fluid)
    boundary_mask[1:-1, 1:-1] = boundary # fill the empty boundary
    custom_curve_boundary = boundary_mask.T # transpose back
    boundary_indices = np.where(custom_curve_boundary.T) # mark boundary indices
    right_neighbors = (boundary_indices[0] + 1, boundary_indices[1]) # right index (neighboring grid points in each direction)
    left_neighbors = (boundary_indices[0] - 1, boundary_indices[1]) # left index
    top_neighbors = (boundary_indices[0], boundary_indices[1] + 1) # top index
    bottom_neighbors = (boundary_indices[0], boundary_indices[1] - 1) # bottom index
    # identify valid neighbor indices, ensure the neighbor is not inside airfoil (polygon) i.e. is inside fluid)
    valid_right = (boundary_indices[0] + 1 < X.shape[0]) & (~curve[right_neighbors])
    valid_left = (boundary_indices[0] - 1 >= 0) & (~curve[left_neighbors])
    valid_top = (boundary_indices[1] + 1 < X.shape[1]) & (~curve[top_neighbors])
    valid_bottom = (boundary_indices[1] - 1 >= 0) & (~curve[bottom_neighbors])
    pn = p.copy()
    p[1:-1, 1:-1] = 0.25 * (pn[2:, 1:-1] + pn[:-2, 1:-1] + pn[1:-1, 2:] + pn[1:-1, :-2]) - P1 * (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] = p[:, -2] # dp/dy = 0 at y = D
    p[curve] = 0 # p = 0 inside shape
    p[boundary_indices] = np.where(valid_right, p[right_neighbors], p[boundary_indices]) # right neighbor is fluid
    p[boundary_indices] = np.where(valid_left, p[left_neighbors], p[boundary_indices]) # left neighbor is fluid
    p[boundary_indices] = np.where(valid_top, p[top_neighbors], p[boundary_indices]) # top neighbor is fluid
    p[boundary_indices] = np.where(valid_bottom, p[bottom_neighbors], p[boundary_indices]) # bottom neighbor is fluid
    un = u.copy()
    vn = v.copy()
    u[1:-1, 1:-1] = un[1:-1, 1:-1] * P4 - P3 * (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]) + p[2:, 1:-1] - p[:-2, 1:-1]) + P2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2]) # x momentum
    u[0, :] = Uinf # u = Uinf at x = 0
    u[-1, :] = u[-2, :] # du/dx = 0 at x = L
    u[:, 0] = Uinf # u = Uinf at y = 0
    u[:, -1] = Uinf # u = Uinf at y = D
    u[curve] = 0 # u = 0 inside shape
    u[custom_curve_boundary.T] = 0 # no slip
    v[1:-1, 1:-1] = vn[1:-1, 1:-1] * P4 - P3 * (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]) + p[1:-1, 2:] - p[1:-1, :-2]) + P2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2]) # y momentum
    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[curve] = 0 # u = 0 inside shape
    v[custom_curve_boundary.T] = 0 # no slip
    boundary_x = X[boundary_indices[1], boundary_indices[0]] # get actual x-coordinate values of all boundary points
    x_frac_boundary = (boundary_x - foil_center_x) / c # normalized streamwise position along the airfoil for each boundary point
    vinf_foil_boundary = (a0 + a1 * x_frac_boundary + a2 * x_frac_boundary**2) * factor * np.sin(2 * np.pi * x_frac_boundary - factor * nt * dt) # vertical velocity at boundaries
    v[top_neighbors] = vinf_foil_boundary # above the boundary
    v[bottom_neighbors] = vinf_foil_boundary # below the boundary
    v[right_neighbors] = vinf_foil_boundary # right of boundary
    v[left_neighbors] = vinf_foil_boundary # left of boundary

#%% post process
u1 = u.copy() # u-velocity for plotting with foil
v1 = v.copy() # v-velocity for plotting with foil
p1 = p.copy() # pressure for plotting with foil
u1[custom_curve.T] = np.nan # shape geometry for plotting
v1[custom_curve.T] = np.nan
p1[custom_curve.T] = np.nan
velocity_magnitude1 = np.sqrt(u1**2 + v1**2) # velocity magnitude with shape

# visualize velocity vectors and pressure contours
plt.figure(dpi = 500)
plt.contourf(X, Y, u1.T, 128, cmap = 'jet')
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 1)
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.axis('off')
plt.show()

plt.figure(dpi = 500)
plt.contourf(X, Y, v1.T, 128, cmap = 'jet')
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 1)
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.axis('off')
plt.show()

plt.figure(dpi = 500)
plt.contourf(X, Y, p1.T, 128, cmap = 'jet')
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 1)
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.axis('off')
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.plot(x1, y1, color='black', alpha = 1, linewidth = 1)
plt.gca().set_aspect('equal', adjustable = 'box')
plt.xlim([0, L])
plt.ylim([0, D])
plt.axis('off')
plt.show()

     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!

Tuesday, 22 April 2025

17th Step of the 12 Steps to Navier-Stokes 😑 (Moving Cylinder)

      FOANSS, i.e. Fadoobaba's Open Advanced Navier-Stokes 🌬 Solver is now capable to simulate flow with moving objects 🤓. In this example, the objects are square and circular cylinders. These blog posts could have been a master's thesis or a peer-reviewed publication but yours truly decided to are write here for educational purposes! The 

     The simulated case is called the case of flow around an obstacle. For validation, read. This code and blog post is not endorsed or approved by Dr. Barba, I just continue the open-source work of her. The 13th, 14th, 15th and 16th Steps are available for reading along with code. The resulting motion of the square cylinder is shown in Fig. 1. The Fig. 1 is colored using the horizontal velocity. The Fig. 2 shows the example of moving circle. Within Fig. 2, the results of u and v velocities are shown on top while the pressure and streamlines are shown at the bottom.  The code for stationery curved / arbitrary boundaries is made available here. A customary remainder that you are reading a blog, not a Q1 journal 😃.

     If you plan to use these codes in your scholarly work, do cite this blog as:

     Fahad Butt (2025). 17th Step of the 12 Steps to Navier-Stokes (https://fluiddynamicscomputer.blogspot.com/2025/04/17th-step-of-12-steps-to-navier-stokes.html), Blogger. Retrieved Month Date, Year


Fig. 1, The animation

Code

#%%
#Copyright <2025> <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 parameters
l_cr = 1 # characteristic length
h = l_cr / 50 # grid spacing
dt = 0.0001 # time step
L = 10 # domain length
D = 5 # 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
Re = round(l_cr * Uinf / nu) # Reynolds number

#%% intialization
u = np.zeros((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure

#%% pre calculate for speed
P1 = h / (16 * dt)
P2 = (2 / Re) * dt / h**2
P3 = dt / h
P4 = 1 - (4 * P2)

#%% add square
square_center_x = 0.75 # box starting position x-axis
square_center_y = D / 2 # box starting position y-axis
freq = 0.32 # f = 2 * St * Uinf / l_cr
factor = 2 * np.pi * freq # 2 * pi * f
a = 1 # amplitude of vibration
TP = 1 / freq # time period
ns = int(2 * TP / dt) # number of time steps
uinf_square = Uinf # horizontal velocity of box

#%% solve 2D Navier-Stokes equations
for nt in range(ns):
  square_center_y_variable = square_center_y +  a * np.sin(factor * dt * nt) # vertical position of box
  square_center_x_variable = square_center_x + uinf_square * dt * nt # horizontal position of box
  vinf_square = a * factor * np.cos(factor * dt * nt) # vertical velocity of box
  square_left = round((square_center_x_variable - l_cr / 2) * Nx / L) # box left
  square_right = round((square_center_x_variable + l_cr / 2) * Nx / L) # box right
  square_bottom = round((square_center_y_variable - l_cr / 2) * Ny / D) # box bottom
  square_top = round((square_center_y_variable + l_cr / 2)* Ny / D) # box top  
  pn = p.copy()
  p[1:-1, 1:-1] = 0.25 * (pn[2:, 1:-1] + pn[:-2, 1:-1] + pn[1:-1, 2:] + pn[1:-1, :-2]) - P1 * (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] = p[:, -2] # dp/dy = 0 at y = D
  p[square_left:square_right, square_bottom:square_top] = 0 # box geometry
  p[square_left, square_bottom:square_top] = p[square_left - 1, square_bottom:square_top] # box left
  p[square_right, square_bottom:square_top] = p[square_right + 1, square_bottom:square_top] # box right
  p[square_left:square_right, square_bottom] = p[square_left:square_right, square_bottom - 1] # box bottom
  p[square_left:square_right, square_top] = p[square_left:square_right, square_top + 1] # box top
  un = u.copy()
  vn = v.copy()
  u[1:-1, 1:-1] = un[1:-1, 1:-1] * P4 - P3 * (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]) + p[2:, 1:-1] - p[:-2, 1:-1]) + P2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2]) # x momentum
  u[0, :] = u[1, :] # du/dx = 0 at x = 0
  u[-1, :] = u[-2, :] # du/dx = 0 at x = L
  u[:, 0] = 0 # u = 0 at y = 0
  u[:, -1] = 0 # u = 0 at y = D
  u[square_left:square_right, square_bottom:square_top] = 0 # box geometry
  u[square_left, square_bottom:square_top] = 0 # box left
  u[square_right, square_bottom:square_top] = 0 # box right
  u[square_left:square_right, square_bottom] = 0 # box bottom
  u[square_left:square_right, square_top] = 0 # box top
  u[square_left - 1, square_bottom:square_top] = uinf_square # box left
  u[square_right + 1, square_bottom:square_top] = uinf_square # box right
  u[square_left:square_right, square_bottom - 1] = uinf_square # box bottom
  u[square_left:square_right, square_top + 1] = uinf_square # box top  
  v[1:-1, 1:-1] = vn[1:-1, 1:-1] * P4 - P3 * (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]) + p[1:-1, 2:] - p[1:-1, :-2]) + P2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2]) # y momentum
  v[0, :] = v[1, :] # dv/dx = 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[square_left:square_right, square_bottom:square_top] = 0 # box geometry
  v[square_left, square_bottom:square_top] = 0 # box left
  v[square_right, square_bottom:square_top] = 0 # box right
  v[square_left:square_right, square_bottom] = 0 # box bottom
  v[square_left:square_right, square_top] = 0 # box top
  v[square_left - 1, square_bottom:square_top] = vinf_square # box left
  v[square_right + 1, square_bottom:square_top] = vinf_square # box right
  v[square_left:square_right, square_bottom - 1] = vinf_square # box bottom
  v[square_left:square_right, square_top + 1] = vinf_square # box top

#%% post processing
u1 = u # copy for plotting
v1 = v
p1 = p
u1[square_left:square_right, square_bottom:square_top] = np.nan # create cavity for plotting
v1[square_left:square_right, square_bottom:square_top] = np.nan
p1[square_left:square_right, square_bottom:square_top] = np.nan

X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
plt.figure(dpi = 200)
plt.contourf(X, Y, u1.T, 128, cmap = 'jet') # plot contours
# 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 = 200)
plt.contourf(X, Y, v1.T, 128, cmap = 'jet') # plot contours
# 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 = 200)
plt.contourf(X, Y, p1.T, 128, cmap = 'jet') # plot contours
# 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 = 200)
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.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.show()

Code (Curved / Slanted Boundaries)

#Copyright <2025> <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
from matplotlib.path import Path

#%% define parameters
l_cr = 1 # characteristic length
h = l_cr / 20 # grid spacing
dt = 0.001 # time step
L = 24 # domain length
D = 5 # 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
Re = round(l_cr * Uinf / nu) # Reynolds number

#%% intialization
u = np.zeros((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure

#%% pre calculate for speed
P1 = h / (16 * dt)
P2 = (2 / Re) * dt / h**2
P3 = dt / h
P4 = 1 - (4 * P2)

#%% create a shape
X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
theta = np.linspace(0, 2 * np.pi, 100) # create equally spaced angles from 0 to 2 * pi
radius = 0.5; # radius of circle
circle_center_x = 0.75 # circle center x (starting point)
circle_center_y = D / 2 # circle center y

#%% motion parameters
freq = 0.32 # f = 2 * St * Uinf / l_cr
factor = 2 * np.pi * freq # 2 * pi * f
a = 1 # amplitude of vibration
TP = 1 / freq # time period
ns = int(6 * TP / dt) # number of time steps
uinf_circle = Uinf # horizontal velocity of box

#%% solve 2D Navier-Stokes equations
for nt in range(ns):
    circle_center_x_variable = circle_center_x + uinf_circle * dt * nt # horizontal position of box
    circle_center_y_variable = circle_center_y +  a * np.sin(factor * dt * nt) # vertical position of circle
    vinf_circle = a * factor * np.cos(factor * dt * nt) # vertical velocity of circle
    x1 = circle_center_x_variable + (radius * np.sin(theta)) # x-coordinates
    y1 = circle_center_y_variable + (radius * np.cos(theta)) # y-coordinates
    cylinder_path = Path(np.column_stack((x1, y1))) # cylinder region
    points = np.vstack((X.ravel(), Y.ravel())).T # check if inside region
    custom_curve = cylinder_path.contains_points(points).reshape(X.shape) # create boolean mask
    curve = custom_curve.T # transpose
    boundary_mask = np.zeros_like(curve, dtype = bool) # find boundary of cylinder
    interior = curve[1:-1, 1:-1] # interior of circle
    right = curve[2:, 1:-1] # mark neighbours
    left = curve[:-2, 1:-1]
    top = curve[1:-1, 2:]
    bottom = curve[1:-1, :-2]
    boundary = interior & ~(right & left & top & bottom) # mark if point is inside cylinder and at least one neighbor is outside cylinder
    boundary_mask[1:-1, 1:-1] = boundary # set boundary
    custom_curve_boundary = boundary_mask.T # transpose back
    boundary_indices = np.where(custom_curve_boundary.T) # mark boundary indices
    right_neighbors = (boundary_indices[0] + 1, boundary_indices[1]) # right index
    left_neighbors = (boundary_indices[0] - 1, boundary_indices[1]) # left index
    top_neighbors = (boundary_indices[0], boundary_indices[1] + 1) # top index
    bottom_neighbors = (boundary_indices[0], boundary_indices[1] - 1) # bottom index
    valid_right = ~curve[right_neighbors] # check if points are on shape boundary
    valid_left = ~curve[left_neighbors]
    valid_top = ~curve[top_neighbors]
    valid_bottom = ~curve[bottom_neighbors]
    pn = p.copy()
    p[1:-1, 1:-1] = 0.25 * (pn[2:, 1:-1] + pn[:-2, 1:-1] + pn[1:-1, 2:] + pn[1:-1, :-2]) - P1 * (u[2:, 1:-1] - u[:-2, 1:-1] + v[1:-1, 2:] - v[1:-1, :-2]) # pressure
    p[0, :] = 0 # p = 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[curve] = 0 # p = 0 inside shape
    p[boundary_indices] = np.where(valid_right, p[right_neighbors], p[boundary_indices]) # right neighbor is fluid
    p[boundary_indices] = np.where(valid_left, p[left_neighbors], p[boundary_indices]) # left neighbor is fluid
    p[boundary_indices] = np.where(valid_top, p[top_neighbors], p[boundary_indices]) # top neighbor is fluid
    p[boundary_indices] = np.where(valid_bottom, p[bottom_neighbors], p[boundary_indices]) # bottom neighbor is fluid
    un = u.copy()
    vn = v.copy()
    u[1:-1, 1:-1] = un[1:-1, 1:-1] * P4 - P3 * (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]) + p[2:, 1:-1] - p[:-2, 1:-1]) + P2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2]) # 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] = 0 # u = 0 at y = D
    u[curve] = 0 # u = 0 inside shape
    u[custom_curve_boundary.T] = 0 # no slip
    u[top_neighbors] = uinf_circle # above the boundary
    u[bottom_neighbors] = uinf_circle # below the boundary
    u[right_neighbors] = uinf_circle # right of boundary
    u[left_neighbors] = uinf_circle # left of boundary
    v[1:-1, 1:-1] = vn[1:-1, 1:-1] * P4 - P3 * (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]) + p[1:-1, 2:] - p[1:-1, :-2]) + P2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2]) # 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
    v[curve] = 0 # u = 0 inside shape
    v[custom_curve_boundary.T] = 0 # no slip
    v[top_neighbors] = vinf_circle # above the boundary
    v[bottom_neighbors] = vinf_circle # below the boundary
    v[right_neighbors] = vinf_circle # right of boundary
    v[left_neighbors] = vinf_circle # left of boundary

#%% post process
u1 = u.copy() # u-velocity for plotting with circle
v1 = v.copy() # v-velocity for plotting with circle
p1 = p.copy() # pressure for plotting with circle
u1[custom_curve.T] = np.nan # shape geometry for plotting
v1[custom_curve.T] = np.nan
p1[custom_curve.T] = np.nan
velocity_magnitude1 = np.sqrt(u1**2 + v1**2) # velocity magnitude with shape

# visualize velocity vectors and pressure contours
plt.figure(dpi = 500)
plt.contourf(X, Y, u1.T, 128, cmap = 'jet', vmin = -2, vmax = 3)
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 2)
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.axis('off')
plt.show()

plt.figure(dpi = 500)
plt.contourf(X, Y, v1.T, 128, cmap = 'jet', vmin = -2, vmax = 2)
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 2)
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.axis('off')
plt.show()

plt.figure(dpi = 500)
plt.contourf(X, Y, p1.T, 128, cmap = 'jet', vmin = -10, vmax = 6)
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 2)
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.axis('off')
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.plot(x1, y1, color='black', alpha = 1, linewidth = 1)
plt.gca().set_aspect('equal', adjustable = 'box')
plt.xlim([0, L])
plt.ylim([0, D])
plt.axis('off')
plt.show()

Fig. 2, Results from curved boundary simulation


     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!

Thursday, 20 February 2025

Flow Simulation around Shapes (Includes Free Code)

     This post is about the simulation of flow 🍃 around and through various objects 🪈 and obstacles ⭕. The simulated cases include flow through a partially blocked pipe, shown in Fig. 1. Flow around flat plates arranged in the shape of the letter "T", shown in Fig. 2. Flow around a wedge and flow around a triangle 🔺, which are shown in Fig. 3 and 4 respectively.

     To create obstacles in Python 🐍, the Path statement is used. This is similar to the inpolygon statement in MATLAB 🧮. For example, the following code 🖳 is used to create an ellipse ⬭.

X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
theta = np.linspace(0, np.pi, 100) # create equally spaced angles from 0 to pi
a = 0.05 # semi-major axis (along x)
b = 0.025 # semi-minor axis (along y)
shape_center_x = L / 2 # shape center x
shape_center_y = 0 # ellipse center x
x1 = shape_center_x + (a * np.cos(theta)) # x-coordinates
y1 = shape_center_y + (b * np.sin(theta)) # y-coordinates
shape_path = Path(np.column_stack((x1, y1))) # shape region
points = np.vstack((X.ravel(), Y.ravel())).T # mark inside region
custom_curve = shape_path.contains_points(points).reshape(X.shape) # create boolean mask
custom_curve_boundary = np.zeros_like(custom_curve, dtype=bool) # find boundary of shape
for i in range(1, Nx-1):
    for j in range(1, Ny-1):
        if custom_curve.T[i, j]: # inside shape
            if (not custom_curve.T[i+1, j] or not custom_curve.T[i-1, j] or 
                not custom_curve.T[i, j+1] or not custom_curve.T[i, j-1]):
                custom_curve_boundary.T[i, j] = True # mark as boundary
boundary_indices = np.where(custom_curve_boundary.T) # mark boundary
right_neighbors = (boundary_indices[0] + 1, boundary_indices[1]) # right index
left_neighbors = (boundary_indices[0] - 1, boundary_indices[1]) # left index
top_neighbors = (boundary_indices[0], boundary_indices[1] + 1) # top index
bottom_neighbors = (boundary_indices[0], boundary_indices[1] - 1) # bottom index
valid_right = ~custom_curve.T[right_neighbors] # check if points are on shape boundary
valid_left = ~custom_curve.T[left_neighbors]
valid_top = ~custom_curve.T[top_neighbors]
valid_bottom = ~custom_curve.T[bottom_neighbors]

     The arrays x1 and y1 are created using the equation for ellipse with the required parameters. The ellipse region is marked using the Path statement. Indices inside the ellipse are marked using a Boolean mask. Nested loops are used to mark the ellipse boundary using a curve. The right, left, top and bottom neighbor points are identified to be used for the application of Neumann boundary conditions for pressure (no-slip). Within the time loop, "where" statement is used to identify and apply the Neumann boundary conditions on the ellipse wall. The same method applied on any shape, for example aero-foils, circles, nozzles etc. The complete code to reproduce Fig. 1 is made available 😇. 

     It should be noted that, that the mesh is still stairstep. It doesn't matter how small the mesh resolution 😲. This code is developed for educational and research purposes only as there is not much application to stairstep mesh in real world❗

Code

#Copyright <2025> <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
from matplotlib.path import Path
#%% define parameters
l_square = 1 # length of square
h = 0.025 / 25 # grid spacing
dt = 0.00001 # time step
L = 0.3 # domain length
D = 0.05 # 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 = 5 # 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
#%% initialize variables
u = np.zeros((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure
#%% create a shape
X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
theta = np.linspace(0, np.pi, 100) # create equally spaced angles from 0 to pi
a = 0.05 # semi-major axis (along x)
b = 0.025 # semi-minor axis (along y)
shape_center_x = L / 2 # shape center x
shape_center_y = 0 # ellipse center x
x1 = shape_center_x + (a * np.cos(theta)) # x-coordinates
y1 = shape_center_y + (b * np.sin(theta)) # y-coordinates
shape_path = Path(np.column_stack((x1, y1))) # shape region
points = np.vstack((X.ravel(), Y.ravel())).T # mark inside region
custom_curve = shape_path.contains_points(points).reshape(X.shape) # create boolean mask
custom_curve_boundary = np.zeros_like(custom_curve, dtype=bool) # find boundary of shape
for i in range(1, Nx-1):
    for j in range(1, Ny-1):
        if custom_curve.T[i, j]: # inside shape
            if (not custom_curve.T[i+1, j] or not custom_curve.T[i-1, j] or 
                not custom_curve.T[i, j+1] or not custom_curve.T[i, j-1]):
                custom_curve_boundary.T[i, j] = True # mark as boundary
boundary_indices = np.where(custom_curve_boundary.T) # mark boundary
right_neighbors = (boundary_indices[0] + 1, boundary_indices[1]) # right index
left_neighbors = (boundary_indices[0] - 1, boundary_indices[1]) # left index
top_neighbors = (boundary_indices[0], boundary_indices[1] + 1) # top index
bottom_neighbors = (boundary_indices[0], boundary_indices[1] - 1) # bottom index
valid_right = ~custom_curve.T[right_neighbors] # check if points are on shape boundary
valid_left = ~custom_curve.T[left_neighbors]
valid_top = ~custom_curve.T[top_neighbors]
valid_bottom = ~custom_curve.T[bottom_neighbors]
#%% 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 / (8 * dt) * (u[2:, 1:-1] - u[:-2, 1:-1] + v[1:-1, 2:] - v[1:-1, :-2]) # pressure
    # apply pressure boundary conditions
    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 / 2
    p[custom_curve.T] = 0 # p = 0 inside shape
    # dp/dn = 0 at shape boundary (no slip)
    p[boundary_indices] = np.where(valid_right, p[right_neighbors], p[boundary_indices]) # right neighbor is fluid
    p[boundary_indices] = np.where(valid_left, p[left_neighbors], p[boundary_indices]) # left neighbor is fluid
    p[boundary_indices] = np.where(valid_top, p[top_neighbors], p[boundary_indices]) # top neighbor is fluid
    p[boundary_indices] = np.where(valid_bottom, p[bottom_neighbors], p[boundary_indices]) # bottom neighbor is fluid
    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 boundary conditions
    u[0, :] = Uinf # u = Uinf at x = 0
    u[-1, :] = u[-2, :] # du/dx = 0 at x = L
    u[:, 0] = 0 # u = 0 at y = 0
    u[:, -1] = u[:, -2] # du/dy = 0 at y = D / 2
    u[custom_curve.T] = 0 # u = 0 inside shape
    u[custom_curve_boundary.T] = 0 # no slip
    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 boundary conditions
    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 / 2
    v[custom_curve.T] = 0 # u = 0 inside shape
    v[custom_curve_boundary.T] = 0 # no slip
#%% post process
u1 = u.copy() # u-velocity for plotting with shape
v1 = v.copy() # v-velocity for plotting with shape
p1 = p.copy() # pressure for plotting with shape
# shape geometry for plotting
u1[custom_curve.T] = np.nan
v1[custom_curve.T] = np.nan
p1[custom_curve.T] = np.nan
velocity_magnitude1 = np.sqrt(u1**2 + v1**2) # velocity magnitude with shape
# visualize velocity vectors and pressure contours
plt.figure(dpi = 500)
plt.contourf(X, Y, u1.T, 128, cmap = 'jet')
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 2)
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.axis('off')
plt.show()
plt.figure(dpi = 500)
plt.contourf(X, Y, v1.T, 128, cmap = 'jet')
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 2)
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.axis('off')
plt.show()
plt.figure(dpi = 500)
plt.contourf(X, Y, p1.T, 128, cmap = 'jet')
plt.plot(x1, y1, color='black', alpha = 1, linewidth = 2)
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.axis('off')
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.plot(x1, y1, color='black', alpha = 1, linewidth = 2)
plt.gca().set_aspect('equal', adjustable = 'box')
plt.axis('off')
plt.show()


Fig. 1, Flow in a clogged pipe


Fig. 2, Flow around a blunt obstacle


Fig. 3, Flow around asymmetric wedge



Fig. 4, Flow around a triangle

     Within Figs. 1 - 4, top row shows u and v components of velocity, bottom row shows pressure and streamlines 💫

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

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!

The new version of the code is faster as the equations are simplified and many factors are precalculated, resulting in quicker execution times.

Code

# Copyright <2025> <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 / 500 # grid spacing
dt = 0.00002 # 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 = 200 # 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()

Lid-Driven Cavity

     The case of lid-driven cavity in the turbulent flow regime can now be solved in reasonable amount of time. The results are shown in Fig. 1. I stopped the code while the flow is still developing as you are reading a blog and not a Q1 journal. 😆 Within Fig. 1, streamlines, v and u component of velocity and pressure are shown going from left to right and top to bottom. At the center of Fig. 1, the velocity magnitude is superimposed. As this is DNS, the smallest spatial scale resolved is ~8e-3 m [8 mm]. While, the smallest time-scale ⌛ resolved is ~8e-4 s [0.8 ms].

Fig. 1, The results at Reynolds number of 10,000

Free-Jet

          The case of free jets in the turbulent flow regime can now be solved in reasonable amount of time. The results are shown in Fig. 2. I stopped the code while the flow is still developing. Once again, I remind you that you are reading a blog and not a Q1 journal. 😆 Within Fig. 2, streamlines and species are shown. As this is DNS, the smallest spatial scale resolved is ~0.02 m [2 cm]. While, the smallest time-scale ⌛ resolved is ~4e-4 s [0.4 ms]. The code for implementing species, in this case temperature using the energy equation is available on the previous post.

Fig. 2, Free jet at Reynolds number 10000

Heated Room

     The benchmark case of mixed convection in an open room in the turbulent flow regime can now be solved in reasonable amount of time as well. The results are shown in Fig. 3. I stopped the code while the flow field stopped showing any changes. 😆 As this is DNS, the smallest spatial scale resolved is ~0.0144 m [1.44 cm]. While, the smallest time-scale ⌛ resolved is ~1e-4 s [1 ms]. The code for implementing species, in this case temperature using the energy equation is available on the previous post. In the previous post, the momentum equation has no changes as the gravity vector is at 0 m/s2. For this example, Boussinesq assumption is used.

Fig. 3, Flow inside a heated room at Reynolds number of 5000

Backward - Facing Step (BFS)

     Another benchmark case of flow around a backwards facing step can now be solved in reasonable amount of time as well. The flow is fully turbulent. The results are shown in Fig. 4. I stopped the code while the flow field is still developing. 😆 As this is DNS, the smallest spatial scale resolved is ~0.01 m [1 cm]. While, the smallest time-scale ⌛ resolved is ~1e-4 s [1 ms]. As can be seen from Fig. 4, there are no abnormalities in the flow field.

Fig. 4, Flow around a backwards facing step at Reynolds number of 10000

PS: I fully understand, there is no such thing as 2D turbulence 🍃. Just don't kill the vibe please 💫.

Artificial Compressibility

     The artificial compressibility method is now implemented in the code. The output is flow inside the lid-driven cavity at Reynolds number 10,000. The smallest scale resolved is at 0.001 m and smallest time scale resolved is at 0.0001 s. This version of code seems to be more stable as compared to the one that uses pressure Poisson equation. The results are shown in Fig. 5.

Fig. 5, Look at all those secondary vortices 😚



#Copyright <2025> <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 parameters
l_cr = 1 # characteristic length
h = l_cr / 1000 # grid spacing
dt = 0.0001 # 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 / 10000 # 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_cr * Uinf / nu) # Reynolds number

#%% intialization
u = np.zeros((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure

#%% pre calculate for speed
P1 = dt / h
P2 = (2 / Re) * dt / h**2
P3 = 1 - (4 * P2)

#%% solve 2D Navier-Stokes equations
for nt in range(ns):
    pn = p.copy()
    p[1:-1, 1:-1] = pn[1:-1, 1:-1] - P1 * (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] = p[:, -2] # dp/dy = 0 at y = D
    un = u.copy()
    vn = v.copy()
    u[1:-1, 1:-1] = un[1:-1, 1:-1] * P3 - P1 * (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]) + p[2:, 1:-1] - p[:-2, 1:-1]) + P2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2]) # 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] * P3 - P1 * (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]) + p[1:-1, 2:] - p[1:-1, :-2]) + P2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2]) # 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

#%% post processing
X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
plt.figure(dpi = 200)
plt.contourf(X, Y, u.T, 128, cmap = 'jet') # plot contours
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 = 200)
plt.contourf(X, Y, v.T, 128, cmap = 'jet') # plot contours
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 = 200)
plt.contourf(X, Y, p.T, 128, cmap = 'jet') # plot contours
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 = 200)
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()

velocity_magnitude = np.sqrt(u**2 + v**2)  # calculate velocity magnitude
plt.figure(dpi = 200)
plt.contourf(X, Y, velocity_magnitude.T, 128, cmap = 'plasma_r') # plot contours
plt.streamplot(X, Y, u.T, v.T, color = 'black', cmap = 'jet', density = 2, linewidth = 0.1, arrowstyle='->', arrowsize = 0.5) # 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.axis("off")
plt.show()

Relaxation

     The relaxation parameter along with equations is now added! The "omega" parameter can be adjusted to over / under relax the simulation according to requirements! At Reynolds number of 5000, the code provides up to 4x speed in convergence with over-relaxation.

#Copyright <2025> <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 parameters
l_cr = 1 # characteristic length
h = l_cr / 600 # grid spacing
dt = 0.0001 # 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 / 5000 # kinematic viscosity
Uinf = 1 # free stream velocity / inlet velocity / lid velocity
cfl = dt * Uinf / h # cfl number
travel = 5 # 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_cr * Uinf / nu) # Reynolds number

#%% intialization
u = np.zeros((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure
u_new = u.copy() # x-velocity (relaxation)
v_new = v.copy() # y-velocity (relaxation)
p_new = p.copy() # pressure (relaxation)

#%% pre calculate for speed
P1 = dt / h
P2 = (2 / Re) * dt / h**2
P3 = 1 - (4 * P2)
omega = 4 # relaxation parameter (omega < 5)

#%% solve 2D Navier-Stokes equations
for nt in range(ns):
    pn = p.copy()
    p_new[1:-1, 1:-1] = pn[1:-1, 1:-1] - P1 * (u[2:, 1:-1] - u[:-2, 1:-1] + v[1:-1, 2:] - v[1:-1, :-2]) # pressure
    p[1:-1, 1:-1] = (1 - omega) * pn[1:-1, 1:-1] + omega * p_new[1:-1, 1:-1] # relaxation
    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] = p[:, -2] # dp/dy = 0 at y = D
    un = u.copy()
    vn = v.copy()
    u_new[1:-1, 1:-1] = un[1:-1, 1:-1] * P3 - P1 * (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]) + p[2:, 1:-1] - p[:-2, 1:-1]) + P2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2]) # x momentum
    u[1:-1, 1:-1] = (1 - omega) * un[1:-1, 1:-1] + omega * u_new[1:-1, 1:-1] # relaxation
    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_new[1:-1, 1:-1] = vn[1:-1, 1:-1] * P3 - P1 * (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]) + p[1:-1, 2:] - p[1:-1, :-2]) + P2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2]) # y momentum
    v[1:-1, 1:-1] = (1 - omega) * vn[1:-1, 1:-1] + omega * v_new[1:-1, 1:-1] # relaxation
    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

#%% post processing
X, Y = np.meshgrid(np.linspace(0, L, Nx), np.linspace(0, D, Ny)) # spatial grid
plt.figure(dpi = 200)
plt.contourf(X, Y, u.T, 128, cmap = 'jet') # plot contours
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 = 200)
plt.contourf(X, Y, v.T, 128, cmap = 'jet') # plot contours
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 = 200)
plt.contourf(X, Y, p.T, 128, cmap = 'jet') # plot contours
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 = 200)
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()

velocity_magnitude = np.sqrt(u**2 + v**2)  # calculate velocity magnitude
plt.figure(dpi = 200)
plt.contourf(X, Y, velocity_magnitude.T, 128, cmap = 'plasma_r') # plot contours
plt.streamplot(X, Y, u.T, v.T, color = 'black', cmap = 'jet', density = 2, linewidth = 0.1, arrowstyle='->', arrowsize = 0.5) # 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.axis("off")
plt.show()

Pre-Calculation

# Copyright <2025> <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_cr = 1 # characteristic length
h = l_cr / 120 # grid spacing
dt = 0.0001 # 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 = 10 # 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_cr * Uinf / nu) # Reynolds number
u = np.zeros((Nx, Ny)) # x-velocity
v = np.zeros((Nx, Ny)) # y-velocity
p = np.zeros((Nx, Ny)) # pressure
P1 = h / (16 * dt)
P2 = (2 / Re) * dt / h**2
P3 = dt / h
P4 = 1 - (4 * P2)
for nt in range(ns):
    pn = p.copy()
    p[1:-1, 1:-1] = 0.25 * (pn[2:, 1:-1] + pn[:-2, 1:-1] + pn[1:-1, 2:] + pn[1:-1, :-2]) - P1 * (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] = p[:, -2] # dp/dy = 0 at y = D
    un = u.copy()
    vn = v.copy()
    u[1:-1, 1:-1] = un[1:-1, 1:-1] * P4 - P3 * (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]) + p[2:, 1:-1] - p[:-2, 1:-1]) + P2 * (un[2:, 1:-1] + un[:-2, 1:-1] + un[1:-1, 2:] + un[1:-1, :-2]) # 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 = 0 at y = D
    v[1:-1, 1:-1] = vn[1:-1, 1:-1] * P4 - P3 * (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]) + p[1:-1, 2:] - p[1:-1, :-2]) + P2 * (vn[2:, 1:-1] + vn[:-2, 1:-1] + vn[1:-1, 2:] + vn[1:-1, :-2]) # 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 = 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.axis('off')
plt.show()
plt.figure(dpi = 500)
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.xlim([0, L])
plt.ylim([0, D])
plt.axis('off')
plt.show()
     
     Thank you for reading! If you want to hire me as your next shinning post-doc, do let reach out!