Files
sps-chapter/numerics.tex
T
Patrick Kilian 9b7b212630 Platz sparen
bei Bildchen und in den Referenzen
2019-04-19 18:47:46 -06:00

1188 lines
70 KiB
TeX

\section{Numerical Implementation}
\label{sec:num}
Particle-in-Cell codes are semi-Lagrangian in that they follow a Lagrangian
description of phase space samples represented as macro particles coupled to
electromagnetic fields described in an Eulerian way on a grid. Connecting the
two parts correctly is crucial in the numerical implementation, but let us
start with the relatively simple step of evolving the electric and magnetic
fields on the grid for one time step.
\subsection{Field Solvers}
\label{sec:num:field}
This subsection discusses how electromagnetic fields are calculated from
source terms (moments of the distribution function of all charged particle
species). The source are assumed to be known on a uniform grid of rectangular
cells. How the source terms are calculated is discussed in section
\ref{subsec:num:depostion}. Non-rectangular grids are discussed in the
review \cite{Meierbachtol_2015}.
%In this subsection we will assume that the source terms that are based on
%moments of the distribution function of all charged species are known on the
%grid. How this is actually accomplished will be discussed in the next
%subsection. We will further more assume that we have a uniform grid of
%rectangular or cubic cells. Triangular or tetrahedral cells are much more
%complicated to deal with and are typically only used when a body-fitted mesh
%around or inside a metal body is needed. More details can be found in the
%review \cite{Meierbachtol_2015}.
Particle-in-Cell codes commonly use a finite difference formulation based on
the electromagnetic fields (as opposed to scalar electrostatic potential and
magnetic vector potential). The typical arrangement of field samples is then
given by the Yee lattice described in \cite{Yee_1966}. Component of the
electric field $E_i$ are located at the mid points of edges pointing in
coordinate direction $x_i$ whereas magnetic flux components $B_i$ are located
at the center of cell phases with have normal vectors pointing in direction
$x_i$.
%In principle the two dual subgrids could be interchanged, but this
%arrangement neatly follows the view of electromagnetism as a discrete exterior
%calculus, where the electric field is a one-form that naturally lives on cell
%edges. The magnetic flux is represented by two-forms assigned to cell phases.
%This view of computational electrodynamics is rather recent but has proven
%useful when designing field solvers on unstructured grids \cite{Rabina_2014, Na_2018}.
The staggered arrangement of components looks complicated as first and the
reader might fear that it will require a lot of re-interpolation. But the
contrary is true as we will see in a moment. We start our consideration from
Maxwell's equation in CGS units. These are still customarily used in
Particle-in-Cell codes as they make the magnitude of electric and magnetic
components similar. Since we treat all material effects due to the plasma
explicitly by having particles react to the fields $\vec{E}$ and $\vec{H}$,
we can use them interchangeably with the respective flux densities $\vec{D}$
and $\vec{B}$.
\begin{align}
\nabla \times \vec{E} &= - \frac{1}{c} \frac{\partial \vec{B}}{\partial t} \label{eq:num:faraday}\\
\nabla \times \vec{B} &= \phantom{-} \frac{1}{c} \frac{\partial \vec{E}}{\partial t} + \frac{4 \pi}{c} \vec{\jmath} \label{eq:num:ampere} \\
\nabla \cdot \vec{E} &= 4 \pi\,\rho \label{eq:num:gauss}\\
\nabla \cdot \vec{B} &= 0 \label{eq:num:monopol}
\end{align}
Gauss's Law in Eq.~\eqref{eq:num:gauss} is the corner stone for electrostatic
Particle-in-cell codes, but we will ignore it for now. It's equivalent for the
magnetic field, Eq.~\eqref{eq:num:monopol}, that describes the absence of
monopole is mostly relevant as an initial condition. Faraday's Law and Ampere's
law can be rewritten as evolution equations:
\begin{align}
\frac{\partial \vec{B}}{\partial t} &= -c \, \nabla \times \vec{E} \label{eq:num:Bevolution} \\
\frac{\partial \vec{E}}{\partial t} &= \phantom{-} c \nabla \times \vec{B} - \frac{4 \pi}{c} \vec{\jmath} \label{eq:num:Eevolution}
\end{align}
This implies that the curl of the electric field does not have to be known at
the location of the electric field, but rather at the location of the dual,
magnetic field.
\begin{figure}[h!]
\centering
\begin{subfigure}{0.4\hsize}
\centering
\includegraphics[width=3cm]{figure/numerics/rotation_yee.png}
\caption{Finite difference approximation in Yee scheme}
\label{fig:num:rot_yee}
\end{subfigure}
\begin{subfigure}{0.4\hsize}
\centering
\includegraphics[width=3.5cm]{figure/numerics/rotation_o4.png}
\caption{Finite difference approximation in simplest $4^{th}$ order scheme}
\label{fig:num:rot_o4}
\end{subfigure}
\caption{$2^{nd}$ and $4^{th}$ order Finite-Difference Time-Domain schemes}
\end{figure}
%%\begin{figure}[h!]
%%\centering
%%\includegraphics[width=0.5\hsize]{figure/numerics/rotation_yee.png}
%%\caption{Finite difference approximation in Yee scheme}
%%\label{fig:num:rot_yee}
%%\end{figure}
%%
%%As figure \ref{fig:num:rot_yee} illustrates, there is an elegant finite
%%difference approximation for the curl of the electric field at the location of
%%the magnetic flux, based on the four edges that surround the magnetic flux at
%%the center of the face. If we write this approximation carefully it reads
%%\begin{align}
%%\left(\nabla \times \vec{E}\right)_x&(i\Delta{x},(j+1/2)\Delta{y},(k+1/2)\Delta{z}) \approx \nonumber \\
%%&\frac{E_y(i\Delta{x},(j+1/2)\Delta{y},k\Delta{z}) - E_y(i\Delta{x},(j+1/2)\Delta{y},(k+1)\Delta{z})}{\Delta{z}} + \nonumber \\
%%&\frac{E_z(i\Delta{x},(j+1)\Delta{y},(k+1/2)\Delta{z}) - E_z(i\Delta{x},j\Delta{y},(k+1/2)\Delta{z})}{\Delta{y}} \quad . \label{eq:num:rot_yee_long}
%%\end{align}
%%This expression is of course rather unwieldy, so customarily the edge length as
%%well as the offsets required to center components along edges and on faces are
%%suppressed and Eq.~\eqref{eq:num:rot_yee_long} is simply written as
%%\begin{equation}
%%\left(\nabla \times \vec{E}\right)_x(i,j,k) \approx
%%\frac{E_y(i,j,k) - E_y(i,j,k+1)}{\Delta{z}} +
%%\frac{E_z(i,j+1,k) - E_z(i,j,k)}{\Delta{y}} \quad . \label{eq:num:rot_yee}
%%\end{equation}
%%When presented with such an expression the reader needs to know that the use of
%%the electric field at locations $k\Delta{z}$ and $(k+1)\Delta{z}$ implies that
%%the magnetic flux (where the curl is used) is located at $(k+1/2)\Delta{z}$.
%%This can make reading papers tedious, but is much more compact and closer to
%%the actual implementation where the array indices into the arrays holding the
%%values of the field components are naturally integers.
%%
The classical solution to store electric and magnetic fields on the grids that yields the curl of the fields at the required position is the Yee grid. Here e.g. $B_y$ is stored at cell face $(i+1/2,j,k+1/2)$, while $E_y$ is stored at $(i,j+1/2,k)$. Not only does this process result in curls calculated at the correct position without interpolation, but the curl is calculated in second order immediately.
The temporal derivative in Eqs.~\eqref{eq:num:Bevolution} and \eqref{eq:num:Eevolution} can be solved using the second-order spatial derivatives. The customary
solution is to leap-frog the fields, i.e. use the curl of the electric field at
time $t\Delta{t}$ to update the magnetic field from time $(t-1/2)\Delta{t}$ to
$(t+1/2)\Delta{t}$ and then use the curl of the magnetic field at that time to
update the electric field to $(t+1)\Delta{t}$. This leads to a scheme that is
also second order accurate in time. However to update the particle position and
location it is useful to have electric and magnetic fields at the position of
the particle at the same time. The solution to this is to split the update of
the magnetic field and use
\begin{align}
\vec{B}^{t\phantom{+1/2}} &= \vec{B}^{t-1/2} - \frac{1}{2} c \cdot \Delta t \cdot \nabla \times \vec{E}^{t} \label{eq:num:B1update} \quad ,\\
\vec{B}^{t+1/2} &= \vec{B}^{t\phantom{-1/2}} - \frac{1}{2} c \cdot \Delta t \cdot \nabla \times \vec{E}^{t} \label{eq:num:B2update} \quad ,\\
\vec{E}^{t+1\phantom{/2}} &= \vec{E}^{t\phantom{-1/2}} + c \cdot \Delta t \cdot \nabla \times \vec{B}^{t+1/2} - 4 \pi \Delta t \cdot \vec{\jmath}^{t+1/2} \label{eq:num:Eupdate} \quad .
\end{align}
This solver is the most common method and is accurate to second order with respect to a given current. Since small numbers of macroparticles lead to an increased noise, solvers are sought after to remove the noise. Increasing particles numbers is typically not an option as the noise level decreases as $1/\sqrt{N}$. Either the source term $\vec{\jmath}^{t+1/2}$ can be filtered or the noise can be damped. The latter is possible since noise is concentrated at high $k$ values. This low-pass filtering is described in \cite{Friedman_1990} and changes Eqs.~\eqref{eq:num:B1update} and \eqref{eq:num:B2update}.
%%This solver works well and is implemented in many codes. However the
%%electromagnetic fields can be rather noisy in Particle-in-cell simulations.
%%There is a limited number of options to combat this. Increasing the number of
%%macro particles to bring it close to the number of physical particles works,
%%but is rather expensive as the noise level only goes down as $1/\sqrt{N}$.
%%Another commonly used method is to filter the the source term
%%$\vec{\jmath}^{t+1/2}$.
%%%FIXME do that below and reference here
%%The third option is to make use of the fact that most of that noise is
%%concentrated at high $k$ and modify the field solver to damp those modes. This
%%is exactly what the method described in \cite{Friedman_1990} does. It replaces
%%Eqs.~\eqref{eq:num:B1update} and \eqref{eq:num:B2update} by
%%\begin{align}
%%\vec{B}^{t+1/2} &= \vec{B}^{t-1/2} - c \cdot \Delta t \cdot \nabla \times \left[\left(1+\frac{\theta}{4}\right)\vec{E}^t-\frac{1}{2}\vec{E}^{t-1}+\left(\frac{1}{2}-\frac{\theta}{4}\right)\vec{\bar{E}}^{t-2}\right]\quad , \label{eq:num:Bupfriedman}\\
%%\vec{\bar{E}}^{t-2} &= \left(1-\frac{\theta}{2}\right)\vec{E}^{t-1} + \frac{\theta}{2}\vec{\bar{E}}^{t-3} \quad .
%%\end{align}
%%If desired Eq.~\eqref{eq:num:Bupfriedman} can be split into two steps to get
%%access to $\vec{B}^t$. The method allows tuneable damping by selecting $\theta$
%%between 0 and 1 at the extra expense of storing and updating $\vec{\bar{E}}$.
%%The damping rate $\gamma$ is given by
%%\begin{equation}
%%\gamma\Delta{t} = - \frac{8\,\theta}{(2-\theta)^2} \left(\frac{c\,\Delta{t}}{\Delta{x}}\right)^4\sin^4\left(\frac{k\,\Delta{x}}{2}\right) \quad .
%%\end{equation}
The one instability that plagues electromagnetic Particle-in-Cell codes and is
the main driver to go beyond the simple and robust field solver described above
is the Numerical Cherenkov Instability. This long known instability (see
\cite{Godfrey_1974}) occurs when particles move close to the speed of light
and couple to light waves. In reality this only happens when then influence of
a medium reduces the speed of light below the vacuum value and particle can
reach the local phase velocity. Numerically this can happen when the numerical
scheme introduces a dispersion error which reduces the speed of light. The
Maxwell solver presented above does that, especially for short wavelength
comparable to the length of the cell edges.
%\begin{figure}[h!]
% \centering
% \includegraphics[width=0.25\hsize]{figure/numerics/rotation_o4.png}
% \caption{Finite difference approximation in simplest $4^{th}$ order scheme}
% \label{fig:num:rot_o4}
%\end{figure}
In other applications of finite-difference time-domain (FDTD) schemes the
solution would typically be to use a higher order approximation of the discrete
curl operator. Fig.~\ref{fig:num:rot_o4} shows how the straight forward
extension to $4^{th}$ order in space would look like.
% The equivalent to Eq.~\eqref{eq:num:rot_yee} reads
The right hand side of Eq.~\eqref{eq:num:Bevolution} now reads
\begin{align}
\left(\nabla \times \vec{E}\right)_x(i,j,k) \approx & \frac{27}{24}\frac{E_y(i,j,k) - E_y(i,j,k+1)}{\Delta{z}} \nonumber \\
& - \frac{E_y(i,j,k-1) - E_y(i,j,k+2)}{\Delta{z}} \nonumber \\
& + \frac{27}{24}\frac{E_z(i,j+1,k) - E_z(i,j,k)}{\Delta{y}} \nonumber \\
& - \frac{E_z(i,j+2,k) - E_z(i,j-1,k)}{\Delta{y}} \label{eq:num:rot_o4}
\end{align}
in this case. Also the temporal derivatives can be approximated in fourth order
\cite{Fang_1989}. For typical PiC simulations with marginal stable time steps
the gain in accuracy is negligible compared to the computational cost.
%It is also possible to make the approximation of the temporal
%derivative accurate to $4{th}$ order in the timestep $\Delta{t}$ as shown in
%\cite{Fang_1989}. The problem is that Particle-in-Cell simulation tend to use
%space and time steps that are just sufficient to get stable results. Using
%substantially smaller steps is usually prohibitively expensive. This means that
%$\lambda/\Delta{x}$ or $\omega \Delta{t}$ tend to be close to unity and the
%difference between second and fourth order is small.
The way forward has therefore been to use schemes that are still ``only''
second order, but with a small constant in front of the error term. Many such
non-standard finite-difference (NSFD) schemes have been investigated over the
years.
%\begin{figure}[h!]
% \centering
% \includegraphics[width=0.25\hsize]{figure/numerics/rotation_m24.png}
% \caption{Finite difference approximation in M24 scheme}
% \label{fig:num:rot_m24}
%\end{figure}
\begin{figure}[h!]
\centering
\begin{subfigure}{0.4\hsize}
\centering
\includegraphics[width=2.84cm]{figure/numerics/rotation_m24.png}
\caption{Finite difference approximation in M24 scheme}
\label{fig:num:rot_m24}
\end{subfigure}
\begin{subfigure}{0.4\hsize}
\centering
\includegraphics[width=6cm]{figure/numerics/rotation_nsfd.png}
\caption{Finite difference approximation in Cole-Karkkainen schemes}
\label{fig:num:rot_ck}
\end{subfigure}
\caption{Non-standard Finite-Difference Time-Domain schemes}
\end{figure}
%\begin{figure}[h!]
%\centering
%\includegraphics[width=0.25\hsize]{figure/numerics/rotation_m24.png}
%\caption{Finite difference approximation in M24 scheme}
%\label{fig:num:rot_m24}
%\end{figure}
One such scheme, proposed by \cite{Hadi_1997} under the name ``M24'' makes use
of the grid locations used by the standard Yee scheme, the locations used by
the fourth order scheme and additional locations that close a larger loop
around the mid point. The relative weights of the three loops are in principle
arbitrary, subject to the constraint that they have to sum to one. The
remaining two free parameters can be tuned to optimize the dispersion
properties of the scheme. The original paper suggests some values, but more
interesting is \cite{Greenwood_2004} that shows how these parameters can be
chosen to reduce NCI.
%\begin{figure}[h!]
% \centering
% \includegraphics[width=0.5\hsize]{figure/numerics/rotation_nsfd.png}
% \caption{Finite difference approximation in Cole-Karkkainen schemes}
% \label{fig:num:rot_ck}
%\end{figure}
So far all schemes only used grid locations at $i\Delta{x}$, but
\cite{Cole_2002} shows that using $(i\pm1)\Delta{x}$ can be useful, at least
for a narrow range of frequencies propagating on the grid. Subsequently
\cite{Karkkainen_2006} extended that to broad bandwidth.
Fig.\ref{fig:num:rot_ck} illustrates all the grid locations that are used in this
family of schemes. Choosing different relative weights between the different
grid locations allows to tune for different optimization goals. An overview is
given in \cite{Vay_2011}.
%Of course the development did not stop at this point, but to keep the page number limited, the interested reader is referred to \cite{Shlager_1993, Garcia_1996, Pukhov_1999, Finkelstein_2006, Yang_2006, Hadi_2007, Smith_2012, Lehe_2013, Blinne_2018} as entry points to further reading on this fascinating topic.
%%Das ist fast eine halbe Seite an Referenzen, die sich daraus ergeben...
% Shlager_1993.pdf Dispersion error of FDTD schemes
% Garcia_1996.pdf construction of high order FDTD in anisotropic dielectrica
% Pukhov_1999.pdf Laser-Plasma simulation with tuned Maxwell solver, open boundaries
% Finkelstein_2006.pdf M24 scheme for low dispersion FDTD
% Yang_2006.pdf nummerically tuned FDTD solvers
% Hadi_2007.pdf finite volume based low dispersion FDTD
% Smith_2012.pdf low-dispersion and low-anisotropy FDTD
% Jung_2013.pdf optimized 2,4 FDTD scheme
% Lehe_2013.pdf NCI suppression with tuned FDTD
% Blinne_2018.pdf optimized FTDT stencils
A different approach is the pseudo-spectral solution of the field equations.
As known from e.g. hydrodynamics the partial differential equations in real space
are converted to ordinary equations in Fourier space. This eliminates finite stencils,
but requires a global FFT \cite{Haber_1973, Jalas_2017}. For constant current density
Maxwell's equations can be integrated analytically in time leading to pseudo-spectral
analytic time domain (PDATD) schemes that are completely free of numerical dispersion.
Since global FFTs require a lot of communication and can limited scalability, there
have been some attempts to avoid them and instead use local FFTs to build field
solvers (\cite{Vay_2013}).
%An old idea that has recently gained traction again is to try field solvers
%that are not based on FDTD schemes, but based on solving Maxwell's equations in
%the spectral domain (\cite{Haber_1973, Jalas_2017}). This requires global FFTs
%to convert the fields between real space and the spectral domain. The upside
%is that there is no need to use a finite stencil that approximates the curl to
%some low order. Instead the differential operator can be expressed as a
%multiplication by $\imath k$ which gives rise to the class of pseudo-spectral
%time domain solvers which have basically infinite stencil order. Under the
%assumption of fixed source terms, i.e. constant current density, is is
%additionally possible to integrate Maxwell's equation analytically in time and
%derive pseudo-spectral analytic time domain (PDATD) schemes that are completely
%free of numerical dispersion. Since global FFTs require a lot of communication
%and can limited scalability, there have been some attempts to avoid them and
%instead use local FFTs to build field solvers (\cite{Vay_2013}) or correction
%methods for more conservative FDTD schemes (\cite{Yu_2016, Li_2017}).
% Jalas_2017.pdf pseudo spectral analytic time domain
% Li_2017.pdf local FFT correction to FTDT to remove NCI
% Yu_2017.pdf yee-fft
% Na_2018b.pdf diagnosing NCI on general meshes
% electrostatic
%%If all particle motion is slow compared to the speed of light life is much
%%easier. Not only do all NCI related problems go away, but it might be possible
%%to remove light waves completely from the plasma model and to reduce
%%computational expense. The straight forward way to do this is the electrostatic
%%plasma model, where the electric field is not updated using an evolution
%%equation based on Amperes Law (Eq.~\eqref{eq:num:Eevolution}), but is directly
%%calculated from Gauss Law (Eq.~\eqref{eq:num:gauss}). This of course limits the
%%electric field to is longitudinal, curl-free component. Bases on
%%Eq.~\eqref{eq:num:Bevolution} this tell us that the magnetic field will not
%%evoluve in time, but is restricted to an initial magnetic field that stays
%%constant in time. Intuitively that makes sense as very slow (comparted to the
%%speed of light) particle motion implies very small currents. Historically some
%%of the first Particle-in-Cell codes were electrostatic (see e.g.
%%\cite{Hockney_1966, Gitomer_1972}) and very also the first to be expressed in
%%implicit form (\cite{Cohen_1989}). Numerically there is several options to
%%solve Eq.~\eqref{eq:num:gauss}. In one spatial dimension direct integration is
%%possible, in higher dimension two methods are worth considering. A basic
%%spectral solver is simple to implementr and the book \cite{Birdsall_2005} has a
%%good overview of the more subtil design trade-off one can make. The other
%%option is a multigrid solver. This is somewhat harder to implement but has the
%%possibility for better parallelisation for large systems, when the FFTs are
%%communication limited.
For the limit of very small particle velocities (as compared to the speed of light) the situation becomes much simpler. This is the electrostatic limit, where electric fields are calculated using Gauss Law (Eq.~\eqref{eq:num:gauss}) and magnetic fields are no longer time dependent. This of course limits the electric field to is longitudinal, curl-free component. Historically some of the first Particle-in-Cell codes were electrostatic (see e.g. \cite{Hockney_1966, Gitomer_1972}). Gauss Law can be solved in higher dimensions using either spectral solvers \cite{Birdsall_2005} or multigrid solvers.
% darwin
%%Between the electrostatic and electromagnetic plasma model that is rarely
%%considered, but can be very effective and successfull in its domain of
%%application. In the Darwin approximation \cite{Darwin_1920}, effects up to
%%order $\mathcal{O}((v/c)^2)$ are retained, which allows for magnetic field
%%fluctuations but removes light waves. Alternatively it can be though of the
%%approximation where the time retardation due to the finite speed of light is
%%removed. Aquivalently the divergence-free part of the displacement current is
%%removed, which explicitly removes lightwaves from the problem. Interestingly
%%all these approximation turn out to be identically as demonstrated by
%%\cite{Krause_2007}. Some codes have been implemented in this approximation (see
%%e.g. \cite{Eremin_2013}). The approximation does however change the natural of
%%the system of differential equations to elliptic, requiring a global field
%%solve in every time step. This makes the timestep more expensive and can limit
%%scalability. Thus the Darwin approximation only results in a net speed up if
%%the time step covers a much longer duration then the CFL limit for an
%%electromagnetic code. Another limitation to keep in mind is that some low
%%frequency modes that are not ordered out are still modified as demonstrated by
%%\cite{Xie_2014}.
%%
%%The Vlasov-Poiswell model that only retains effects up to $\mathcal{O}(v/c)$
%%can be formulated in a consistent manner (see \cite{Besse_2007}), but is rarely
%%used in practice.
Besides the domain of electrostatic and electromagnetic models there is another intermediate regime called Darwin approximation \cite{Darwin_1920} which includes magnetodynamic effects up to order $\mathcal{O}((v/c)^2)$, but which does not consider light waves. This equivalent to removing the divergence-free part of the displacement current. While time resolution constraints are relaxed since the speed of light is no longer present, the differential equations representing the electromagnetic field are now elliptic requiring a global field solver.
\subsection*{Interpolation}
The previous section only discussed Eulerian quantities on the regular grid.
But the electromagnetic fields act on the Lagranian particles, which requires
knowledge of the field strength at the location of the particle, not just at
the regular grid locations. This crutial switch in view point is done by means
of an interpolation that we will discuss next.
\begin{figure}[h!]
\centering
\includegraphics[width=0.25\hsize]{figure/numerics/interpolation.png}
\caption{Interpolation using the overlap between the cell and the particle, weightes by the shape function}
\label{fig:num:interpolation}
\end{figure}
Fig.~\ref{fig:num:interpolation} illustrates how the interpolation from grid
quantities (magnetic field $B_z$ in this case) to the particle location is
done. The computational macro-particle represents a large number of physical
particles and is thus seen as a chunk of phase space with a density
distribution over a finite extend. The fraction of particle that fall in the
cell are used as a weigth to multiply the field strength at the center of that
cell. Contributions from different cells are then added up to compute the mean
magnetic field strength at the particle location. In a single dimension, this calculation can be expressed by
\begin{equation}
\bar{B}_z(x_p) = \sum_{i} B_z((i+1/2)\Delta{x}) \cdot \int_{i\Delta{x}}^{(i+1)\Delta{x}} S(x - x_p)\, \mathrm{d}x \quad .
\end{equation}
Since this calculation is required for all particles and all field components
in each timestep, the integral over the shape function $S$ is not performed
numerically, but rather done analytically ahead of time to obtain the weight
function $W$:
\begin{equation}
W(x) = \int_{-\Delta{x}/2}^{\Delta{x}/2} S(x - x'), \mathrm{d}x' \quad .
\end{equation}
Using this and suppressing the explicit location of the gridded quantity in the
cell we can write the two-dimensional interpolation as
\begin{equation}
\bar{B}_z(\vec{x}_p) = \sum_{i,j} B_z(i,j) \cdot W(x_p-(i+1/2)\Delta{x}) \cdot W(y_p - (j+1/2)\Delta{y}) \label{eq:num:Bzinterpol}\quad .
\end{equation}
Many different choices for the shape function $S$ are possible and different
codes make different design choices here. Some properties are however required.
The shape function has to be normalized, i.e.
$\int_{-\infty}^{\infty}S(x)\,\mathrm{d}x = 1$ and should be symmetric, i.e.
$S(-x) = S(x)$. To allow efficient evaluation of
Eq.~\eqref{eq:num:Bzinterpol}, the shape function should have compact support,
i.e. be non-zero only up to some small $x_{max}$.
In principle all these properties are satiesfied by a $\delta$-function. This
use of $S(x) = \delta(x)$ is also refered to as \textit{Nearest Grip Point} or
NGP scheme. Computationally it is very cheap, as no interpolation or summation
has to be done, we just assume that the field at the particle location is
identical to nearest available field on a grid locaton. The downside however is
that the field that particles see is non-contiguous and the current induced by
particles using this shape function switches from one cell to another when an
interface is crossed. This leads to a high level of numerically induced
fluctuations in the source terms and consequently the fields.
The Cloud-in-Cell efficiently the algorithm by \cite{Birdsall_1968} has a major
step forward in the performance and usefulness of Particle-in-Cell codes. Here
each particle is viewed as a cloud of constant density and with the same size
as a grid cell (but freely movable relative to the grid). The shape function
that generates that view is given by
\begin{equation}
S_{CIC}(x) = \left\{
\begin{array}{ll}
1 & |x|\leq 1/2 \\
0 & \mathrm{else}
\end{array}
\right.
\end{equation}
and illustrated in Fig.~\ref{fig:num:S_CIC}. The associated weight function $W_{CIC}$ is
straight forward to calculate and given by
\begin{equation}
W_{CIC}(x) = \left\{
\begin{array}{ll}
1-|x| & |x|\leq 1 \\
0 & \mathrm{else}
\end{array}
\right.
\end{equation}
\begin{figure}[h!]
\centering
\begin{subfigure}{0.25\hsize}
\centering
\includegraphics[width=\hsize]{figure/numerics/formfaktor_CIC_S.png}
\caption{Cloud-in-Cell \phantom{andere zeile}}
\label{fig:num:S_CIC}
\end{subfigure}
\begin{subfigure}{0.25\hsize}
\centering
\includegraphics[width=\hsize]{figure/numerics/formfaktor_TSC_S.png}
\caption{Triangluar Shaped Cloud}
\label{fig:num:S_TSC}
\end{subfigure}
\begin{subfigure}{0.25\hsize}
\centering
\includegraphics[width=\hsize]{figure/numerics/formfaktor_PQS_S.png}
\caption{Piecewise Quadratic Shape}
\label{fig:num:S_PQS}
\end{subfigure}
\\
\begin{subfigure}{0.25\hsize}
\centering
\includegraphics[width=\hsize]{figure/numerics/formfaktor_CIC_density.png}
\caption{Cloud-in-Cell \phantom{andere zeile}}
\label{fig:num:density_CIC}
\end{subfigure}
\begin{subfigure}{0.25\hsize}
\centering
\includegraphics[width=\hsize]{figure/numerics/formfaktor_TSC_density.png}
\caption{Triangluar densityhaped Cloud}
\label{fig:num:density_TSC}
\end{subfigure}
\begin{subfigure}{0.25\hsize}
\centering
\includegraphics[width=\hsize]{figure/numerics/formfaktor_PQS_density.png}
\caption{Piecewise Quadratic Shape}
\label{fig:num:density_PQdensity}
\end{subfigure}
\caption{Different shape functions in 1d and 2d}
\label{fig:num:shape_function}
\end{figure}
This simple shape function is not only a major step forward, but has the added
benefit of generating an entire family of shape function of increasing order,
by using the weight function $W$ for the previous order as the shape function
$S$ of the new, higer order. The next step after CIC in this chain is called
\textit{triangular shaped cloud} or TSC. This shape function has the advantage
of being continous. This implies that the Fourier transform of it falls faster
towards higher $k$. As \cite{Langdon_1970} showed this correspondes to reduced
aliasing of higher $k$ to low $k$ that can be represented by the Eulerian grid
and consequently a reduction of the finite grid instability. This numerical
instability heats the plasma when the numerical grid does not resolve the Debye
length and can outgrow the physical processes the simulation is supposed to
study. Using higher order shape function suppress the instability and allows
the use of (slightly) larger grid cells or alternatively a better conservation
of the plasma thermal energy at identical resolution \cite{Shadwick_2009}. A
similar [problem exists when the cell size does not resolve the gyro radius of
electrons, as shown by \cite{Horky_2017}, and again higher order shape function
can help. The downside is that the finite support of the shape function is
larger and more grid cells are involved in both the interpolation of the fields
to the particle location as well as the deposition.
Higher order shape function from the same family such as \textit{Piecewise
Quadratic Shape} PQS illustrated in Fig.~\ref{fig:num:S_PQS} have been used.
Higher order have an increasing number of continous derivatives and therefore
quicker drop off in Fourier space, but at the cost of each particle interacting
with an increasing number of cells. The smoother fields generated by higher
order shape functions reduce unphysical binary forces between nearby particles
and therefore numerical collisionallity (see \cite{Eastwood_1974,
Matsuda_1975}). The EPOCH code \cite{} might be the most widely used code to
use high order shape function. Otherwise order beyond TSC are not used widely
enough that a consensus as to their names has emerged.
Historically another family of shape function was used, the so-called
subtracted dipole shapes, see \cite{Kruer_1973} for more detail. If the code
uses cylindrical or spherical coordinates one can either use unmodified shape
function in ``index space'' that look cartician, just like the grids we discuss
here. Or one can take into account that grid cells become smaller and
eventually have a singularity as they approch $r=0$ and follow the approach by
\cite{Ruyten_1993} to obtain a correct density representation, even at the
symmetry axis.
So far only interpolation in one dimension has been discussed or interpolation
that treats all dimensions the same. This construction leads to codes that
conserve total momentum. Alternatively it is possible to combine shape function
of different orders to obtain a code that conserves total energy
\cite{Sokolov_2013}. A good example of this is the VPIC code (description in
\cite{Bowers_2008}) that mixed NGP and CIC shape functions. Magnetic field
components $B_i$ are interpolated using linear interpolation in the $x_i$
coordinate and NGP in the other two coordinates. Electric field components
$E_i$ use NGP in the $x_i$ coordinate and CIC for the other two directions.
The use of only six locations to obtain the local magnetic field and twelve for
the electric field allows to handle larger numbers of particles efficiently.
The downside is of course that hundreds or thousands of particles per species
are required to bring down the noise level.
Since many different choices for shape functions are possible, many
comparisions have been made, including \cite{Abe_1986,Kilian_2013} and
\cite{Munoz_2014}. No universal winner has emerged and it is advisable to test
different shape function to make sure that physical results are insensitive to
the choices made. A recent idea by \cite{Wu_2018} is to use adaptive width per
particle and update them during the course of the simulation to reduce overall
noise. Other schemes that pick or modify the width of the shape function to
reduce known numerical problems might follow.
\subsection*{Particle Motion}
Once the electromagnetic fields have been interpolated to the locaton of the
particle, it is necessary to update the position and velocity of the particle
accordingly. Since the first publication of the particle push by
\cite{Boris_1970} bascially all codes use this method, possibly with minor
adjustments.
Similar to the leap-frog procedure for the electromagnetic fields the particle
is updated according to
\begin{align}
\vec{v}(t+\Delta{t}/2) &= \vec{v}(t-\Delta{t}/2) + \vec{F}(x(t),v(t))\cdot\Delta{t}/m \quad , \label{eq:num:velupdate}\\
\vec{x}(t+\Delta{t})\phantom{/2} &= \vec{x}(t)\phantom{-\Delta{t}/2}\,\,\, + \vec{v}(t+\Delta{t}/2)\cdot\Delta{t} \quad . \label{eq:num:posupdate}
\end{align}
Without magnetic field, when the force $\vec{F}$ only depends on the particle
position $x(t)$, this is straight forward to solve. If there is however a
magnetic field, the Lorentz force introduces a dependance on the velocity
$\vec(t)$ that we do not know. The straight forward next step is to approximate
the velocity at this point in time by $\vec{v}(t) \approx
1/2\left(\vec{v}(t-\Delta{t}/2)+\vec{v}(t+\Delta{t}/2)\right)$, but now
Eq.~\eqref{eq:num:velupdate} has new new velocity $\vec{v}(t+\Delta{t}/2)$ on
both sides. The Boris push allows us to solve this implicit equation without
matrix inversion or iteration.
Since different modifications of the Boris push differ in how they handle the
relativistic case it is worthwhile to switch from velocities $\vec{v}$ to the
relativistic momentum per rest mass $\vec{u} = \vec{p}/m = \gamma\vec{v}$.
This quantity does not suffer from the problem that it has a fixed upper value
and thus we avoid the loss of precission due to the finite resolution of
floating point numbers close to the speed of light.
Eqs.~\eqref{eq:num:velupdate} and \eqref{eq:num:posupdate} then read
\begin{align}
\vec{u}(t+\Delta{t}/2) &= \vec{u}(t-\Delta{t}/2) + \vec{F}(x(t),v(t))\cdot\Delta{t}/m \quad , \\
\gamma(+\Delta{t}/2) &= \sqrt{1 + \frac{\vec{u}(t+\Delta{t}/2) \cdot \vec{u}(t+\Delta{t}/2)}{c^2}} \\
\vec{x}(t+\Delta{t})\phantom{/2} &= \vec{x}(t)\phantom{-\Delta{t}/2}\,\,\, + \vec{u}(t+\Delta{t}/2)\cdot\Delta{t}/\gamma(+\Delta{t}/2) \quad . \\
\end{align}
\begin{figure}[h!]
\centering
\includegraphics[width=0.5\hsize]{figure/numerics/boris_push.pdf}
\caption{Illustration of the Boris push: The red arrows in the velocity diagram indicate the additional velocity $q/m \vec{E}(t) \Delta{t}/2$ that comes from the acceleration caused by the electric field $E(t)$ acting on the particle at the beginning and end of the Boris push. The vector $\vec{\Omega}$ is obtained by scaling the magnetic field $\vec{B}$ such that a crossproduct with it produces half the final rotation. This allows the construction of $\vec{v}_2$ that bisects the rotation and thus a accurate solution.}
\label{fig:num:boris_push}
\end{figure}
The major insight that allows to solve the problem is that the magnetic field
can only change the direction of the velocity vector. It is therefore possible
to construct a suitable rotation using geometric considerations. The effect of
the electric field is purely an accceleration in the direction of the electric
field. To maintain reversability in time and second order accuracy it is split
into two equal parts perform before and after handling the magentic field. Using this insight we can perform the following steps:
\begin{align}
\vec{u}_1 &= \vec{u}(t-\Delta{t}/2) + \frac{q}{m}\vec{E}(t)\frac{\Delta{t}}{2} \\
\vec{\Omega} &= \tan{\left(\frac{q}{\gamma\,m}|B(t)|\frac{\Delta{t}}{2}\right)}\frac{\vec{B}}{|\vec{B}|} \label{eq:num:tanrotation} \\
\vec{t} &= \frac{2}{1 + \vec{\Omega}\cdot\vec{\Omega}} \vec{\Omega}\\
\vec{u}_2 &= \vec{u}_1 + \vec{u}_1 \times \vec{\Omega} \\
\vec{u}_3 &= \vec{u}_1 + \vec{u}_2 \times \vec{t} \\
\vec{u}(t+\Delta{t}/2) &= \vec{u}_3 + \frac{q}{m}\vec{E}(t)\frac{\Delta{t}}{2}
\end{align}
It is worth noting that the original algorithm by Boris contains the $\tan$ in
Eq.~\eqref{eq:num:tanrotation} and the suggestion to use to power series
expansion at least up to fourth order. Many codes since then have made the
approximation $\vec{\Omega} \approx q/(\gamma\,m)\,\vec{B}(t)\,\Delta{t}/2$,
This is cheaper, but only produces the correct gyro radius, not the correct
gyro angle.
The Lorentz factor $\gamma$ in Eq.~\eqref{eq:num:tanrotation} is given by
$\gamma = \sqrt{1 + \vec{u}_1\cdot\vec{u}_1 / c^2}$. According to
\cite{Vay_2008} this approximation can lead to spurious forces and he suggests
a more complicated expression.
%
% He therefor suggests to use
% \begin{align}
% \vec{u}_1 &= \vec{u}(t-\Delta{t}/2) + \frac{q}{m}\vec{E}(t)\frac{\Delta{t}}{2} \\
% \vec{\tau} &= \frac{q}{m}\vec{B}(t)\frac{\Delta{t}}{2} \\
% \vec{u}' &= \vec{u}_2 + \frac{q}{m}\vec{E}(t)\frac{\Delta{t}}{2} \\
% u^{*} &= \left(\vec{u}' \cdot \vec{\tau}\right) / c \\
% \gamma' &= \sqrt{1 + \frac{\vec{u}' \cdot \vec{u}'}{c^2}} \\
% \sigma &= \gamma'^2 - \vec{\tau} \cdot \vec{\tau} \\
% \gamma &= \sqrt{\frac{\sigma+\sqrt{\sigma^2 + 4(\vec{\tau}\cdot\vec{\tau} + u^{*2})}}2{}}\\
% s &= \frac{1}{1 + \vec{\tau}\cdot\vec{\tau}}\\
% \vec{u}(t+\Delta{t}/2) &= s\left( \vec{u}' + (\vec{u}' \cdot \vec{\tau})\vec{\tau} + \vec{u}' \times \vec{\tau}\right)
% \end{align}
%
Other modifications of the Boris push, such as \cite{Higuera_2017} and
\cite{Umeda_2018} exist as well. Some comparision between different variants
can be found in \cite{Ripperda_2018} or \cite{Zenitani_2018}.
% All of these algorithm assume that the electric and magnetic fields do not
% change during the time step $\Delta{t}$, nor is the field reinterpolated to the
% changing position of the particle. The particle therefore effectively
% experiences a constant and homogenous field. The solution to the (relativistic)
% equation of motion is in principle known analytically (see e.g.
% \cite{Hyman_1997}), but no particle pusher based on this analytic solution is
% in widespread use.
\subsection{Deposition and Filtering}
\label{subsec:num:depostion}
Now that the electromagnetic field has acted on the particle we need to
calculate -- in the case of an electrostatic code -- the charge density
distribution resulting from the new locations of the particles, or -- in the
case of an electromagnetic code -- the current density distribution. This
requires interpolation from the particle locations back to the grid. As
\cite{Birdsall_2005} shows it is desirable to use the same interpolation method
for both the interpolation from the grid to the particle location as well as
the deposition of the particle quantities $\rho$ and $\vec{\jmath}$ onto the
grid to avoid spurious self-forces.
The deposition of $\rho(t+\Delta{t})$ based on the newly calcuated
$\vec{x}(t+\Delta{t}$ is straight forward and simply given by
\begin{equation}
\rho(i\Delta{x},j\Delta{y} = \sum_{p} q_p W(x_p - i\Delta{x}) \cdot W(y_p - j\Delta{y}) \quad .
\end{equation}
The sum is taken over all particles, multiplying their charge with the weight
function based on the distance between the particle position
$\vec{x}_p(t+\Delta{t})$ and the origin of the grid cell, where the charge
density is located. One might be tempted to locate the charge density at the
center of the cell, to allow for the nice interpretation as the charge
contained in the cell, but typically the field solver calculates the
electrostatic potential at the location where the charge density is located.
Picking the corners of the cell allows to use a straight forward finite
difference approximation to calculate the electric field at the midpoint of
the edges.
Calculating the current $\vec{\jmath}(t+\Delta{t}/2)$ based on the old location
$\vec{x}(t)$, the new location $\vec{x}(t+\Delta{t})$ and the velocity
$\vec{v}(t+\Delta{t}/2)$ is slightly more complicated.
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=0.5\textwidth]{currentassignment_naive.pdf}
\caption{Naive current deposition for a charged particle moving as indicated by the black arrow and deposition current density onto the grid as shown in green. Solid black lines indicate grid cells, dashed line illustrate midplanes of cell faces.}
\label{fig:num:currentassignment_naive}
\end{center}
\end{figure}
The current carried by a particle with charge $q_p$ moving at velocity
$\vec{v}(t+\Delta{t}/2)$ is given by $\vec{\jmath} = q_p
\vec{v}(t+\Delta{t}/2)$ and it is located around the position at this time,
$\vec{x}(t+\Delta{t}/2)$ that can be approximated by
$\left(\vec{x}(t)+\vec{x}(t+\Delta{t})\right)/2$.
Fig.~\ref{fig:num:currentassignment_naive} illustrates that this current can
simply be interpolated onto the grid using the weight functions, just as for
the charge density. The current on a cell edge is then simply the charge
flowing through the associated cell face over the course of a time step.
The problem with this straightforward procedure is that the current deposited
in this way does not satisfies the discrete continuity equation given by
\begin{align}
&\frac{\rho(i\Delta{x},j\Delta{y},t+\Delta{t})-\rho(i\Delta{x},j\Delta{y},t)}{\Delta{t}} \nonumber \\
&\quad + \frac{j_x((i+1/2)\Delta{x},j\Delta{y},t+\Delta{t}/2) - j_x((i-1/2)\Delta{x},j\Delta{y},t+\Delta{t}/2)}{\Delta{x}} \nonumber \\
&\quad + \frac{j_y(i\Delta{x},(j+1/2)\Delta{y},t+\Delta{t}/2) - j_y(i\Delta{x},(j-1/2)\Delta{y},t+\Delta{t}/2)}{\Delta{y}} = 0 \quad .
\end{align}
Since this current enters Maxwells' equations as a source term it will lead to
an electric field that does not actually satisfy Gauss' Law. In other words the
curl-free component of the electric field in an electromagnetic code using this
current deposition scheme will differ from the electric field in an
electrostatic code with the same particle distribution. This is clearly not
desirable and different methods have been used to correct the problem. One is
deposit the charge density separately and to solve a Poisson equation to get
the longitudinal part of the electric field correct. Computationally cheaper
and very effective is to make use of the fact that the electric field is nearly
correct and to clean up the remaining error using a correction scheme, such as
the one by \cite{Marder_1987}.
This problem is solved all-together by current deposition schemes that
depositing a current that satisfies the discrete continuity equation directly.
The first of these so called \textit{charge conserving} schemes is by
\cite{Eastwood_1991}\footnote{this paper is probably better known for the novel
Maxwell solver described therein, not the current deposition algorithm.}, but
several others have been developed since. The deposition in these schemes is
slightly more expensive than in the naive algorithm, but the the need to remove
violations of Gauss' Law is completely eliminated.
Somewhat more widely implemented in the scheme by \cite{Villasenor_1992}. The
down side of this scheme is the need to threat the particle motion differently
depending how many cell interfaces the particle interacts with. The need to
branch to different sub-algorithms for each particle is computationally not
optimal on pipelined CPUs or GPUs where divergent branches incure large costs.
Additionally this scheme is tedious to extend to shape functions beyond CIC.
% \begin{figure}[htbp]
% \begin{center}
% \includegraphics[width=0.5\textwidth]{currentassignment_esirkepov.pdf}
% \caption{Current deposition using the algorithm by \cite{Esirkepov_2001}. The particle motion is decomposed into axis-parallel segments that are individually weighted.}
% \label{fig:num:currentassignment_esirkepov}
% \end{center}
% \end{figure}
\begin{figure}[h!]
\centering
\begin{subfigure}{0.4\hsize}
\centering
\includegraphics[width=\textwidth]{currentassignment_esirkepov.pdf}
\caption{Current deposition using the algorithm by \cite{Esirkepov_2001}. The particle motion is decomposed into axis-parallel segments that are individually weighted.}
\label{fig:num:currentassignment_esirkepov}
\end{subfigure}
\begin{subfigure}{0.4\hsize}
\centering
\includegraphics[width=\textwidth]{currentassignment_umeda.pdf}
\caption{Current deposition using the Zig-Zag algorithm by \cite{Umeda_2003}. As the particle closes from one cell to another (across the solid black line indicating the cell interface), it's trajectory is modified to go via the midpoint.}
\label{fig:num:currentassignment_umeda}
\end{subfigure}
\caption{Charge conserving current desposition}
\end{figure}
A scheme that works with arbitray shape functions (as long as they are products
of separate one-dimensional shape functions) and without the need for different
treatment of special cases is the current deposition by \cite{Esirkepov_2001}.
Fig.~\ref{fig:num:currentassignment_esirkepov} illustrates the current density
that is deposited using this algorithm for the same particle move as used in
Fig.~\ref{fig:num:currentassignment_naive}. The reader can verify that the
total current is identical, but the distribution onto the different grid points
is different. In this algorithm the motion of the particle is decomposed into
separate displacements parallel to the grid axis that are weighted
individually. Readers that are interested in implementing this algorithm are
refered back to the excellent original paper.
The other widely used scheme in modern codes is the Zig-Zag scheme described in
\cite{Umeda_2003}. In this scheme particles can only cross between cells at the
midpoint of the interface. A particle that does not naturally go through that
point has it's motion split into a motion from the starting position to the mid
point, followed by a separate motion from the midpoint to the final location,
resulting in a Zig-Zag trajectory that gave the scheme it's name.
Fig.~\ref{fig:num:currentassignment_umeda} illustrates this motion and the
resulting current for the same particle trajectory we have used before. Finding
the midpoints for the fraction of particles that does not stay in the same cell
requires some conditional code, but the upside is that the current deposition
inside each cell is slightly simpler. Overall the computational cost and
noise-properties between the two deposition schemes is similar.
% \begin{figure}[htbp]
% \begin{center}
% \includegraphics[width=0.5\textwidth]{currentassignment_umeda.pdf}
% \caption{Current deposition using the Zig-Zag algorithm by \cite{Umeda_2003}. As the particle closes from one cell to another (across the solid black line indicating the cell interface), it's trajectory is modified to go via the midpoint.}
% \label{fig:num:currentassignment_umeda}
% \end{center}
% \end{figure}
Even in the case of unstructed grids, a charge-conserving current deposition
method has been developed by \cite{Moon_2015}, that makes use of the
discrete exterior algebra in its derivation.
Once the current is deposited on the grid it can be filtered to remove unwanted
noise. The paper by \cite{Vay_2011} has an introduction to some digital filters
and the associated terminology. Many codes simply use one or more passes of a
simple binomial filter to reduce high frequency fluctuactions, but it is
possible to tune filters specifically to the problem at hand and get much
better performance.
\subsection*{Initalization and Particle Handling}
\label{subsec:num:init}
We can now covered how the particle based source terms are incorporated in the
evolution of the gridded electromagnetic quantities, how those act on the
particles and how new source terms are deposited onto the grid based on the
updated particle properties. An important part that is still undescribed is the
setup of the initial conditions. For the field quantities on the grid these are
usually simply set base on analytic expression for known equalibria. Most of
them only require an inital magnetic field and have vanishing electric field.
Creating the inital particle population is a little bit more complicated and
can have an important influence on the noise level in the simulation.
The difficulty is to create a number of particles that represent the desired
distribution function $f(\vec{x},\vec{v},t_0)$. We will approach this problem
step by step.
The easiest case (and not actually uncommon) is constant spatial density and
and a velocity distribution that follows a non-relativistic Maxwellian. In this
case we can pick the initial position of the particle at random using
\begin{equation}
\vec{x} = \left(L_x\cdot \mathcal{U}(0,1), L_y \cdot \mathcal{U}(0,1), L_z \cdot \mathcal{U}(0,1)\right) \quad,
\end{equation}
where the three calls to the random generator using
the function $\mathcal{U}$ produce three independent (pseudo-)random numbers,
uniformly distributed between zero and one. Some cells might receive more then
the expected number of \textit{particles per cell} -- often denoted as
\textit{ppc} --, while others receive slightly more. Given that our system has
much fewer macro particles then there are physcial particles in the scenario we
aim to simulate and each macro particles carries the charge of many physical
particles, this can lead to fluctuations in the charge density that are larger
than in the physical system. One easy step to remidy this to some extend is to
create exactly the expected number of macro particles per cell and only choose
the position inside the cell at random. This also makes it easy to represent
spatially changing densities, be computing the number of particles in each cell
from a known analytic function $n(\vec{x})$. This works well as long as the
scale length $l_n = n / \frac{\partial\, n}{\partial{x}}$ is large compared to
the cell size $\Delta{x}$.
Fpr uniform densities there is also the possibility to use \textit{low
discrepancy series} such as the Halton sequence \cite{Halton_1964}, a straight
forward extension of the van der Corput sequence to multiple dimensions. This
sequence distributes particles less randomly, but more uniformly in the
simulation domain. This leads to a reduced noise level that scales as
$\mathcal{O}(1/N)$ with the particle number. This is much cheaper than reducing
the noise using the $\mathcal{O}(1/\sqrt{N})$ scaling of adding more particles
randomly. This \textit{quiet start} has successfully used e.g. in the study of
instabilities (see \cite{Byers_1970} for an example).
The non-relativistic Maxwellian distribution is simply the composition of three
velocity components that individually follow a normal distribution. We can
therefore simply pick random velocities
\begin{equation}
\vec{v} = \left(\mathcal{N}(u_x, v_{th}), \mathcal{N}(u_y, v_{th}), \mathcal{N}(u_z,v_{th})\right) \quad.
\end{equation}
The call to $\mathcal{N}(\mu,\sigma)$ produced a random number from a normal
distribution with mean $\mu$ and standard deviation $\sigma$. The mean can be
the average drift velocity of that species (and can depend on position and
particle species, e.g. in the setup of a current sheet) and the standard
deviation is set by the thermal speed
\begin{equation}
v_{th} = \sqrt{\frac{k_B T}{m}} \quad .
\end{equation}
Note that there is a second popular definition of the thermal speed that
includes a factor of two. When comparing with other codes and results this is a
point worth double-checking. Different species of different masses will have
different thermal speeds at the same temperature. The extension of this method
to include species of different temperatures for different species or spatial
directions is straight forward.
Some early simulations used other methods to approximate a Maxwellian
distribution, but on modern machines the generation of $\mathcal{N}$ using the
Box-Muller method or the ziggurat algorithm is sufficiently fast that a
straight-forward approach performs well. This is both thanks to the fast
evaluation of $\log$ and trigonometric functions and to the increased
performance of the underlying generators producing pseudo-random integers.
If the drift speed $\vec{u}$ approaches relativistic speeds, but the thermal
speeds are still sufficiently low, some accuracy can be gained by generating a
non-drifting distribution and boosting it with a Lorentz boost. If the thermal
speed is large as well, it is necessary to generate a proper Maxwell-J\"uttner
distribution. This used to be problematic and many older codes neglect this,
however this leads to problematic deviations from the correct distribution as
demonstrated in \cite{Melzani_2013}. Fortunately an efficient algorithm is
described in \cite{Zenitani_2015}.
Sometimes it is desired to generate new particles from a given distribition
during initalization, but also later in the simulation, e.g. to fill a portion
of newly expanded simulation space or to inject plasma through an inflow
boundary. This is possibly, but some subtelies need to be considered due to the
interaction with existing fields in the domain \cite{Cartwright_2000}.
% particle splitting and merging
In many simulations particles are created once and afterwards their number
never changes. It can however be useful to split particles in regions of
(phase-)space, where there is a low number of particles, to get better
statistics and reduce noise. Many of those particles however leave the
interesting region again and need to be merged together again to avoid a
balloning of the computational cost.
Splitting particles in a way that conserved mass, momentum and energy is
straight forward, as we can simply pick a source particle, split it into two
equal parts of half the statistical weigth and displace them slightly from the
centre mass to ensure that the following plasma dynamics will transport them
separately. Some care can be taken that the displacement does not change the
energy in the electromagnetic fields, but even without that the naive algorithm
works well. The main problem is particle merging, as we will never find two
particles of exactly equal velocities close to each other. Combining two
particles of unequal speeds however can not conserve both momentum and energy
at the same time \cite{Lapenta_1994}.
A first solution was offered by \cite{Shon_2001}, combining several particles
into several new particles to conserve charge density, momentum and energy. In
simulations where many new particles are created the algorithm by
\cite{Welch_2007} that estimates the distribution function from $N >> 2$
particles and replaces them with $M$ ($2 << M < N$) new particles can be
useful. The method of \cite{Faghihi_2017} extends this to include also the
stress tensor. If we do not want to redraw the complete particle population,
e.g. because we want to preserve features in phase space that are not well
described by the first few fluid moments, it is necessary to find particles of
similar speeds. The method by \cite{Martin_2012} to find such particle pairs or
groups can be useful for this task. The method by \cite{Vranic_2015} aims to
merge $N$ exisiting particles into two new particles while conserving charge,
momentum and energy. If the reason for splitting particles is mesh-refinement
in one of the rate AMR codes, the method by \cite{Drouin_2018} can help with
splitting, but merging remains a problem.
Handling of dynamic particle numbers in a way that covers phase space well, is
numerically efficient and conserves all global quantities remains a problem,
despite all the described attempts and many others in recent year.
\subsection*{Boundary Conditions}
As mentioned before it might be desireable to create new particles at the
boundary and proper care has to be taken for to match the existing fields
there. This is a generell problem with boundary conditions in Particle-in-cell
codes. One has to handle both the fields and the particles there and should do
so in a consistent way to avoid problems.
Nummerically easiest are periodic boundary conditions where the cell at the
upper end of a coordinate is logically wrapped around to be just below the
lower end of the coordinate. Particles that leave through one side are
reinjected unmodified at the other end. Periodic boundary conditions mimic
infinite space resomably well, as there are no fixed walls or ends to the
simulations. The periodic nature of the simulation does however select a finite
number of modes -- out of the inifinite possibilities that exist in free space
-- that have an integer number of wavelength in the simulation box. If the
number of grid cells is small, so is the number of allowed wave modes and the
quantization of the spectrum can have visible, undesirable effects.
Another set of boundary conditions that are resonably popular is a version of
Dirichlet boundary conditions for some field components. More specifically the
normal component of the magnetic field is held fixed in time and the two
tangential components of the electric field are set to zero. Geometrically this
affects the three field components that are located at that face of the unit
cell. The two magnetic field components on the perpendicular faces and the
electric field on the edge normal to the boundary are not needed at the
boundary and are not modified by evolved freely, same as in the interior of the
domain. Vanishing electric field, even in the presence of an electric current
is typical for a \textit{perfect electric conductor} (PEC). This boundary
therefore mimics a metal wall with vanishing conductivity. If a realistic metal
boundary is required, much more effort is needed. This boundary condition does
reflect impinging electromagnetic waves.
The PEC boundary is therefore often coupled with a reflecting boundary
condition for particles. When a particle ends outside the boundary at the end
of the timestep, both the component of the position normal to the wall, as well
as the normal component of the velocity are flipped. This results in a particle
that is at the same position and velocity as if it had undergone specular
reflection when reaching the boundary.
More complicated boundary conditions for particles might absorb the particle or
emit one or more new particles drawn from some distribution function, possibly
depending on the energy of the incoming particle. This can simulate more or
less realistic metal wall including effects such as wall charging or secondary
electron emission.
While physcially not a boundary condition, moving simulation domains are often
implemented in terms of boundary conditions. One example is the moving window
in the XOOPIC code \cite{Bruhwiler_2001}. Here the Eulerian mesh it not moving,
but instead new grid cells are created on one side and populated with
background magnetic field and fresh thermal particles. On the other side the
grid is truncated and particles removed. If the window happens to move at the
speed of light -- common in simulation that follow the path of a laser pulse
through a plasma (see e.g. \cite{Yu_2016}) -- no perturbation caused by the
downstream boundary can reach the interior of the simulation domain, greatly
simplying the implementation. If the window is moving slower, a boundary that
absorbes waves and does not reflect them back into the interior is needed at
the lower end of the moving window.
This brings us to the topic of absorbing boundary conditions. These have been a
problem for a long time. Initially Liao boundary conditions \cite{Liao_1984}
and Mur \cite{Mur_1981} have been used. These boundary condition (and others)
are described in detail in the great book on FDTD methods by
\cite{Taflove_2000}. The problem with these boundary conditions is that they
rely on fixed waves speeds. The presence of the plasma changes the wave speed
from the speed of light to a lower speed that might depend on wavelength,
incident angle and plasma parameters such as the magnetizations. This makes is
very hard to absorb all wave modes that reach the boundary sufficiently well.
A great step forward was the development of the \textit{Perfectly Matched
Layer} (PML) by \cite{Berenger_1994}. This layer is technically not a boundary
condition, but rather a region of space with modified permeability and
permitivity. These material properties are choosen such that the impedance of
the material is identical to the adject free space. Therefore the refractive
index does not change from free space to the material layer and now waves are
reflected. Inside the material the wave is however damped, attenuating before
it reaches the actual boundary. There a simple boundary condition such as PEC
can be choosen. And wave that does reach the boundary and gets reflected is
attenuated a second time on the way out, greatly improving performance of this
scheme. Several different formulations of PML have been developed such as
split-PML (where each electric and magnetic field component inside the boundary
is split into two independent, unphysical fields that are damped separately),
uniaxial PML (UPML) and more general stretched-coordinate PML wave been
developed. One version known as convolutional PML (CPML) has been used
successfully in multiple coes. The book \cite{Berenger_2007} explains the
different methods and their connections.
Even before the development of these methods was completed, PML conditions were
used in Particle-in-Cell simulations, see e.g. \cite{Pasik_1999, Pukhov_1999}.
PML boundary conditions are often combined with particle boundaries that absorb
outgoing particles and replace them in some scheme to simuate the presence of a
thermal plasma bath outside the simulation domain that can act as the source of
unperturbed upstream. This has been used in particular in the simulation of
magnetic reconnection, where the removal of plasma in the outflow regions and
the injection of fresh upstream with not-yet-reconnected magnetic flux allows
for the study of larger systems and long time effects (see \cite{Daughton_2006,
Klimas_2008, Ohtani_2009}).
Besides the injection of thermal plasma on the boundary it is also possible to
inject electromagnetic waves to study their propagation. This can either be
achieved by the means of an artifical current, acting as an antenna or by
manipulating the electromagnetic field directly. More complicated inject
schemes that allow for the injection of realistic laser pulses
(\cite{Thiele_2016}), of oblique waves with arbitray envelops
(\cite{Perez_2018}) or of magnetized plasma without unwanted numerical noise
(\cite{Kilian_2018}) are possible as well, but require a bit of care.
% Eliasson_2002.pdf outflow condition for fourier transformed vlasov-poison system
\subsection*{Diagnostics}
As much fun as it can be to write and run a Particle-in-Cell code, the ultimate
goal is to produce output that can be used to gain understanding of the
physical system. This requires the calculation of diagnostic quantities and
storing them in a way that persists beyond the duration of the simulation. As
tempting as it might be to simply save the complete state of the simulation and
use later post-processing to produce higher-level diagnostics and plots, it is
usally a bad idea from a performance standpoint. Whenever possible the
simulation code should calculate diagnositics as close to the final plots and
output only them. After all, a simple histogram for a velocity distribution
might only be a few kilobytes, where the dump of all particles is serval
terabytes. Saving the simulation state for later analysis or restart might
still be necessary but should be performed as rarely as possible.
There are of course many high-level diagnostics and it is impossible to cover
all of them. This section will therefore mostly cover general-purpose output
that can be postprocessed further.
To gain high-level insight into the simulation at low I/O cost it is often
useful to calculate a breakdown of the energy content in the simulation in
several rough categories, such as the energy in the electric field, the energy
in the magnetic field and in the particles.
Another obvious candidate for output are all the gridded quantities, such as
electric and magnetic field as well as current density. These quantites do not
require any extra calculation, but there size prohibits writing them out as
text files. The two most widely used choices are dumping the memory of every
MPI domain to a separate binary file or writing a global view to a structured
format such as HDF5. The first choice has the advantage of very little
overhead, even is a small header is included. The downside is that the separate
views of the different doamins need to combined for further analysis. The
overhead of creating many files in the same directory at once and the tedious
file handling make this alternative an increasing poor choice once the
simulation used more than a few hundred cores. Parallel I/O to HDF5 requires
slightly more complicated I/O code and introduces some overhead, but allows for
the inclusing of meta-data and easy loading into analysis tool, independend of
programming language and CPU architecture.
Other field data that need to be computed just for diagnostic purposes such as
the mass density, charge density, average bulk velocities, or components of the
pressure tensor can also be good choices for grid based output. Even if many of
these quantities are required it is typically cheaper to computer the
diagnostics during the parallel simulation instead of dumping the full particle
information and doing post-processing.
In many cases not all of the three-dimensional field data is required.
Averaging over one or two dimensions to obtain line profiles or two-dimensional
selections is an option. Alternatively lineouts or two-dimensional cuts can be
useful. If points of interest are known beforehand or can easily be computed on
the fly it is interesting to output time histories of those points at high
cadance. If a global overview is needed, but not the full resolutions, it is
possible to output a downsampled grid. Care should be taken to apply a digital
low-pass filter -- such as a Kaiser window \cite{Kaiser_1980} -- before the
decimation to avoid aliasing.
In some cases it is necessary to restart the code, either due to reaching a
wallclock limit, or due to a compute node crashing (this is actually an
increasing problems with supercomputers pushing the 10000 limit and
mean-time-between-failures meassured in days at best). Also some analysis can
only be performed as post-processing, either due to poor scalability or because
it is actively being developed based on the simulation results. In this case,
the pull particle information needs to be stored. Again direct binary dumps or
higher-level self-desribing formats are the two main possibilities. Some codes
even implement both, the high-level format for scientific analysis and binary
dumps that are overwritten periodically as faster checkpoints that are only
used for restarts.
Many other diagnostics have been developed and the following list of examples
is certainly incomplete: one-dimensional histogramms of particle quantities
such as speed or energy, two-dimensional cuts in phasespace showing e.g.
$x-v_x$-densities, fourier transforms of other quantites such as
$\tilde{B}(|k|)$, time averages of other quantities to remove high-frequency
noise, trajectories of specially selected particles of interest, often together
with local field quantities at the position of the tracer particles,
reconstruction of the particle phasespace density on a six-dimensional grid,
discrete estimates of the entropy based on a binned phasespace. The
possibilities are endless here and a large fraction of the delevopment time of
a mature code will be invested in probiding userfriendly, scalable, efficient
diagnostics.
One special diagnostic that is of interest in astrophysical applications in the
calculation of radiation spectra. This is different from the spectrum of the
field inside the simulation domain that is limited to frequencies that are
explicitly resolved. Often there is synchrotron or inverse-Compton radiation at
much higher frequenies that can be calculated separately. See
\cite{Pausch_2014,Pausch_2018} on how to implement and properly test such
radiation diagnostics. Some recent codes include the production of gamma rays
and electron-positron pairs \cite{Nerush_2017}. This is especially relevant for
the nascent field of pulsar magnetosphere simulations, where the back reaction
of the radiation processes on the energetic particles in the similation needs
to be included \cite{Kalapotharakos_2018}.
\subsection*{Test Cases}
Unlike hydro codes that tend to develop negative densities or pressures when
numerical problems occure Particle-in-Cell codes are relatively robust. This
can be a good, but brings the risk of obtaining a plausible but wrong result.
It is therefore important that the researcher employs a healthy scepticism
towords the code and that the code is tested. Other communities have a large
number of test cases for which analytic solutions are known, or at least
results from other codes are available. In the Particle-in-Cell community
effort into validation (making sure that the employed plasma model is adaquate
and that the underlying assumptions are met), benchmarking (comparisson with
other codes) and valdidation (testing proper implementation) are relativly new
and rare. One of the reasons is that the number of test problems with known,
analytic solutions is rather low.
But there some test cases that can be recommended. The paper by
\cite{Jacobs_2006} introduced a discontinuous galerkin code on unstructured
mesh, but also includes several useful test cases. The study of
Kelvin-Helmholtz instability in saturns magnetopause in \cite{Delamere_2011}
has been used by several hybrid codes. Code description paper such as the one
for the Apart-T code \cite{Melzani_2013} or the SHARP code \cite{Shalaby_2017}
lists several test problems that are solvable with that code and offers
opportunity for benchmarking. Papers that investigate new hybrid codes such as
\cite{Amano_2014,Munoz_2018} contain testproblems to demonstrate the new
method, but many of them are also accessible to PiC codes. The paper by
\cite{Kilian_2017} contains a list of wave modes and suggested parameters that
are accessible to different plasma models that can be implemented by PiC codes.
Physical setups for which analytic solutions exist include the study of plasma
waves \cite{Aastroem_1950, Bernstein_1958, Andre_1985, Swanson_2003} and the
thermal excitation of fluctuations oin density \cite{Dougherty_1960} or
electromagnetic fields \cite{Akhiezer_1975, Yoon_2017}. For complicated
distribution function that do not admit analytic solutions for the dispersion
relation of plasma waves comparisson with numeric dispersion solver
\cite{Roennmark_1982, Xie_2016} is useful. The study of Landau damping has a
long tradition \cite{Dawson_1961} and can be useful to test the long term
stability of the code \cite{Manfredi_1997}.
The comparison between different code types such as in \cite{Dimits_2000,
Munoz_2015} can be useful to find the limits of applicability. This kind of
comparison is especially popular in the Fusion power community
\cite{Falchetto_2008}. The expected scaling behaviour when improving numerical
resolution can also be used to test the code, even without outside reference
simulations, as shown in \cite{Riva_2017}.