Algorithmcore
Particle-in-cell plasma simulation
Also called electrostatic particle-in-cell, electromagnetic particle-in-cell.
Moves charged macroparticles in fields computed on a grid from their deposited charge and current; the main method of kinetic plasma simulation.
- Time
- Θ(T (N + M)) worst
- Space
- Θ(M) extra
- Where
- M = the number of grid points; N = the number of particles; T = the number of time steps
- Model
- Real RAM
- Properties
- conservativedeterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John M. Dawson, Charles K. Birdsall, A. Bruce Langdon, 1962
Particle-in-cell (PIC) plasma simulation solves the kinetic equations of a collisionless plasma by following a large number of charged macroparticles, each of which stands for many real electrons or ions, in fields that are computed on a grid. In each time step the code deposits the charge (and in electromagnetic codes the current) of the particles on the grid, solves the field equations on the grid, interpolates the fields back to the particles, and moves the particles with the Boris pusher or the leapfrog. The particles sample the phase space density of the Vlasov-Poisson system (or Vlasov-Maxwell system), so PIC captures kinetic effects such as Landau damping, beam instabilities and particle acceleration that fluid models miss. The graphics pages particle-in-cell, fluid-implicit-particle and affine-particle-in-cell share the name and the particle to grid transfers, but they carry fluid velocity on the particles and project it to be divergence free; the plasma method carries charge and solves for electric and magnetic fields.
In plain words
A plasma is a hot gas of charged particles, far too many to follow one by one. A PIC code follows a smaller number of heavy, highly charged stand-ins instead. Each stand-in moves like the real particles it represents.
The stand-ins never push each other directly. Instead each one leaves its charge on the nearby points of a fixed grid. The code then works out the electric field on the grid from all the charge at once, which is fast. Each stand-in reads the field at its own place from the same grid points and moves a short time forward. Then the cycle repeats. Because the grid smooths the field over a cell, close collisions between stand-ins are weak, which is what a hot, thin plasma needs.
The problem
In the electrostatic case, the input is a periodic domain of length with grid points, and particles with positions , velocities , charge and mass . The unknown is the phase space density of the electrons, which obeys the Vlasov-Poisson system
in normalized units: , the electrons have , the ions are a fixed background of density 1, times are in units of and lengths in units of , so the Debye length is the thermal speed. The particles are a sample of : each carries and , so that their mean density is 1. The output is the particle state and the grid field at each step, and from them the measured quantities, such as the field energy .
The algorithm
ES-PIC(x[1..N], v[1..N], M, L, h, T) ▷ v given at t = 0- 1
ρ ← CIC-DEPOSIT(x, q_p) + 1 ▷ electrons plus ion background - 2
E ← GAUSS(ρ) ▷ E_{j+1/2} - E_{j-1/2} = Δx ρ_j, mean zero - 3
E_p ← CIC-INTERPOLATE(E, x_p) for every p - 4
v_p ← v_p - (h / 2)(q/m) E_p for every p ▷ start the leapfrog at t = -h/2 - 5
for n ← 1 to T do - 6
v_p ← v_p + h (q/m) E_p for every p - 7
x_p ← (x_p + h v_p) mod L for every p - 8
ρ ← CIC-DEPOSIT(x, q_p) + 1 - 9
E ← GAUSS(ρ) - 10
E_p ← CIC-INTERPOLATE(E, x_p) for every p - 11
record W_n = ½ Σ_j E_j² Δx - 12
return x, v, W
Lines L1 and L8 use cloud-in-cell assignment. Lines L2 and L9 solve Gauss's law with a running sum on the half points, remove the mean, and average to the grid points; this equals minus the centred difference of the potential of the 3-point Poisson equation, so the field kernel is odd. Lines L6 and L7 are the leapfrog; with a magnetic field, line L6 becomes the Boris step. In an electromagnetic code, line L8 also deposits the current, and lines L9 and L10 advance and with the Yee scheme instead of solving Gauss's law.
Example
Take , () and electrons, so . At each grid point gets from the electrons and from the ions, so and .
Now move the first electron to . Line L1 gives : point 0 has an extra half electron and point 1 a missing half. Line L2 gives , and line L3 gives the fields at the four electrons. The forces are : the electrons at 0 and 2.5 move toward point 1, where positive charge is in excess, and the forces sum to 0. With , line L4 gives , line L6 gives , and line L7 moves the first electron to .
A measurement with this code (with lines L1 to L12 and the mode amplitude of recorded): with , , , , electrons, a density perturbation of 1 percent and a quiet start (velocities from the inverse normal distribution at bit-reversed quantiles), the amplitude of the mode of decays at the rate 0.147, fitted over its peaks for from 2.5 to 18, and oscillates at about 1.42. Linear theory gives and (see the Vlasov-Poisson system).
Correctness
The full proof is in the correctness proof. It shows these facts (theorems on the scheme, in exact arithmetic):
- The grid charge is neutral: at every step, because each electron deposits exactly and .
- Lines L2 and L9 return for the mean-free solution of .
- The total momentum does not change in any step, including the start in line L4, because the forces sum to zero (the argument of the cloud-in-cell page).
What PIC computes is a statistical estimate of the solution of the Vlasov equation, not the solution itself. As grows with the grid and the step fixed, the particle density converges to the solution of the semi-discrete Vlasov equation, with a statistical error of order for particles per cell (a heuristic from the central limit theorem, as in Monte Carlo integration). The grid and the leapfrog add errors of order and .
Proof: The electrostatic PIC loop keeps the grid neutral, solves the discrete Poisson equation and conserves the total momentumfull
We use the pseudocode of the page and exact arithmetic. The grid has points, , indices are taken mod , and there are electrons with charge , mass and . We use two results proved on the cloud-in-cell assignment page: (A) the CIC weights of one particle add to 1, and the deposit is while the interpolation is with the same ; (B) if with an odd kernel, , then .
Claim 1 (neutral grid). After lines L1 and L8, .
Proof. The background adds to each of the points, so in total. By (A) the electrons add .
Claim 2 (the field solve). Lines L2 and L9 return , where is the unique mean-free solution of .
Proof. The routine forms for , subtracts the mean of the , and sets , where means . Since , , so the index is consistent with the periodic extension and holds for every mod . Let be the mean-free solution of the 3-point equation; it exists and is unique because the periodic 3-point Laplacian has the constants as its kernel and its range is the grid functions of zero mean. Set , the field at the half point . Then , and because the sum telescopes round the ring. So and have the same differences and both have mean zero, hence . Then .
Claim 3 (the kernel is odd). for an odd kernel .
Proof. By Claim 2, , where is the Green's function of the periodic 3-point Laplacian on mean-free functions. The stencil is symmetric under , and the solution is unique, so is even. The centred difference is a convolution with the odd stencil , . So with odd. An odd kernel sums to zero, so and .
Claim 4 (momentum). Lines L4 and L6 leave unchanged, and line L7 does not change any velocity. So after line L12 equals at the start.
Proof. Line L4 changes by , since . Line L6 changes it by . In both cases comes from a deposit and an interpolation with the same weights (lines L1 and L3, or L8 and L10) and from a field with an odd (Claim 3). By (B), . The background is a constant, which the field solve removes with the mean, so it does not change .
Complexity
In the real-RAM model, lines L1 and L8 cost , lines L2 and L9 cost , lines L3, L6, L7 and L10 cost , and line L11 costs . So steps cost time with extra space beyond the particle arrays. In 2D and 3D with an FFT field solve the cost is , and the particle part dominates in practice because is tens to hundreds of times .
Properties
- Momentum conserving. With the same weights in deposit and interpolation and an odd field kernel, the total momentum is exact (Birdsall and Langdon, Part 2).
- Energy approximately conserved. The total energy is not an exact invariant of the momentum-conserving scheme. It drifts slowly, and much faster when is large compared with , which is the finite grid instability or grid heating. Keep (a rule of thumb, Birdsall and Langdon, Part 2).
- Noisy. The field has statistical noise of relative size about . Quiet starts reduce the initial noise, but the noise returns as particle orbits mix.
- Time step limit. The leapfrog on a plasma oscillation is stable only for ; for accuracy, to 0.2 is usual.
- Collisionless by design. The grid smooths the force below a cell, so close collisions are much weaker than in a real plasma with the same number of particles per Debye sphere; collisions are added by a separate Monte Carlo step when needed.
- Deterministic. With a fixed initial loading, the run has no random choices.
Variants and improvements
- Electromagnetic PIC. The fields and are advanced on a staggered Yee grid, the particles with the Boris pusher. The current is deposited with charge-conserving weights, so that Gauss's law stays true without a separate correction.
- Implicit and energy-conserving PIC. Implicit time steps allow , and some implicit schemes conserve the total energy exactly at the cost of a nonlinear solve per step.
- delta-f PIC. The particles carry only the deviation of from a known equilibrium, which cuts the noise when the deviation is small.
- Higher order shapes. TSC and higher B-splines reduce aliasing and grid heating.
- Monte Carlo collisions. Binary collision models between particles in the same cell add Coulomb collisions or collisions with a neutral gas.
- Gyrokinetic PIC. For strongly magnetized plasmas, the particles follow gyrocentres, which removes the fast gyration from the time step.
When to use it
Use PIC when the physics is kinetic: when the velocity distribution is far from a Maxwellian, when wave-particle resonances matter (Landau damping, beam-plasma instabilities), or when particles are accelerated, as in laser-plasma interaction, magnetic reconnection and plasma sheaths. For a smooth in low dimension, a grid in phase space (a semi-Lagrangian Vlasov solver) has no statistical noise and is often more accurate per unit of cost. For large-scale behaviour close to equilibrium, a fluid model such as magnetohydrodynamics is far cheaper.
Pitfalls
- Grid heating. With several times , a thermal plasma heats up on its own. Resolve the Debye length, or use an energy-conserving or a higher order scheme.
- Too few particles per cell. With a few particles per cell, the noise hides small signals such as a 1 percent wave; a damping rate fitted to noise is meaningless.
- Recurrence and beam instabilities from quiet starts. A start that loads particles in a few cold beams is quiet at first but can become unstable later, so check the result against a second loading.
- Wrong start of the leapfrog. Without the half step back in line L4, the method is only first order and the phase of oscillations is wrong.
- Mixing up the half steps for diagnostics. The kinetic energy must be computed from the mean of the velocities at and , not from one of them.
- Not neutral. A periodic Poisson problem needs zero net charge; forgetting the ion background makes the mean mode undefined.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plasma-particle-in-cell/. The authors are listed in prov/ZFSET4.jsonl.
"""A 1D electrostatic particle-in-cell (PIC) code in the style of ES1.
Normalized units: epsilon_0 = 1, the electrons have charge -1 per unit
density and q/m = -1, and the ions are a fixed uniform background of
density 1. Then the plasma frequency is omega_p = 1 and the Debye length is
lambda_D = v_th, the thermal speed.
The domain is the periodic interval [0, L) with M grid points, dx = L / M.
N simulation particles ("macro-particles") each carry the charge q_p = -L / N
and the mass m_p = L / N, so that their mean density is 1.
Each step: deposit charge with cloud-in-cell weights, solve Gauss's law
dE/dx = rho on the grid, interpolate E to the particles with the same weights,
and push the particles with the leapfrog. Velocities live at half steps.
Cost per step: Theta(N + M) time and Theta(M) extra space.
"""
import math
from typing import Sequence
def deposit(xs: Sequence[float], qp: float, m: int, length: float, background: float = 1.0) -> list[float]:
"""Net charge density on the grid: particle charge by CIC plus the uniform ion background."""
dx = length / m
rho = [background] * m
for x in xs:
s = x / dx
j = math.floor(s)
w = s - j
rho[j % m] += qp * (1 - w) / dx
rho[(j + 1) % m] += qp * w / dx
return rho
def gauss_field(rho: Sequence[float], length: float) -> list[float]:
"""Grid field with E_{j+1/2} - E_{j-1/2} = dx rho_j, zero mean, E_j = (E_{j-1/2} + E_{j+1/2}) / 2.
This equals -(phi_{j+1} - phi_{j-1}) / (2 dx) for the mean-free solution of
the 3-point Poisson equation -(phi_{j+1} - 2 phi_j + phi_{j-1}) / dx^2 = rho_j - mean(rho).
"""
m = len(rho)
dx = length / m
mean = sum(rho) / m
half, acc = [], 0.0
for r in rho:
acc += dx * (r - mean)
half.append(acc) # half[j] = E_{j+1/2} up to a constant
shift = sum(half) / m
half = [e - shift for e in half]
return [(half[j] + half[j - 1]) / 2 for j in range(m)]
def interpolate(field: Sequence[float], xs: Sequence[float], length: float) -> list[float]:
m = len(field)
dx = length / m
out = []
for x in xs:
s = x / dx
j = math.floor(s)
w = s - j
out.append((1 - w) * field[j % m] + w * field[(j + 1) % m])
return out
def field_energy(e: Sequence[float], length: float) -> float:
return 0.5 * sum(v * v for v in e) * length / len(e)
def pic_run(
xs: Sequence[float], vs: Sequence[float], m: int, length: float, h: float, steps: int, qm: float = -1.0
) -> tuple[list[float], list[float], list[float]]:
"""Run the PIC loop from positions x(0) and velocities v(0).
Returns (x_steps, v_{steps-1/2}, W) where W[n] is the field energy at step n,
n = 0, ..., steps.
"""
n = len(xs)
qp = -length / n # electrons of mean density 1
x = [p % length for p in xs]
rho = deposit(x, qp, m, length) # @line L1
e = gauss_field(rho, length) # @line L2
ep = interpolate(e, x, length) # @line L3
v = [u - 0.5 * h * qm * a for u, a in zip(vs, ep)] # @line L4
energies = [field_energy(e, length)]
for _ in range(steps): # @line L5
v = [u + h * qm * a for u, a in zip(v, ep)] # @line L6
x = [(p + h * u) % length for p, u in zip(x, v)] # @line L7
rho = deposit(x, qp, m, length) # @line L8
e = gauss_field(rho, length) # @line L9
ep = interpolate(e, x, length) # @line L10
energies.append(field_energy(e, length)) # @line L11
return x, v, energies # @line L12
test_plasma_particle_in_cell.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plasma-particle-in-cell/. The authors are listed in prov/ZFSET4.jsonl.
import cmath
import math
import random
import pytest
from plasma_particle_in_cell import deposit, field_energy, gauss_field, interpolate, pic_run
def poisson_field_by_dft(rho, length):
"""Oracle: solve -(phi_{j+1} - 2 phi_j + phi_{j-1}) / dx^2 = rho_j - mean by a dense DFT, then E = -centred difference."""
m = len(rho)
dx = length / m
rhat = [sum(rho[j] * cmath.exp(-2j * math.pi * j * k / m) for j in range(m)) for k in range(m)]
phat = [0j] + [rhat[k] * dx * dx / (4 * math.sin(math.pi * k / m) ** 2) for k in range(1, m)]
phi = [sum(phat[k] * cmath.exp(2j * math.pi * j * k / m) for k in range(m)).real / m for j in range(m)]
return [-(phi[(j + 1) % m] - phi[j - 1]) / (2 * dx) for j in range(m)]
def test_page_example():
assert deposit([0.5, 1.5, 2.5, 3.5], -1.0, 4, 4.0) == [0.0, 0.0, 0.0, 0.0]
xs = [0.0, 1.5, 2.5, 3.5]
rho = deposit(xs, -1.0, 4, 4.0)
assert rho == [-0.5, 0.5, 0.0, 0.0]
e = gauss_field(rho, 4.0)
assert e == [-0.125, -0.125, 0.125, 0.125]
assert interpolate(e, xs, 4.0) == [-0.125, 0.0, 0.125, 0.0]
x, v, _ = pic_run(xs, [0.0] * 4, 4, 4.0, 0.5, 1)
assert x == pytest.approx([0.015625, 1.5, 2.484375, 3.5], abs=1e-15)
assert v == pytest.approx([0.03125, 0.0, -0.03125, 0.0], abs=1e-15)
def test_gauss_field_matches_poisson_oracle():
rng = random.Random(1)
for _ in range(40):
m = rng.randint(1, 24)
length = rng.uniform(0.5, 10)
rho = [rng.uniform(-2, 2) for _ in range(m)]
assert gauss_field(rho, length) == pytest.approx(poisson_field_by_dft(rho, length), abs=1e-9)
def test_neutral_plasma_has_zero_net_charge():
rng = random.Random(2)
for _ in range(50):
m, length, n = rng.randint(2, 40), rng.uniform(1, 20), rng.randint(1, 300)
xs = [rng.uniform(0, length) for _ in range(n)]
rho = deposit(xs, -length / n, m, length)
assert sum(rho) * length / m == pytest.approx(0, abs=1e-9)
def test_momentum_conserved_in_a_warm_plasma():
rng = random.Random(3)
length, m, n = 4 * math.pi, 32, 400
xs = [rng.uniform(0, length) for _ in range(n)]
vs = [rng.gauss(0, 1) for _ in range(n)]
x, v, _ = pic_run(xs, vs, m, length, 0.1, 200)
# the first half step changes the momentum by -(h/2) qm sum E_p = 0, so sum v is kept
assert sum(v) == pytest.approx(sum(vs), abs=1e-10)
def test_cold_plasma_oscillates_at_the_plasma_frequency():
length, n, m, h = 2 * math.pi, 256, 32, 0.05
xs = [(i + 0.5) * length / n + 0.01 * math.cos((i + 0.5) * length / n) for i in range(n)]
_, _, w = pic_run(xs, [0.0] * n, m, length, h, 400)
# W(0) is close to the continuum field energy (1/2) delta^2 (L/2) of the displacement delta = 0.01
assert w[0] == pytest.approx(0.5 * 0.01**2 * length / 2, rel=0.03)
# the field energy oscillates at 2 omega_p = 2
peaks = [i for i in range(1, len(w) - 1) if w[i] >= w[i - 1] and w[i] > w[i + 1]]
period = (peaks[-1] - peaks[0]) * h / (len(peaks) - 1)
assert math.pi / period == pytest.approx(1.0, abs=0.02)
def test_field_energy_formula():
assert field_energy([1.0, -1.0, 2.0, 0.0], 2.0) == pytest.approx(0.5 * 6 * 0.5)
History
Dawson (1962) followed a large number of charged sheets in one dimension and measured Debye shielding and the Landau damping of the Fourier modes, which showed that a simulation with far fewer particles than a real plasma can reproduce its collective behaviour. Grid-based methods with charge assignment came next, and Birdsall and Fuss (1969) introduced the clouds-in-cells weighting that is now standard. Birdsall and Langdon (1985, reprinted 1991) wrote the standard text, with the programs ES1 and EM1, and Hockney and Eastwood (1981, second edition 1988) treated plasma simulation together with the other particle-mesh methods.
References
- Charles K. Birdsall and A. Bruce Langdon, Plasma Physics via Computer Simulation, Taylor and Francis, 2004 (reprint of the IOP edition of 1991), Part 1 (the electrostatic program ES1 and the electromagnetic program EM1) and Part 2 (the effects of the spatial grid and of the finite time step)
- Roger W. Hockney and James W. Eastwood, Computer Simulation Using Particles, Adam Hilger, 1988, Chapter 9 (plasma simulation)
- John Dawson, One-dimensional plasma model, The Physics of Fluids 5(4), 1962, 445-459, the charge sheet model and its measurements of Debye shielding and Landau damping
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ZFSET4 Edit this page History Report an error Markdown