Skip to content
Projects

Quadtree patches

Download notebookView on GitHubRun when the site was built.

regrid places patches in one of two ways. The default, method="cluster", covers the tagged cells with few rectangles fitted to them (the Berger-Rigoutsos algorithm, see Regridding). method="quadtree" cuts every level into aligned square blocks of block_size cells and makes a patch of each block that holds a tag: the blocks of a level are the children of those of the level below, so the patches are the nodes of a quadtree (an octree in 3D), all of one size.

Both give an ordinary hierarchy: halos, regridding of the fields, markers, deposits and the solvers work on either. They differ in how many patches there are, how many cells are refined, and how much the mesh changes when the tags change a little.

import matplotlib.pyplot as plt
import numpy as np
from patchwork import (
AMRHierarchy,
NodalPoisson,
function_tags,
marker_tags,
plot_patches,
)

The same tags, a ring refined by three levels, placed both ways:

mesh = AMRHierarchy(base_shape=(32, 32))
def ring(x, y):
return np.abs(np.hypot(x - 0.5, y - 0.5) - 0.3) < 0.03
tags = function_tags(mesh, ring, levels=3)
meshes = {
"cluster": mesh.regrid(tags, max_patch_size=32),
"quadtree": mesh.regrid(tags, method="quadtree", block_size=16),
}
def cells(mesh, level):
return sum(
int(np.prod([hi - lo for lo, hi in patch.box]))
for patch in mesh.patches_at_level(level)
)
fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)
for ax, (method, new) in zip(axes, meshes.items(), strict=True):
plot_patches(new, ax=ax, show_grid=False)
ax.set_title(f"{method}: {len(new.patches)} patches")
for level in range(1, new.max_level + 1):
print(
f"{method:8s} level {level}: {len(new.patches_at_level(level)):3d} patches, "
f"{cells(new, level):6d} cells"
)
cluster level 1: 4 patches, 2704 cells
cluster level 2: 24 patches, 5696 cells
cluster level 3: 70 patches, 12352 cells
quadtree level 1: 16 patches, 4096 cells
quadtree level 2: 52 patches, 13312 cells
quadtree level 3: 72 patches, 18432 cells
Notebook output

The clusters follow the ring closely with few, unequal rectangles. The quadtree refines whole blocks, so it covers more cells, but every patch is a square of 16 x 16 cells: one kernel size for every patch, and patches that are easy to share out between ranks.

A block of level k+1k + 1 is block_size cells of its level wide, half a block of level kk (refinement ratio 2), and its corners are on multiples of block_size. So each block lies in exactly one block of the level below, its parent, and each parent has four children. Where a block is refined, the level below is refined around it as well, with a margin of nesting cells, so neighbouring blocks differ by at most one level: the tree is balanced.

tree = meshes["quadtree"]
child = tree.patches_at_level(3)[0]
parent = next(
patch
for patch in tree.patches_at_level(2)
if all(
2 * lo <= clo and chi <= 2 * hi
for (clo, chi), (lo, hi) in zip(child.box, patch.box, strict=True)
)
)
print("block of level 3:", child.box, " its parent on level 2:", parent.box)
block of level 3: ((32, 48), (96, 112)) its parent on level 2: ((16, 32), (48, 64))

A block at the edge of the domain or of a forbidden region (forbid) is cut to the cells it may cover, so a patch can be narrower than block_size there, as in the notch of an L.

marker_tags tags the cells that hold more than per_cell markers, on every level. A particle tree stops splitting a box when it holds few enough particles; regridding with these tags stops refining where the cells hold few enough markers. The markers are counted over all ranks, so each rank passes its own. Here a dense beam and a wider cloud on a uniform background:

rng = np.random.default_rng(3)
def markers(n, cx, cy):
x = np.concatenate(
[
rng.normal(cx, 0.04, n),
rng.normal(0.7, 0.1, n // 2),
rng.uniform(0, 1, n // 4),
]
)
y = np.concatenate(
[
rng.normal(cy, 0.04, n),
rng.normal(0.35, 0.06, n // 2),
rng.uniform(0, 1, n // 4),
]
)
inside = (x > 0) & (x < 1) & (y > 0) & (y < 1)
return x[inside], y[inside]
x, y = markers(40_000, 0.3, 0.6)
base = AMRHierarchy(base_shape=(32, 32))
base.allocate_field("rho", centering="node")
mesh = base
for _ in range(3): # a level can only be tagged once it exists: one more each time
mesh = mesh.regrid(
marker_tags(mesh, x, y, per_cell=20, levels=3), method="quadtree", block_size=16
)
fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)
ax.plot(x[::10], y[::10], ",", color="0.5")
plot_patches(mesh, ax=ax, show_grid=False)
ax.set_title(f"{len(mesh.patches)} patches, {mesh.max_level} levels")
Text(0.5, 1.0, '72 patches, 3 levels')
Notebook output

The mesh is a hierarchy like any other: deposit the markers’ charge on it and solve for the potential (grounded faces).

charge = np.full(x.size, 1.0 / x.size)
mx, my, mq = mesh.migrate(x, y, charge, name="rho")
mesh.deposit(mx, my, mq, "rho")
mesh.accumulate_halos("rho")
solver = NodalPoisson(mesh)
density = solver.nodes.from_patches("rho") / solver.nodes.volumes
solver.solve(density, potential="phi")
print(f"total charge {solver.nodes.from_patches('rho').sum():.6f}")
fig, ax = plot_patches(mesh, field="phi", show_grid=False)
total charge 1.000000
Notebook output

The beam moves to the right, and the mesh is regridded after every step. Between two regrids the clusters are recut wherever the tags change, even by a few cells, while the quadtree adds and removes blocks only where the beam has come or gone and keeps the others as they are: the same patches, on the same ranks, with their fields copied rather than interpolated. Kept patches are grey, new ones red:

from matplotlib.patches import Rectangle
def draw(ax, mesh, previous):
for patch in mesh.patches:
if patch.level == 0:
continue
(i0, i1), (j0, j1) = patch.box
xs = mesh.node_positions(patch.level, 0)
ys = mesh.node_positions(patch.level, 1)
kept = (patch.level, patch.box) in previous
ax.add_patch(
Rectangle(
(xs[i0], ys[j0]),
xs[i1] - xs[i0],
ys[j1] - ys[j0],
fill=not kept,
facecolor="tab:red",
edgecolor="0.4" if kept else "tab:red",
alpha=0.6 if kept else 0.35,
lw=0.8,
)
)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_aspect("equal")
fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)
for ax, (method, options) in zip(
axes, [("cluster", {}), ("quadtree", {"block_size": 8})], strict=True
):
mesh, previous, kept = base, set(), []
for step in range(12):
x, y = markers(40_000, 0.25 + 0.04 * step, 0.6)
tags = marker_tags(mesh, x, y, per_cell=20, levels=3)
new = mesh.regrid(tags, method=method, **options)
boxes = {(patch.level, patch.box) for patch in new.patches if patch.level}
if step > 3: # once all levels are there
kept.append(len(boxes & previous) / len(boxes))
if step == 11:
draw(ax, new, previous)
mesh, previous = new, boxes
refined = sum(cells(mesh, level) for level in range(1, mesh.max_level + 1))
ax.set_title(
f"{method}: {len(boxes)} patches, {refined} refined cells,\n"
f"{np.mean(kept):.0%} of the patches kept per regrid"
)
Notebook output

Under MPI, placement="morton" puts the patches of a regrid on the ranks along a Morton (Z-order) curve (curve_ranks): the patches of all levels in the order of the curve, keyed by their lower corner in cells of the finest level, cut into runs of about equal cells, the base level’s cells counted. Neighbouring patches, and a patch and the patches over it, then tend to share a rank, which saves messages between ranks. Here the ranks four processes would give the patches of the beam’s mesh:

from patchwork import box_costs, curve_ranks, marker_counts
boxes = {
level: [patch.box for patch in mesh.patches_at_level(level)]
for level in range(1, mesh.max_level + 1)
}
colours = plt.get_cmap("tab10").colors
def draw_ranks(ranks, title):
fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)
for level in sorted(boxes):
xs, ys = mesh.node_positions(level, 0), mesh.node_positions(level, 1)
for ((i0, i1), (j0, j1)), rank in zip(boxes[level], ranks[level], strict=True):
ax.add_patch(
Rectangle(
(xs[i0], ys[j0]),
xs[i1] - xs[i0],
ys[j1] - ys[j0],
facecolor=colours[rank],
edgecolor="k",
alpha=0.25,
lw=0.6,
)
)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_aspect("equal")
ax.set_title(title)
def per_rank(ranks, values, base):
"""The sum of ``values`` per rank, with the base level's ``base`` on rank 0."""
totals = [base, 0.0, 0.0, 0.0]
for level in boxes:
for value, rank in zip(values[level], ranks[level], strict=True):
totals[rank] += value
return [round(total) for total in totals]
cells = {
level: [np.prod([hi - lo for lo, hi in b]) for b in boxes[level]] for level in boxes
}
ranks = curve_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0
draw_ranks(ranks, f"cells per rank: {per_rank(ranks, cells, 1024)}")
Notebook output

Equal cells are not equal work in a particle code: the ranks with the beam hold most of the markers. With cost, regrid(..., placement="morton", cost=...) weighs every patch by its cells plus the cost of its leaf cells (a cell’s markers deposit and gather on the finest patch over it), here the counts of marker_counts at a tenth of a cell per marker. box_costs gives these weights, and rebalance(cost) places the patches of an existing hierarchy again by them and moves the fields (send the markers after them with migrate). The ranks with the beam now get fewer cells and about the same cost:

counts = marker_counts(mesh, x, y, levels=mesh.max_level + 1)
cost = {level: 0.1 * found for level, found in counts.items()}
weights, (base,) = box_costs(mesh, boxes, cost) # one rank here: the base's cost
weighted = curve_ranks(boxes, 4, load=[base, 0, 0, 0], weights=weights)
print("cells per rank:", per_rank(weighted, cells, 1024))
print("cost per rank, by cells: ", per_rank(ranks, weights, base))
print("cost per rank, by markers: ", per_rank(weighted, weights, base))
draw_ranks(weighted, "the same patches, cut by cells plus markers")
cells per rank: [3584, 3392, 2368, 2944]
cost per rank, by cells: [4113, 4390, 5268, 5515]
cost per rank, by markers: [4832, 4809, 4742, 4904]
Notebook output

The few new blocks far from the beam come from the uniform background: its count per cell fluctuates around per_cell there, so a block or two switches on or off. With fewer markers per cell than per_cell in the background they would not appear.

  • "cluster" refines the fewest cells with the fewest patches: the choice when the tags change slowly and the per-patch overhead matters.
  • "quadtree" refines more cells, in more and smaller patches, but they are all of one size and a regrid leaves most of them untouched: the choice when the tags change every few steps, as with markers that move, and for spreading many equal patches over ranks (placement="balanced").

block_size sets the balance: small blocks follow the tags as closely as clusters do, with many patches; large blocks give few patches and refine more cells.