Algorithm Search⌘K

Algorithmcore

Cloud-in-cell assignment

Also called cloud-in-cell scheme, CIC assignment.

Spreads each particle's charge or mass over the nearest grid points with linear weights, and uses the same weights to interpolate the field back, so no particle feels its own field.

Time
Θ(N + M) worst
Space
Θ(M) extra
Where
M = the number of grid points; N = the number of particles
Properties
conservativedeterministic
Origin
Charles K. Birdsall, Dieter Fuss, 1969

Cloud-in-cell (CIC) assignment is the step of a particle-mesh method that moves charge or mass from particles to a grid, and moves the grid field back to the particles. Each particle is a uniform cloud one cell wide, and the part of the cloud that falls in the cell of a grid point goes to that point. In one dimension this gives linear weights to the 2 nearest grid points, in two dimensions bilinear weights to 4 points, and in three dimensions trilinear weights to 8 points. When the same weights are used in both directions, the total charge is kept exactly and the total force on all particles is zero, so no particle pushes itself. The graphics particle-in-cell transfer of velocities uses the same bilinear weights; this page treats the weights as part of a field solver, where the conservation of charge and momentum is what makes the result accurate.

In plain words

Particles sit anywhere, but a fast field solver needs values on a grid. So each particle shares its charge with the grid points next to it. A particle close to a point gives most of its charge to that point, and a particle halfway between two points gives each one half.

After the solver finds the field on the grid, each particle reads the field back by the same rule: it mixes the values of the same points in the same shares. Using one rule in both directions is important. It makes the push from a particle on the others balance the push from the others on it, so the particles cannot speed up all together, and a lone particle stays at rest.

The problem

The input is a periodic grid of MM points xj=j Δxx_j = j\,\Delta x, j=0,…,M−1j = 0, \ldots, M - 1, on [0,L)[0, L) with Δx=L/M\Delta x = L / M, and NN particles with positions xix_i and charges qiq_i (masses on gravity pages). The first output is the grid density

ρj=1Δx∑i=1Nqi W(xi−xj),W(s)=max⁡(0,  1−∣s∣Δx),\rho_j = \frac{1}{\Delta x} \sum_{i=1}^{N} q_i \, W(x_i - x_j), \qquad W(s) = \max\Bigl(0, \; 1 - \frac{|s|}{\Delta x}\Bigr),

with xi−xjx_i - x_j taken over the periodic images. The second output, for a grid field EjE_j, is the field at each particle, E(xi)=∑jW(xi−xj)EjE(x_i) = \sum_j W(x_i - x_j) E_j. The function WW is the overlap of a cloud of width Δx\Delta x centred at xix_i with the cell [xj−Δx/2,xj+Δx/2][x_j - \Delta x/2, x_j + \Delta x/2], divided by Δx\Delta x. Hockney and Eastwood write the assignment function as WW and call this choice CIC; nearest grid point (NGP) and triangular shaped cloud (TSC) are its neighbours of lower and higher order.

The algorithm

  1. CIC-DEPOSIT(x[1..N], q[1..N], M, L)
  2. 1dx ← L / M; ρ[j] ← 0 for j = 0, ..., M - 1
  3. 2for i ← 1 to N do
  4. 3s ← x[i] / dx; j ← ⌊s⌋; w ← s - j ▷ 0 ≤ w < 1
  5. 4ρ[j mod M] ← ρ[j mod M] + q[i] (1 - w) / dx
  6. 5ρ[(j + 1) mod M] ← ρ[(j + 1) mod M] + q[i] w / dx
  7. 6return ρ
  8. CIC-INTERPOLATE(E[0..M-1], x[1..N], L)
  9. 7for i ← 1 to N do
  10. 8s ← x[i] / dx; j ← ⌊s⌋; w ← s - j ▷ the same j and w as in L3
  11. 9E_i ← (1 - w) E[j mod M] + w E[(j + 1) mod M]
  12. 10return (E_1, ..., E_N)

Line L3 finds the grid point jj to the left of the particle and the fraction ww of a cell from that point to the particle. Lines L4 and L5 split the charge in the shares 1−w1 - w and ww; the point nearer to the particle gets the larger share. Division by Δx\Delta x turns a charge into a charge per length. Line L9 reads the field with the same two shares. In two dimensions, lines L3 to L5 run in each direction, and the 4 products (1−wx)(1−wy)(1 - w_x)(1 - w_y), wx(1−wy)w_x (1 - w_y), (1−wx)wy(1 - w_x) w_y and wxwyw_x w_y are the weights.

Example

Take M=4M = 4 and L=4L = 4, so Δx=1\Delta x = 1 and the grid points are 0, 1, 2 and 3. Three particles have (x,q)=(0.25,1)(x, q) = (0.25, 1), (1.5,2)(1.5, 2) and (3.75,1)(3.75, 1).

particle jj ww to point jj to point j+1j + 1
x=0.25x = 0.25, q=1q = 1 0 0.25 0.75 to point 0 0.25 to point 1
x=1.5x = 1.5, q=2q = 2 1 0.5 1 to point 1 1 to point 2
x=3.75x = 3.75, q=1q = 1 3 0.75 0.25 to point 3 0.75 to point 0 (periodic)

So ρ=(1.5,1.25,1,0.25)\rho = (1.5, 1.25, 1, 0.25), and ∑jρjΔx=4=∑iqi\sum_j \rho_j \Delta x = 4 = \sum_i q_i.

Now solve for a field on the grid. In normalized units, Gauss's law dE/dx=ρ−ρˉdE/dx = \rho - \bar\rho with ρˉ=1\bar\rho = 1, differenced as Ej+1/2−Ej−1/2=Δx(ρj−ρˉ)E_{j+1/2} - E_{j-1/2} = \Delta x (\rho_j - \bar\rho) with a mean-free EE and Ej=(Ej−1/2+Ej+1/2)/2E_j = (E_{j-1/2} + E_{j+1/2}) / 2, gives E=(−0.25,0.125,0.25,−0.125)E = (-0.25, 0.125, 0.25, -0.125). This is minus the centred difference of the potential of the 3-point Laplacian. Lines L7 to L9 give the fields −0.15625-0.15625, 0.18750.1875 and −0.21875-0.21875 at the three particles. The forces qiEiq_i E_i are −0.15625-0.15625, 0.3750.375 and −0.21875-0.21875, and their sum is exactly 0.

Correctness

The full proof is in the correctness proof. It shows four facts. Lines L3 to L5 compute ρj=∑iqiW(xi−xj)/Δx\rho_j = \sum_i q_i W(x_i - x_j) / \Delta x exactly. The weights of one particle add to 1, so ∑jρjΔx=∑iqi\sum_j \rho_j \Delta x = \sum_i q_i exactly, in rational arithmetic and up to rounding in floating point. Line L9 is exact for every field that is linear between two grid points. And if the grid field is Ej=∑kKj−kρkE_j = \sum_k K_{j - k} \rho_k with an odd kernel, K−m=−KmK_{-m} = -K_m, then the total force ∑iqiE(xi)\sum_i q_i E(x_i) is zero; for a single particle this sum is its self-force, so the self-force is zero.

The key step is a change of the order of summation: ∑iqiE(xi)=∑iqi∑jW(xi−xj)Ej=Δx∑jρjEj\sum_i q_i E(x_i) = \sum_i q_i \sum_j W(x_i - x_j) E_j = \Delta x \sum_j \rho_j E_j, which uses the same WW in L4, L5 and L9.

Proof: CIC assignment computes the linear weights, conserves charge, interpolates linear fields exactly and gives zero total force with an odd kernelfull

We use the pseudocode of the page and exact arithmetic. The grid points are xj=jΔxx_j = j \Delta x with Δx=L/M\Delta x = L / M, and indices are taken mod MM. For a particle at xx, line L3 sets s=x/Δxs = x / \Delta x, j=⌊s⌋j = \lfloor s \rfloor and w=s−jw = s - j, so 0≤w<10 \le w < 1 and x=(j+w)Δxx = (j + w) \Delta x. Let W(r)=max⁡(0,1−∣r∣/Δx)W(r) = \max(0, 1 - |r| / \Delta x), and let WP(x−xk)=∑n∈ZW(x−xk−nL)W_P(x - x_k) = \sum_{n \in \mathbb{Z}} W(x - x_k - nL) be its periodic sum.

Claim 1 (the weights). A particle at xx adds q(1−w)/Δxq (1 - w) / \Delta x to ρj mod M\rho_{j \bmod M} and qw/Δxq w / \Delta x to ρ(j+1) mod M\rho_{(j+1) \bmod M}, and for every kk the total it adds to ρk\rho_k is qWP(x−xk)/Δxq W_P(x - x_k) / \Delta x.

Proof. The first part is lines L4 and L5. For the second part, look at the grid points of the line, before the reduction mod MM. The point jΔxj \Delta x is at distance wΔxw \Delta x from xx, so W(x−jΔx)=1−wW(x - j \Delta x) = 1 - w. The point (j+1)Δx(j + 1) \Delta x is at distance (1−w)Δx(1 - w) \Delta x, so W=wW = w. Every other point mΔxm \Delta x with m≤j−1m \le j - 1 or m≥j+2m \ge j + 2 is at distance at least Δx\Delta x, so W=0W = 0. The grid point xkx_k and its images xk+nLx_k + nL are the points mΔxm \Delta x with m≡k(modM)m \equiv k \pmod M. So WP(x−xk)W_P(x - x_k) is the sum of WW over these mm, which is 1−w1 - w if j≡kj \equiv k, plus ww if j+1≡kj + 1 \equiv k, and 0 otherwise. When M=1M = 1 both cases hold for k=0k = 0, and both lines L4 and L5 add to ρ0\rho_0, which again matches. □\square

Claim 2 (charge). ∑k=0M−1ρkΔx=∑i=1Nqi\sum_{k=0}^{M-1} \rho_k \Delta x = \sum_{i=1}^{N} q_i.

Proof. Line L1 sets ρ=0\rho = 0. By Claim 1, particle ii adds qi(1−wi)/Δx+qiwi/Δx=qi/Δxq_i (1 - w_i) / \Delta x + q_i w_i / \Delta x = q_i / \Delta x to the sum ∑kρk\sum_k \rho_k, and nothing else changes ρ\rho. After line L6, ∑kρk=∑iqi/Δx\sum_k \rho_k = \sum_i q_i / \Delta x. □\square

Claim 3 (linear fields). Let Ek=a+bxkE_k = a + b x_k for the points kk and k+1k + 1 next to a particle with j=kj = k, 0≤k≤M−20 \le k \le M - 2. Then line L9 returns a+bxa + b x.

Proof. Line L8 computes the same jj and ww as line L3, with x=xj+wΔxx = x_j + w \Delta x. Line L9 returns (1−w)(a+bxj)+w(a+bxj+bΔx)=a+bxj+bwΔx=a+bx(1 - w)(a + b x_j) + w (a + b x_j + b \Delta x) = a + b x_j + b w \Delta x = a + b x. □\square

Claim 4 (zero total force). Let Ej=∑k=0M−1Kj−kρkE_j = \sum_{k=0}^{M-1} K_{j - k} \rho_k with indices mod MM, and assume that K−m=−KmK_{-m} = -K_m for every mm (an odd kernel). Then ∑iqiE(xi)=0\sum_i q_i E(x_i) = 0, where E(xi)E(x_i) is the output of line L9. For N=1N = 1 this says that the self-force q1E(x1)q_1 E(x_1) is zero.

Proof. By Claim 1 applied to line L9 (lines L8 and L9 use the same shares as lines L3 to L5), E(xi)=∑kWP(xi−xk)EkE(x_i) = \sum_k W_P(x_i - x_k) E_k. Then

∑iqiE(xi)=∑kEk∑iqiWP(xi−xk)=Δx∑kρkEk=Δx∑k∑lρkKk−lρl.\sum_i q_i E(x_i) = \sum_k E_k \sum_i q_i W_P(x_i - x_k) = \Delta x \sum_k \rho_k E_k = \Delta x \sum_k \sum_l \rho_k K_{k - l} \rho_l.

Call the double sum SS. Exchange the names kk and ll: S=∑l∑kρlKl−kρk=−∑k∑lρkKk−lρl=−SS = \sum_l \sum_k \rho_l K_{l - k} \rho_k = -\sum_k \sum_l \rho_k K_{k - l} \rho_l = -S, by the oddness of KK. So S=0S = 0. □\square

The field of the example is odd. The field of the page example satisfies Ej+1/2−Ej−1/2=Δx(ρj−ρˉ)E_{j+1/2} - E_{j-1/2} = \Delta x (\rho_j - \bar\rho), ∑jEj+1/2=0\sum_j E_{j+1/2} = 0 and Ej=(Ej−1/2+Ej+1/2)/2E_j = (E_{j-1/2} + E_{j+1/2}) / 2. Let ϕ\phi be the mean-free solution of (ϕj+1−2ϕj+ϕj−1)/Δx2=−(ρj−ρˉ)(\phi_{j+1} - 2 \phi_j + \phi_{j-1}) / \Delta x^2 = -(\rho_j - \bar\rho), which is unique because the periodic 3-point Laplacian has the constants as its kernel and ρ−ρˉ\rho - \bar\rho has mean zero. Then Ej+1/2=−(ϕj+1−ϕj)/ΔxE_{j+1/2} = -(\phi_{j+1} - \phi_j) / \Delta x satisfies both conditions on the half point values, and these conditions fix them (the running sum fixes them up to one constant, and the zero mean fixes the constant). So Ej=−(ϕj+1−ϕj−1)/(2Δx)E_j = -(\phi_{j+1} - \phi_{j-1}) / (2 \Delta x). The map ρ↦ϕ\rho \mapsto \phi is a convolution with a kernel GG that is even, because the Laplacian stencil is symmetric under j↦−jj \mapsto -j. The centred difference is a convolution with an odd stencil. A convolution of an even kernel with an odd stencil is odd, so E=K∗(ρ−ρˉ)E = K * (\rho - \bar\rho) with an odd KK. An odd KK has ∑mKm=0\sum_m K_m = 0, so K∗ρˉ=0K * \bar\rho = 0 and E=K∗ρE = K * \rho. So Claim 4 applies. ■\blacksquare

Complexity

In the real-RAM model, line L1 costs Θ(M)\Theta(M) and each particle costs O(1)O(1) in lines L3 to L5 and in lines L8 and L9. So a deposit and an interpolation cost Θ(N+M)\Theta(N + M) time in each case, and Θ(M)\Theta(M) extra space for the grid. In dd dimensions each particle touches 2d2^d grid points, which gives Θ(2dN+M)\Theta(2^d N + M). The cost of the whole force step is that of the field solver, for example O(Mlog⁡M)O(M \log M) with the fast Fourier transform on the particle-mesh method page.

Properties

  • Charge is conserved exactly. The two shares of each particle add to 1.
  • Momentum is conserved. With the same weights in both directions and an odd field kernel, the forces sum to zero, and a lone particle feels no force from its own charge (Hockney and Eastwood, chapter 5).
  • Continuous density. The density at each grid point is a continuous, piecewise linear function of the particle position. With NGP the density jumps when a particle crosses a cell boundary, which makes the force jump and adds noise.
  • Not smooth. The CIC force is continuous, but its derivative jumps when a particle crosses a grid point. TSC has a continuous derivative.
  • Second order interpolation. Line L9 is linear interpolation, with an error of O(Δx2)O(\Delta x^2) for a smooth field.
  • Not translation invariant. The force between two particles at a fixed separation depends a little on where the pair sits relative to the grid. This error is largest for separations of one or two cells, and is one source of grid heating in plasma codes (Birdsall and Langdon, Part 2).

Variants and improvements

  • Nearest grid point (NGP). All the charge goes to the nearest point. It costs one point per particle in each direction, but the force jumps by a large amount when a particle crosses a cell boundary.
  • Triangular shaped cloud (TSC). The cloud is a triangle of width 2Δx2 \Delta x, which gives quadratic weights on 3 points in each direction. The force has a continuous first derivative and less aliasing noise, at a cost of 3d3^d points per particle.
  • Higher order B-splines. NGP, CIC and TSC are the B-splines of order 1, 2 and 3. Higher orders are used in smooth particle mesh Ewald and in the P3M method.
  • Deconvolution. In Fourier space, the CIC weight is sinc⁡2(kΔx/2)\operatorname{sinc}^2(k \Delta x / 2) in each direction. Dividing the density by this factor, or folding it into the Green's function, reduces the smoothing of short waves.
  • Charge-conserving current deposit. Electromagnetic PIC codes deposit the current with weights that satisfy the discrete continuity equation, so that Gauss's law stays true without a correction step.

When to use it

Use CIC as the default in a particle-mesh method or a plasma particle-in-cell code. It is the least costly scheme with a continuous force, and its noise is much lower than that of NGP (Birdsall and Fuss 1969). Use TSC or a higher order spline when the force must be smooth or when aliasing noise matters, for example in cosmological runs and in particle mesh Ewald. Use NGP only when the cost per particle must be as low as possible.

Pitfalls

  • Different weights in the two directions. Depositing with CIC in lines L4 and L5 but interpolating with NGP in line L9 breaks the identity ∑iqiE(xi)=Δx∑jρjEj\sum_i q_i E(x_i) = \Delta x \sum_j \rho_j E_j. The particles then feel self-forces and the total momentum drifts. Use the same jj and ww in line L8 as in line L3.
  • A wrong floor for negative positions. Using truncation toward zero in line L3, as int(s) does, gives w<0w < 0 for a particle at x<0x < 0. Use the floor, or wrap the position into [0,L)[0, L) first.
  • Forgetting to divide by Δx\Delta x. Lines L4 and L5 give a density. Without the division, the field solver receives a charge per cell, and every field is off by the factor Δx\Delta x.
  • The periodic seam. For a particle in the last cell, point j+1j + 1 is point 0. Without the reduction mod MM, the program writes outside the array.
  • An even kernel. The momentum identity needs an odd field kernel. A one-sided difference of the potential gives a kernel that is not odd, and then the self-force is not zero even with CIC.

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.

cloud_in_cell_assignment.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cloud-in-cell-assignment/. The authors are listed in prov/JDCYVP.jsonl.
"""Cloud-in-cell (CIC) charge assignment and force interpolation on a periodic grid.

The grid has M points x_j = j dx, j = 0, ..., M - 1, with dx = L / M, on the
periodic interval [0, L). A particle at x with charge q is a uniform cloud of
width dx. The part of the cloud that lies in the cell of grid point j goes to
point j, which gives the linear weight W(x - x_j) = max(0, 1 - |x - x_j| / dx).
Each particle touches the 2 grid points around it (4 in 2D). The same weights
interpolate a grid field back to the particles.

The functions work with float or with fractions.Fraction inputs; with Fraction
every result is exact.

Cost: Theta(N) time for N particles in 1D (Theta(2^d N) in d dimensions) and
Theta(M) extra space for the grid.
"""

import math
from typing import Sequence


def cic_index(x, dx) -> tuple[int, object]:
    """The left grid index j = floor(x / dx) and the fraction w = x / dx - j in [0, 1)."""
    s = x / dx
    j = math.floor(s)
    return j, s - j


def cic_deposit(xs: Sequence, qs: Sequence, m: int, length) -> list:
    """Charge density on the M grid points of the periodic interval [0, length).

    Precondition: m >= 1, length > 0, len(xs) == len(qs). Positions may lie
    outside [0, length); they are taken modulo the period.
    """
    dx = length / m  # @line L1
    rho = [0 * dx for _ in range(m)]  # @line L1
    for x, q in zip(xs, qs):  # @line L2
        j, w = cic_index(x, dx)  # @line L3
        rho[j % m] += q * (1 - w) / dx  # @line L4
        rho[(j + 1) % m] += q * w / dx  # @line L5
    return rho  # @line L6


def cic_interpolate(field: Sequence, xs: Sequence, length) -> list:
    """Values of a grid field at the particle positions, with the CIC weights."""
    m = len(field)
    dx = length / m
    out = []
    for x in xs:  # @line L7
        j, w = cic_index(x, dx)  # @line L8
        out.append((1 - w) * field[j % m] + w * field[(j + 1) % m])  # @line L9
    return out  # @line L10


def cic_deposit_2d(ps: Sequence, qs: Sequence, nx: int, ny: int, lx, ly) -> list:
    """Charge density on an nx by ny periodic grid, rho[i][j] at (i dx, j dy).

    Each particle (x, y) gives the bilinear weights (1 - wx)(1 - wy), wx (1 - wy),
    (1 - wx) wy and wx wy to its 4 grid points.
    """
    dx, dy = lx / nx, ly / ny
    rho = [[0 * dx for _ in range(ny)] for _ in range(nx)]
    for (x, y), q in zip(ps, qs):
        i, wx = cic_index(x, dx)
        j, wy = cic_index(y, dy)
        c = q / (dx * dy)
        for a, fa in ((i, 1 - wx), (i + 1, wx)):
            for b, fb in ((j, 1 - wy), (j + 1, wy)):
                rho[a % nx][b % ny] += c * fa * fb
    return rho


def cic_interpolate_2d(field: Sequence, ps: Sequence, lx, ly) -> list:
    """Values of a 2D grid field field[i][j] at the particle positions, with the bilinear weights."""
    nx, ny = len(field), len(field[0])
    dx, dy = lx / nx, ly / ny
    out = []
    for x, y in ps:
        i, wx = cic_index(x, dx)
        j, wy = cic_index(y, dy)
        v = 0 * dx
        for a, fa in ((i, 1 - wx), (i + 1, wx)):
            for b, fb in ((j, 1 - wy), (j + 1, wy)):
                v += fa * fb * field[a % nx][b % ny]
        out.append(v)
    return out
test_cloud_in_cell_assignment.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cloud-in-cell-assignment/. The authors are listed in prov/JDCYVP.jsonl.
import random
from fractions import Fraction as Fr

import pytest

from cloud_in_cell_assignment import (
    cic_deposit,
    cic_deposit_2d,
    cic_interpolate,
    cic_interpolate_2d,
)


def brute_deposit(xs, qs, m, length):
    """Oracle: rho_j = sum_i q_i W(x_i - x_j) / dx with the hat W, summed over periodic images."""
    dx = length / m
    rho = []
    for j in range(m):
        s = 0.0
        for x, q in zip(xs, qs):
            for k in range(-4, 5):
                d = abs(x - j * dx - k * length)
                s += q * max(0.0, 1 - d / dx) / dx
        rho.append(s)
    return rho


def field_from_density(rho, length):
    """Periodic 1D field with dE/dx = rho - mean(rho) and zero mean.

    E at the half points is a running sum; E at grid point j is the mean of the
    two half points around it. This is minus the centred difference of the
    potential of the 3-point Laplacian, so its kernel is antisymmetric.
    """
    m = len(rho)
    dx = length / m
    mean = sum(rho) / m
    half, acc = [], 0 * dx
    for r in rho:
        acc += dx * (r - mean)
        half.append(acc)
    shift = sum(half) / m
    half = [h - shift for h in half]
    return [(half[j] + half[j - 1]) / 2 for j in range(m)]


def test_page_example():
    rho = cic_deposit([0.25, 1.5, 3.75], [1, 2, 1], 4, 4.0)
    assert rho == [1.5, 1.25, 1.0, 0.25]
    e = cic_interpolate([1.0, 0.0, -1.0, 0.0], [0.25, 1.5, 3.75], 4.0)
    assert e == [0.75, -0.5, 0.75]


def test_matches_brute_force():
    rng = random.Random(11)
    for _ in range(500):
        m = rng.randint(1, 9)
        length = rng.uniform(0.5, 5.0)
        n = rng.randint(0, 6)
        xs = [rng.uniform(-length, 2 * length) for _ in range(n)]
        qs = [rng.uniform(-2, 2) for _ in range(n)]
        got = cic_deposit(xs, qs, m, length)
        want = brute_deposit(xs, qs, m, length)
        assert got == pytest.approx(want, abs=1e-9)


def test_charge_conserved_exactly():
    rng = random.Random(5)
    for _ in range(200):
        m = rng.randint(1, 12)
        length = Fr(rng.randint(1, 30), rng.randint(1, 7))
        n = rng.randint(0, 8)
        xs = [Fr(rng.randint(-500, 500), rng.randint(1, 50)) for _ in range(n)]
        qs = [Fr(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(n)]
        rho = cic_deposit(xs, qs, m, length)
        assert sum(rho) * (length / m) == sum(qs)


def test_particle_on_grid_point():
    rho = cic_deposit([Fr(3)], [Fr(2)], 8, Fr(8))
    assert rho == [0, 0, 0, 2, 0, 0, 0, 0]
    assert cic_deposit([], [], 3, 1.0) == [0.0, 0.0, 0.0]


def test_interpolation_reproduces_linear_fields():
    # Away from the periodic seam, CIC interpolation is exact for a + b x.
    m, length = 10, Fr(10)
    field = [Fr(3) - Fr(1, 2) * j for j in range(m)]
    rng = random.Random(2)
    xs = [Fr(rng.randint(0, 899), 100) for _ in range(100)]
    got = cic_interpolate(field, xs, length)
    assert got == [Fr(3) - Fr(1, 2) * x for x in xs]


def test_no_self_force_and_momentum_conserved_exactly():
    rng = random.Random(7)
    length, m = Fr(16), 16
    # one particle: its own field gives it no force, wherever it is
    for _ in range(50):
        x = Fr(rng.randint(0, 1599), 100)
        rho = cic_deposit([x], [Fr(1)], m, length)
        e = cic_interpolate(field_from_density(rho, length), [x], length)
        assert e == [0]
    # many particles: the forces sum to zero exactly
    for _ in range(30):
        n = rng.randint(2, 10)
        xs = [Fr(rng.randint(0, 1599), 100) for _ in range(n)]
        qs = [Fr(rng.randint(-5, 5)) for _ in range(n)]
        rho = cic_deposit(xs, qs, m, length)
        e = cic_interpolate(field_from_density(rho, length), xs, length)
        assert sum(q * ei for q, ei in zip(qs, e)) == 0


def test_2d_conservation_and_bilinear_reproduction():
    rng = random.Random(3)
    nx, ny, lx, ly = 4, 6, Fr(2), Fr(3)
    ps = [(Fr(rng.randint(0, 199), 100), Fr(rng.randint(0, 299), 100)) for _ in range(20)]
    qs = [Fr(rng.randint(1, 4)) for _ in ps]
    rho = cic_deposit_2d(ps, qs, nx, ny, lx, ly)
    assert sum(map(sum, rho)) * (lx / nx) * (ly / ny) == sum(qs)
    # a bilinear field a + b x + c y + d x y is reproduced inside one period
    dx, dy = lx / nx, ly / ny
    f = lambda x, y: 1 + 2 * x - 3 * y + x * y
    field = [[f(i * dx, j * dy) for j in range(ny)] for i in range(nx)]
    inside = [(x, y) for x, y in ps if x < lx - dx and y < ly - dy]
    got = cic_interpolate_2d(field, inside, lx, ly)
    assert got == [f(x, y) for x, y in inside]


def test_2d_matches_product_of_1d_weights():
    rng = random.Random(9)
    for _ in range(100):
        x, y = rng.uniform(0, 3), rng.uniform(0, 2)
        rho = cic_deposit_2d([(x, y)], [1.0], 3, 2, 3.0, 2.0)
        rx = cic_deposit([x], [1.0], 3, 3.0)
        ry = cic_deposit([y], [1.0], 2, 2.0)
        for i in range(3):
            for j in range(2):
                assert rho[i][j] == pytest.approx(rx[i] * ry[j], abs=1e-12)

History

Birdsall and Fuss (1969) introduced the clouds-in-cells method for plasma simulation, and showed that it has much less noise than nearest grid point assignment. Hockney and Eastwood (1988) treat NGP, CIC and TSC as one family of assignment functions, and derive the conditions for momentum conservation and for a zero self-force.

References

  1. Roger W. Hockney and James W. Eastwood, Computer Simulation Using Particles, Adam Hilger, 1988, Chapter 5 (the particle-mesh force calculation, the assignment functions NGP, CIC and TSC, momentum conservation and the self-force)
  2. 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 chapter on the numerical methods of the program ES1 (linear weighting), and Part 2, the chapter on the effects of the spatial grid
  3. Charles K. Birdsall and Dieter Fuss, Clouds-in-clouds, clouds-in-cells physics for many-body plasma simulation, Journal of Computational Physics 3(4), 1969, 494-511, the clouds-in-cells method and its lower noise compared with nearest grid point assignment

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