Here’s an electrostatic particle-in-cell code for collisionless plasmas using Fourier fields and nearest grid point particles that squeezes into 7 lines. It’s set up to simulate the two-stream instability:
using FFTW, Plots;N=128;P=64N;dt=1/4N;NT=1024;w=200/P;Δ=1/N; x=rand(P);v=rand([-1.0,1.0],P);u()=(x.=mod.(x.+v/2*dt,1)); ik=im.*2π*vcat(1,1:N/2,-N/2+1:-1)./N; ic(x)=Int.(ceil.(x));n=zeros(N); @gif for t in 1:NT; u(); E=real.(ifft((E=fft((n.*=0;for j∈x;n[ic(j*N)]+=w;end;n))./ik;E*=0;E))); u(); v+=E[ic(mod.(x*N,N))]*dt;scatter(x,v,ylims=(-3,3)); end every 8
The counter-streaming particles are plotted with velocity against position. Small perturbations to their charge density are unstable. An electrostatic wave, supported by the particles’ charge density, grows exponentially and eventually traps the particles!
P.S. The energy in the electric field and particles are
Edits: collisionless, remove extra