Skip to content

Native coagulation work budgets

Download Python script

Choosing a coagulation timestep from native work diagnostics

Section titled “Choosing a coagulation timestep from native work diagnostics”

Can a bimodal population larger than the former 256-slot limit coagulate without losing collision demand? This example combines Brownian motion, differential settling and turbulent shear in one physical box. Preflight exposes the trial demand before a step; excessive demand raises an error.

The default is explicitly Warp CPU, suitable for inspecting the workflow. Pass device="cuda:0" to simulate for native CUDA; it never falls back. Exact pair reductions have quadratic work even though their storage is linear. The timestep below meets a resource bound, not a numerical accuracy tolerance.

Python · section 1
"""Demonstrate additive native sampling with resource admission and inventories."""
import time
import matplotlib.pyplot as plt
import numpy as np
import warp as wp
from particula.gpu import from_warp_particle_data, to_warp_particle_data
from particula.gpu.kernels.coagulation import (
CoagulationMechanismConfig,
CoagulationWorkConfig,
coagulation_preflight_gpu,
coagulation_step_gpu,
)
from particula.particles import ParticleData
def simulate(device="cpu", sizes=(257, 2000, 5000)):
"""Measure one admitted step for each equal-count bimodal population."""
wp.init()
if device.startswith("cuda") and not wp.is_cuda_available():
raise RuntimeError("This requested run requires native CUDA")
rows = []
for count in sizes:
# Ten percent collector droplets deliberately resolve the minority mode.
small = count - count // 10
radius = np.concatenate(
(
np.geomspace(50e-9, 200e-9, small),
np.geomspace(2e-6, 8e-6, count - small),
)
)
masses = (4 * np.pi / 3 * 1000 * radius**3)[None, :, None]
cpu = ParticleData(
masses=masses,
concentration=np.ones((1, count)),
charge=np.zeros((1, count)),
density=np.array([1000.0]),
volume=np.array([count / 2e9]),
distribution_type="particle_resolved",
)
particles = to_warp_particle_data(cpu, device=device)
config = CoagulationMechanismConfig(
(
"brownian",
"sedimentation_sp2016",
"turbulent_shear_st1956",
)
)
inputs = dict(
temperature=283.15,
pressure=101325.0,
max_collisions=count // 2,
mechanism_config=config,
work_config=CoagulationWorkConfig(max_trials_per_box=256),
turbulent_dissipation=1e-4,
fluid_density=1.2,
)
start = time.perf_counter()
report = coagulation_preflight_gpu(particles, time_step=1.0, **inputs)
inspection_seconds = time.perf_counter() - start
step = min(1000.0, 0.5 * float(report["max_time_step"][0]))
counts = wp.zeros((1, 2), dtype=wp.int32, device=device)
_, _, collisions = coagulation_step_gpu(
particles,
time_step=step,
rng_seed=17,
work_counts=counts,
**inputs,
)
wp.synchronize_device(device)
after = from_warp_particle_data(particles)
initial_mass = np.sum(cpu.masses * cpu.concentration[..., None])
final_mass = np.sum(after.masses * after.concentration[..., None])
np.testing.assert_allclose(final_mass, initial_mass, rtol=2e-14)
np.testing.assert_array_equal(after.charge, 0.0)
accepted = int(collisions.numpy()[0])
assert np.sum(after.concentration) == count - accepted
rows.append(
dict(
particles=count,
timestep_s=step,
collisions=accepted,
scheduled_trials=int(counts.numpy()[0, 0]),
attempted_trials=int(counts.numpy()[0, 1]),
expected_trials_at_1s=float(report["expected_trials"][0]),
workspace_bytes=report["workspace_and_collision_bytes"],
inspection_seconds=inspection_seconds,
)
)
return {"device": device, "warp_version": wp.__version__, "rows": rows}
def plot_results(report):
"""Show demand and selected resource-admitted step without timing claims."""
rows = report["rows"]
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), constrained_layout=True)
sizes = [row["particles"] for row in rows]
axes[0].plot(sizes, [r["expected_trials_at_1s"] for r in rows], "o-")
axes[0].set(xlabel="Active particles", ylabel="Expected trials at 1 s")
axes[1].plot(sizes, [r["timestep_s"] for r in rows], "o-")
axes[1].set(xlabel="Active particles", ylabel="Admitted timestep (s)")
fig.suptitle(f"Brownian + settling + shear — {report['device']}")
return fig

Higher particle counts can require smaller steps even at fixed number density. The outputs verify a complete admitted step and conserved material; they do not establish timestep convergence or physical scavenging accuracy. Preflight timings include first-use compilation and must not be read as kernel benchmarks.

To study rare collectors, repeat with more particles and inspect ensemble and timestep convergence. At a 10^6:1 number ratio, 10,000 equal-count IID samples contain only about 0.01 minority particles in expectation. Removing a cap does not resolve that sampling problem, and unequal weights require another algorithm.

Python · section 2
if __name__ == "__main__":
report = simulate()
print(report)
figure = plot_results(report)
plt.show()
Warp 1.11.1 initialized:
   CUDA Toolkit 12.9, Driver 13.4
   Devices:
     "cpu"      : "CPU"
     "cuda:0"   : "NVIDIA GeForce RTX 5060" (8 GiB, sm_120, mempool enabled)
   Kernel cache:
     <checkout>-cache/warp/1.11.1
Module particula.gpu.kernels.coagulation be5b77f load on device 'cpu' took 1.02 ms  (cached)
Module particula.gpu.kernels.coagulation 6d96d28 load on device 'cpu' took 0.11 ms  (cached)
Module particula.gpu.kernels.environment 0749c5a load on device 'cpu' took 0.10 ms  (cached)
Module particula.gpu.kernels._coagulation_native c1df7de load on device 'cpu' took 0.09 ms  (cached)
Module particula.gpu.kernels._brownian_parallel 10fb4d0 load on device 'cpu' took 0.17 ms  (cached)
Module particula.gpu.kernels._brownian_parallel 8c63643 load on device 'cpu' took 0.13 ms  (cached)
Module particula.gpu.kernels._coagulation_budget 45a9ea0 load on device 'cpu' took 0.09 ms  (cached)
Module particula.gpu.kernels._brownian_parallel 0c1eadd load on device 'cpu' took 1927.96 ms  (compiled)
Module particula.gpu.kernels.coagulation de78f7b load on device 'cpu' took 0.13 ms  (cached)
Module particula.gpu.kernels.coagulation f8eed71 load on device 'cpu' took 0.11 ms  (cached)
{'device': 'cpu', 'warp_version': '1.11.1', 'rows': [{'particles': 257, 'timestep_s': 92.42142091505107, 'collisions': 0, 'scheduled_trials': 64, 'attempted_trials': 64, 'expected_trials_at_1s': 0.6924801562921808, 'workspace_bytes': 32036, 'inspection_seconds': 0.02634848898742348}, {'particles': 2000, 'timestep_s': 23.671902195712104, 'collisions': 4, 'scheduled_trials': 128, 'attempted_trials': 128, 'expected_trials_at_1s': 5.407254513884641, 'workspace_bytes': 152868, 'inspection_seconds': 0.07911499904002994}, {'particles': 5000, 'timestep_s': 9.46585764479806, 'collisions': 6, 'scheduled_trials': 128, 'attempted_trials': 128, 'expected_trials_at_1s': 13.522282375579787, 'workspace_bytes': 332868, 'inspection_seconds': 0.4954371169442311}]}
Native coagulation work budgets: saved scientific figure
Native coagulation work budgets · saved execution output

Explore this topic: Direct kernels