Algorithm Search⌘K

Algorithmcore

Boris pusher

Also called Boris algorithm, Boris integrator.

Advances a charged particle in electric and magnetic fields by half an electric kick, a rotation about B and another half kick, preserving phase-space volume.

Time
Θ(N T) worst
Space
Θ(1) extra
Where
N = the number of particles; T = the number of time steps
Properties
conservativedeterministic
Origin
Jay P. Boris, 1970

The Boris pusher is the standard time step for charged particles in plasma particle-in-cell codes. It advances the position and velocity of a particle in given electric and magnetic fields E\mathbf{E} and B\mathbf{B} in three parts: half an electric kick, a rotation of the velocity about B\mathbf{B}, and another half electric kick. The rotation keeps the length of the velocity exactly, so in a pure magnetic field the particle never gains or loses energy, however large the step. The method is second order, time reversible, and it conserves phase space volume, which explains its good behaviour over millions of steps.

In plain words

A charged particle in a magnetic field goes round in circles, and an electric field pushes it along a line. A simple step that follows the push of the magnetic field in a straight line makes the particle drift outward a little on each turn, so it slowly gains energy that it should not have.

The Boris step avoids this. It first gives the particle half of the electric push. Then it turns the velocity by an angle about the magnetic field, without changing its length. Then it gives the second half of the electric push and moves the particle. Because the turn keeps the speed fixed, a particle in a magnetic field alone keeps its energy forever, and the circles stay closed.

The problem

A particle of charge qq and mass mm moves by

dxdt=v,dvdt=qm(E(x)+v×B(x)),\frac{d\mathbf{x}}{dt} = \mathbf{v}, \qquad \frac{d\mathbf{v}}{dt} = \frac{q}{m} \bigl(\mathbf{E}(\mathbf{x}) + \mathbf{v} \times \mathbf{B}(\mathbf{x})\bigr),

with speeds well below the speed of light. The fields are given; in a PIC code they come from the grid. The input is x0\mathbf{x}_0, the velocity v−1/2\mathbf{v}_{-1/2} half a step before t=0t = 0, the step hh and the number of steps TT. The output is xT\mathbf{x}_T and vT−1/2\mathbf{v}_{T - 1/2}. The gyrofrequency is Ω=q∣B∣/m\Omega = q |\mathbf{B}| / m, and in a uniform field B\mathbf{B} the exact velocity turns about B\mathbf{B} by the angle −Ωt-\Omega t.

The algorithm

The step solves the implicit midpoint equation for the velocity,

vn+1/2−vn−1/2h=qm(En+vn+1/2+vn−1/22×Bn),\frac{\mathbf{v}_{n+1/2} - \mathbf{v}_{n-1/2}}{h} = \frac{q}{m} \Bigl(\mathbf{E}_n + \frac{\mathbf{v}_{n+1/2} + \mathbf{v}_{n-1/2}}{2} \times \mathbf{B}_n\Bigr),

in closed form, with the fields at xn\mathbf{x}_n.

  1. BORIS-RUN(x, v, E, B, q/m, h, T)
  2. 1for n ← 1 to T do
  3. 2e ← E(x); b ← B(x)
  4. 3v⁻ ← v + (q h / 2m) e ▷ first half electric kick
  5. 4t ← (q h / 2m) b; s ← 2 t / (1 + |t|²)
  6. 5v′ ← v⁻ + v⁻ × t
  7. 6v⁺ ← v⁻ + v′ × s ▷ rotation about b, |v⁺| = |v⁻|
  8. 7v ← v⁺ + (q h / 2m) e ▷ second half electric kick
  9. 8x ← x + h v
  10. 9return x, v

Lines L3 and L7 are the two halves of the electric impulse. Lines L4 to L6 turn v−\mathbf{v}^- about b\mathbf{b} by the angle −2arctan⁡(Ωh/2)-2 \arctan(\Omega h / 2), where ∣t∣=∣Ω∣h/2|\mathbf{t}| = |\Omega| h / 2. The length of t\mathbf{t} is the tangent of half the angle, and the length of s\mathbf{s} is the sine of the full angle; this pair makes the result have the same length as v−\mathbf{v}^-. Line L8 is the drift of the leapfrog. To start from a velocity v(0)\mathbf{v}(0), set v−1/2\mathbf{v}_{-1/2} by one explicit half step backward; this keeps the method second order.

Example

Take q/m=1q/m = 1, h=1h = 1, B=(0,0,1)\mathbf{B} = (0, 0, 1) and v−1/2=(1,0,0)\mathbf{v}_{-1/2} = (1, 0, 0).

With E=0\mathbf{E} = 0: line L4 gives t=(0,0,0.5)\mathbf{t} = (0, 0, 0.5) and s=(0,0,0.8)\mathbf{s} = (0, 0, 0.8). Line L5 gives v′=(1,−0.5,0)\mathbf{v}' = (1, -0.5, 0), and line L6 gives v+=(1,0,0)+(−0.4,−0.8,0)=(0.6,−0.8,0)\mathbf{v}^+ = (1, 0, 0) + (-0.4, -0.8, 0) = (0.6, -0.8, 0). The speed is still 1, and the velocity has turned clockwise by arctan⁡(0.8/0.6)=2arctan⁡(0.5)≈0.9273\arctan(0.8 / 0.6) = 2 \arctan(0.5) \approx 0.9273, a little less than the exact angle Ωh=1\Omega h = 1.

With E=(0.5,0,0)\mathbf{E} = (0.5, 0, 0): line L3 gives v−=(1.25,0,0)\mathbf{v}^- = (1.25, 0, 0), lines L5 and L6 give v′=(1.25,−0.625,0)\mathbf{v}' = (1.25, -0.625, 0) and v+=(0.75,−1,0)\mathbf{v}^+ = (0.75, -1, 0), and line L7 gives v1/2=(1,−1,0)\mathbf{v}_{1/2} = (1, -1, 0). As a check of the midpoint equation, the mean velocity is (1,−0.5,0)(1, -0.5, 0), its cross product with B\mathbf{B} is (−0.5,−1,0)(-0.5, -1, 0), and E\mathbf{E} plus this is (0,−1,0)(0, -1, 0), which is the change of the velocity.

Correctness

The full proof is in the correctness proof. It shows these facts (all theorems).

  • Lines L3 to L7 return the unique solution vn+1/2\mathbf{v}_{n+1/2} of the implicit midpoint equation above.
  • Lines L4 to L6 are a rotation: ∣v+∣=∣v−∣|\mathbf{v}^+| = |\mathbf{v}^-|, and the angle is 2arctan⁡(∣Ω∣h/2)2 \arctan(|\Omega| h / 2). So with E=0\mathbf{E} = 0 the speed is conserved exactly, for any hh and any field B(x)\mathbf{B}(\mathbf{x}).
  • For uniform fields with E⊥B\mathbf{E} \perp \mathbf{B}, the drift velocity E×B/∣B∣2\mathbf{E} \times \mathbf{B} / |\mathbf{B}|^2 is a fixed point of lines L3 to L7.
  • The step is time reversible when B\mathbf{B} is reversed with the velocity, as the exact motion is.
  • One step, as a map of (x,v)(\mathbf{x}, \mathbf{v}) in R6\mathbb{R}^6, has Jacobian determinant 1 (Qin and coworkers 2013).

The method is second order: it is a symmetric composition of a drift and a velocity map that is itself a symmetric (midpoint) rule. The tests measure an error ratio near 4 when hh is halved.

Proof: The Boris step solves the implicit midpoint equation, rotates the velocity without changing its length, keeps the E×B drift, is time reversible and preserves phase space volumefull

We use the pseudocode of the page and exact arithmetic. Fix one pass of lines L2 to L8 at the position x\mathbf{x}, with e=E(x)\mathbf{e} = \mathbf{E}(\mathbf{x}), b=B(x)\mathbf{b} = \mathbf{B}(\mathbf{x}), a=qh/(2m)a = q h / (2m), t=ab\mathbf{t} = a \mathbf{b}, τ=∣t∣\tau = |\mathbf{t}| and s=2t/(1+τ2)\mathbf{s} = 2\mathbf{t} / (1 + \tau^2). Write v\mathbf{v} for the velocity before the pass, p=v−=v+ae\mathbf{p} = \mathbf{v}^- = \mathbf{v} + a\mathbf{e}, u=v+\mathbf{u} = \mathbf{v}^+, and w=u+ae\mathbf{w} = \mathbf{u} + a\mathbf{e} for the velocity after line L7. We use (a×b)×c=b(a⋅c)−a(b⋅c)(\mathbf{a} \times \mathbf{b}) \times \mathbf{c} = \mathbf{b}(\mathbf{a} \cdot \mathbf{c}) - \mathbf{a}(\mathbf{b} \cdot \mathbf{c}).

Claim 1 (the midpoint equation). w\mathbf{w} is the unique solution of w−v=(qh/m)(e+12(w+v)×b)\mathbf{w} - \mathbf{v} = (q h / m) \bigl(\mathbf{e} + \tfrac{1}{2}(\mathbf{w} + \mathbf{v}) \times \mathbf{b}\bigr).

Proof. Since w−v=u−p+2ae\mathbf{w} - \mathbf{v} = \mathbf{u} - \mathbf{p} + 2a\mathbf{e} and w+v=u+p\mathbf{w} + \mathbf{v} = \mathbf{u} + \mathbf{p}, the equation is the same as

u−p=(u+p)×t.(R)\mathbf{u} - \mathbf{p} = (\mathbf{u} + \mathbf{p}) \times \mathbf{t}. \tag{R}

Uniqueness: if two solutions u1\mathbf{u}_1 and u2\mathbf{u}_2 exist, their difference d\mathbf{d} satisfies d=d×t\mathbf{d} = \mathbf{d} \times \mathbf{t}, so ∣d∣2=d⋅(d×t)=0|\mathbf{d}|^2 = \mathbf{d} \cdot (\mathbf{d} \times \mathbf{t}) = 0. Existence: lines L5 and L6 give D=u−p=v′×s\mathbf{D} = \mathbf{u} - \mathbf{p} = \mathbf{v}' \times \mathbf{s} with v′=p+p×t\mathbf{v}' = \mathbf{p} + \mathbf{p} \times \mathbf{t}. Using (p×t)×t=t(p⋅t)−τ2p(\mathbf{p} \times \mathbf{t}) \times \mathbf{t} = \mathbf{t}(\mathbf{p} \cdot \mathbf{t}) - \tau^2 \mathbf{p},

D=21+τ2(p×t+t(p⋅t)−τ2p).\mathbf{D} = \frac{2}{1 + \tau^2} \bigl(\mathbf{p} \times \mathbf{t} + \mathbf{t}(\mathbf{p} \cdot \mathbf{t}) - \tau^2 \mathbf{p}\bigr).

Then D×t=21+τ2(t(p⋅t)−τ2p−τ2 p×t)\mathbf{D} \times \mathbf{t} = \frac{2}{1 + \tau^2} \bigl(\mathbf{t}(\mathbf{p} \cdot \mathbf{t}) - \tau^2 \mathbf{p} - \tau^2 \, \mathbf{p} \times \mathbf{t}\bigr), and

(u+p)×t=2 p×t+D×t=21+τ2((1+τ2) p×t+t(p⋅t)−τ2p−τ2 p×t)=D.(\mathbf{u} + \mathbf{p}) \times \mathbf{t} = 2\,\mathbf{p} \times \mathbf{t} + \mathbf{D} \times \mathbf{t} = \frac{2}{1 + \tau^2} \bigl((1 + \tau^2)\,\mathbf{p} \times \mathbf{t} + \mathbf{t}(\mathbf{p} \cdot \mathbf{t}) - \tau^2 \mathbf{p} - \tau^2 \, \mathbf{p} \times \mathbf{t}\bigr) = \mathbf{D}.

So u\mathbf{u} satisfies (R). □\square

Claim 2 (a rotation). ∣u∣=∣p∣|\mathbf{u}| = |\mathbf{p}|, and if τ>0\tau > 0 then u\mathbf{u} is p\mathbf{p} turned about the unit vector n=t/τ\mathbf{n} = \mathbf{t} / \tau by the angle −2arctan⁡τ-2 \arctan \tau (right-hand rule). With e=0\mathbf{e} = 0 the speed is conserved exactly.

Proof. The dot product of (R) with u+p\mathbf{u} + \mathbf{p} gives ∣u∣2−∣p∣2=0|\mathbf{u}|^2 - |\mathbf{p}|^2 = 0. The dot product of (R) with t\mathbf{t} gives (u−p)⋅t=0(\mathbf{u} - \mathbf{p}) \cdot \mathbf{t} = 0, so the components along n\mathbf{n} agree. For the components u⊥\mathbf{u}_\perp and p⊥\mathbf{p}_\perp normal to n\mathbf{n}, (R) reads u⊥−p⊥=τJ(u⊥+p⊥)\mathbf{u}_\perp - \mathbf{p}_\perp = \tau J(\mathbf{u}_\perp + \mathbf{p}_\perp) with Jy=y×nJ \mathbf{y} = \mathbf{y} \times \mathbf{n}, which is the turn by −π/2-\pi/2 about n\mathbf{n} in the plane normal to n\mathbf{n}. Identify that plane with C\mathbb{C} so that JJ is multiplication by −i-\mathrm{i}. Then u⊥=1−iτ1+iτp⊥\mathbf{u}_\perp = \frac{1 - \mathrm{i}\tau}{1 + \mathrm{i}\tau} \mathbf{p}_\perp, and 1−iτ1+iτ=e−2iarctan⁡τ\frac{1 - \mathrm{i}\tau}{1 + \mathrm{i}\tau} = e^{-2\mathrm{i} \arctan \tau}. With e=0\mathbf{e} = 0, p=v\mathbf{p} = \mathbf{v} and w=u\mathbf{w} = \mathbf{u}, so ∣w∣=∣v∣|\mathbf{w}| = |\mathbf{v}|. □\square

Since τ=∣q∣∣b∣h/(2m)\tau = |q| |\mathbf{b}| h / (2m), the angle is 2arctan⁡(∣Ω∣h/2)2 \arctan(|\Omega| h / 2), with the sense of −qb-q\mathbf{b}.

Claim 3 (the drift). If e⋅b=0\mathbf{e} \cdot \mathbf{b} = 0, b≠0\mathbf{b} \ne 0 and v=vd=e×b/∣b∣2\mathbf{v} = \mathbf{v}_d = \mathbf{e} \times \mathbf{b} / |\mathbf{b}|^2, then w=vd\mathbf{w} = \mathbf{v}_d.

Proof. vd×b=((e×b)×b)/∣b∣2=(b(e⋅b)−e∣b∣2)/∣b∣2=−e\mathbf{v}_d \times \mathbf{b} = ((\mathbf{e} \times \mathbf{b}) \times \mathbf{b}) / |\mathbf{b}|^2 = (\mathbf{b}(\mathbf{e} \cdot \mathbf{b}) - \mathbf{e} |\mathbf{b}|^2) / |\mathbf{b}|^2 = -\mathbf{e}. So w=vd\mathbf{w} = \mathbf{v}_d makes both sides of the equation of Claim 1 zero, and by uniqueness it is the result. □\square

Claim 4 (time reversibility). Write KB(x,v)K_{\mathbf{B}}(\mathbf{x}, \mathbf{v}) for the result of lines L3 to L7. Then K−B(x,−KB(x,v))=−vK_{-\mathbf{B}}(\mathbf{x}, -K_{\mathbf{B}}(\mathbf{x}, \mathbf{v})) = -\mathbf{v}. Let the forward run produce x0,…,xT\mathbf{x}_0, \ldots, \mathbf{x}_T and v−1/2,…,vT+1/2\mathbf{v}_{-1/2}, \ldots, \mathbf{v}_{T+1/2} (one more kick after the last pass). Then TT passes with B\mathbf{B} replaced by −B-\mathbf{B}, from (xT,−vT+1/2)(\mathbf{x}_T, -\mathbf{v}_{T+1/2}), return (x0,−v1/2)(\mathbf{x}_0, -\mathbf{v}_{1/2}).

Proof. Let w=KB(x,v)\mathbf{w} = K_{\mathbf{B}}(\mathbf{x}, \mathbf{v}). By Claim 1, K−B(x,−w)K_{-\mathbf{B}}(\mathbf{x}, -\mathbf{w}) is the unique z\mathbf{z} with z+w=(qh/m)(e+12(z−w)×(−b))\mathbf{z} + \mathbf{w} = (q h / m)(\mathbf{e} + \tfrac{1}{2}(\mathbf{z} - \mathbf{w}) \times (-\mathbf{b})). Put z=−v\mathbf{z} = -\mathbf{v}: the equation becomes w−v=(qh/m)(e+12(v+w)×b)\mathbf{w} - \mathbf{v} = (q h / m)(\mathbf{e} + \tfrac{1}{2}(\mathbf{v} + \mathbf{w}) \times \mathbf{b}), which holds. For the run, show by induction on kk that the backward state after kk passes is (xT−k,−vT−k+1/2)(\mathbf{x}_{T-k}, -\mathbf{v}_{T-k+1/2}). It holds for k=0k = 0. If it holds for kk, the kick gives K−B(xT−k,−vT−k+1/2)=−vT−k−1/2K_{-\mathbf{B}}(\mathbf{x}_{T-k}, -\mathbf{v}_{T-k+1/2}) = -\mathbf{v}_{T-k-1/2}, because vT−k+1/2=KB(xT−k,vT−k−1/2)\mathbf{v}_{T-k+1/2} = K_{\mathbf{B}}(\mathbf{x}_{T-k}, \mathbf{v}_{T-k-1/2}). The drift gives xT−k−hvT−k−1/2=xT−k−1\mathbf{x}_{T-k} - h \mathbf{v}_{T-k-1/2} = \mathbf{x}_{T-k-1}. □\square

Claim 5 (phase space volume). The map (x,v)↦(x′,w)(\mathbf{x}, \mathbf{v}) \mapsto (\mathbf{x}', \mathbf{w}) of one pass, with x′=x+hw\mathbf{x}' = \mathbf{x} + h \mathbf{w}, has Jacobian determinant 1 when E\mathbf{E} and B\mathbf{B} are differentiable.

Proof. The pass is the composition of four maps of R6\mathbb{R}^6: (1) (x,v)↦(x,v+aE(x))(\mathbf{x}, \mathbf{v}) \mapsto (\mathbf{x}, \mathbf{v} + a\mathbf{E}(\mathbf{x})); (2) (x,p)↦(x,R(x)p)(\mathbf{x}, \mathbf{p}) \mapsto (\mathbf{x}, R(\mathbf{x})\mathbf{p}), where R(x)R(\mathbf{x}) is the rotation of Claim 2; (3) (x,u)↦(x,u+aE(x))(\mathbf{x}, \mathbf{u}) \mapsto (\mathbf{x}, \mathbf{u} + a\mathbf{E}(\mathbf{x})); (4) (x,w)↦(x+hw,w)(\mathbf{x}, \mathbf{w}) \mapsto (\mathbf{x} + h\mathbf{w}, \mathbf{w}). The Jacobians of (1) and (3) are block lower triangular with identity blocks on the diagonal, and that of (4) is block upper triangular with identity blocks, so all three have determinant 1. The Jacobian of (2) is block lower triangular with the diagonal blocks II and R(x)R(\mathbf{x}), and det⁡R(x)=1\det R(\mathbf{x}) = 1 because R(x)R(\mathbf{x}) is a rotation. By the chain rule the determinant of the composition is the product, which is 1. ■\blacksquare

Complexity

In the real-RAM model, one step of one particle costs one evaluation of the fields and a fixed number of arithmetic operations (two cross products, a few additions and one division), so TT steps for NN particles cost Θ(NT)\Theta(N T) time plus the cost of the field evaluations. The extra space is Θ(1)\Theta(1) per particle beyond its position and velocity. The step needs no square root and no trigonometric function.

Properties

  • Exact speed in a magnetic field. The rotation of lines L4 to L6 keeps ∣v∣|\mathbf{v}|, so the kinetic energy is constant when E=0\mathbf{E} = 0.
  • Phase error in the gyration. The angle per step is 2arctan⁡(Ωh/2)2 \arctan(\Omega h / 2) instead of Ωh\Omega h. The relative error is about (Ωh)2/12(\Omega h)^2 / 12 for small Ωh\Omega h. For Ωh≫1\Omega h \gg 1 the particle still moves on a circle of the right radius for its speed, but turns at most by π\pi per step.
  • Correct E×B drift. The drift velocity is exact for uniform fields, for any hh.
  • Volume preserving but not symplectic. Qin and coworkers (2013) showed that the step conserves phase space volume, and that it is not symplectic in general. Volume preservation is one reason why errors do not build up over very long runs (a heuristic: no theorem bounds the energy error of the Boris step for all fields).
  • Time reversible. With B\mathbf{B} reversed, running the step backward returns the start.
  • Explicit. No equation is solved by iteration; the implicit midpoint equation has the closed form solution of lines L3 to L7.

Variants and improvements

  • Relativistic Boris push. Advance u=γv\mathbf{u} = \gamma \mathbf{v} instead of v\mathbf{v}, and use t=qhB/(2mγ)\mathbf{t} = q h \mathbf{B} / (2 m \gamma), with γ\gamma computed from u−\mathbf{u}^-. At very large γ\gamma this variant gives a wrong drift in strong crossed fields, and later pushers change the rotation step to fix it.
  • Exact-angle rotation. Replace t\mathbf{t} by tan⁡(Ωh/2) b/∣b∣\tan(\Omega h / 2) \, \mathbf{b} / |\mathbf{b}|, which makes the gyration angle exact in a uniform field, at the cost of a tangent.
  • Guiding-centre and gyrokinetic codes. When Ωh\Omega h must be large, codes follow the guiding centre instead of the full orbit.
  • Higher order. Symmetric compositions of the Boris step (as for symplectic integrators) give methods of order 4 and higher.

When to use it

Use the Boris pusher for charged particles in any code where magnetic fields matter and the step is a fixed fraction of the gyroperiod, which is the usual case in PIC simulation and in test particle studies. Keep Ωh\Omega h below about 0.5 if the gyration phase must be accurate, since the phase error per step grows as (Ωh)3(\Omega h)^3. For a pure electric field the step reduces to the leapfrog, so it can be used everywhere without a switch. Use a guiding-centre method instead when the gyration is much faster than every other time scale.

Pitfalls

  • The wrong sign of the rotation. The force is qv×Bq \mathbf{v} \times \mathbf{B}, so with q>0q > 0 and B\mathbf{B} along zz the velocity turns clockwise. Swapping the order of the cross product in line L5 or L6 reverses it.
  • Fields at the wrong time. E\mathbf{E} and B\mathbf{B} must be taken at xn\mathbf{x}_n, between the two half-step velocities. In electromagnetic codes B\mathbf{B} is often stored at half steps and must be averaged to whole steps.
  • Mixing up the half steps. The velocity in the output is vT−1/2\mathbf{v}_{T - 1/2}, not v(T)\mathbf{v}(T). Kinetic energy computed from it is off by O(h)O(h), so average vT−1/2\mathbf{v}_{T - 1/2} and vT+1/2\mathbf{v}_{T + 1/2} for diagnostics.
  • Using s=ts = t. With s=t\mathbf{s} = \mathbf{t} the rotation changes the speed by a factor 1+O(∣t∣2)1 + O(|\mathbf{t}|^2) per step, and the energy grows.
  • A large Ωh\Omega h. The step is stable for any Ωh\Omega h, but the gyration angle saturates at π\pi per step, so the motion is wrong in phase even though the radius is right.

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.

boris_pusher.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boris-pusher/. The authors are listed in prov/F8XC41.jsonl.
"""The Boris pusher for a charged particle in electric and magnetic fields.

The equations of motion are dx/dt = v and dv/dt = (q/m)(E(x) + v x B(x)),
nonrelativistic. The positions live at whole steps and the velocities at half
steps (leapfrog). One step is half an electric kick, an exact-length rotation
of the velocity about B, and another half electric kick, then a drift.

The step is the same as the implicit midpoint rule for the velocity,
(v_new - v_old) / h = (q/m) (E + (v_new + v_old)/2 x B), solved in closed form.

Cost: O(1) time and space per particle per step, plus one field evaluation.
"""

import math
from typing import Callable

Vec3 = tuple[float, float, float]
Field = Callable[[Vec3], tuple[Vec3, Vec3]]


def cross(a: Vec3, b: Vec3) -> Vec3:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def boris_velocity(v: Vec3, e: Vec3, b: Vec3, qm: float, h: float) -> Vec3:
    """New half-step velocity from the old one, for the fields e and b at the particle."""
    a = 0.5 * qm * h
    vm = tuple(v[k] + a * e[k] for k in range(3))  # @line L3
    t = tuple(a * b[k] for k in range(3))  # @line L4
    t2 = t[0] ** 2 + t[1] ** 2 + t[2] ** 2  # @line L4
    s = tuple(2 * t[k] / (1 + t2) for k in range(3))  # @line L4
    c = cross(vm, t)  # @line L5
    vp1 = tuple(vm[k] + c[k] for k in range(3))  # @line L5
    c = cross(vp1, s)  # @line L6
    vp = tuple(vm[k] + c[k] for k in range(3))  # @line L6
    return tuple(vp[k] + a * e[k] for k in range(3))  # @line L7


def boris_run(x: Vec3, v_half: Vec3, field: Field, qm: float, h: float, steps: int) -> tuple[Vec3, Vec3]:
    """Advance (x_0, v_{-1/2}) by `steps` Boris steps; return (x_steps, v_{steps-1/2})."""
    x, v = tuple(x), tuple(v_half)
    for _ in range(steps):  # @line L1
        e, b = field(x)  # @line L2
        v = boris_velocity(v, e, b, qm, h)
        x = tuple(x[k] + h * v[k] for k in range(3))  # @line L8
    return x, v  # @line L9


def start_velocity(x: Vec3, v0: Vec3, field: Field, qm: float, h: float) -> Vec3:
    """v_{-1/2} from v(0) by one explicit half step backward (error O(h^2))."""
    e, b = field(x)
    c = cross(v0, b)
    return tuple(v0[k] - 0.5 * h * qm * (e[k] + c[k]) for k in range(3))


def rotation_angle(omega_h: float) -> float:
    """The angle the velocity turns in one step in a pure field B, with omega_h = q |B| h / m."""
    return 2 * math.atan(omega_h / 2)
test_boris_pusher.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boris-pusher/. The authors are listed in prov/F8XC41.jsonl.
import math
import random

import pytest

from boris_pusher import boris_run, boris_velocity, cross, rotation_angle, start_velocity


def norm(a):
    return math.sqrt(sum(c * c for c in a))


def rotate(v, axis, angle):
    """Rodrigues rotation of v about the unit vector axis by angle (right-hand rule)."""
    c, s = math.cos(angle), math.sin(angle)
    kv = cross(axis, v)
    kd = sum(axis[i] * v[i] for i in range(3))
    return tuple(v[i] * c + kv[i] * s + axis[i] * kd * (1 - c) for i in range(3))


def rand_vec(rng, r=1.0):
    return tuple(rng.uniform(-r, r) for _ in range(3))


def field_a(x):
    e = (0.1 * x[0] - 0.05 * x[1], -0.2 + 0.1 * math.cos(x[2]), 0.05 * x[2])
    b = (0.3 + 0.1 * x[1], 0.1 * x[0], 1.0 + 0.2 * math.sin(x[0]))
    return e, b


def flip_b(field):
    def g(x):
        e, b = field(x)
        return e, tuple(-c for c in b)

    return g


def test_page_example():
    assert boris_velocity((1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 1.0, 1.0) == pytest.approx(
        (0.6, -0.8, 0.0), abs=1e-15
    )
    assert boris_velocity((1.0, 0.0, 0.0), (0.5, 0.0, 0.0), (0.0, 0.0, 1.0), 1.0, 1.0) == pytest.approx(
        (1.0, -1.0, 0.0), abs=1e-15
    )
    assert rotation_angle(1.0) == pytest.approx(math.atan2(0.8, 0.6), abs=1e-15)


def test_pure_magnetic_field_is_exact_rotation():
    rng = random.Random(1)
    for _ in range(300):
        v = rand_vec(rng, 3)
        b = rand_vec(rng, 2)
        qm, h = rng.uniform(-2, 2), rng.uniform(0.01, 3)
        got = boris_velocity(v, (0, 0, 0), b, qm, h)
        bn = norm(b)
        axis = tuple(c / bn for c in b)
        # dv/dt = (q/m) v x B turns v about B by the angle -(q/m)|B| t; Boris turns it by -2 atan(Omega h / 2)
        want = rotate(v, axis, -rotation_angle(qm * bn * h))
        assert got == pytest.approx(want, abs=1e-12)
        assert norm(got) == pytest.approx(norm(v), rel=1e-14)


def test_speed_conserved_over_many_steps_in_nonuniform_b():
    def field(x):
        return (0.0, 0.0, 0.0), (0.2 * x[1], 0.1, 1.0 + 0.5 * math.sin(x[0]))

    v0 = (0.3, -0.7, 0.2)
    _, v = boris_run((0.1, 0.2, 0.3), v0, field, 1.3, 0.2, 10000)
    assert norm(v) == pytest.approx(norm(v0), rel=1e-12)


def test_matches_implicit_midpoint_form():
    rng = random.Random(2)
    for _ in range(300):
        v, e, b = rand_vec(rng, 2), rand_vec(rng, 2), rand_vec(rng, 2)
        qm, h = rng.uniform(-2, 2), rng.uniform(0.01, 2)
        w = boris_velocity(v, e, b, qm, h)
        mid = tuple((w[i] + v[i]) / 2 for i in range(3))
        c = cross(mid, b)
        for i in range(3):
            assert (w[i] - v[i]) / h == pytest.approx(qm * (e[i] + c[i]), abs=1e-10)


def test_e_cross_b_drift_is_a_fixed_point():
    rng = random.Random(3)
    for _ in range(100):
        b = rand_vec(rng, 2)
        e0 = rand_vec(rng, 1)
        bb = sum(c * c for c in b)
        eb = sum(e0[j] * b[j] for j in range(3))
        e = tuple(e0[i] - b[i] * eb / bb for i in range(3))  # the part of E normal to B
        vd = tuple(c / bb for c in cross(e, b))
        w = boris_velocity(vd, e, b, rng.uniform(-3, 3), rng.uniform(0.1, 5))
        assert w == pytest.approx(vd, abs=1e-12)


def test_time_reversible_with_b_reversed():
    # Forward: (x_0, v_{-1/2}) -> (x_T, v_{T-1/2}). One more kick gives v_{T+1/2}.
    # Backward from (x_T, -v_{T+1/2}) with B -> -B gives (x_0, -v_{1/2}).
    h, qm, steps = 0.1, 1.0, 400
    x0, vm = (0.5, -0.2, 0.1), (0.2, 0.4, -0.1)
    xt, vt = boris_run(x0, vm, field_a, qm, h, steps)
    e, b = field_a(xt)
    vnext = boris_velocity(vt, e, b, qm, h)
    xb, vb = boris_run(xt, tuple(-c for c in vnext), flip_b(field_a), qm, h, steps)
    e, b = field_a(x0)
    v_half = boris_velocity(vm, e, b, qm, h)
    assert xb == pytest.approx(x0, abs=1e-9)
    assert vb == pytest.approx(tuple(-c for c in v_half), abs=1e-9)


def det(a):
    a = [row[:] for row in a]
    n, d = len(a), 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(a[r][c]))
        if p != c:
            a[c], a[p] = a[p], a[c]
            d = -d
        d *= a[c][c]
        for r in range(c + 1, n):
            f = a[r][c] / a[c][c]
            for k in range(c, n):
                a[r][k] -= f * a[c][k]
    return d


def test_one_step_preserves_phase_space_volume():
    rng = random.Random(4)
    for _ in range(10):
        z = [rng.uniform(-1, 1) for _ in range(6)]
        qm, h = rng.uniform(-2, 2), rng.uniform(0.05, 0.8)

        def step(z):
            x, v = boris_run(tuple(z[:3]), tuple(z[3:]), field_a, qm, h, 1)
            return list(x) + list(v)

        eps = 1e-5
        cols = []
        for k in range(6):
            zp, zm = z[:], z[:]
            zp[k] += eps
            zm[k] -= eps
            fp, fm = step(zp), step(zm)
            cols.append([(fp[i] - fm[i]) / (2 * eps) for i in range(6)])
        jac = [[cols[k][i] for k in range(6)] for i in range(6)]
        assert det(jac) == pytest.approx(1.0, abs=1e-7)


def rk4_run(x, v, field, qm, h, steps):
    def f(z):
        e, b = field(z[:3])
        c = cross(z[3:], b)
        return z[3:] + tuple(qm * (e[i] + c[i]) for i in range(3))

    z = tuple(x) + tuple(v)
    for _ in range(steps):
        k1 = f(z)
        k2 = f(tuple(z[i] + 0.5 * h * k1[i] for i in range(6)))
        k3 = f(tuple(z[i] + 0.5 * h * k2[i] for i in range(6)))
        k4 = f(tuple(z[i] + h * k3[i] for i in range(6)))
        z = tuple(z[i] + h / 6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(6))
    return z[:3]


def test_second_order_convergence():
    x0, v0, qm, t_end = (0.3, 0.1, -0.2), (0.4, -0.3, 0.2), 1.5, 2.0
    ref = rk4_run(x0, v0, field_a, qm, t_end / 2000, 2000)
    errs = []
    for n in (40, 80, 160):
        h = t_end / n
        x, _ = boris_run(x0, start_velocity(x0, v0, field_a, qm, h), field_a, qm, h, n)
        errs.append(norm(tuple(x[i] - ref[i] for i in range(3))))
    for e1, e2 in zip(errs, errs[1:]):
        assert 3.5 < e1 / e2 < 4.5

History

Boris presented the method in 1970 at the Fourth Conference on Numerical Simulation of Plasmas, held at the Naval Research Laboratory in Washington, in a paper on a relativistic hybrid code. Birdsall and Langdon describe it as the standard velocity rotation in their plasma programs. Its long-term accuracy was long known in practice, and Qin, Zhang, Xiao, Liu, Sun and Tang (2013) gave an explanation: the step conserves phase space volume, although it is not symplectic.

References

  1. Jay P. Boris, Relativistic plasma simulation: optimization of a hybrid code, Proceedings of the Fourth Conference on Numerical Simulation of Plasmas, Naval Research Laboratory, Washington DC, November 1970, 3-67
  2. Hong Qin, Shuangxi Zhang, Jianyuan Xiao, Jian Liu, Yajuan Sun and William M. Tang, Why is Boris algorithm so good?, Physics of Plasmas 20(8), 2013, 084503, the proof that the Boris step conserves phase space volume and the remark that it is not symplectic
  3. 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 leapfrog mover with a magnetic field)

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example