Certainly! Let's implement the mvp function for a 2D heat PDE system using Moving Least Squares (MLS) shape functions in the context of the Material Point Method (MPM). This function will compute the matrix-vector product ( \mathbf{mv} = \mathbf{A} \mathbf{v} ), where ( \mathbf{A} ) is the system matrix arising from the discretization of the heat equation, and ( \mathbf{v} ) is the input vector.
In this implementation, we'll use the Conjugate Gradient (CG) method, which requires us to compute the matrix-vector product without forming the matrix ( \mathbf{A} ) explicitly. Instead, we'll perform operations that are mathematically equivalent to multiplying ( \mathbf{A} ) with ( \mathbf{v} ).
Here's the implementation:
import taichi as ti
ti.init(arch=ti.cpu) # You can switch to ti.gpu if you have a GPU
# Simulation parameters
dim = 2
N_particles = 1000 # Number of particles
grid_size = 64 # Grid resolution
dx = 1.0 / grid_size
inv_dx = 1.0 / dx
# Material properties
thermal_conductivity = 1.0
dt = 1e-3 # Time step size
particle_mass = 1.0
# Fields
x = ti.Vector.field(dim, dtype=ti.f32, shape=N_particles) # Particle positions
v = ti.field(dtype=ti.f32, shape=N_particles) # Input vector (e.g., temperature)
mv = ti.field(dtype=ti.f32, shape=N_particles) # Result of matrix-vector product
grid_m = ti.field(dtype=ti.f32, shape=(grid_size, grid_size)) # Grid mass
grid_v = ti.field(dtype=ti.f32, shape=(grid_size, grid_size)) # Grid values
grid_mv = ti.field(dtype=ti.f32, shape=(grid_size, grid_size)) # Grid mv values
# Helper function to compute weight and its gradient for MLS
@ti.func
def MLS_weight(fx):
# Quadratic B-spline weights and their gradients
w = ti.Vector.zero(ti.f32, 3)
dw = ti.Vector.zero(ti.f32, 3)
for i in ti.static(range(3)):
x = fx - (i - 1)
abs_x = abs(x)
if abs_x < 0.5:
w[i] = 0.75 - x ** 2
dw[i] = -2 * x
elif abs_x < 1.5:
w[i] = 0.5 * (1.5 - abs_x) ** 2
dw[i] = -ti.math.copysign(1.0, x) * (1.5 - abs_x)
else:
w[i] = 0.0
dw[i] = 0.0
return w, dw
# Matrix-vector product kernel
@ti.kernel
def mvp(v: ti.template(), mv: ti.template()):
# Zero out grid fields
for I in ti.grouped(grid_m):
grid_m[I] = 0.0
grid_v[I] = 0.0
grid_mv[I] = 0.0
# P2G (Particle to Grid)
for p in x:
Xp = x[p] * inv_dx
base = int(ti.floor(Xp - 0.5))
fx = Xp - base
# Weight functions and their gradients
w, dw = MLS_weight(fx)
# Mass and value transfer to grid
for offset in ti.grouped(ti.ndrange(3, 3)):
dpos = (offset - fx)
weight = w[offset.x][0] * w[offset.y][1]
grid_idx = base + offset
# Scatter particle mass and values to grid nodes
if 0 <= grid_idx[0] < grid_size and 0 <= grid_idx[1] < grid_size:
ti.atomic_add(grid_m[grid_idx], particle_mass * weight)
ti.atomic_add(grid_v[grid_idx], v[p] * particle_mass * weight)
# Grid computation (Laplacian)
for I in ti.grouped(grid_m):
if grid_m[I] > 0:
# Normalize grid_v by mass to get nodal values
grid_v[I] /= grid_m[I]
else:
grid_v[I] = 0.0
# Apply Laplacian operator on grid_v to compute grid_mv
for i, j in grid_m:
# Discrete Laplacian (5-point stencil)
center = grid_v[i, j]
laplacian = 0.0
for offset in [ti.Vector([1, 0]), ti.Vector([-1, 0]), ti.Vector([0, 1]), ti.Vector([0, -1])]:
nei = ti.Vector([i, j]) + offset
if 0 <= nei[0] < grid_size and 0 <= nei[1] < grid_size:
laplacian += grid_v[nei[0], nei[1]] - center
grid_mv[i, j] = thermal_conductivity * laplacian / (dx * dx)
# G2P (Grid to Particle)
for p in x:
Xp = x[p] * inv_dx
base = int(ti.floor(Xp - 0.5))
fx = Xp - base
# Weight functions and their gradients
w, dw = MLS_weight(fx)
mv_p = 0.0 # Initialize mv at particle p
for offset in ti.grouped(ti.ndrange(3, 3)):
dpos = (offset - fx)
weight = w[offset.x][0] * w[offset.y][1]
grid_idx = base + offset
if 0 <= grid_idx[0] < grid_size and 0 <= grid_idx[1] < grid_size:
# Gather from grid to particle
mv_p += grid_mv[grid_idx] * weight
# Divide by particle mass (assumed constant here)
mv[p] = mv_p / particle_mass
Explanation:
-
Initialization:
- We define the simulation parameters, such as the number of particles, grid resolution, and other constants.
- We declare the fields for particle positions (
x), input vector (v), and output vector (mv).
- We also define grid fields for mass (
grid_m), values (grid_v), and the result of the matrix-vector product (grid_mv).
-
Helper Function:
MLS_weight(fx) computes the MLS shape functions (quadratic B-spline) and their gradients. This function returns the weights w and their derivatives dw.
-
Matrix-Vector Product Kernel (mvp):
-
Zeroing Grid Fields: We initialize the grid fields to zero at the beginning of the kernel to avoid leftover values from previous iterations.
-
Particle-to-Grid (P2G) Transfer:
- For each particle, we compute its position relative to the grid and calculate the weights and their gradients.
- We loop over the neighboring grid nodes (a 3x3 stencil) and scatter the particle's mass and value to the grid nodes using the computed weights.
- We use
ti.atomic_add because multiple particles may contribute to the same grid node.
-
Grid Computation:
- After P2G, we normalize the grid values (
grid_v) by the grid mass (grid_m) to get the nodal values.
- We apply the Laplacian operator to
grid_v to compute grid_mv. We use a discrete 5-point stencil to approximate the Laplacian.
- The Laplacian is scaled by the thermal conductivity and divided by
dx^2 to account for the discrete spatial steps.
-
Grid-to-Particle (G2P) Transfer:
- We loop over the particles again, compute the weights, and gather the values from the grid back to the particles.
- The result is the product of the system matrix ( \mathbf{A} ) with the input vector ( \mathbf{v} ), stored in
mv[p].
- We divide by the particle mass to obtain the per-particle result (assuming uniform mass for simplicity).
Notes:
- Boundary Conditions: The implementation assumes periodic boundary conditions or zero padding outside the grid. If you have specific boundary conditions, you should handle them appropriately in the grid computation step.
- Mass Matrix: In MPM, the mass matrix is typically lumped and diagonal. By normalizing the grid values by the mass, we're effectively applying ( M^{-1} ) in ( \mathbf{mv} = M^{-1} K \mathbf{v} ).
- Conjugate Gradient Compatibility: This
mvp function can be used within a Conjugate Gradient solver, where you need to compute the matrix-vector product at each iteration without forming the matrix explicitly.
- Optimization: For performance, you may consider optimizing the weight computations and avoiding unnecessary operations, especially when dealing with a large number of particles and grid nodes.
Usage Example:
# Initialize particle positions and input vector v
@ti.kernel
def initialize():
for p in x:
x[p] = ti.Vector([ti.random(), ti.random()])
v[p] = ti.random()
initialize()
# Compute mv = A * v
mvp(v, mv)
Conclusion:
This implementation provides a matrix-free way to compute the matrix-vector product required for solving the 2D heat equation using the Conjugate Gradient method in an MPM simulation. The use of MLS shape functions allows for smooth interpolation and accurate gradient computation, which are essential for the heat equation.