0% found this document useful (0 votes)
114 views17 pages

Assignments On Simple Laticce-Boltzman Simulator in Python (ID - 20225149-Mihir Dutta)

This document summarizes a Python-based lattice Boltzmann method (LBM) simulation for fluid flow. It begins with an abstract and keywords about LBM simulation in Python on GPU. It then provides background on LBM, describing it as a computational fluid dynamics method that simulates fluid density and streaming/collision processes on a lattice, unlike Navier-Stokes methods. The document outlines the LBM algorithm and collision/streaming steps. It discusses advantages like efficiency on parallel architectures and incorporating molecular interactions. Limitations described include interfacing thickness and modeling high-speed flows. The document concludes with descriptions of 2D LBM modeling in Python and a simple LBM simulator code.

Uploaded by

Mihirdutta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views17 pages

Assignments On Simple Laticce-Boltzman Simulator in Python (ID - 20225149-Mihir Dutta)

This document summarizes a Python-based lattice Boltzmann method (LBM) simulation for fluid flow. It begins with an abstract and keywords about LBM simulation in Python on GPU. It then provides background on LBM, describing it as a computational fluid dynamics method that simulates fluid density and streaming/collision processes on a lattice, unlike Navier-Stokes methods. The document outlines the LBM algorithm and collision/streaming steps. It discusses advantages like efficiency on parallel architectures and incorporating molecular interactions. Limitations described include interfacing thickness and modeling high-speed flows. The document concludes with descriptions of 2D LBM modeling in Python and a simple LBM simulator code.

Uploaded by

Mihirdutta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Assignments on Simple Lattice-Boltzmann Simulator in Python

Mihir Dutta a, See Jo Kim b


a
Master Student, Department of Mechanical Engineering, Andong National University
b
Professor, Department of Mechanical Engineering, Andong National University

Abstract
The assignment consists of YouTube video lecture based on Python based lattice Boltzmann Model on
GPU and simple lattice-Boltzmann simulator in Python.
Keywords: Lattice, Simulation, Diagram.

Lattice-Boltzmann Method
The lattice Boltzmann methods (LBM), originated from the lattice gas automata (LGA) method
(Hardy-Pomeau-Pazzis and Frisch-Hasslacher-Pomeau models), is a class of computational fluid
dynamics (CFD) methods for fluid simulation. Instead of solving the Navier–Stokes equations
directly, a fluid density on a lattice is simulated with streaming and collision (relaxation) processes.
The method is versatile as the model fluid can straightforwardly be made to mimic common fluid
behaviour like vapour/liquid coexistence, and so fluid systems such as liquid droplets can be
simulated. Also, fluids in complex environments such as porous media can be straightforwardly
simulated, whereas with complex boundaries other CFD methods can be hard to work with.
Unlike CFD methods that solve the conservation equations of macroscopic properties (i.e., mass,
momentum, and energy) numerically, LBM models the fluid consisting of fictive particles, and
such particles perform consecutive propagation and collision processes over a discrete lattice. Due
to its particulate nature and local dynamics, LBM has several advantages over other conventional
CFD methods, especially in dealing with complex boundaries, incorporating microscopic
interactions, and parallelization of the algorithm. A different interpretation of the lattice Boltzmann
equation is that of a discrete-velocity Boltzmann equation. The numerical methods of solution of
the system of partial differential equations then give rise to a discrete map, which can be interpreted
as the propagation and collision of fictitious particles.
In an algorithm, there are collision and streaming steps. These evolve the density of the fluid
𝜌(𝑥⃗, 𝑡), the position and t the time. As the fluid is on a lattice, the density has a number of
components 𝑓𝑖 , 𝑖 = 0, … . , 𝑎 equal to the number of lattice vectors connected to each lattice point.
As an example, the lattice vectors for a simple lattice used in simulations in two dimensions is
shown here. This lattice is usually denoted D2Q9, for two dimensions and nine vectors: four
vectors along north, east, south and west, plus four vectors to the corners of a unit square, plus a
vector with both components zero. Then, for example vector 𝑒⃗4 = (0, −1), i.e., it points due south
and so has no x component but a y component of -1. So, one of the nine components of the total
density at the central lattice point, 𝑓4 (𝑥⃗, 𝑡)is that part of the fluid at point x moving due south, at a
speed in lattice units of one.

Then the steps that evolve the fluid in time are:


The Collision Steps
𝒇𝒊 𝒆𝒒 (𝒙
⃗⃗, 𝒕) − 𝑓𝑖 (𝑥⃗, 𝑡)
𝒇𝒊 (𝒙
⃗⃗, 𝒕 + 𝜹𝒕 ) = 𝒇𝒊 (𝒙
⃗⃗, 𝒕) +
𝝉𝒇

which is the Bhatnagar Gross and Krook (BGK) model for relaxation to equilibrium via collisions
between the molecules of a fluid. 𝑓 𝑒𝑞 𝑖 (𝑥⃗, 𝑡) is the equilibrium density along direction i at the
current density there. The model assumes that the fluid locally relaxes to equilibrium over a
characteristic timescale. This timescale determines the kinematic viscosity, the larger it is, the
larger is the kinematic viscosity.
The streaming step
𝑓𝑖 (𝑥⃗ + ⃗⃗⃗,
𝑒𝑖 𝒕 + 𝜹𝒕 ) = 𝑓𝑖 (𝑥⃗, 𝑡)
As 𝑓𝑖 (𝑥⃗, 𝑡) is, by definition, the fluid density at point 𝑥⃗ at time t, that is moving at a velocity of ⃗⃗⃗
𝑒𝑖
per time step, then at the next time step 𝒕 + 𝜹𝒕 it will have flowed to point𝑥⃗ + ⃗⃗⃗. 𝑒𝑖
Advantages
• The LBM was designed from scratch to run efficiently on massively parallel architectures,
ranging from inexpensive embedded FPGAs and DSPs up to GPUs and heterogeneous
clusters and supercomputers (even with a slow interconnection network). It enables
complex physics and sophisticated algorithms. Efficiency leads to a qualitatively new level
of understanding since it allows solving problems that previously could not be approached
(or only with insufficient accuracy).
• The method originates from a molecular description of a fluid and can directly incorporate
physical terms stemming from a knowledge of the interaction between molecules. Hence
it is an indispensable instrument in fundamental research, as it keeps the cycle between the
elaboration of a theory and the formulation of a corresponding numerical model short.
• Automated data pre-processing and lattice generation in a time that accounts for a small
fraction of the total simulation.
• Parallel data analysis, post-processing and evaluation.
• Fully resolved multi-phase flow with small droplets and bubbles.
• Fully resolved flow through complex geometries and porous media.
• Complex, coupled flow with heat transfer and chemical reactions
Limitations
Despite the increasing popularity of LBM in simulating complex fluid systems, this novel
approach has some limitations. At present, high-Mach number flows in aerodynamics are still
difficult for LBM, and a consistent thermo-hydrodynamic scheme is absent. However, as with
Navier–Stokes based CFD, LBM methods have been successfully coupled with thermal-specific
solutions to enable heat transfer (solids-based conduction, convection and radiation) simulation
capability. For multiphase/multicomponent models, the interface thickness is usually large and the
density ratio across the interface is small when compared with real fluids. Recently this problem
has been resolved by Yuan and Schaefer who improved on models by Shan and Chen, Swift, and
He, Chen, and Zhang. They were able to reach density ratios of 1000:1 by simply changing the
equation of state. It has been proposed to apply Galilean Transformation to overcome the limitation
of modelling high-speed fluid flows. Nevertheless, the wide applications and fast advancements
of this method during the past twenty years have proven its potential in computational physics,
including microfluidics. LBM demonstrates promising results in the area of high Knudsen number
flows
Simulation of mixtures
Simulating multiphase/multicomponent flows has always been a challenge to conventional CFD
because of the moving and deformable interfaces. More fundamentally, the interfaces between
different phases (liquid and vapor) or components (e.g., oil and water) originate from the specific
interactions among fluid molecules. Therefore, it is difficult to implement such microscopic
interactions into the macroscopic Navier–Stokes equation. However, in LBM, the particulate
kinetics provides a relatively easy and consistent way to incorporate the underlying microscopic
interactions by modifying the collision operator. Several LBM multiphase/multicomponent
models have been developed. Here phase separations are generated automatically from the particle
dynamics and no special treatment is needed to manipulate the interfaces as in traditional CFD
methods. Successful applications of multiphase/multicomponent LBM models can be found in
various complex fluid systems, including interface instability, bubble/droplet dynamics, wetting
on solid surfaces, interfacial slip, and droplet electrohydrodynamic deformations.
A lattice Boltzmann model for simulation of gas mixture combustion capable of accommodating
significant density variations at low-Mach number regime has been recently proposed.
To this respect, it is worth to notice that, since LBM deals with a larger set of fields (as compared
to conventional CFD), the simulation of reactive gas mixtures presents some additional challenges
in terms of memory demand as far as large, detailed combustion mechanisms are concerned. Those
issues may be addressed, though, by resorting to systematic model reduction techniques
2D Lattice-Boltzmann Modeling
The lattice Boltzmann method (LBM) is intrinsically a mesoscopic computational fluid dynamics
(CFD) approach based on the evolution of statistical distribution on lattices and has achieved
considerable success in simulating fluid flows and associated transport phenomena.
Simple Lattice-Boltzmann Simulator in Python
##LBM simulations

import numpy as np
import matplotlib.pyplot as plt
from time import time as ti
from matplotlib import cm
from tqdm import tqdm

def obstacle_fun(cx, cy, r):


def inner(x, y):
return (x-cx)**2+(y-cy)**2<r**2
return inner

def inivel( uLB, ly):


def inner(d,x,y):
return (1-d) * uLB * (1+1e-4*np.sin(y/ly*2*np.pi))
return inner

def equilibrium(rho, u, v, t, nx, ny):


usqr = (3/2)*(u[0]**2+u[1]**2)
feq = np.zeros((9,nx,ny))
for i in range(9):
cu = 3*(v[i,0]*u[0,:,:] + v[i,1]*u[1,:,:])
feq[i,:,:] = rho*t[i]*(1+cu+0.5*cu**2-usqr)
return feq

def macroscopic(fin, nx, ny, v):


rho = np.sum(fin,axis=0)
u = np.zeros((2,nx,ny))
for i in range(9):
u[0,:,:] += v[i,0]*fin[i,:,:]
u[1,:,:] += v[i,1]*fin[i,:,:]
u /= rho
return rho, u

Re = 10.0 # Reynolds number


#------------------------------------------------------------------------------
maxIter = 1000
nx,ny = 420,180 # Domain dimensions
ly = ny-1
uLB = 0.04 # Inlet velocity NON PHYSICAL??
cx,cy,r = nx//4,ny//2,ny/9 # cylinder coordinates and radius (as integers)
nulb = uLB*r/Re # Viscosity
omega = 1 / (3*nulb+0.5) # Relaxation parameter

# lattice velocities
v = np.array([ [1,1],
[1,0],
[1,-1],
[0,1],
[0,0],
[0,-1],
[-1,1],
[-1,0],
[-1,-1]
])

# weights
t = np.array([
1/36,
1/9,
1/36,
1/9,
4/9,
1/9,
1/36,
1/9,
1/36
])

col_0 = np.array([0,1,2])
col_1 = np.array([3,4,5])
col_2 = np.array([6,7,8])

# instantiate the cylindrical obstacle


obstacle = np.fromfunction(obstacle_fun(cx,cy,r),(nx, ny))
if True:
plt.imshow(obstacle)
# initial velocity profile
vel = np.fromfunction(inivel(uLB,ly),(2,nx,ny))

# initialize fin to equilibirum (rho = 1)


fin = equilibrium(1,vel,v,t,nx,ny)

####################################################

#====================================================================
==========
# Time-Stepping
#====================================================================
==========
t0 = ti()
for time in tqdm(range(maxIter)):
# outflow boundary condition (right side) NEUMANN BC! No gradient
fin[col_2,-1,:] = fin[col_2,-2,:]

# compute macroscopic variables


rho,u = macroscopic(fin,nx,ny,v)

# inlet boundary condition (left wall)


u[:,0,:] = vel[:,0,:]
rho[0,:] = 1/(1-u[0,0,:])*( np.sum(fin[col_1,0,:], axis = 0)+
2*np.sum(fin[col_2,0,:], axis = 0))

feq = equilibrium(rho,u,v,t,nx,ny)
fin[col_0,0,:] = feq[col_0,0,:] + fin[col_2,0,:]-feq[col_2,0,:]

# Collide
fout = fin - omega*(fin-feq)

# bounceback
for i in range(9):
fout[i,obstacle] = fin[8-i,obstacle]

# stream
for i in range(9):
# be careful with this -> numpy.roll cycles through an array by an axis
# and the last element becomes the first. this implements a periodic
# boundary in a very compact syntax, but needs to be reworked for other
# implementations
fin[i,:,:] = np.roll(
np.roll(
fout[i,:,:], v[i,0], axis = 0
),
v[i,1], axis = 1
)

# Output an image every 100 iterations


if (time%100 == 0):
plt.clf()
plt.imshow(np.sqrt(u[0]**2+u[1]**2).T, cmap = cm.Reds)
plt.savefig("vel{0:03d}.png".format(time//100))
tf = ti() - t0
print("time to execute = ",tf)

##Plotting Lattice directions

fontsize = 14
length = 2
plt.style.use('bmh')
def draw_lattice( ax, coords, width=.025, head_width=.2, head_length=.2,
annotation_offset=1.25):
ax.arrow( 0,0,coords[0],coords[1],
width = width,
head_length=head_width,
head_width=head_length,
color = 'k')
aos = annotation_offset

ax.annotate(coords[2],xy=(aos*coords[0],aos*coords[1]),xytext=(aos*coords[0],aos*coords[1]),
horizontalalignment = 'center',
verticalalignment = 'center',
fontsize = fontsize)

def plot_column(ax,x0,x2,y, alpha = 0.3):


for x in [x0,x2]:
ax.plot([x,x],[-y/2,y/2],'k', linestyle = (0,(5,5)), alpha = alpha)

def lattice_fig(fig, ax, coords):


for pair in coords:
draw_lattice(ax,pair)
#plt.box(False)
ax.set_xlim(-length*1.5,length*1.5)
ax.set_ylim(-length*1.5,length*1.7)
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
ax.set_aspect('equal')
ax.xaxis.set_tick_params(bottom=False,top=False,right=False,left=False)
ax.yaxis.set_tick_params(right=False,left=False)

#====================================================================
==========
# Draw D2Q9 Lattice
#====================================================================
==========
op = [
(length,length,'0'),
(length,0,'1'),
(length,-length,'2'),
(0,length,'3'),
(0,-length,'5'),
(-length,length,'6'),
(-length,0,'7'),
(-length,-length,'8'),
]

fig,ax = plt.subplots(1, 2, num = 0,figsize = (14,7))


xval = .066
yval = .185
for a in ax:
lattice_fig(fig,a,op)
a.annotate('4',xy=(xval,yval),xytext=(xval,yval),
horizontalalignment = 'left',
verticalalignment = 'bottom',
fontsize = fontsize)
a.grid(False)
# Overlaying the Columns
dx = .4
dy = .4
fs = 16
plot_column(ax[1], length, length*(1+dx), length*(1+dy)*2)
plot_column(ax[1], -length, -length*(1+dx), length*(1+dy)*2)
plot_column(ax[1], -dx, dx, length*(1+dy)*2)
# Annotations for column names
ax[1].text(length*1.2, length*1.5,'Col$_0$', horizontalalignment = 'center', fontsize = fs)
ax[1].text(0, length*1.5,'Col$_1$', horizontalalignment = 'center', fontsize = fs)
ax[1].text(-length*1.2, length*1.5,'Col$_2$', horizontalalignment = 'center', fontsize = fs)
fig.tight_layout()
plt.savefig("lattice_diagram.png")
plt.show()
Lattice Diagram
A lattice graph, also known as a mesh graph or grid graph, is a graph possessing an embedding in
a Euclidean space. that forms a regular tiling.
After running the code, lattice diagram has been found.

Results
Conclusion
The lattice Boltzmann equation (LBE) is a minimal form of Boltzmann kinetic equation which is
meant to simulate the dynamic behaviour of fluid flows without directly solving the equations of
continuum fluid mechanics

Reference
[1] https://www.openlb.net/news/openlb-community-youtube-channel-update-6/
[2] https://www.youtube.com/watch?v=1WknsFIXv5I

You might also like