Particle-in-cell simulation tutorial: write a 1D PIC code in Python
Updated · Scientifically reviewed by Dinkar Mishra, PhD on
Short answer
A minimal electrostatic PIC code needs four steps per time step: deposit particle charge on a grid (cloud-in-cell), solve Poisson's equation for the electric field (an FFT on a periodic grid), interpolate the field back to the particles, and push them with a leapfrog integrator. The 1D code below does exactly that in normalised units and is verified by checking that a small density perturbation oscillates at the plasma frequency ωp.
Who this is for
Physics and engineering students, and researchers who use PIC codes and want to understand what happens inside them.
Software
Python ≥ 3.9NumPy ≥ 1.22
Prerequisites
- Python 3.9 or newer with NumPy (
pip install numpy). Matplotlib is optional, for plotting. - Basic familiarity with the plasma frequency . If you want the concepts first, read what is PIC simulation.
Step 1: the physics and units
We simulate a cold, periodic electron plasma with a fixed neutralising ion background. A small sinusoidal displacement of the electrons creates a charge imbalance, and the resulting electric field pulls them back. The plasma oscillates at exactly for a cold plasma.
In normalised units (, electron charge , mass , mean density ), . Gauss’s law in 1D, , becomes in Fourier space.
Step 2: the code
import numpy as np
# Normalised units: eps0 = 1, electron charge -1, mass 1, mean density 1 -> omega_p = 1
L = 2 * np.pi # box length: one wavelength of the perturbation (k = 1)
Ng = 64 # grid cells
N = 20000 # macro-particles
dt = 0.05 # time step: omega_p * dt = 0.05
steps = 400
dx = L / Ng
qm = -1.0 # electron charge-to-mass ratio
q = -L / N # macro-particle charge, so the mean electron density is 1
rho_ion = 1.0 # uniform, immobile ion background
# Quiet start: evenly spaced particles, then a small sinusoidal displacement
x = np.linspace(0.0, L, N, endpoint=False)
x = (x + 0.01 * np.cos(x)) % L
v = np.zeros(N)
k = 2 * np.pi * np.fft.rfftfreq(Ng, d=dx)
def field(x):
"""Cloud-in-cell charge deposit, FFT Poisson solve, E on the grid."""
g = x / dx
i = np.floor(g).astype(int)
w = g - i
rho = np.bincount(i % Ng, weights=1.0 - w, minlength=Ng)
rho += np.bincount((i + 1) % Ng, weights=w, minlength=Ng)
rho = rho * q / dx + rho_ion
rho_k = np.fft.rfft(rho)
E_k = np.zeros_like(rho_k)
E_k[1:] = -1j * rho_k[1:] / k[1:] # i k E_k = rho_k
return np.fft.irfft(E_k, n=Ng), i, w
def gather(E, i, w):
"""Interpolate the grid field to particle positions (same CIC weights)."""
return E[i % Ng] * (1.0 - w) + E[(i + 1) % Ng] * w
# Leapfrog: velocities live at half steps, so start v at t = -dt/2
E, i, w = field(x)
v -= 0.5 * dt * qm * gather(E, i, w)
energy = np.empty(steps)
for n in range(steps):
E, i, w = field(x)
energy[n] = 0.5 * np.sum(E**2) * dx # electrostatic field energy
v += dt * qm * gather(E, i, w)
x = (x + dt * v) % L
# Field energy oscillates at 2*omega_p: measure the period between maxima
t = np.arange(steps) * dt
peaks = [n for n in range(1, steps - 1) if energy[n - 1] < energy[n] > energy[n + 1]]
period = np.mean(np.diff(t[peaks]))
omega = 2 * np.pi / (2 * period)
print(f"measured omega = {omega:.4f} omega_p (cold-plasma theory: 1)")
Step 3: what each part does
- Deposit.
np.bincountadds each particle’s weight to its two nearest grid cells. This is linear “cloud-in-cell” weighting. - Field solve. The FFT turns Gauss’s law into the algebraic relation . The mode is zero because the plasma is neutral overall.
- Gather. Fields are interpolated back with the same weights as the deposit. Using the same weights avoids a spurious self-force on each particle.
- Push. Leapfrog updates velocity, then position. It is second-order accurate and stable for .
Verify
Run the script:
python pic1d.py
The measured frequency should be very close to 1 (in units of ). The leapfrog scheme itself predicts a numerical frequency for . Grid effects add a small further deviation. Then run three checks:
- Halve
dt. The result should change only in the fourth decimal place. - Increase the amplitude from 0.01 to 0.3. Non-linear effects appear and the oscillation is no longer a clean sinusoid. This is a useful lesson in the limits of linear theory.
- Set
dt = 2.1. The leapfrog stability limit is violated and the simulation blows up. Seeing a known instability is part of verification.
This “reproduce an analytical result first” habit is the core of simulation verification.
Troubleshooting
- The measured frequency is far from 1. Check the sign convention: with
qm = -1and the ion background+1, a displacement must produce a restoring force. A sign error makes the perturbation grow instead of oscillate. peaksis empty or the period is noisy. IncreaseN, or make sure the quiet start (evenly spaced particles) is used. Random positions add noise that masks a small perturbation.- The energy grows steadily over time. For thermal plasmas (add
v = vth * np.random.randn(N)), cells larger than the Debye length cause numerical heating. See choosing PIC grid size.
Assumptions and limitations
- One-dimensional, electrostatic, non-relativistic, periodic boundaries, immobile ions and no collisions. These are deliberate simplifications for learning.
- Cold-plasma theory predicts independent of . With temperature, the Bohm–Gross relation applies instead.
- For research, use a maintained, tested code. This script is for education and verification practice.
Frequently asked questions
Why use normalised units?+
Choosing ε0 = 1, electron mass and charge magnitude = 1 and mean density = 1 makes the plasma frequency equal to 1, so times are in units of 1/ωp and lengths in units of c/ωp (or of the Debye length for thermal plasmas). It removes huge and tiny numbers and makes stability limits easy to read.
Why is the velocity shifted by half a time step at the start?+
The leapfrog scheme stores velocities at half-integer times and positions at integer times. This makes it second-order accurate and time-reversible. Shifting v back by half a step with the initial field sets up that staggering correctly.
How do I turn this into a two-stream instability simulation?+
Initialise two counter-propagating electron beams, for example half the particles with v = +v0 and half with v = −v0 plus a small random velocity perturbation, and run longer. The field energy grows exponentially at a rate you can compare with linear theory.
Can this code handle magnetic fields or lasers?+
No. It is electrostatic and one-dimensional. Electromagnetic PIC adds a Maxwell solver (usually the Yee scheme), current deposition and a relativistic Boris pusher. Production codes such as EPOCH, Smilei or WarpX provide these.
References
- Birdsall & Langdon, Plasma Physics via Computer Simulation (CRC Press) · Standard textbook
- Hockney & Eastwood, Computer Simulation Using Particles (CRC Press) · Standard textbook
- NRL Plasma Formulary · U.S. Naval Research Laboratory
- NumPy FFT documentation (numpy.fft) · NumPy
Want this set up and verified for you?
We install, configure and validate scientific software on your workstation, cluster or cloud, and train your team to run it.
Services listed on this page are available today. Products marked “early access” or “in development” on our platform page are not yet generally available.
Spotted an error or an outdated command? Tell us. We correct verified issues promptly.