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
- Model
- Real RAM
- Properties
- conservativedeterministic
- Evidence
- Proof sketchCode in 1 languages
- 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 points , , on with , and particles with positions and charges (masses on gravity pages). The first output is the grid density
with taken over the periodic images. The second output, for a grid field , is the field at each particle, . The function is the overlap of a cloud of width centred at with the cell , divided by . Hockney and Eastwood write the assignment function as and call this choice CIC; nearest grid point (NGP) and triangular shaped cloud (TSC) are its neighbours of lower and higher order.
The algorithm
CIC-DEPOSIT(x[1..N], q[1..N], M, L)- 1
dx ← L / M; ρ[j] ← 0 for j = 0, ..., M - 1 - 2
for i ← 1 to N do - 3
s ← x[i] / dx; j ← ⌊s⌋; w ← s - j ▷ 0 ≤ w < 1 - 4
ρ[j mod M] ← ρ[j mod M] + q[i] (1 - w) / dx - 5
ρ[(j + 1) mod M] ← ρ[(j + 1) mod M] + q[i] w / dx - 6
return ρ CIC-INTERPOLATE(E[0..M-1], x[1..N], L)- 7
for i ← 1 to N do - 8
s ← x[i] / dx; j ← ⌊s⌋; w ← s - j ▷ the same j and w as in L3 - 9
E_i ← (1 - w) E[j mod M] + w E[(j + 1) mod M] - 10
return (E_1, ..., E_N)
Line L3 finds the grid point to the left of the particle and the fraction of a cell from that point to the particle. Lines L4 and L5 split the charge in the shares and ; the point nearer to the particle gets the larger share. Division by 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 , , and are the weights.
Example
Take and , so and the grid points are 0, 1, 2 and 3. Three particles have , and .
| particle | to point | to point | ||
|---|---|---|---|---|
| , | 0 | 0.25 | 0.75 to point 0 | 0.25 to point 1 |
| , | 1 | 0.5 | 1 to point 1 | 1 to point 2 |
| , | 3 | 0.75 | 0.25 to point 3 | 0.75 to point 0 (periodic) |
So , and .
Now solve for a field on the grid. In normalized units, Gauss's law with , differenced as with a mean-free and , gives . This is minus the centred difference of the potential of the 3-point Laplacian. Lines L7 to L9 give the fields , and at the three particles. The forces are , and , and their sum is exactly 0.
Correctness
The full proof is in the correctness proof. It shows four facts. Lines L3 to L5 compute exactly. The weights of one particle add to 1, so 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 with an odd kernel, , then the total force 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: , which uses the same 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 with , and indices are taken mod . For a particle at , line L3 sets , and , so and . Let , and let be its periodic sum.
Claim 1 (the weights). A particle at adds to and to , and for every the total it adds to is .
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 . The point is at distance from , so . The point is at distance , so . Every other point with or is at distance at least , so . The grid point and its images are the points with . So is the sum of over these , which is if , plus if , and 0 otherwise. When both cases hold for , and both lines L4 and L5 add to , which again matches.
Claim 2 (charge). .
Proof. Line L1 sets . By Claim 1, particle adds to the sum , and nothing else changes . After line L6, .
Claim 3 (linear fields). Let for the points and next to a particle with , . Then line L9 returns .
Proof. Line L8 computes the same and as line L3, with . Line L9 returns .
Claim 4 (zero total force). Let with indices mod , and assume that for every (an odd kernel). Then , where is the output of line L9. For this says that the self-force is zero.
Proof. By Claim 1 applied to line L9 (lines L8 and L9 use the same shares as lines L3 to L5), . Then
Call the double sum . Exchange the names and : , by the oddness of . So .
The field of the example is odd. The field of the page example satisfies , and . Let be the mean-free solution of , which is unique because the periodic 3-point Laplacian has the constants as its kernel and has mean zero. Then 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 . The map is a convolution with a kernel that is even, because the Laplacian stencil is symmetric under . The centred difference is a convolution with an odd stencil. A convolution of an even kernel with an odd stencil is odd, so with an odd . An odd has , so and . So Claim 4 applies.
Complexity
In the real-RAM model, line L1 costs and each particle costs in lines L3 to L5 and in lines L8 and L9. So a deposit and an interpolation cost time in each case, and extra space for the grid. In dimensions each particle touches grid points, which gives . The cost of the whole force step is that of the field solver, for example 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 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 , 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 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 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 . The particles then feel self-forces and the total momentum drifts. Use the same and 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 for a particle at . Use the floor, or wrap the position into first. - Forgetting to divide by . 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 .
- The periodic seam. For a particle in the last cell, point is point 0. Without the reduction mod , 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.
# 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JDCYVP Edit this page History Report an error Markdown