From soccer balls to ferrofluids

A 2021 homework rolled soccer balls across a field and asked whether any two would collide. Rebuilding it properly turned a counting exercise into physics: forces instead of overlaps, spheres that spin, magnetic dipoles that pull them into chains, and a test suite that checks every step against theory and published reference data.

Open the player →

Chapter 1The toy

The original program was small and honest. Each ball is a 4.45-inch disk with a position and a velocity. Every time step it moves by x += v·dt, rolling resistance takes 1% of its speed per second, and a ball that rolls fully over a touchline stops where it is. Before each step the program checks every pair of balls; the first pair closer than two radii ends the game with "Collision occurred between ball i and ball j."

That design has one deep flaw, and it is the same flaw every naive simulation has: it only looks at the world at the sample times.

Chapter 2Balls that pass through each other

The course's own test cases expose it. Six balls start on one diagonal. With a time step of 0.01 s the program correctly reports that balls 2 and 3 collide after 7 steps. With a step of 1.234 s it reports balls 3 and 5; with 10 s steps and four more balls it reports no collision at all. Balls 2 and 3 are heading straight at each other at a combined 438 inches per second. They can't miss, but between two snapshots they simply swap places.

Distance between balls 2 and 3 over time. The exact trajectory reaches the touching distance at 0.06 seconds; the 0.01 s steps follow it down; a single 1.234 s step jumps from 35 inches apart to 505 inches apart without ever sampling the contact.
Distance between balls 2 and 3. Small steps catch the contact at 0.06 s; one big step jumps from 35 to 505 inches apart and never sees it. The faint curve shows what happens next when the balls bounce.

The fix is to stop sampling and solve. Every rolling ball slows at the same rate γ = −ln 0.99, so measured from any moment each ball sits at its start point plus its velocity times a common "distance budget"

s(τ)=1−e−γτγ

Two balls touch when their separation reaches two radii, which is a quadratic in s. Its earliest root, written in a form that avoids cancellation, gives the exact contact time; exits over the touchlines and the moment a ball slows below 1 in/s are solved the same way. Event by event, the answer no longer depends on any time step: balls 2 and 3 meet at t = 0.06036266 s, in all three versions of the test. The rebuilt "legacy" mode still reproduces all five of the original outputs exactly, so the old answers and the corrected ones can be shown side by side.

Chapter 3From collisions to forces

Real particles never "detect" collisions. They push on each other continuously. In the new engine every interaction is a potential energy, and forces are its slope. Close contact is a steep but smooth repulsion (the Weeks–Chandler–Andersen form of Lennard-Jones), and motion is integrated with velocity Verlet, a symplectic scheme: its energy error stays bounded instead of drifting, and it shrinks with the square of the step.

Log-log plot of energy fluctuation against time step, following a line of slope two.
Halve the step and the energy error drops four-fold: measured ratios 3.90 and 3.95.

Chapter 4Giving the balls a spin

Each sphere now has an orientation, stored as a unit quaternion, and an angular velocity. Anything that depends on orientation (today, a magnetic dipole fixed in the sphere) is handed to the physics as a vector in space. One identity then turns every energy into torques as well as forces:

τ=−∑uu×∂U∂u

The engine is written in PyTorch, so automatic differentiation computes ∂U/∂u and ∂U/∂r for every potential. Adding a new interaction means writing one energy function; tests confirm the forces and torques against finite differences to better than one part in a hundred million.

Chapter 5Spin you can see: billiards

Before the spins get magnetic, a detour back to the table the project started from, now with real balls. A pool ball struck by the cue slides: the cloth rubs at its contact point until the spin catches up with the speed, and from then on it rolls. Hit it low and it carries backspin (draw), high and it carries topspin (follow), off-center and it spins about the vertical (english). Sliding friction obeys one tidy law: the speed plus two-fifths of the spin's rim speed stays fixed until the ball rolls. Everything a pool player calls a rule follows from it.

v+25Rω×z^=constvroll=57(1+h)v0

The simulator keeps the soccer chapter's lesson: it never steps through time. Within each kind of motion a ball's position is a quadratic in time, so every collision, cushion hit and pocket drop is the exact root of a polynomial (a quartic for two balls). Balls cannot tunnel, and each collision is computed at the instant the balls touch.

Left: simulated deflection angles of a rolling cue ball lie exactly on the theoretical curve against cut angle, peaking at 33.7 degrees for a half-ball hit. Right: cue ball speed against time for draw, stun, follow and natural-roll strokes, each sliding and then rolling at five sevenths of one plus h times the starting speed.
Two textbook results, reproduced to nine decimal places. Left: the "30° rule" for a rolling cue ball. Right: slide, then roll, at a speed set by where the tip struck.

Then the fun part. Could one stroke sink every ball? From a normal rack, essentially never. But the layout can be designed: a search with the simulator in the loop builds a domino chain in which the cue ball strikes ball 1, each ball knocks the next one on and peels off into a pocket, and the last ball drops too: six balls, six pockets. Each placement is found by scanning the cut angle with exact physics, spin and all, and taking the middle of the window that works; the whole layout counts only if the full simulation reproduces every planned contact.

Top view of the table. The cue ball comes down from the upper left and clips ball 1; balls 1 to 6 sit in a line along the bottom of the table, and each one's path runs from its spot into a different pocket, balls 2 and 3 after banking off the bottom cushion. The cue ball draws back off two cushions and stops near the middle.
One stroke at 5.5 m/s with draw. The cue ball clips ball 1 and the chain fires in half a second: each ball knocks the next one on and peels off, balls 2 and 3 banking off the bottom cushion. All six pockets fill within 3.2 seconds (4 first, 5 last) while the cue ball comes back off two cushions to rest mid-table. Every cut in the chain could be off by up to 0.9° either way and still drop its ball.

Watch it in 3D: numbered balls rolling and spinning on the table, the cue ball's dots turning as it slides and grips, energy and slip plots, every contact in the event log. Open the trick shot →

Chapter 6Magnetism, measured

Two dimensionless numbers describe magnetic spheres in a warm bath. The coupling λ compares the attraction of two touching dipoles with thermal energy; the field strength α compares a dipole's energy in the field with thermal energy:

λ=m2σ3kTα=mBkT

For independent dipoles, statistical mechanics predicts exactly how much they line up with a field: the Langevin function L(α) = coth α − 1/α. Thousands of simulated spinning dipoles, kept at temperature by rotational Langevin dynamics, land on that curve within statistical error at every field tested.

The Langevin function curve with simulated points lying on it at alpha equal to 0.5, 1, 2, 5 and 10.
Theory (line) and simulation (points) for dipoles in a field.
Magnetization stepping up through five field plateaus, tracking the Langevin prediction on each plateau.
Weakly coupled spheres (λ = 1) on a field staircase follow the independent-dipole prediction plateau by plateau.

Chapter 7Chains

Turn the coupling up to λ = 6 and the spheres stop behaving independently. Head-to-tail contact is worth 12 kT, so dipoles snap together into wandering chains and closed rings even with no field at all. At t = 20 the field ramps on. Within a few time units the rings open, the chains swing into line, and nine in ten spheres end up in field-aligned chains averaging 15 spheres long. The magnetization overshoots what independent dipoles could manage (0.88 against 0.80), because the chains help each other along.

Before the field: 512 spheres tangled into curling chains and closed rings, colored by the length of the chain each belongs to. With the field on: the same spheres stand in long vertical chains aligned with the field.
The same 512 spheres before the field (t = 15, left: chains curl and close into rings) and long after it switches on (t = 150, right: chains stand along the field, which points up). Color is chain length, from dark (free) through teal to yellow (24 or more). Rendered offline with OVITO from the run's GSD trajectory.
Left: fraction of spheres in chains rises to about 0.9 while rings vanish after the field turns on. Right: chain alignment and magnetization both rise to about 0.9 after t equals 20.
512 spheres, 150 time units, 3.6 minutes on a laptop. The gold band marks the field ramp.

Watch it happen: the player shows every sphere's dipole as a cone and a marker on its surface turning as it spins. Color them by orientation, by alignment with the field, or by the length of the chain they belong to. Open the player →

EvidenceHow we know it's right

Every claim above is a test that runs on each change. Selected results (float64 on the CPU):

CheckRequirementResult
Forces and torques against finite differences< 10⁻⁶ relative3.6 × 10⁻⁹
NIST Lennard-Jones reference energies and virials (12 cases)all 5 published digits12 / 12
Energy error vs. time step (velocity Verlet)∝ dt² (ratio ≈ 4)3.90, 3.95
Total angular momentum, orbital + spin, over 10⁴ steps< 10⁻¹⁰1.2 × 10⁻¹²
Run backwards to the start after 1000 steps< 10⁻⁸ σ1.5 × 10⁻¹⁴ σ
Dipoles in a field vs. the Langevin functionwithin 3σ at 5 fields≤ 1.1σ
Translational vs. rotational temperatureboth within 2% of target1.003, 1.001
Soccer: original outputs; exact contact timesexact; 50-digit cross-check5 / 5; 10⁻¹²
Billiards: 5/7 rolling speed; 30° rule for a rolling cue ballclosed forms10⁻¹²; 10⁻⁹ °
Billiards: contacts exact, no ball escapes (12 random breaks)< 10⁻⁹ mpass

NextMolecules as graphs

The spheres are the first step. Next, atoms become nodes and bonds become edges of a graph, from which every bond angle, torsion and exclusion follows automatically: hydrogen, nitrogen, oxygen, carbon dioxide, water. After that come rigid multi-site molecules, Ewald sums for charges and dipoles in periodic boxes (checked against NIST's water reference energies), a live mode with sliders for field and temperature, and machine-learned potentials. The engine was built so each of these is a new energy term, not a rewrite.

Open the player →