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
- Model
- Real RAM
- Properties
- deterministicexactnot iterativenot randomized
- Evidence
- Proof sketchCode in 1 languages
A transport sweep solves the discrete transport equation for one direction of flight when the source is known. Particles that fly along 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 and a source in every cell. The mesh has cells with volumes and the total cross section in , and faces with the area and a unit normal that points out of one of its cells. For a face, is the flow of particles through it per unit angular flux. The incoming angular flux is given on the boundary faces where , 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 is
The problem is to solve these equations for all cells. The upwind graph has an edge from cell to cell when particles flow from into through a shared face.
The algorithm
SWEEP(mesh, Σt, q, Ω, inflow values)- 1
for each interior face f between cells a and b, with g_f = (Ω·n_f) A_f - 2
if g_f > 0 then add the edge a → b and indeg(b) ← indeg(b) + 1; if g_f < 0 the same for b → a - 3
Q ← the cells with indeg = 0 - 4
while Q is not empty do - 5
c ← 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) - 6
for each edge c → d do indeg(d) ← indeg(d) − 1; if indeg(d) = 0 then push d on Q - 7
if 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 is a boundary value or the value of a cell that is already done. The order depends only on 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: with and , and then , .
Example
A two by two grid by hand. Take cells of cm, , , vacuum inflow and . Number the cells 0 (lower left), 1 (lower right), 2 (upper left) and 3 (upper right). The faces have in and in , so every denominator in line L5 is .
- Line L3: only cell 0 has no upstream cell. .
- Line L6 frees cells 1 and 2. and .
- Cell 3 gets , so .
The outflow through the right and top sides is . The absorption is , and the two add to the total source 4. The cells form 3 wavefronts: , and .
First order on triangles. On the unit square cut into triangles, a pure absorber with , , vacuum inflow and has the exact solution , where is the distance back to the inflow side along . The error of the step sweep, summed over the cells with the cell areas, is:
| triangles | error | ratio | outflow | |
|---|---|---|---|---|
| 8 | 128 | 0.642776 | ||
| 16 | 512 | 1.71 | 0.649119 | |
| 32 | 2048 | 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 on every mesh.
Second order with diamond difference. For , , on the unit square, the source and the matching inflow have the solution . The largest error of the cell values on an grid is , , and for . The ratios , and tend to 4, which is second order (a measurement).
A negative value. One cell of cm with , no source, and the inflow 1 on both sides gives the cell value and the outgoing values 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 nonzero, cell is on wavefront , so there are 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 and the lines L1 to L7 are those of the page. Every cell has a volume and . For a face with the unit normal out of cell , write . The upwind graph has an edge when and an edge when , for every interior face. A face with gives no edge. The cell equation of the step scheme is
where is taken with the normal out of , are the faces of with , those with , and 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 . They output every cell if and only if 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 to the number of edges into . 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 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 be a cell that is not output. Then at the end , so has an upstream cell that is not output. Repeat with . The mesh is finite, so the chain repeats a cell, which gives a cycle from which can be reached.
So line L7 raises an error exactly when the mesh has a cycle for , and the implementation names the blocked cells.
Theorem 2 (one sweep solves the direction). If has no cycle, the system (1) for all cells has exactly one solution, and line L5 computes it.
Proof. When line L5 solves cell , every term with 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 with the coefficient , so 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.
Theorem 3 (balance). The values of Theorem 2 satisfy
where over the boundary faces with and over the boundary faces with .
Proof. Add (1) over all cells. An interior face with appears in two equations: with in the equation of its upstream cell, where it is an out face, and with in the equation of its downstream cell, where it is an in face. These cancel. What remains are the boundary faces.
Theorem 4 (positivity). If for every cell and the inflow values are not negative, then every . If moreover each cell is closed, , then a constant with and the inflow 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 , so satisfies (1) in every cell, and Theorem 2 makes it the solution.
Theorem 5 (wavefronts on a grid). On an by grid of rectangles with and , the level of cell , counted from 0, is , so there are levels. Cells with the same level have no edge between them. If , there are levels.
Proof. The edges of are and . Cell has no upstream cell and level 1. By induction on , the upstream cells of are and when they exist, both with level , so has level . Every edge raises the level by exactly 1, so it never joins two cells of one level. If , the faces between rows have , only the edges in remain, and the level of is .
So the cells of one level can be solved at the same time, and a grid sweep has at most cells at the same level.
Theorem 6 (the diamond difference sweep on a grid). For a direction with and , and every cell , the equations
with the incoming values and known, have exactly one solution, with and , and , . The loop of the implementation, rows in the direction of and cells in a row in the direction of , solves all cells.
Proof. The two diamond relations give and . Put them into the balance: , 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.
With and , both outgoing values are , which is negative when . The page shows the case , , , which gives .
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 operations and directions cost . If the order of each direction is stored, the later sweeps skip lines L1 to L3, but the storage is . The extra memory of one sweep is for the graph and the counters. On a grid this is , the same as the cell loop of the discrete ordinates method.
The sweep is sequential along each path of the graph. With processors the time of one direction is at least the number of wavefronts, on a two-dimensional grid (Theorem 5 of the proof), and at least .
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 (line L2). Such a face carries no flow and must not add an edge. Rounding can make 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.
# 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 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
- 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
- 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
- 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
- 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
- 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.
| 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 WZRH6P Edit this page History Report an error Markdown