Skip to content

Integrate collisions - #2171

Open
danieljvickers wants to merge 20 commits into
MFlowCode:masterfrom
danieljvickers:integrate-collisions
Open

danieljvickers wants to merge 20 commits into
MFlowCode:masterfrom
danieljvickers:integrate-collisions

Conversation

@danieljvickers

@danieljvickers danieljvickers commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Redo of a previous branch that suffered from compiler errors. This is a more stable version of the same refactor where I have expanded the collision module to include EL particles. This was done by taking the tact of separating the collision subroutines into kernels, which each collision type having its own wrapper kernel. This exposes some common functionality, but does require manual selection of collision kernels for a given type. I am working on way sot alleviate this before merge.

Examples

Head on Collision

Compiler: NVHPC/25.9
Hardware: Nvidia A100

In this example, I perform a head-on collision with an arbitrarily high stokes number, so that the flow does not meaningfully impact the particle motion. I place two particles identically; one stationary and the other moving towards a collision. This test was performed with IBM and EL particles calling the same collision parameters. The difference in final positions of both particles agree to $$10^{-7}$$. The bottom panel plots the velocity of all 4 particles shown over time. You only see two lines because the EL and IBM curves are plotted on top of one another.

head_on_collision.mp4

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Claude Code Review

Head SHA: 50a7055

Files changed:

  • 20
  • src/simulation/m_collisions.fpp
  • src/simulation/m_particles_EL.fpp
  • src/simulation/m_mpi_proxy.fpp
  • src/simulation/m_start_up.fpp
  • src/simulation/m_global_parameters.fpp
  • src/simulation/m_ibm.fpp
  • src/simulation/m_rhs.fpp
  • toolchain/mfc/case_validator.py
  • toolchain/mfc/params/definitions.py
  • toolchain/mfc/test/cases.py

Findings:

  • medium src/simulation/m_particles_EL.fpp: s_build_halo_particles only guarantees capacity for 2*n_sources before appending images, but each source can add up to two images per direction (periodic or reflective at both faces, for example a rank one cell wide in a periodic direction). The worst case is n_sources + 2*n_sources, so s_copy_lag_particle(image, k) in s_append_halo_image could write past particle_cap. Typical cases (at most one image per source) are covered. Suggested fix: grow to 3*n_sources, or check capacity inside s_append_halo_image. Confidence: medium-low, since it needs a degenerate decomposition.
  • medium toolchain/mfc/params/definitions.py: coefficient_of_friction is still registered with the {"ib"} tag (_r("coefficient_of_friction", REAL, {"ib"})), as are coefficient_of_restitution and collision_time. The collision_model requires: ["ib", ...] entry was relaxed so four-way particle cases can run without ib. If the tag controls case-optimization or namelist handling, EL-only cases may not pass these parameters through consistently. Please confirm that particles_lagrange cases without ib accept and broadcast all three parameters. The new 2D_particle_periodic_collision example and an ib=F four-way test would exercise this. Confidence: low.
  • medium src/simulation/m_particles_EL.fpp: the new four-way path (halo exchange, periodic and reflective images, s_apply_EL_collisions) has no regression test. 2D_particle_periodic_collision is excluded in cases.py and verified only by a manual analyze.py. The contributing guide asks for a ppn=2 test for rank-communication changes (a single-rank golden file cannot catch halo bugs). Suggested fix: add a small 2-rank four-way case to cases.py.

@danieljvickers
danieljvickers marked this pull request as ready for review November 18, 2026 22:15
@danieljvickers
danieljvickers requested a review from a team as a code owner November 18, 2026 22:15
@danieljvickers
danieljvickers requested review from sbryngelson and removed request for a team November 18, 2026 22:15
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 57.04467% with 125 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.88%. Comparing base (aae503e) to head (a57f53a).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
src/simulation/m_collisions.fpp 50.58% 65 Missing and 20 partials ⚠️
src/simulation/m_particles_EL.fpp 71.64% 6 Missing and 13 partials ⚠️
src/simulation/m_mpi_proxy.fpp 62.50% 4 Missing and 8 partials ⚠️
src/simulation/m_euler_lagrange.fpp 46.15% 5 Missing and 2 partials ⚠️
src/simulation/m_rhs.fpp 0.00% 0 Missing and 1 partial ⚠️
src/simulation/m_start_up.fpp 75.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2171      +/-   ##
==========================================
+ Coverage   65.75%   65.88%   +0.12%     
==========================================
  Files         111      111              
  Lines       30480    30669     +189     
  Branches     4663     4709      +46     
==========================================
+ Hits        20041    20205     +164     
+ Misses       6687     6660      -27     
- Partials     3752     3804      +52     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sbryngelson

Copy link
Copy Markdown
Member

Review of the full diff, read against the helpers it relies on in master. I did not build or run it. CI is green (49 pass).

What it does

  • Splits the IB soft-sphere collision code into shared kernels: s_perform_soft_sphere_collision, s_soft_sphere_wall_force and s_detect_wall_overlaps.
  • Adds Euler-Lagrange particle collisions as particle_params%coupling = four_way (two-way plus contacts), with a one-cell particle halo across rank faces, periodic images and mirror images at reflective walls.
  • Renames ib_coefficient_of_friction to coefficient_of_friction.
  • Removes the validator rule that rejected periodic and reflective boundaries with particles_lagrange.

The IB path looks like a faithful refactor: same ownership test, same force and torque formulas, same periodic-image decoding. The halo logic also holds up, including across a periodic seam between ranks (received copies are shifted by s_wrap_lag_entity_positions, which wraps relative to the rank's extents).

Before merging

  1. No regression test for the new physics. Four-way coupling, the MPI halo, periodic images and mirror images have no golden test. The one new example is excluded from the test suite ("verified by its analyze.py instead"). The head-on comparison in the description is good evidence, but nothing guards it. A four-way golden on two ranks with a periodic direction would cover most of it.

  2. Periodic and reflective boundaries are now allowed for all particle runs, not only four-way. The deleted rule said the smeared-field boundary routines and particle wrapping were "not yet verified for particles". This PR adds the wrapping, but does not say the smearing at those boundaries was checked for one-way and two-way runs. Could you state that, or add a test?

  3. Possible NaN at a reflective wall. With four-way coupling the wall clamp in s_enforce_EL_particles_boundary_conditions uses offset 0, so a particle that penetrates by a full radius is placed exactly on the wall. Its mirror image is then at the same point, the pair passes the overlap test in s_detect_el_collisions, and s_perform_soft_sphere_collision divides by a zero distance. It takes a badly under-resolved impact, but a guard is cheap.

  4. The pair search is O(N^2) every RK stage. s_detect_el_collisions tests every owned particle against every stored one. Fine for the demo, unusable for large clouds. The comment says "naive"; the docs or the validator should state the practical limit, or it needs a cell list before four-way is advertised.

  5. coefficient_of_friction is never validated. It defaults to dflt_real, and collision_model only requires the restitution coefficient and the collision time. An unset friction coefficient gives a tangential force of about 1e6 times the normal force, with the wrong sign. This predates the PR under the old name, but the rename is a good moment to require it.

  6. The rename breaks existing case files. A case with ib_coefficient_of_friction now gets an unknown-parameter error. Worth a note in the description, or keeping the old name as an alias.

Minor

  • collision_lookup is sized 12*nparticles_glb on every rank and on the device, from the global particle count: a million particles is 48 million integers per rank.
  • The lookup is filled through an atomic counter, so the pair order, and therefore the summation order, varies run to run on GPU. Identical runs will differ at roundoff.
  • In s_perform_soft_sphere_collision, torque_2 and the angular velocities are used whenever torque_1 is present, without their own present checks. Both callers pass all or none, so it works today.
  • s_finalize_collisions_module deallocates under particles_lagrange .or. ib, while the allocation is under max_collisions > 0. They agree in practice.
  • The description says the manual kernel selection is still being reworked "before merge".

Summary

Careful code and a clean refactor. I'd like a four-way golden test and an answer on item 2 before merging; items 3 and 5 are small fixes.

Review written with Claude Code (AI-assisted).

@danieljvickers

Copy link
Copy Markdown
Member Author

@sbryngelson I have addressed all of the comments that I think need addressing. Comments accepted

  • New unit tests added, which has a single test for perioric, normal, and reflected collisions
  • Reflected boundaries have the NaN bug resolved
  • coefficient_of_friction is now validated and defaults ot 0._wp
  • EL particles now have a maximum particles per rank, matching IBs to limit the size of the array
  • Module is finalized appropriately.

Comments on unaddressed changes

  • the N^2 collision detection is defered. @thierrydaoud said he had ideas for specific algorithms that he wanted to try here, so I am just leaving a naive algorithm that works.
  • I am not concerned as much with collisions through pair order, and I have not seen nor believe that this will result in meaningful divergence of code performance. I think taking the time to sort a potentially large array is more harmful than helpful.

I am sure I forgot to mention something, but I went through them yesterday.

@github-actions

Copy link
Copy Markdown

Lines of Code

File Lines Diff
src/simulation/m_collisions.fpp 459 +146
src/simulation/m_particles_EL.fpp 908 +83
src/simulation/m_mpi_proxy.fpp 495 +47
src/simulation/m_euler_lagrange.fpp 308 +19
src/simulation/m_start_up.fpp 1533 +6
src/simulation/m_ibm.fpp 3701 -2
src/common/m_constants.fpp 106 +1
Directory Lines Diff
common 11121 +1
simulation 41185 +299
total 61250 +300

@sbryngelson

Copy link
Copy Markdown
Member

Thanks for this. I read the diff for the GPU pitfalls in docs/documentation/gpuParallelization.md (Silent-Failure
Traps) and did not find a conditional private scalar, an out-of-range patch_ib index or a pre-binding device update in
the new code. Items to settle in the rebase onto master:

  1. Ib collision optimization #2201 replaced s_detect_ib_collisions with a pair bitset. Please take master's detector, and keep
    s_resize_pair_bits (init, under if (ib)) plus the capacity check and s_clear_pair_bits at the end of
    s_apply_IB_collisions. If the clear call is dropped, a pair is found only the first time and collisions stop with no
    error. The finalizer's pair_bits deallocation also needs the if (ib) guard for EL-only runs.
  2. ib_coefficient_of_friction is renamed; examples/3D_mibm_wall_collision/case.py on master (and the open IBM: opt-in friction slip regularisation for soft-sphere collisions #2354) still
    use the old name.
  3. In the EL pair loop, pid2 can be a halo slot, so p_AM(pid2) and particle_dveldt(pid2,:) are read/updated while
    undefined on the device. It does not change the result today, but if (pid2 <= num_particles) around the second update
    avoids the undefined read and the atomics.
  4. contact_point divides by distance; two coincident centers give NaN, which every rank rejects as "not owner", so the
    pair is dropped. A distance < sgm_eps guard would match the one in s_perform_soft_sphere_collision.
  5. After the rebase, please run the two four-way tests on an NVIDIA GPU with 2 ranks on one GPU and on two GPUs (see the
    GPU: send num_procs and proc_rank to the device after the rank is bound to its GPU #2371 entry in the Silent-Failure Traps); AMD CI cannot show that class of bug. s_detect_el_collisions is O(n^2) per
    rank, which is fine as a first version but worth a note in the docs.

AI-assisted (Claude Code).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants