Skip to content
VLASIFY™
TutorialPlasma & PIC simulation

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 ωp=ne2/(ε0me)\omega_p = \sqrt{n e^2/(\varepsilon_0 m_e)}. 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 ω=ωp\omega = \omega_p for a cold plasma.

In normalised units (ε0=1\varepsilon_0 = 1, electron charge −1-1, mass 11, mean density 11), ωp=1\omega_p = 1. Gauss’s law in 1D, ∂E/∂x=ρ\partial E/\partial x = \rho, becomes ikEk=ρkikE_k = \rho_k 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.bincount adds 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 Ek=−iρk/kE_k = -i\rho_k/k. The k=0k = 0 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 ωpΔt<2\omega_p\Delta t < 2.

Verify

Run the script:

python pic1d.py

The measured frequency should be very close to 1 (in units of ωp\omega_p). The leapfrog scheme itself predicts a numerical frequency ωnum=(2/Δt)arcsin⁡(ωpΔt/2)≈1.0001\omega_{num} = (2/\Delta t)\arcsin(\omega_p\Delta t/2) \approx 1.0001 for Δt=0.05\Delta t = 0.05. Grid effects add a small further deviation. Then run three checks:

  1. Halve dt. The result should change only in the fourth decimal place.
  2. 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.
  3. Set dt = 2.1. The leapfrog stability limit ωpΔt<2\omega_p\Delta t < 2 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 = -1 and the ion background +1, a displacement must produce a restoring force. A sign error makes the perturbation grow instead of oscillate.
  • peaks is empty or the period is noisy. Increase N, 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 ω=ωp\omega = \omega_p independent of kk. With temperature, the Bohm–Gross relation ω2=ωp2+3k2vth2\omega^2 = \omega_p^2 + 3k^2v_{th}^2 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

  1. Birdsall & Langdon, Plasma Physics via Computer Simulation (CRC Press) · Standard textbook
  2. Hockney & Eastwood, Computer Simulation Using Particles (CRC Press) · Standard textbook
  3. NRL Plasma Formulary · U.S. Naval Research Laboratory
  4. 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.

Related guides

How Vlasify can help

Get a Quote