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!