Write a 3D SPH simulator in taichi
- User
Write a 3D SPH simulator in taichi
- Assistant
Write a 3D SPH simulator in taichi
Certainly! Below is a step-by-step implementation of a basic 3D Smoothed Particle Hydrodynamics (SPH) simulator using the Taichi programming language. This simulator will simulate incompressible fluid dynamics using the SPH method.
Note: This is a simplified implementation intended for educational purposes. In a production-grade simulator, you might want to include additional features like adaptive time-stepping, neighborhood search optimizations, more accurate boundary conditions, and advanced fluid models.
The SPH method approximates fluid properties by computing weighted sums over neighboring particles. The key steps in each simulation time step are:
Now, let's dive into the implementation.
import taichi as ti
import numpy as np
ti.init(arch=ti.gpu) # Initialize Taichi to use the GPU for better performance
# Simulation parameters
dim = 3 # 3D simulation
particle_radius = 0.005
h = particle_radius * 4 # Kernel radius
mass = 1.0
rho0 = 1000.0 # Rest density
dt = 1e-4 # Time step
epsilon = 1e-5 # Small number to prevent division by zero
# Solver parameters
viscosity = 0.1
k = 1000.0 # Bulk modulus (stiffness of the fluid)
# Simulation domain
domain_size = (1.0, 1.0, 1.0)
# Number of particles in each dimension
nx = 20
ny = 20
nz = 20
num_particles = nx * ny * nz
# Maximum number of neighbors (for simplicity, use a fixed-size array)
max_num_neighbors = 100
# Particle properties
x = ti.Vector.field(dim, dtype=ti.f32, shape=num_particles) # Positions
v = ti.Vector.field(dim, dtype=ti.f32, shape=num_particles) # Velocities
rho = ti.field(dtype=ti.f32, shape=num_particles) # Densities
p = ti.field(dtype=ti.f32, shape=num_particles) # Pressures
F = ti.Vector.field(dim, dtype=ti.f32, shape=num_particles) # Forces
# Neighbor list
neighbor_list = ti.field(dtype=ti.i32)
ti.root.dense(ti.i, num_particles).dense(ti.j, max_num_neighbors).place(neighbor_list)
num_neighbors = ti.field(dtype=ti.i32, shape=num_particles)
# Boundary handling parameters
boundary_stiffness = 10000.0
boundary_damping = -0.5
# Initialize particle positions in a grid
@ti.kernel
def initialize_particles():
idx = 0
spacing = particle_radius * 2.0
for i in range(nx):
for j in range(ny):
for k in range(nz):
x[idx] = ti.Vector([
i * spacing + 0.1,
j * spacing + 0.1,
k * spacing + 0.1
])
v[idx] = ti.Vector([0.0, 0.0, 0.0])
idx += 1
# Compute neighbor list using a simple O(N^2) search (for demonstration)
@ti.kernel
def find_neighbors():
for i in range(num_particles):
num_neighbors[i] = 0 # Reset neighbor count
xi = x[i]
for j in range(num_particles):
if i != j:
xj = x[j]
rij = xi - xj
if rij.norm() < h:
idx = num_neighbors[i]
if idx < max_num_neighbors:
neighbor_list[i, idx] = j
num_neighbors[i] += 1
# Compute densities
@ti.kernel
def compute_density():
for i in range(num_particles):
rho_i = 0.0
xi = x[i]
for idx in range(num_neighbors[i]):
j = neighbor_list[i, idx]
xj = x[j]
rij = xi - xj
r = rij.norm()
rho_i += mass * W_poly6(r, h)
rho[i] = rho_i
# Compute pressures using Tait equation
@ti.kernel
def compute_pressure():
for i in range(num_particles):
rho_i = rho[i]
p[i] = k * (rho_i - rho0)
# Compute forces
@ti.kernel
def compute_forces():
for i in range(num_particles):
F_pressure = ti.Vector([0.0, 0.0, 0.0])
F_viscosity = ti.Vector([0.0, 0.0, 0.0])
xi = x[i]
vi = v[i]
pi = p[i]
rhoi = rho[i]
for idx in range(num_neighbors[i]):
j = neighbor_list[i, idx]
xj = x[j]
vj = v[j]
pj = p[j]
rhoj = rho[j]
rij = xi - xj
r = rij.norm()
# Compute pressure force contribution
grad_W = grad_W_spiky(rij, h)
F_pressure += -mass * (pi + pj) / (2 * rhoj) * grad_W
# Compute viscosity force contribution
vij = vj - vi
F_viscosity += viscosity * mass * vij / rhoj * W_viscosity(r, h)
F[i] = F_pressure + F_viscosity + ti.Vector([0.0, -9.8 * mass / rhoi, 0.0]) # Gravity
# Integrate velocities and positions
@ti.kernel
def integrate():
for i in range(num_particles):
vi = v[i]
xi = x[i]
Fi = F[i]
# Update velocity
vi += dt * Fi / rho[i]
# Simple boundary handling
for d in ti.static(range(dim)):
if xi[d] < particle_radius:
vi[d] *= boundary_damping
xi[d] = particle_radius
if xi[d] > domain_size[d] - particle_radius:
vi[d] *= boundary_damping
xi[d] = domain_size[d] - particle_radius
# Update position
xi += dt * vi
v[i] = vi
x[i] = xi
# Kernel Functions for SPH
@ti.func
def W_poly6(r, h):
result = 0.0
if 0 <= r < h:
result = 315.0 / (64.0 * np.pi * h ** 9) * (h ** 2 - r ** 2) ** 3
return result
@ti.func
def grad_W_spiky(rij, h):
r = rij.norm()
result = ti.Vector([0.0, 0.0, 0.0])
if 0 < r < h:
coeff = -45.0 / (np.pi * h ** 6) * (h - r) ** 2 / r
result = coeff * rij
return result
@ti.func
def W_viscosity(r, h):
result = 0.0
if 0 <= r < h:
result = 45.0 / (np.pi * h ** 6) * (h - r)
return result
# Main simulation loop
def run_simulation(steps):
initialize_particles()
gui = ti.GUI('3D SPH Simulation', res=(800, 600), background_color=0xFFFFFF)
for step in range(steps):
find_neighbors()
compute_density()
compute_pressure()
compute_forces()
integrate()
# Visualization (project to 2D for display)
pos = x.to_numpy()
pos_2d = pos[:, [0, 1]] / np.array([domain_size[0], domain_size[1]])
gui.clear(0xFFFFFF)
gui.circles(pos_2d, radius=particle_radius * 800, color=0x3287A8)
gui.show()
# Run the simulation for 2000 steps
run_simulation(steps=2000)
Poly6 Kernel (( W_{\text{poly6}} )): [ W_{\text{poly6}}(r, h) = \frac{315}{64\pi h^9} (h^2 - r^2)^3 \quad \text{for } 0 \leq r \leq h ]
Spiky Kernel Gradient (( \nabla W_{\text{spiky}} )): [ \nabla W_{\text{spiky}}(r, h) = -\frac{45}{\pi h^6} (h - r)^2 \frac{\mathbf{r}}{r} \quad \text{for } 0 < r \leq h ]
Viscosity Kernel (( W_{\text{viscosity}} )): [ W_{\text{viscosity}}(r, h) = \frac{45}{\pi h^6} (h - r) \quad \text{for } 0 \leq r \leq h ]
max_num_neighbors parameter limits the number of neighbors per particle. Ensure it's large enough to accommodate all neighbors within ( h ).To run this simulation:
pip install taichi
sph_simulation.py, and run:
python sph_simulation.py
To improve and extend the simulator:
mpl_toolkits.mplot3d), PyVista, or OpenGL for 3D rendering.Feel free to adjust the parameters and extend the code to suit your needs. Happy simulating!
Not yet included in a published release.