Live 1D electrostatic PIC

Fusion simulation in C++ and CUDA

Hyperion

A particle-in-cell plasma simulation I’m building toward magnetic confinement fusion, checked against known physics at every stage.

What you’re looking at: two electron beams passing through each other. Random thermal noise grows exponentially until the beams trap each other in phase-space vortices, which wind around each other and merge. No two loads play out the same. This is the two-stream instability, the physics Stage 2 targets, computed in your browser. The field-energy trace in the corner climbs in a straight line on a log scale, then flattens as the instability saturates. After that the vortex, now an electron hole, drifts through the plasma on its own; the view follows it, which is why the x ticks slide.

Summary

Fusion reactors hold plasma hotter than the sun’s core in place with magnetic fields. Whether that works depends on how billions of charged particles move together, and the only way to see that in detail is to simulate them. Hyperion is my simulation of that plasma, built on the GPU one stage at a time, and every stage has to reproduce physics with a known answer before the next one starts.

Built so far
A CUDA particle engine with real-time rendering, verified against an exact orbital solution.
Shows
GPU programming, numerical methods, tests that check physics against exact answers, and benchmarks with their method written down.
Next
Electrostatic particle-in-cell: 84 million particles on a 128³ grid.

Idea

Plasma behaves like a crowd. Each particle moves in the field all the others make together, and that decides how it has to be simulated.

A tokamak plasma has a density around 1020 particles per cubic metre at roughly 10 keV. Each charge’s field is screened by its neighbours beyond the Debye length, about 74 µm here, and around 1.7×108 particles share each Debye sphere. Individual collisions barely matter. What matters is the collective field all of them make together.

That rules out the tools that work for gravity. A Barnes-Hut tree exists to compute long-range pair forces cheaply, but in a plasma the long range is carried by the field instead. So Hyperion uses particle-in-cell: spread the charge onto a grid, solve for the field there, and push each particle through it. The same family of method runs production fusion codes like GENE, XGC, GTC and OSIRIS.

Architecture

The engine is split so the physics can change without touching anything else.

Interfaces take whole particle buffers, never single particles, so there’s one virtual call per step instead of one per body. Particle state is a structure of arrays, which is what the GPU wants. Next to the fast FP32 CUDA path sits a slow FP64 CPU path whose only job is to be right: the tests check the GPU against it. The renderer reads particle positions straight from GPU memory through CUDA-OpenGL interop, so nothing is copied back to the CPU to draw a frame.

Stage 1 engine: SimState feeds an integrator and a force model. The FP64 CPU force model is the oracle the tests check the FP32 CUDA path against. The GPU writes positions into an OpenGL buffer that the renderer draws without a copy. Physics State Display IIntegratorLeapfrogKdk, Euler, Boris IForceModelwhole-buffer interface GravityCpuFP64, the oracle GravityGpuFP32, CUDA tiled direct sumstepLeapfrog on deviceno host round trip SimStatestructure of arrays: px py pz, vx vy vz, ax ay az, mass ParticleRendererSDL3, OpenGL 4.6 Interop VBOzero copy tests positions
Stage 1 as built. Ice blue marks what runs on the GPU.

Stage 2 swaps the direct sum for the particle-in-cell loop. Each step does four things, and three of them are linear in the number of particles. That’s the point: particle count stops being the limit.

The particle-in-cell loop: deposit charge to the grid, solve for the field with an FFT, gather the field back to each particle, push the particles, and repeat. Depositcharge onto the gridO(N) Solvefield via FFTO(M log M) Gatherfield to each particleO(N) Pushleapfrog stepO(N) every step
N particles, M grid cells. At 128³, M is about 2.1 million.

Design decisions

Each of these had a reasonable alternative. Here’s what I picked and why.

The first four are built and tested in Stage 1. The last four are Stage 2 design, settled before writing the code.

  1. Structure of arrays

    Over an array of particle structs.

    Neighbouring GPU threads read neighbouring memory, so loads coalesce. The original struct Particle was ported, and the Kepler test proved the port changed nothing.

  2. Leapfrog, kick-drift-kick

    Over semi-implicit Euler, the integrator it replaced.

    Second order and symplectic for the same memory: energy stays bounded instead of drifting. At the large timesteps a real-time sim needs, it’s the biggest accuracy gain per cost. Measured: halving dt cuts the error about 4x.

  3. An FP64 oracle checks the FP32 GPU

    Over trusting the kernel because the picture looks right.

    FP64 is 40x slower on this GPU, measured, so the fast path has to be FP32. A slow CPU path in FP64 gives every GPU test a reference. Tests assert finiteness first, because std::max(0, NaN) is 0 and would let a broken kernel pass.

  4. A p99.9 frame-time gate

    Over “never drop below 120 fps”.

    The worst single frame keeps getting worse the longer you measure, so no finite run can pass it. Average ≥ 144 fps and p99.9 ≥ 120 fps keeps the intent and can actually be measured.

  5. Normalized units on the GPU Stage 2

    Over SI units.

    The electron charge squared is 2.6×10−38, only twice FP32’s smallest normal number. In SI, anything that multiplies it by a small length drops into denormals or to zero. In Debye lengths and plasma periods, everything is order one.

  6. Spectral field solve Stage 2

    Over finite-differencing the potential.

    Ek = −ikφk is an exact derivative. It keeps charge deposit and field gather adjoint, so a particle feels no force from itself and total momentum is conserved. Both get their own tests.

  7. The k = 0 mode forced to zero Stage 2

    Over leaving the FFT’s mean term alone.

    It’s the undefined average potential. Left in, it shows up as a slow global drift that looks like a bug somewhere else. Stage 2 has a test just for this.

  8. Periodic boundaries first Stage 2

    Over walls or toroidal geometry from day one.

    The FFT assumes periodicity, and every analytic test (Langmuir, two-stream, ion-acoustic) is a periodic problem. Real geometry needs a different solver, and comes later.

Evidence

Every number here comes from the repository, along with the program that produced it.

Error against timestep on log axes. Euler falls on a slope-one line, first order. Leapfrog falls on a slope-two line, second order, until it reaches the FP64 round-off floor near 1e-5 metres.
Earth–Moon orbit after one hour, error against the exact solution, from metis_bench_convergence. Euler halves its error when dt halves; leapfrog quarters it, until it hits the FP64 round-off floor.
Frames per second against particle count, average and p99.9, with gate lines at 144 and 120 fps. p99.9 drops below 120 fps between 26,880 and 27,136 particles.
RTX 2060, 1280×720, vsync off, rendering included, from metis_bench_noio. The ceiling sits between 26,880 and 27,136 particles. 32,768 still averages 169 fps, but fails p99.9.
The metis_app render loop, 32,768 particles, recorded on an RTX 2060 and sped up 4x. A cold, uniform cloud collapses under its own gravity, rebounds, and settles into a dense core with an ejected halo.

Roadmap

Each stage has to pass physics with a known answer before the next one begins.

  1. Done

    GPU particle engine

    CUDA direct sum, leapfrog on the device, real-time rendering.

    Kepler orbit to 4.8 mm, second-order convergence, GPU against FP64

  2. Designed

    Electrostatic particle-in-cell

    Two species, 128³ grid, cuFFT field solve, about 84 million particles.

    Langmuir oscillation, two-stream growth rate, ion-acoustic dispersion

  3. Planned

    Boris pusher

    Magnetized particles. Tokamak physics starts here.

    Gyrofrequency and Larmor radius, exact

  4. Planned

    Electromagnetic PIC

    Full Maxwell on a Yee grid.

    Energy and momentum, CFL c·dt < dx

  5. Planned

    Gyrokinetics

    Averaging over the fast gyration to reach reactor timescales.