Showing posts with label turbulent. Show all posts
Showing posts with label turbulent. Show all posts

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 <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 💫.

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

Saturday, 1 April 2023

Turbulent Fluid Structure Interaction (FSI) - Benchmark Case

     After weeks spent self-learning about this type of simulation and countless nights spent troubleshooting this complex problem, I am pleased to share results. 😇 This post is about the FSI analysis of the FSI-PfS-2a. A case designed by Dr. Breuer. The geometry is shown in Fig. 1. The geometry details are available in ref. [1]. The geometry is made in SolidWorks CAD package and then imported to ANSYS via .STEP file. FSI combines Computational Fluid Dynamics (CFD) and structural analysis, i.e. the Finite Element Method (FEM).

Fig. 1, The geometry

     A combination of ANSYS Fluent, Mechanical and System Coupling are used for the analysis. Fig. 2 shows post-processing animation from the simulation. The top left shows stress while the displacements of the material are shown in top right. Bottom left and right show fluid velocity and vorticity, respectively. The vorticity is plotted along the axis perpendicular to the both lift and drag forces. the image in the center of animation shows fluid pressure acting on the cylinder and plate. Stagnation pressure is observed to change with time.

Fig. 2, The animation

     The boundary conditions from Mechanical are shown in Fig. 3. The condition A refers to gravity at 9.8066 m/s2 while B refers to fixed-support condition applied to the edge touching the cylinder. Boundary condition C refers to the fluid-solid interface. It is at these regions forces and displacements are exchanged. The structural mesh has 180 elements and 1,156 nodes. It is to be noted that the fluid regions are not meshed in mechanical and vice-versa. Furthermore, the number of mesh elements is limited by the system memory. The steel and rubber portions are connected via 4 connections i.e. edge/edge and edge/face contacts. The unmarked regions within Fig. 3 (top) are made symmetric. The  steel and rubber are considered linear elastic. No external force is applied in mechanical so this case can also be called as a case of vortex-induced vibrations. The direct sparse FEM solver is used for the Structural-FSI simulation.

Fig. 3, The boundary conditions and mesh

     The CFD mesh is shown in Fig. 4. The mesh is created using sweep method. Refinements are applied in areas of interest, i.e. wake and around the structure, using bodies of influence. Moreover, inflation mesh for y+ of 7.55 is applied on the cylinder to properly capture the boundary layer. The FSI-CFD simulation is initialized with data from static transient analysis using k–ω SST DES turbulence model. The k–ω DES model is initialized using static steady-state k–ω SST model. The flow parameters include a velocity of 1.385 m/s [1] corresponding to a Reynolds number of 30,470. The mesh has 79,305 cells. The dynamic mesh is handled through remeshing and smoothing via the radial basis function. Water is taken as a fluid for this simulation, same as [1]. Symmetry is applied to the walls facing perpendicular to flow. Top and bottom walls of the structure are considered adiabatic and with no shear. The SIMPLE algorithm is used. 2nd order accurate discretization schemes are used.

Fig. 4, The computational domain and the mesh

     It should be noted that for this simulations only 20 mm section of the whole geometry is simulated. This is because of computational resources limitations. The simulations took ~12 hours to solve 0.268 s of physical time with 32 GB RAM and 6 core CPU. The mesh motion along with vorticity iso-surfaces are shown in Fig. 5.

Fig. 5, The mesh and vorticity animation

     Thank you for reading, if you would like to hire me as your PhD student / post-doc  / collaborate on projects, please reach out.

References

[1] A. Kalmbach and M. Breuer, "Experimental PIV/V3Vmeasurementsofvortex-induced fluid–structure interaction in turbulent flow—A new benchmark FSI-PfS-2a", Journal of Fluids and Structures, Vol. 42, pp 369–387, 2013