template <class T, int dim>
class FractureSimulation : public MpmSimulationBase<T, dim> {
public:
using Base = MpmSimulationBase<T, dim>;
using Base::autorestart;
using Base::begin_time_step_callbacks;
using Base::block_offset;
using Base::cfl;
using Base::dt;
using Base::dx;
using Base::flip_pic_ratio;
using Base::force;
using Base::frame;
using Base::grid;
using Base::mls_mpm;
using Base::num_nodes;
using Base::particle_base_offset;
using Base::particle_group;
using Base::particle_order;
using Base::particles;
using Base::restart_callbacks;
using Base::scratch_gradV;
using Base::start_frame;
using Base::step;
using Base::symplectic;
using Base::transfer_scheme;
bool use_phase_field = false;
bool useNaiveDamage = false; //turn on so we can use the naive damage and compare with PFF!
T sigmaF = 0;
T parabolic_M = 0;
T delete_particle_threshold = 0;
bool lumping = true;
using Simulation = FractureSimulation<T, dim>;
using Objective = PhaseFieldSystem;
if (!use_phase_field) return;
auto& Xarray = particles.X.array;
auto& Varray = particles.V.array;
auto& marray = particles.mass.array;
auto* pf_pointer = &particles.DataManager::get(phase_field_range());
phaseP2G();
/*if (parabolic_M > 0) {
for (uint64_t color = 0; color < (1 << dim); ++color) {
tbb::parallel_for(0, (int) particle_group.size(), [&](int group_idx) {
if ((block_offset[group_idx] & ((1 << dim) - 1)) != color)
return;
for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {
int i = particle_order[idx];
TV &Xp = Xarray[i];
BSplineWeights<T, dim> spline(Xp, dx);
grid.iterateKernel(spline, particle_base_offset[i],
[&](const IV &node, T w, const TV &dw, GridState<T, dim> &g) {
g.phase_field_multiplier += w;
g.phase_field += (*pf_pointer)[i].c * w;
});
}
});
}
grid.iterateGrid([&](IV node, GridState<T, dim> &g) {
g.phase_field /= g.phase_field_multiplier;
});
}
tbb::parallel_for(particles.X.ranges,
[&](DisjointRanges &subrange) {
DisjointRanges subset(subrange,
particles.commonRanges(phase_field_range(),
element_measure_range(),
F_range()));
for (auto iter = particles.subsetIter(subset, phase_field_range(),
element_measure_range(), F_range()); iter; ++iter) {
auto &phase_field = iter.template get<0>();
auto &vol0 = iter.template get<1>();
auto &F = iter.template get<2>();
phase_field.vol = vol0 * F.determinant();
}
});*/
Vec x = Vec::Zero(num_nodes, 1);
Vec rhs = Vec::Zero(num_nodes, 1);
// build rhs
for (uint64_t color = 0; color < (1 << dim); ++color) {
tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {
if ((block_offset[group_idx] & ((1 << dim) - 1)) != color)
return;
for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {
int i = particle_order[idx];
T vol = (*pf_pointer)[i].vol;
TV& Xp = particles.X[i];
BSplineWeights<T, dim> spline(Xp, dx);
grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {
int node_id = g.idx;
if (node_id < 0)
return;
if (parabolic_M > 0) {
rhs(node_id) += (parabolic_M + g.phase_field / dt) * vol * w;
}
else {
rhs(node_id) += vol * w;
}
});
}
});
}
cg_objective.setMultiplier([&](const Vec& x, Vec& b) {
Vec c_scp = Vec::Zero(particles.count, 1);
Mat gradc_scp = Mat::Zero(dim, particles.count);
tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {
for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {
int i = particle_order[idx];
TV& Xp = particles.X[i];
T vol = (*pf_pointer)[i].vol;
BSplineWeights<T, dim> spline(Xp, dx);
grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {
int node_id = g.idx;
if (node_id < 0)
return;
if (!lumping) {
c_scp(i) += x(node_id) * w;
}
gradc_scp.col(i) += x(node_id) * dw;
});
if (!lumping) {
c_scp(i) *= vol * (*pf_pointer)[i].pf_Fp;
}
T l0 = (*pf_pointer)[i].l0;
gradc_scp.col(i) *= vol * (T)4 * l0 * l0;
}
});
b.setZero();
for (uint64_t color = 0; color < (1 << dim); ++color) {
tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {
if ((block_offset[group_idx] & ((1 << dim) - 1)) != color)
return;
for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {
int i = particle_order[idx];
T vol = (*pf_pointer)[i].vol;
TV& Xp = particles.X[i];
BSplineWeights<T, dim> spline(Xp, dx);
grid.iterateKernel(spline, particle_base_offset[i],
[&](IV node, T w, TV dw, GridState<T, dim>& g) {
int node_id = g.idx;
if (node_id < 0)
return;
const PhaseField<T, dim>& phase = (*pf_pointer)[i];
if (!lumping) {
b(node_id) += c_scp(i) * w;
}
else {
if (parabolic_M > 0) {
b(node_id) += vol * (phase.pf_Fp * parabolic_M + (T)1 / dt) * w * x(node_id);
}
else {
b(node_id) += vol * phase.pf_Fp * w * x(node_id);
}
}
if (parabolic_M > 0) {
b(node_id) += gradc_scp.col(i).dot(dw) * parabolic_M;
}
else {
b(node_id) += gradc_scp.col(i).dot(dw);
}
});
}
});
}
});
cg_objective.setPreconditioner([&](const Vec& in, Vec& out) {
if (!lumping) {
out = in;
}
out.setZero();
for (uint64_t color = 0; color < (1 << dim); ++color) {
tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {
if ((block_offset[group_idx] & ((1 << dim) - 1)) != color)
return;
for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {
int i = particle_order[idx];
T vol = (*pf_pointer)[i].vol;
TV& Xp = particles.X[i];
BSplineWeights<T, dim> spline(Xp, dx);
grid.iterateKernel(spline, particle_base_offset[i],
[&](IV node, T w, TV dw, GridState<T, dim>& g) {
int node_id = g.idx;
if (node_id < 0)
return;
const PhaseField<T, dim>& phase = (*pf_pointer)[i];
if (parabolic_M > 0) {
out(node_id) += vol * (parabolic_M * phase.pf_Fp + (T)1 / dt) * w;
}
else {
out(node_id) += vol * phase.pf_Fp * w;
}
});
}
});
}
for (int i = 0; i < num_nodes; ++i)
out(i) = in(i) / out(i);
});
T tolerance = 1e-6;
cg.setTolerance(tolerance);
cg.solve(cg_objective, x, rhs, false);
if (parabolic_M > 0) {
grid.iterateGrid([&](IV node, GridState<T, dim>& g) {
g.phase_field = x(g.idx) - g.phase_field;
});
}
else {
grid.iterateGrid([&](IV node, GridState<T, dim>& g) {
g.phase_field = x(g.idx);
});
}
phaseG2P(); //transfer to particle view to update particle phase
}
void phaseG2P()
{
code
ZIRAN_TIMER();
auto* pf_pointer = &particles.DataManager::get(phase_field_range());
tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {
for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {
int i = particle_order[idx];
if (!(*pf_pointer)[i].allow_damage)
continue;
TV& Xp = particles.X[i];
T pf = (T)0;
BSplineWeights<T, dim> spline(Xp, dx);
grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {
if (g.idx >= 0)
pf += w * g.phase_field;
});
// FLIP
T& c = (*pf_pointer)[i].c;
T new_c;
if (parabolic_M > 0) {
new_c = c + pf;
}
else {
new_c = pf;
}
c = std::max(std::min(c, new_c), (T)0);
}
});
auto ranges = particles.X.ranges;
tbb::parallel_for(ranges,
[&](DisjointRanges& subrange) {
DisjointRanges subset(subrange,
particles.commonRanges(phase_field_range(),
neohookean_borden_range(),
F_range()));
for (auto iter = particles.subsetIter(subset, phase_field_range(), neohookean_borden_range(), F_range()); iter; ++iter) {
auto& phase_field = iter.template get<0>();
auto& model = iter.template get<1>();
auto& F = iter.template get<2>();
T tmp = model.get_psi_pos(F);
phase_field.Update_Phase_Field_Fp(tmp);
T c = phase_field.c;
T k = phase_field.residual_phase;
model.g = c * c * (1 - k) + k;
}
});
}
void solvePhaseFieldSystemNaive()
{
code
auto ranges = particles.X.ranges;
tbb::parallel_for(ranges,
[&](DisjointRanges& subrange) {
DisjointRanges subset(subrange,
particles.commonRanges(phase_field_range(),
neohookean_borden_range(),
F_range()));
for (auto iter = particles.subsetIter(subset, phase_field_range(), neohookean_borden_range(), F_range()); iter; ++iter) {
auto& phase_field = iter.template get<0>();
auto& model = iter.template get<1>();
auto& F = iter.template get<2>();
//T tmp = model.get_psi_pos(F);
//phase_field.Update_Phase_Field_Fp(tmp);
T c = phase_field.c;
T k = phase_field.residual_phase;
//Now, compute c based on naive damage assumption (using sigmaF as our defined threshold)
T J = F.determinant();
TM tau;
typename NeoHookeanBorden<T, dim>::Scratch s;
s.F = F;
s.J = J;
//set model.g to 1 so we compute based on the undegraded principal stress
model.g = 1;
model.kirchhoff(s, tau); //get tau (kirchoff stress)
TM cauchy = ((T)1 / J) * tau;
//Now that we have cauchy stress take eigen value decomposition of it
Eigen::VectorXcd eigenVals = cauchy.eigenvalues(); //TODO: NEED TO CHANGE THIS WHEN SWITCHING BETWEEN FLOAT AND DOUBLE!!!!
T sigmaMax = (T)eigenVals[0].real(); //get the real part of the first eigen value (which shouldnt have be complex anyway lol)
T newC = c;
if (sigmaMax > sigmaF) {
newC = std::min(c, (sigmaF / sigmaMax));
}
//Update c and g
phase_field.c = newC;
model.g = newC * newC * (1 - k) + k;
}
});
}
Implement this in taichi
To implement the given C++ code for a fracture simulation in Taichi, we'll replicate the core functionalities of the FractureSimulation class using Taichi's programming paradigm. This involves setting up the MPM simulation framework, implementing the phase field fracture model, and integrating it into the simulation loop.
Below is a step-by-step guide to help you translate and implement the fracture simulation in Taichi.
1. Initialize Taichi and Set Up Simulation Parameters
First, initialize Taichi and define the simulation parameters such as dimension, grid size, time step, and physical constants.
python
import taichi as ti
ti.init(arch=ti.cpu) # or ti.gpu
# Simulation parameters
dim = 2
real = ti.f32
dt = 1e-4
dx = 0.01
inv_dx = 1 / dx
p_vol = (dx * 0.5) ** dim
p_rho = 1e3
p_mass = p_vol * p_rho
gravity = 9.8
# Grid parameters
N_grid = 128
grid_size = N_grid ** dim
2. Define Fields for Particles and Grid
Create fields to store particle and grid data, including positions, velocities, deformation gradients (F), and the phase field variable (c).
python
# Particle fields
max_num_particles = 100_000
num_particles = ti.field(dtype=ti.i32, shape=())
x = ti.Vector.field(dim, dtype=real, shape=max_num_particles)
v = ti.Vector.field(dim, dtype=real, shape=max_num_particles)
F = ti.Matrix.field(dim, dim, dtype=real, shape=max_num_particles)
c = ti.field(dtype=real, shape=max_num_particles) # Phase field variable
vol = ti.field(dtype=real, shape=max_num_particles) # Volume for each particle
# Grid fields
grid_v = ti.Vector.field(dim, dtype=real)
grid_m = ti.field(dtype=real)
grid_c = ti.field(dtype=real)
grid_c_new = ti.field(dtype=real) # For phase field update
grid = ti.root.dense(ti.ij, N_grid)
grid.place(grid_v, grid_m, grid_c, grid_c_new)
# Additional fields for the linear system solver
A_builder = ti.linalg.SparseMatrixBuilder(grid_size, grid_size, max_num_triplets=grid_size * 5)
rhs = ti.field(dtype=real, shape=grid_size)
3. Initialize Particles
Set up the initial positions, velocities, deformation gradients, phase field variables, and volumes for particles.
python
def initialize_particles():
num_particles[None] = ... # Set the number of particles
for i in range(num_particles[None]):
# Initialize positions (x), velocities (v), deformation gradients (F), etc.
x[i] = ...
v[i] = ...
F[i] = ti.Matrix.identity(real, dim)
c[i] = 1.0 # Initial phase field value (undamaged)
vol[i] = p_vol # Initially, all particles have the same volume
4. Implement Particles-to-Grid (P2G) Transfer
Transfer particle data to the grid, including mass, momentum, and phase field variable.
python
@ti.kernel
def p2g():
# Clear grid
for I in ti.grouped(grid_m):
grid_m[I] = 0
grid_v[I] = ti.Vector.zero(real, dim)
grid_c[I] = 0
grid_c_new[I] = 0
# P2G transfer
for p in range(num_particles[None]):
Xp = x[p]
vp = v[p]
cp = c[p]
vol_p = vol[p]
base = (Xp * inv_dx - 0.5).cast(int)
fx = Xp * inv_dx - base.cast(real)
# Quadratic B-spline weights
w = [0.5 * (1.5 - fx) ** 2, 0.75 - (fx - 1.0) ** 2, 0.5 * (fx - 0.5) ** 2]
for offset in ti.static(ti.grouped(ti.ndrange(*((3,) * dim)))):
weight = 1.0
dpos = (offset.cast(real) - fx) * dx
for d in ti.static(range(dim)):
weight *= w[offset[d]][d]
grid_idx = base + offset
if all(0 <= grid_idx[d] < N_grid for d in ti.static(range(dim))):
idx = grid_idx[0] * N_grid + grid_idx[1] # Flattened grid index
mass_contrib = weight * p_mass
momentum_contrib = weight * p_mass * vp
ti.atomic_add(grid_m[grid_idx], mass_contrib)
ti.atomic_add(grid_v[grid_idx], momentum_contrib)
# Transfer phase field variable
ti.atomic_add(grid_c[grid_idx], weight * vol_p * cp)
5. Assemble and Solve the Phase Field System
Assemble the linear system for the phase field variable and solve it using the Conjugate Gradient method.
python
@ti.kernel
def assemble_phase_field_system():
# Assemble RHS vector
for I in ti.grouped(grid_m):
idx = I[0] * N_grid + I[1]
rhs[idx] = 0
if grid_m[I] > 0:
rhs[idx] = grid_c[I] / grid_m[I] # Average phase field value at grid node
# Assemble stiffness matrix (simplified version)
for I in ti.grouped(grid_m):
idx = I[0] * N_grid + I[1]
if grid_m[I] > 0:
A_builder[idx, idx] += 1.0 # Diagonal entries
# Add off-diagonal entries based on neighbors (Laplace operator)
for offset in ti.static([(-1, 0), (1, 0), (0, -1), (0, 1)]):
J = I + ti.Vector(offset)
if all(0 <= J[d] < N_grid for d in ti.static(range(dim))):
idx_J = J[0] * N_grid + J[1]
A_builder[idx, idx_J] -= 0.25
@ti.kernel
def update_phase_field():
# After solving the linear system, update the grid phase field variable
for I in ti.grouped(grid_m):
idx = I[0] * N_grid + I[1]
grid_c_new[I] = x_cg[idx] # x_cg is the solution vector from the solver
Solve the system using Taichi's built-in sparse solver:
python
def solve_phase_field_system():
assemble_phase_field_system()
A = A_builder.build()
solver = ti.linalg.SparseSolver(solver_type="CG")
solver.analyze_pattern(A)
solver.factorize(A)
global x_cg
x_cg = solver.solve(rhs)
update_phase_field()
6. Update Material Properties Based on Phase Field
Use the updated phase field variable on the grid to update the particles' phase field and adjust material properties accordingly.
python
@ti.kernel
def g2p():
for p in range(num_particles[None]):
Xp = x[p]
base = (Xp * inv_dx - 0.5).cast(int)
fx = Xp * inv_dx - base.cast(real)
# Quadratic B-spline weights
w = [0.5 * (1.5 - fx) ** 2, 0.75 - (fx - 1.0) ** 2, 0.5 * (fx - 0.5) ** 2]
cp_new = 0.0 # New phase field variable for particle p
for offset in ti.static(ti.grouped(ti.ndrange(*((3,) * dim)))):
weight = 1.0
for d in ti.static(range(dim)):
weight *= w[offset[d]][d]
grid_idx = base + offset
if all(0 <= grid_idx[d] < N_grid for d in ti.static(range(dim))):
cp_new += weight * grid_c_new[grid_idx]
c[p] = ti.max(0.0, ti.min(c[p], cp_new)) # Ensure c remains between 0 and initial value
# Update material properties based on c[p]
# For example, adjust stiffness or stress computation
# ...
7. Implement the Rest of the MPM Simulation Loop
Complete the MPM simulation loop by updating grid velocities, applying forces like gravity, and transferring updated velocities back to particles.
python
@ti.kernel
def grid_operations():
for I in ti.grouped(grid_m):
if grid_m[I] > 0:
# Update grid velocity
grid_v[I] = grid_v[I] / grid_m[I]
# Apply gravity
grid_v[I].y -= dt * gravity
# Boundary conditions
if I[0] < 3 or I[0] > N_grid - 3:
grid_v[I].x = 0
if I[1] < 3 or I[1] > N_grid - 3:
grid_v[I].y = 0
@ti.kernel
def g2p_and_update():
for p in range(num_particles[None]):
Xp = x[p]
base = (Xp * inv_dx - 0.5).cast(int)
fx = Xp * inv_dx - base.cast(real)
# Quadratic B-spline weights
w = [0.5 * (1.5 - fx) ** 2, 0.75 - (fx - 1.0) ** 2, 0.5 * (fx - 0.5) ** 2]
vp_new = ti.Vector.zero(real, dim)
for offset in ti.static(ti.grouped(ti.ndrange(*((3,) * dim)))):
weight = 1.0
dpos = (offset.cast(real) - fx) * dx
for d in ti.static(range(dim)):
weight *= w[offset[d]][d]
grid_idx = base + offset
if all(0 <= grid_idx[d] < N_grid for d in ti.static(range(dim))):
vp_new += weight * grid_v[grid_idx]
# Update particle velocity and position
v[p] = vp_new
x[p] += dt * v[p]
# Update deformation gradient F
# ...
# Apply deformation to the phase field variable if needed
# ...
8. Run the Simulation Loop
Combine all steps into a simulation loop, updating particles and grids over time.
python
def run_simulation():
initialize_particles()
for frame in range(num_frames):
for step in range(simulation_steps_per_frame):
p2g()
solve_phase_field_system()
grid_operations()
g2p_and_update()
# Render or output results
# ...
Notes:
Constitutive Model: In the original C++ code, the NeoHookeanBorden model is used, which depends on the phase field variable c. You would need to implement or import an equivalent constitutive model in Taichi and adjust the stress computation based on c[p].
Phase Field Update: The above implementation simplifies the phase field update. In practice, you may need to consider the specific form of the phase field evolution equation, incorporating its dependence on strain energy density and possibly solving a more complex PDE.
Linear System Solver: The assembling of the stiffness matrix A and the RHS vector rhs is simplified. For a more accurate simulation, you'll need to implement the correct terms based on the phase field fracture model you're using.
Optimization: The above code may not be optimized for performance. Consider using advanced techniques like mesh-based assembly, sparse data structures, or multigrid solvers for larger simulations.
Debugging and Verification: Validate each part of your implementation separately. Start with a simple elastic MPM simulation, then add the phase field variable, and finally integrate the fracture mechanics.
References:
Taichi MPM Tutorials: Review the official Taichi examples on MPM simulations to understand the basics.
Phase Field Fracture Models: Research articles and textbooks on phase field modeling of brittle fracture can provide the necessary theoretical background.
By following these steps and adapting the code to your specific needs, you can implement a fracture simulation in Taichi that mirrors the functionality of the provided C++ code. Remember that translating complex simulations requires careful consideration of numerical methods and physical models to ensure accuracy and stability.