Algorithm Search⌘K

Algorithmcore

Transport sweep

Solves for each direction cell by cell in upwind order, so a source iteration needs no matrix inversion; parallel versions pipeline the sweeps.

Time
O(N (M + F)) worst
Space
O(M + F) extra
Where
F = the number of faces; M = the number of cells; N = the number of directions
Properties
deterministicexactnot iterativenot randomized

A transport sweep solves the discrete transport equation Ω⋅∇ψ+Σtψ=q\Omega\cdot\nabla\psi + \Sigma_t\psi = q for one direction of flight Ω\Omega when the source qq is known. Particles that fly along Ω\Omega only depend on what lies behind them, so the cells can be solved one at a time in the order in which the particles reach them. Each cell takes its inflow from cells that are already solved. This is the exact inverse of the streaming and collision operator, in a number of operations proportional to the size of the mesh, and it is the inner step of source iteration and of the discrete ordinates method. On an unstructured mesh the order is a topological sort of the upwind graph, which exists only when the graph has no cycle.

In plain words

Think of rain that falls at a slant through a grid of boxes. A box only gets water from the boxes upwind of it. So you start with the boxes at the edge where the rain comes in, and every time all the boxes that feed a box are done, you can do that box.

Each box needs one small calculation: what comes in, what is made inside, and what is lost, gives what goes out. You never need to solve a big system of equations.

If the boxes feed each other in a ring, there is no box to start with, and the method must cut the ring. Many boxes that do not feed each other can be done at the same time, which is how parallel computers do sweeps.

The problem

Fix a direction Ω\Omega and a source qcq_c in every cell. The mesh has cells cc with volumes VcV_c and the total cross section Σt,c\Sigma_{t,c} in cm−1\mathrm{cm}^{-1}, and faces ff with the area AfA_f and a unit normal nfn_f that points out of one of its cells. For a face, gf=(Ω⋅nf)Afg_f = (\Omega\cdot n_f)A_f is the flow of particles through it per unit angular flux. The incoming angular flux is given on the boundary faces where gf<0g_f < 0, with the normal pointing out of the domain.

The step (upwind finite volume) scheme takes the angular flux on each face equal to the value of the cell upstream of it. Its balance in cell cc is

Σt,cVc ψc+∑out facesgf ψc−∑in faces∣gf∣ ψup=qcVc.\Sigma_{t,c}V_c\,\psi_c + \sum_{\text{out faces}} g_f\,\psi_c - \sum_{\text{in faces}} |g_f|\,\psi_{\mathrm{up}} = q_c V_c .

The problem is to solve these equations for all cells. The upwind graph has an edge from cell aa to cell bb when particles flow from aa into bb through a shared face.

The algorithm

  1. SWEEP(mesh, Σt, q, Ω, inflow values)
  2. 1for each interior face f between cells a and b, with g_f = (Ω·n_f) A_f
  3. 2if g_f > 0 then add the edge a → b and indeg(b) ← indeg(b) + 1; if g_f < 0 the same for b → a
  4. 3Q ← the cells with indeg = 0
  5. 4while Q is not empty do
  6. 5c ← pop Q; ψ_c ← (q_c V_c + Σ over the in faces of |g_f| ψ_up) / (Σt_c V_c + Σ over the out faces of g_f)
  7. 6for each edge c → d do indeg(d) ← indeg(d) − 1; if indeg(d) = 0 then push d on Q
  8. 7if some cell was not solved then report a cycle and the cells it blocks

Lines L1 to L3 and L6 are Kahn's algorithm for the topological sort of the upwind graph. Line L5 is the cell solve: when it runs, every upstream value ψup\psi_{\mathrm{up}} is a boundary value or the value of a cell that is already done. The order depends only on Ω\Omega and the mesh, so a code computes it once per direction and keeps it for all iterations.

On a rectangle grid the order is simply row by row and cell by cell in the direction of flight, and the implementation also has the diamond difference sweep of the discrete ordinates page in two dimensions: ψc=(q+aψL+bψB)/(Σt+a+b)\psi_c = (q + a\psi_L + b\psi_B)/(\Sigma_t + a + b) with a=2∣μ∣/Δxa = 2|\mu|/\Delta x and b=2∣η∣/Δyb = 2|\eta|/\Delta y, and then ψR=2ψc−ψL\psi_R = 2\psi_c - \psi_L, ψT=2ψc−ψB\psi_T = 2\psi_c - \psi_B.

Example

A two by two grid by hand. Take cells of 1×11 \times 1 cm, Σt=1 cm−1\Sigma_t = 1\ \mathrm{cm}^{-1}, q=1q = 1, vacuum inflow and Ω=(0.6,0.8)\Omega = (0.6, 0.8). Number the cells 0 (lower left), 1 (lower right), 2 (upper left) and 3 (upper right). The faces have g=0.6g = 0.6 in xx and g=0.8g = 0.8 in yy, so every denominator in line L5 is 1+0.6+0.8=2.41 + 0.6 + 0.8 = 2.4.

  • Line L3: only cell 0 has no upstream cell. ψ0=1/2.4=0.416667\psi_0 = 1/2.4 = 0.416667.
  • Line L6 frees cells 1 and 2. ψ1=(1+0.6⋅0.416667)/2.4=0.520833\psi_1 = (1 + 0.6 \cdot 0.416667)/2.4 = 0.520833 and ψ2=(1+0.8⋅0.416667)/2.4=0.555556\psi_2 = (1 + 0.8 \cdot 0.416667)/2.4 = 0.555556.
  • Cell 3 gets 0.6ψ2+0.8ψ1=0.750.6\psi_2 + 0.8\psi_1 = 0.75, so ψ3=1.75/2.4=0.729167\psi_3 = 1.75/2.4 = 0.729167.

The outflow through the right and top sides is 0.6(ψ1+ψ3)+0.8(ψ2+ψ3)=1.7777780.6(\psi_1 + \psi_3) + 0.8(\psi_2 + \psi_3) = 1.777778. The absorption is ψ0+ψ1+ψ2+ψ3=2.222222\psi_0 + \psi_1 + \psi_2 + \psi_3 = 2.222222, and the two add to the total source 4. The cells form 3 wavefronts: {0}\{0\}, {1,2}\{1, 2\} and {3}\{3\}.

First order on triangles. On the unit square cut into 2n22n^2 triangles, a pure absorber with Σt=1\Sigma_t = 1, q=1q = 1, vacuum inflow and Ω=(cos⁡0.4,sin⁡0.4)\Omega = (\cos 0.4, \sin 0.4) has the exact solution ψ=1−e−s\psi = 1 - e^{-s}, where ss is the distance back to the inflow side along Ω\Omega. The error of the step sweep, summed over the cells with the cell areas, is:

nn triangles error ratio outflow
8 128 2.036×10−22.036 \times 10^{-2} 0.642776
16 512 1.192×10−21.192 \times 10^{-2} 1.71 0.649119
32 2048 6.617×10−36.617 \times 10^{-3} 1.80 0.652428

The ratio tends to 2, the first order of the step scheme; the exact outflow is 0.655832. The balance of absorption, outflow and source holds to 5×10−165 \times 10^{-16} on every mesh.

Second order with diamond difference. For μ=0.6\mu = 0.6, η=0.3\eta = 0.3, Σt=2\Sigma_t = 2 on the unit square, the source q=(Σt−μ−η)e−(x+y)q = (\Sigma_t - \mu - \eta)e^{-(x + y)} and the matching inflow have the solution ψ=e−(x+y)\psi = e^{-(x + y)}. The largest error of the cell values on an n×nn \times n grid is 1.010×10−31.010 \times 10^{-3}, 2.860×10−42.860 \times 10^{-4}, 7.624×10−57.624 \times 10^{-5} and 1.969×10−51.969 \times 10^{-5} for n=8,16,32,64n = 8, 16, 32, 64. The ratios 3.533.53, 3.753.75 and 3.873.87 tend to 4, which is second order (a measurement).

A negative value. One cell of 1×11 \times 1 cm with Σt=1\Sigma_t = 1, no source, μ=η=0.1\mu = \eta = 0.1 and the inflow 1 on both sides gives the cell value 2/72/7 and the outgoing values −3/7-3/7 on both sides with diamond difference.

Correctness

The proofs are in the proof file. Kahn's algorithm outputs a cell only after all its upstream cells, and it outputs every cell exactly when the upwind graph has no cycle; otherwise the unsolved cells are those on a cycle or downstream of one, so line L7 detects cycles exactly. In the sweep order the matrix of the cell equations is lower triangular with a positive diagonal, so line L5 computes the one solution. Adding the cell balances cancels every interior face, so absorption plus outflow equals the source plus the inflow. With a source and inflow that are not negative, the step values are not negative. On a grid with both components of Ω\Omega nonzero, cell (i,j)(i, j) is on wavefront i+j+1i + j + 1, so there are nx+ny−1n_x + n_y - 1 wavefronts.

Proof: The Kahn order of the upwind graph solves every cell with known inflow, a cycle is detected exactly, the converged sweep balances and stays positive, and a grid has i plus j plus 1 wavefront levelsfull

We assume exact arithmetic. The mesh, the faces (a,b,n,A)(a, b, n, A) and the lines L1 to L7 are those of the page. Every cell has a volume Vc>0V_c > 0 and Σt,c>0\Sigma_{t,c} > 0. For a face with the unit normal nn out of cell aa, write g=(Ω⋅n)Ag = (\Omega\cdot n)A. The upwind graph GΩG_\Omega has an edge a→ba \to b when g>0g > 0 and an edge b→ab \to a when g<0g < 0, for every interior face. A face with g=0g = 0 gives no edge. The cell equation of the step scheme is

Σt,cVc ψc+∑f∈out(c)gf ψc−∑f∈in(c)∣gf∣ ψup(f)=qcVc,(1)\Sigma_{t,c}V_c\,\psi_c + \sum_{f \in \mathrm{out}(c)} g_f\,\psi_c - \sum_{f \in \mathrm{in}(c)} |g_f|\,\psi_{\mathrm{up}(f)} = q_c V_c, \tag{1}

where gfg_f is taken with the normal out of cc, out(c)\mathrm{out}(c) are the faces of cc with gf>0g_f > 0, in(c)\mathrm{in}(c) those with gf<0g_f < 0, and ψup(f)\psi_{\mathrm{up}(f)} is the value of the cell on the other side, or the given inflow value on a boundary face.

Lemma 1 (the order). Lines L1 to L6 output a cell only after all its upstream cells in GΩG_\Omega. They output every cell if and only if GΩG_\Omega has no directed cycle. Otherwise the cells they do not output are exactly the cells that lie on a cycle or can be reached from one.

Proof. Line L2 sets indeg(c)\mathrm{indeg}(c) to the number of edges into cc. Line L6 lowers it by one when an upstream cell is output, and a cell enters the queue only when it reaches 0, that is after all its upstream cells. This is Kahn's algorithm for topological sort.

If GΩG_\Omega has a cycle, no cell of the cycle can be output first among the cells of the cycle, because its predecessor on the cycle must come before it. So no cell of a cycle is output, and by the first part no cell that can be reached from one is output. Conversely, let cc be a cell that is not output. Then at the end indeg(c)>0\mathrm{indeg}(c) > 0, so cc has an upstream cell c′c' that is not output. Repeat with c′c'. The mesh is finite, so the chain c←c′←c′′←⋯c \leftarrow c' \leftarrow c'' \leftarrow \cdots repeats a cell, which gives a cycle from which cc can be reached. □\square

So line L7 raises an error exactly when the mesh has a cycle for Ω\Omega, and the implementation names the blocked cells.

Theorem 2 (one sweep solves the direction). If GΩG_\Omega has no cycle, the system (1) for all cells has exactly one solution, and line L5 computes it.

Proof. When line L5 solves cell cc, every term ψup(f)\psi_{\mathrm{up}(f)} with f∈in(c)f \in \mathrm{in}(c) is known: it is boundary data, or the value of an upstream cell, which Lemma 1 has output earlier. Then (1) is one linear equation in ψc\psi_c with the coefficient Σt,cVc+∑out(c)gf>0\Sigma_{t,c}V_c + \sum_{\mathrm{out}(c)} g_f > 0, so ψc\psi_c is unique and line L5 gives it. Ordered in the sweep order, the matrix of (1) is lower triangular with a positive diagonal, so the whole system has exactly one solution. □\square

Theorem 3 (balance). The values of Theorem 2 satisfy

∑cΣt,cVc ψc+Jout=∑cqcVc+Jin,\sum_c \Sigma_{t,c}V_c\,\psi_c + J^{\mathrm{out}} = \sum_c q_c V_c + J^{\mathrm{in}},

where Jout=∑gfψcJ^{\mathrm{out}} = \sum g_f \psi_c over the boundary faces with gf>0g_f > 0 and Jin=∑∣gf∣ ψinJ^{\mathrm{in}} = \sum |g_f|\,\psi_{\mathrm{in}} over the boundary faces with gf<0g_f < 0.

Proof. Add (1) over all cells. An interior face ff with gf≠0g_f \ne 0 appears in two equations: with +∣gf∣ψup+|g_f|\psi_{\mathrm{up}} in the equation of its upstream cell, where it is an out face, and with −∣gf∣ψup-|g_f|\psi_{\mathrm{up}} in the equation of its downstream cell, where it is an in face. These cancel. What remains are the boundary faces. □\square

Theorem 4 (positivity). If qc≥0q_c \ge 0 for every cell and the inflow values are not negative, then every ψc≥0\psi_c \ge 0. If moreover each cell is closed, ∑fnfAf=0\sum_{f} n_f A_f = 0, then a constant ψ0\psi_0 with q=Σtψ0q = \Sigma_t\psi_0 and the inflow ψ0\psi_0 is reproduced exactly.

Proof. By induction in the sweep order, the numerator of line L5 is a sum of terms that are not negative, and the denominator is positive. For the second part, closure gives ∑out(c)gf=∑in(c)∣gf∣\sum_{\mathrm{out}(c)} g_f = \sum_{\mathrm{in}(c)} |g_f|, so ψc=ψ0\psi_c = \psi_0 satisfies (1) in every cell, and Theorem 2 makes it the solution. □\square

Theorem 5 (wavefronts on a grid). On an nxn_x by nyn_y grid of rectangles with Ωx>0\Omega_x > 0 and Ωy>0\Omega_y > 0, the level of cell (i,j)(i, j), counted from 0, is i+j+1i + j + 1, so there are nx+ny−1n_x + n_y - 1 levels. Cells with the same level have no edge between them. If Ωy=0\Omega_y = 0, there are nxn_x levels.

Proof. The edges of GΩG_\Omega are (i,j)→(i+1,j)(i, j) \to (i + 1, j) and (i,j)→(i,j+1)(i, j) \to (i, j + 1). Cell (0,0)(0, 0) has no upstream cell and level 1. By induction on i+ji + j, the upstream cells of (i,j)(i, j) are (i−1,j)(i - 1, j) and (i,j−1)(i, j - 1) when they exist, both with level i+ji + j, so (i,j)(i, j) has level i+j+1i + j + 1. Every edge raises the level by exactly 1, so it never joins two cells of one level. If Ωy=0\Omega_y = 0, the faces between rows have g=0g = 0, only the edges in xx remain, and the level of (i,j)(i, j) is i+1i + 1. □\square

So the cells of one level can be solved at the same time, and a grid sweep has at most min⁡(nx,ny)\min(n_x, n_y) cells at the same level.

Theorem 6 (the diamond difference sweep on a grid). For a direction (μ,η)(\mu, \eta) with μ≠0\mu \ne 0 and η≠0\eta \ne 0, and every cell (i,j)(i, j), the equations

∣μ∣ψR−ψLΔxi+∣η∣ψT−ψBΔyj+Σtψc=q,ψc=ψL+ψR2=ψB+ψT2,|\mu|\frac{\psi_R - \psi_L}{\Delta x_i} + |\eta|\frac{\psi_T - \psi_B}{\Delta y_j} + \Sigma_t\psi_c = q, \qquad \psi_c = \frac{\psi_L + \psi_R}{2} = \frac{\psi_B + \psi_T}{2},

with the incoming values ψL\psi_L and ψB\psi_B known, have exactly one solution, ψc=(q+aψL+bψB)/(Σt+a+b)\psi_c = (q + a\psi_L + b\psi_B)/(\Sigma_t + a + b) with a=2∣μ∣/Δxia = 2|\mu|/\Delta x_i and b=2∣η∣/Δyjb = 2|\eta|/\Delta y_j, and ψR=2ψc−ψL\psi_R = 2\psi_c - \psi_L, ψT=2ψc−ψB\psi_T = 2\psi_c - \psi_B. The loop of the implementation, rows in the direction of η\eta and cells in a row in the direction of μ\mu, solves all cells.

Proof. The two diamond relations give ψR−ψL=2(ψc−ψL)\psi_R - \psi_L = 2(\psi_c - \psi_L) and ψT−ψB=2(ψc−ψB)\psi_T - \psi_B = 2(\psi_c - \psi_B). Put them into the balance: (Σt+a+b)ψc=q+aψL+bψB(\Sigma_t + a + b)\psi_c = q + a\psi_L + b\psi_B, with a positive factor on the left. The row by row order is a topological order of the grid graph of Theorem 5, so the argument of Theorem 2 applies. □\square

With q=0q = 0 and ψL=ψB=1\psi_L = \psi_B = 1, both outgoing values are 2ψc−1=(a+b−Σt)/(Σt+a+b)2\psi_c - 1 = (a + b - \Sigma_t)/(\Sigma_t + a + b), which is negative when Σt>a+b\Sigma_t > a + b. The page shows the case μ=η=0.1\mu = \eta = 0.1, Δx=Δy=1\Delta x = \Delta y = 1, Σt=1\Sigma_t = 1, which gives −3/7-3/7.

Complexity

In the real RAM model, lines L1 and L2 visit each face once, and lines L4 to L6 visit each cell once and each face at most twice, so one direction costs O(M+F)O(M + F) operations and NN directions cost O(N(M+F))O(N(M + F)). If the order of each direction is stored, the later sweeps skip lines L1 to L3, but the storage is O(NM)O(NM). The extra memory of one sweep is O(M+F)O(M + F) for the graph and the counters. On a grid this is O(M)O(M), the same as the cell loop of the discrete ordinates method.

The sweep is sequential along each path of the graph. With PP processors the time of one direction is at least the number of wavefronts, nx+ny−1n_x + n_y - 1 on a two-dimensional grid (Theorem 5 of the proof), and at least M/PM/P.

Properties

  • Direct and exact. For a fixed source, one sweep solves the discrete equations of a direction exactly. No iteration and no matrix are needed.
  • Conservative. Absorption plus outflow equals the source plus the inflow, for every direction and every mesh (Theorem 3 of the proof).
  • Positive for the step scheme. Step values are never negative. Diamond difference is second order but can give negative values in thick cells.
  • Direction dependent order. Each direction has its own order. Directions in the same octant on a grid share it.
  • Parallel only across wavefronts and directions. Cells on one wavefront and different directions are independent; cells along a path are not.

Variants and improvements

  • Higher order cell solves. The same order works with diamond difference, linear discontinuous finite elements and the step characteristic scheme, which solve a small dense system per cell instead of one equation.
  • KBA pipelining. Koch, Baker and Alcouffe (1992) split a three-dimensional grid into columns, one per processor, and pipeline blocks of cells and many directions through the processor grid, so that the processors downstream start before the first ones finish.
  • Cycles on unstructured meshes. Curved or non-convex cells, and some meshes of convex cells in three dimensions, can give cycles. A code finds the strongly connected components of the upwind graph, cuts an edge of each by using the value of the last iteration on that face, and sweeps the rest in order. This lags the inflow on the cut faces; as a rule of thumb, the iteration then converges more slowly, more so when many faces are cut.
  • Graph based scheduling. Codes for unstructured meshes compute a priority for each cell, such as its depth in the graph, and give each processor a part of the mesh, so that many directions are in flight at the same time.

When to use it

Use a sweep whenever a discrete ordinates or characteristics method needs the streaming and collision operator inverted for a known source: inside source iteration, as the operator of a Krylov method, or as a preconditioner. It suits meshes where the cells can be ordered for each direction: rectangle grids, two-dimensional meshes of convex cells, and Delaunay or other regular meshes in any dimension (by the theorem of Edelsbrunner 1990). On meshes with cycles, or on very many processors with few cells each, plan for cut edges and for idle time at the start and end of each pipeline.

Pitfalls

  • Faces with Ω⋅n=0\Omega\cdot n = 0 (line L2). Such a face carries no flow and must not add an edge. Rounding can make gfg_f tiny with either sign; this still gives a valid order, but the code must not treat a tiny negative value as an inflow from a cell that is not done.
  • Normals with the wrong sign. If a face normal points into the cell instead of out of it, the face gives the wrong edge, and the sweep can find a cycle or use a value that is not ready.
  • Silent cycles (line L7). A sweep that walks through a fixed list without checking the counters uses zero or old values on the faces of a cycle, without any error.
  • Thick cells with diamond difference. The outgoing values can be negative even when all data are positive, and a fixup makes the sweep nonlinear.
  • Storing all orders. With many directions and a large mesh, the orders and the angular fluxes use most of the memory; directions that share an order should share storage.

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.

transport_sweep.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transport-sweep/. The authors are listed in prov/WZRH6P.jsonl.
"""Transport sweeps for one direction of flight.

A sweep solves the discrete equation

    Omega . grad psi + sigma_t psi = q

for one fixed direction Omega, cell by cell, in an order in which every cell
comes after the cells that send particles into it (its upstream cells).

Unstructured meshes: a mesh is a number of cells and a list of faces
(a, b, nx, ny, area). The normal (nx, ny) is a unit vector that points out of
cell a. b is the cell on the other side, or -1 for a face on the boundary.
The cell equation is the upwind (step) finite volume balance

    sigma_t V psi_c + sum_out (Omega . n) A psi_c - sum_in |Omega . n| A psi_up = q V,

which is first order and never negative. The order is found by Kahn's
topological sort of the graph upstream cell -> downstream cell; a cycle is
reported with the cells that could not be ordered.

Cartesian meshes: sweep_dd_2d is the diamond difference sweep of one
direction on a rectangle grid, which is second order and can give negative
values in thick cells.
"""

import math
from collections import deque


def _cell_faces(n_cells, faces):
    lists = [[] for _ in range(n_cells)]
    for f, (a, b, _, _, _) in enumerate(faces):
        lists[a].append(f)
        if b >= 0:
            lists[b].append(f)
    return lists


def _flow(face, omega):
    """Omega . n times the area, positive when particles cross from a to b."""
    _, _, nx, ny, area = face
    return (omega[0] * nx + omega[1] * ny) * area


def sweep_order(n_cells, faces, omega):
    """Kahn order of the cells for direction omega. Returns (order, blocked).

    blocked is the list of cells that lie on or after a cycle; it is empty for an acyclic mesh."""
    down = [[] for _ in range(n_cells)]
    indeg = [0] * n_cells
    for face in faces:
        a, b = face[0], face[1]
        if b < 0:
            continue
        g = _flow(face, omega)
        if g > 0:
            down[a].append(b)
            indeg[b] += 1
        elif g < 0:
            down[b].append(a)
            indeg[a] += 1
    queue = deque(c for c in range(n_cells) if indeg[c] == 0)
    order = []
    while queue:
        c = queue.popleft()
        order.append(c)
        for d in down[c]:
            indeg[d] -= 1
            if indeg[d] == 0:
                queue.append(d)
    blocked = [c for c in range(n_cells) if indeg[c] > 0]
    return order, blocked


def wavefronts(n_cells, faces, omega):
    """Level of each cell: 1 for cells without upstream cells, else 1 + the largest level upstream.

    Cells of the same level can be solved at the same time. Returns (levels, number of levels)."""
    order, blocked = sweep_order(n_cells, faces, omega)
    if blocked:
        raise ValueError("the mesh has a cycle for this direction")
    level = [1] * n_cells
    cf = _cell_faces(n_cells, faces)
    for c in order:
        for f in cf[c]:
            a, b = faces[f][0], faces[f][1]
            if b < 0:
                continue
            g = _flow(faces[f], omega)
            up = a if g > 0 else b if g < 0 else -1
            if up >= 0 and up != c:
                level[c] = max(level[c], level[up] + 1)
    return level, max(level)


def sweep_step(n_cells, faces, volume, sigma_t, q, omega, psi_in=0.0):
    """Upwind sweep of one direction on an unstructured mesh.

    psi_in is the incoming angular flux on the boundary (a number, or a function of the face index).
    Returns (psi per cell, outflow through the boundary, inflow through the boundary)."""
    cf = _cell_faces(n_cells, faces)
    down = [[] for _ in range(n_cells)]
    indeg = [0] * n_cells
    for face in faces:  # @line L1
        a, b = face[0], face[1]
        if b < 0:
            continue
        g = _flow(face, omega)
        if g > 0:
            down[a].append(b)
            indeg[b] += 1  # @line L2
        elif g < 0:
            down[b].append(a)
            indeg[a] += 1
    queue = deque(c for c in range(n_cells) if indeg[c] == 0)  # @line L3
    psi = [0.0] * n_cells
    done = [False] * n_cells
    outflow = inflow = 0.0
    while queue:  # @line L4
        c = queue.popleft()
        num = q[c] * volume[c]
        den = sigma_t[c] * volume[c]
        for f in cf[c]:
            a, b = faces[f][0], faces[f][1]
            g = _flow(faces[f], omega)
            if c == b:
                g = -g  # the flow out of c through this face
            other = b if c == a else a
            if g > 0:
                den += g
            elif g < 0:
                if other < 0:
                    v = psi_in(f) if callable(psi_in) else psi_in
                    inflow += -g * v
                else:
                    v = psi[other]
                num += -g * v
        psi[c] = num / den  # @line L5
        done[c] = True
        for d in down[c]:  # @line L6
            indeg[d] -= 1
            if indeg[d] == 0:
                queue.append(d)
    if not all(done):  # @line L7
        raise ValueError("the mesh has a cycle for this direction: cells %s" % [c for c in range(n_cells) if not done[c]])
    for f, (a, b, _, _, _) in enumerate(faces):
        if b < 0:
            g = _flow(faces[f], omega)
            if g > 0:
                outflow += g * psi[a]
    return psi, outflow, inflow


def cartesian_mesh(nx, ny, lx, ly):
    """Rectangle cells numbered i + nx j. Returns (number of cells, faces, volumes, centroids)."""
    hx, hy = lx / nx, ly / ny
    faces = []
    for j in range(ny):
        for i in range(nx):
            c = i + nx * j
            faces.append((c, c + 1 if i < nx - 1 else -1, 1.0, 0.0, hy))
            faces.append((c, c + nx if j < ny - 1 else -1, 0.0, 1.0, hx))
            if i == 0:
                faces.append((c, -1, -1.0, 0.0, hy))
            if j == 0:
                faces.append((c, -1, 0.0, -1.0, hx))
    cent = [((i + 0.5) * hx, (j + 0.5) * hy) for j in range(ny) for i in range(nx)]
    return nx * ny, faces, [hx * hy] * (nx * ny), cent


def triangle_mesh(nx, ny, lx, ly):
    """Each rectangle cut along its rising diagonal into a lower triangle 2k and an upper triangle 2k + 1."""
    hx, hy = lx / nx, ly / ny
    d = math.hypot(hx, hy)
    dn = (-hy / d, hx / d)  # normal of the diagonal, out of the lower triangle
    faces = []
    for j in range(ny):
        for i in range(nx):
            k = i + nx * j
            lo, up = 2 * k, 2 * k + 1
            faces.append((lo, up, dn[0], dn[1], d))
            # the lower triangle has the bottom and right sides, the upper one the top and left sides
            faces.append((lo, 2 * (k - nx) + 1 if j > 0 else -1, 0.0, -1.0, hx))
            faces.append((lo, 2 * (k + 1) + 1 if i < nx - 1 else -1, 1.0, 0.0, hy))
            if j == ny - 1:
                faces.append((up, -1, 0.0, 1.0, hx))
            if i == 0:
                faces.append((up, -1, -1.0, 0.0, hy))
    cent = []
    for j in range(ny):
        for i in range(nx):
            x0, y0 = i * hx, j * hy
            cent.append((x0 + 2 * hx / 3, y0 + hy / 3))
            cent.append((x0 + hx / 3, y0 + 2 * hy / 3))
    return 2 * nx * ny, faces, [hx * hy / 2] * (2 * nx * ny), cent


def sweep_dd_2d(mu, eta, sigma_t, q, dx, dy, inc_x, inc_y):
    """Diamond difference sweep of the direction (mu, eta) on a rectangle grid.

    sigma_t[i][j] and q[i][j] are the cell data, inc_x[j] the incoming values on the x face where the
    direction enters, inc_y[i] those on the y face. Returns (cell values, outgoing x face values,
    outgoing y face values)."""
    nx, ny = len(dx), len(dy)
    ii = list(range(nx)) if mu > 0 else list(range(nx - 1, -1, -1))
    jj = list(range(ny)) if eta > 0 else list(range(ny - 1, -1, -1))
    face_y = list(inc_y)
    out_x = [0.0] * ny
    cells = [[0.0] * ny for _ in range(nx)]
    for j in jj:
        face_x = inc_x[j]
        for i in ii:
            a = 2.0 * abs(mu) / dx[i]
            b = 2.0 * abs(eta) / dy[j]
            c = (q[i][j] + a * face_x + b * face_y[i]) / (sigma_t[i][j] + a + b)
            cells[i][j] = c
            face_x = 2.0 * c - face_x
            face_y[i] = 2.0 * c - face_y[i]
        out_x[j] = face_x
    return cells, out_x, face_y
test_transport_sweep.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transport-sweep/. The authors are listed in prov/WZRH6P.jsonl.
import math
import random
import unittest

from transport_sweep import (cartesian_mesh, sweep_dd_2d, sweep_order, sweep_step, triangle_mesh,
                             wavefronts)

OMEGA = (math.cos(0.4), math.sin(0.4))


def exact_absorber(x, y, sigma_t=1.0):
    # constant source 1, vacuum inflow: psi = (1 - exp(-sigma_t s)) / sigma_t, s = distance to the inflow side
    s = min(x / OMEGA[0], y / OMEGA[1])
    return (1.0 - math.exp(-sigma_t * s)) / sigma_t


def avg_exp(a, b):
    return (math.exp(-a) - math.exp(-b)) / (b - a)


class TestOrder(unittest.TestCase):
    def check_upwind_order(self, n_cells, faces, omega, order):
        pos = {c: k for k, c in enumerate(order)}
        self.assertEqual(sorted(order), list(range(n_cells)))
        for a, b, nx, ny, area in faces:
            if b < 0:
                continue
            g = omega[0] * nx + omega[1] * ny
            if g > 0:
                self.assertLess(pos[a], pos[b])
            elif g < 0:
                self.assertLess(pos[b], pos[a])

    def test_orders_are_upwind_for_many_directions(self):
        rng = random.Random(3)
        meshes = [cartesian_mesh(7, 5, 1.0, 2.0), triangle_mesh(6, 6, 1.0, 1.0)]
        for _ in range(20):
            a = rng.uniform(0.0, 2.0 * math.pi)
            omega = (math.cos(a), math.sin(a))
            for n_cells, faces, _, _ in meshes:
                order, blocked = sweep_order(n_cells, faces, omega)
                self.assertEqual(blocked, [])
                self.check_upwind_order(n_cells, faces, omega, order)

    def test_cycle_is_reported(self):
        faces = [(0, 1, 1.0, 0.0, 1.0), (1, 2, 0.0, 1.0, 1.0), (2, 0, 1.0, 0.0, 1.0), (2, 3, 1.0, 0.0, 1.0),
                 (4, 0, 1.0, 0.0, 1.0)]
        order, blocked = sweep_order(5, faces, (0.8, 0.6))
        self.assertEqual(order, [4])
        self.assertEqual(blocked, [0, 1, 2, 3])
        with self.assertRaises(ValueError):
            sweep_step(5, faces, [1.0] * 5, [1.0] * 5, [1.0] * 5, (0.8, 0.6))
        # the opposite normal on the face 2-0 breaks the cycle
        faces[2] = (2, 0, -1.0, 0.0, 1.0)
        order, blocked = sweep_order(5, faces, (0.8, 0.6))
        self.assertEqual(blocked, [])

    def test_wavefronts_of_a_grid(self):
        for nx, ny in ((4, 4), (7, 3), (16, 9)):
            n_cells, faces, _, _ = cartesian_mesh(nx, ny, 1.0, 1.0)
            level, count = wavefronts(n_cells, faces, (0.6, 0.8))
            self.assertEqual(count, nx + ny - 1)
            for j in range(ny):
                for i in range(nx):
                    self.assertEqual(level[i + nx * j], i + j + 1)
            _, count = wavefronts(n_cells, faces, (1.0, 0.0))
            self.assertEqual(count, nx)


class TestStepSweep(unittest.TestCase):
    def test_two_by_two_by_hand(self):
        n_cells, faces, vol, _ = cartesian_mesh(2, 2, 2.0, 2.0)
        psi, out, inflow = sweep_step(n_cells, faces, vol, [1.0] * 4, [1.0] * 4, (0.6, 0.8))
        for got, want in zip(psi, (1 / 2.4, 1.25 / 2.4, (4 / 3) / 2.4, 1.75 / 2.4)):
            self.assertAlmostEqual(got, want, places=14)
        self.assertAlmostEqual(out, 16.0 / 9.0, places=13)
        self.assertEqual(inflow, 0.0)

    def test_balance_and_positivity(self):
        rng = random.Random(11)
        for n_cells, faces, vol, _ in (cartesian_mesh(10, 8, 3.0, 2.0), triangle_mesh(9, 9, 2.0, 2.0)):
            st = [rng.uniform(0.1, 20.0) for _ in range(n_cells)]
            q = [rng.uniform(0.0, 5.0) for _ in range(n_cells)]
            for _ in range(5):
                a = rng.uniform(0.0, 2.0 * math.pi)
                omega = (math.cos(a), math.sin(a))
                psi, out, inflow = sweep_step(n_cells, faces, vol, st, q, omega, psi_in=0.7)
                absorbed = sum(s * p * v for s, p, v in zip(st, psi, vol))
                source = sum(x * v for x, v in zip(q, vol))
                self.assertAlmostEqual(absorbed + out, source + inflow, delta=1e-11 * (source + inflow))
                self.assertGreaterEqual(min(psi), 0.0)

    def test_pure_absorber_converges_at_first_order(self):
        errors = []
        for n in (8, 16, 32):
            n_cells, faces, vol, cent = triangle_mesh(n, n, 1.0, 1.0)
            psi, _, _ = sweep_step(n_cells, faces, vol, [1.0] * n_cells, [1.0] * n_cells, OMEGA)
            errors.append(sum(abs(p - exact_absorber(*xy)) * v for p, xy, v in zip(psi, cent, vol)))
        self.assertAlmostEqual(errors[0], 2.0361e-02, delta=1e-6)
        self.assertGreater(errors[0] / errors[1], 1.6)
        self.assertGreater(errors[1] / errors[2], 1.7)
        self.assertLess(errors[1] / errors[2], 2.2)

    def test_uniform_inflow_without_source_decays(self):
        n_cells, faces, vol, _ = cartesian_mesh(1, 1, 1.0, 1.0)
        psi, out, inflow = sweep_step(n_cells, faces, vol, [2.0], [0.0], (1.0, 0.0), psi_in=1.0)
        self.assertAlmostEqual(psi[0], 1.0 / 3.0, places=15)
        self.assertAlmostEqual(inflow, 1.0, places=15)
        self.assertAlmostEqual(out, 1.0 / 3.0, places=15)


class TestDiamond2D(unittest.TestCase):
    def manufactured(self, n, mu, eta, st=2.0):
        h = 1.0 / n
        ax = [avg_exp(i * h, (i + 1) * h) for i in range(n)]
        q = [[(st - abs(mu) - abs(eta)) * ax[i] * ax[j] for j in range(n)] for i in range(n)]
        cells, out_x, out_y = sweep_dd_2d(mu, eta, [[st] * n for _ in range(n)], q, [h] * n, [h] * n, ax, ax)
        return max(abs(cells[i][j] - ax[i] * ax[j]) for i in range(n) for j in range(n))

    def test_second_order(self):
        errs = [self.manufactured(n, 0.6, 0.3) for n in (8, 16, 32, 64)]
        for a, b in zip(errs, errs[1:]):
            self.assertGreater(a / b, 3.5)
            self.assertLess(a / b, 4.1)

    def test_direction_signs_mirror(self):
        rng = random.Random(5)
        nx, ny = 6, 4
        st = [[rng.uniform(0.5, 2.0) for _ in range(ny)] for _ in range(nx)]
        q = [[rng.uniform(0.0, 1.0) for _ in range(ny)] for _ in range(nx)]
        dx = [rng.uniform(0.1, 0.5) for _ in range(nx)]
        dy = [rng.uniform(0.1, 0.5) for _ in range(ny)]
        inc_x = [rng.uniform(0, 1) for _ in range(ny)]
        inc_y = [rng.uniform(0, 1) for _ in range(nx)]
        a, ax_, ay_ = sweep_dd_2d(0.7, 0.2, st, q, dx, dy, inc_x, inc_y)
        b, bx, by = sweep_dd_2d(-0.7, 0.2, st[::-1], q[::-1], dx[::-1], dy, inc_x, inc_y[::-1])
        for i in range(nx):
            for j in range(ny):
                self.assertAlmostEqual(a[i][j], b[nx - 1 - i][j], places=13)
        self.assertEqual(ax_, bx)

    def test_negative_outgoing_value_in_a_thick_cell(self):
        cells, out_x, out_y = sweep_dd_2d(0.1, 0.1, [[1.0]], [[0.0]], [1.0], [1.0], [1.0], [1.0])
        self.assertAlmostEqual(cells[0][0], 2.0 / 7.0, places=15)
        self.assertAlmostEqual(out_x[0], -3.0 / 7.0, places=15)
        self.assertAlmostEqual(out_y[0], -3.0 / 7.0, places=15)


if __name__ == "__main__":
    unittest.main()

History

The sweep is as old as the discrete ordinates codes: Carlson's SnS_n codes at Los Alamos in the 1950s solved the cells in the direction of flight on slab and rectangle meshes, and Lewis and Miller (1984) give the sweep in slab and x-y geometry with diamond difference. For parallel computers, Koch, Baker and Alcouffe (1992) introduced the pipelined KBA sweep. The question of when a mesh can be ordered for every direction comes from computational geometry: Guibas and Yao (1980) showed that disjoint convex objects in the plane can be ordered for any direction of translation, and Edelsbrunner (1990) proved that regular cell complexes, which include Delaunay triangulations, have no cycles in any dimension. Unstructured mesh codes compute the order by a topological sort of the upwind graph and break the cycles they find.

References

  1. E. E. Lewis and W. F. Miller, Jr., Computational Methods of Neutron Transport, Wiley, 1984, the sections on the sweep of the discrete ordinates equations in slab and in x-y geometry with diamond difference
  2. Marvin L. Adams and Edward W. Larsen, Fast iterative methods for discrete-ordinates particle transport calculations, Progress in Nuclear Energy 40(1), 2002, 3-159, the discussion of the transport sweep as the exact inversion of the streaming and collision operator
  3. H. Edelsbrunner, An acyclicity theorem for cell complexes in d dimensions, Combinatorica 10(3), 1990, 251-260, the theorem that regular cell complexes, among them Delaunay triangulations, have no cycle in the in-front relation for any direction
  4. L. J. Guibas and F. F. Yao, On translating a set of rectangles, Proceedings of the 12th ACM Symposium on Theory of Computing, 1980, 154-160, the result that disjoint convex objects in the plane can be ordered for every direction
  5. K. R. Koch, R. S. Baker and R. E. Alcouffe, Solution of the first-order form of three-dimensional discrete ordinates equations on a massively parallel machine, Transactions of the American Nuclear Society 65, 1992, 198-199, the KBA pipelined parallel sweep

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
  • History with a source
  • a scene preset for the example