From 789c5ca83b0fd0881c7fe9b92328fbc5caebade0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 04:01:20 +0000 Subject: [PATCH 1/6] Quadtree regridding: patches as the blocks of a balanced quadtree, and tags from marker counts. --- CHANGELOG.md | 10 + README.md | 5 +- README.qmd | 5 +- docs/src/content/docs/examples/index.md | 3 + src/patchwork/__init__.py | 6 +- src/patchwork/mesh/__init__.py | 12 +- src/patchwork/mesh/hierarchy.py | 63 ++++- src/patchwork/mesh/regrid.py | 188 ++++++++++++- src/patchwork/tests/unit/test_mpi.py | 1 + src/patchwork/tests/unit/test_quadtree.py | 217 +++++++++++++++ tutorials/13_quadtree_patches.ipynb | 323 ++++++++++++++++++++++ 11 files changed, 808 insertions(+), 25 deletions(-) create mode 100644 src/patchwork/tests/unit/test_quadtree.py create mode 100644 tutorials/13_quadtree_patches.ipynb diff --git a/CHANGELOG.md b/CHANGELOG.md index ea98e3b..c67d66b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- Quadtree regridding: `AMRHierarchy.regrid(method="quadtree", block_size=16)` places the + patches as the blocks of a quadtree (an octree in 3D) instead of Berger-Rigoutsos clusters: + every level is cut into aligned square blocks of `block_size` cells, a block holding a tag is + a patch, the blocks of a level are the children of those below, and the tree is balanced by + the nesting margin. Blocks at the edge of the domain or of forbidden cells are cut to their + allowed cells. `quadtree_boxes` gives the boxes on their own. More cells are refined than + with clusters, but all patches have one size and a regrid keeps most of them. Tutorial + "Quadtree patches". +- `marker_tags(hierarchy, x, y, per_cell=..., levels=...)`: tag the cells that hold more than + `per_cell` markers, counted over all ranks. - Graded axes: `AMRHierarchy(axis_nodes=...)` takes, per axis, `None` (uniform) or the physical positions of the base nodes. The map from the logical coordinate (the one of the patches, levels and kernels) to the physical one is linear in every base cell, so every leaf diff --git a/README.md b/README.md index a8ab8ae..b57212d 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,9 @@ A hierarchy can also be the axisymmetric r–z plane `regrid` places the patches itself: tag the cells that need finer cells (by a field’s change across a cell, a function of the position, or by -hand), and it covers them with properly nested patches (Berger-Rigoutsos -clustering) and moves the fields over. +hand), and it covers them with properly nested patches (Berger-Rigoutsos clustering, or the blocks of a quadtree with +`method="quadtree"`) and moves the fields over; `marker_tags` tags the cells +that hold too many markers. Markers live on the patches too: `locate` finds the finest patch of each point (a compiled kernel with the `pyccel` extra), `owner` and `migrate` diff --git a/README.qmd b/README.qmd index d16900c..21115b5 100644 --- a/README.qmd +++ b/README.qmd @@ -57,8 +57,9 @@ A hierarchy can also be the axisymmetric r–z plane `regrid` places the patches itself: tag the cells that need finer cells (by a field's change across a cell, a function of the position, or by hand), and it -covers them with properly nested patches (Berger-Rigoutsos clustering) and moves -the fields over. +covers them with properly nested patches (Berger-Rigoutsos clustering, or the blocks of a quadtree with +`method="quadtree"`) and moves the fields over; `marker_tags` tags the cells +that hold too many markers. Markers live on the patches too: `locate` finds the finest patch of each point (a compiled kernel with the `pyccel` extra), diff --git a/docs/src/content/docs/examples/index.md b/docs/src/content/docs/examples/index.md index e40eb7d..36acb3e 100644 --- a/docs/src/content/docs/examples/index.md +++ b/docs/src/content/docs/examples/index.md @@ -35,6 +35,9 @@ Step by step, from a first hierarchy to stencils on patches: 12. [Graded axes](/patchwork/examples/12-graded-axes/): cells that grow smoothly away from a wall (`axis_nodes`), a boundary layer resolved with a few dozen cells, and grading combined with patches. +13. [Quadtree patches](/patchwork/examples/13-quadtree-patches/): `regrid(method="quadtree")`, + patches as the equal blocks of a quadtree, refinement by the number of markers per cell + (`marker_tags`), and how much of the mesh a regrid keeps. Every notebook in `tutorials/` is executed when the site is built and published here with its outputs. Download a notebook from its page to run the steps yourself. diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index fd56bc9..df91035 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -18,7 +18,9 @@ function_tags, graded_nodes, gradient_tags, + marker_tags, plot_patches, + quadtree_boxes, ) from patchwork.solvers import ( AMGBackend, @@ -86,9 +88,11 @@ "cell_body", "cluster", "function_tags", - "gradient_tags", "graded_nodes", + "gradient_tags", + "marker_tags", "plot_patches", + "quadtree_boxes", "solve_nodal_poisson", "solve_poisson", ] diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index b1abce5..898391e 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -11,7 +11,13 @@ from patchwork.mesh.hierarchy import AMRHierarchy, IndexBox, Patch from patchwork.mesh.plotting import plot_patches from patchwork.mesh.reflux import FluxRegister -from patchwork.mesh.regrid import cluster, function_tags, gradient_tags +from patchwork.mesh.regrid import ( + cluster, + function_tags, + gradient_tags, + marker_tags, + quadtree_boxes, +) __all__ = [ "AMRHierarchy", @@ -20,7 +26,9 @@ "Patch", "cluster", "function_tags", - "gradient_tags", "graded_nodes", + "gradient_tags", + "marker_tags", "plot_patches", + "quadtree_boxes", ] diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 2199ac2..232a98a 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -987,6 +987,8 @@ def regrid( self, tags: Mapping[int, Any], *, + method: str = "cluster", + block_size: int = 16, efficiency: float = 0.7, buffer: int = 1, nesting: int = 1, @@ -1005,9 +1007,19 @@ def regrid( from the data it holds, and the tags are combined over the ranks. Level by level from the coarsest, the tagged cells, grown by - ``buffer`` cells, are covered with boxes by - `cluster` (at least ``efficiency`` of their - cells tagged, at most ``max_patch_size`` cells of the new level long). + ``buffer`` cells, are covered with boxes. ``method`` says how: + + - ``"cluster"`` (the default): by `cluster`, the Berger-Rigoutsos + algorithm (at least ``efficiency`` of their cells tagged, at most + ``max_patch_size`` cells of the new level long): few patches, fitted + to the tags; + - ``"quadtree"``: by `quadtree_boxes`, the blocks of a quadtree (an + octree in 3D), square patches of ``block_size`` cells of their level, + aligned so that the blocks of a level are the children of those of the + level below: more patches, all of one size, and a block is added or + removed without moving the others. ``efficiency`` and + ``max_patch_size`` do not apply. + A level also covers, with a margin, what the finer levels need, and each patch keeps ``nesting`` cells of the level below between itself and that level's edge (the edge of the domain excepted). The base level @@ -1037,19 +1049,42 @@ def regrid( the largest first. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ - from patchwork.mesh.regrid import combine_tags, new_boxes, transfer + from patchwork.mesh.regrid import ( + combine_tags, + new_boxes, + quadtree_boxes, + transfer, + ) + if method not in ("cluster", "quadtree"): + raise ValueError(f"method must be 'cluster' or 'quadtree', got {method!r}") + if method == "quadtree" and max_patch_size is not None: + raise ValueError( + "max_patch_size does not apply to method='quadtree': " + "every patch is one block of block_size cells" + ) combined = combine_tags(self, tags) - boxes = new_boxes( - self, - combined, - efficiency=efficiency, - buffer=buffer, - nesting=nesting, - max_patch_size=max_patch_size, - min_patch_size=min_patch_size, - forbid=forbid, - ) + if method == "quadtree": + boxes = quadtree_boxes( + self, + combined, + block_size=block_size, + buffer=buffer, + nesting=nesting, + min_patch_size=min_patch_size, + forbid=forbid, + ) + else: + boxes = new_boxes( + self, + combined, + efficiency=efficiency, + buffer=buffer, + nesting=nesting, + max_patch_size=max_patch_size, + min_patch_size=min_patch_size, + forbid=forbid, + ) base = self.patches_at_level(0) new = AMRHierarchy.__new__(AMRHierarchy) new._communicators = self._communicators diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 8f92ff5..cb48c0d 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -4,11 +4,19 @@ 1. **Tagging** marks the cells of each level that need the next finer level: `gradient_tags` where a field changes by more than a threshold across a - cell, `function_tags` where a function of the position says so, or any + cell, `function_tags` where a function of the position says so, + `marker_tags` where a cell holds more than a number of markers, or any boolean array of a level's shape. -2. **Clustering** (`cluster`, the Berger-Rigoutsos algorithm) covers the - tagged cells of a level with few boxes (intervals in 1D, rectangles in 2D), each at least ``efficiency`` - full of tagged cells and at most ``max_size`` cells long. +2. **Placing the patches**, in one of two ways: + + - clustering (`cluster`, the Berger-Rigoutsos algorithm) covers the + tagged cells of a level with few boxes (intervals in 1D, rectangles in 2D), + each at least ``efficiency`` full of tagged cells and at most ``max_size`` + cells long; + - a quadtree (an octree in 3D, `quadtree_boxes`) cuts every level into + aligned square blocks of ``block_size`` cells and refines each block that + holds a tag: the blocks of level ``k + 1`` are the children of those of + level ``k``, and every patch is one block. 3. `AMRHierarchy.regrid` builds the new hierarchy from the boxes, level by level from the coarsest, and moves the fields into it: copied where an old patch of the same level was, else @@ -87,6 +95,44 @@ def function_tags( return tags +def marker_tags( + hierarchy: AMRHierarchy, *coordinates: Any, per_cell: float, levels: int +) -> dict[int, np.ndarray]: + """Tag the cells of levels ``0 .. levels - 1`` that hold more than ``per_cell`` markers. + + ``marker_tags(x, ...)`` in 1D, ``marker_tags(x, y, ...)`` in 2D: the + positions of this rank's markers (arrays of one shape). The markers are + counted in the cells of every level, whether a patch covers them or not, and + the counts are added over the ranks (collective over ``comm``), so every + rank gets the same tags. Refinement driven by these tags stops where the + cells of a level hold at most ``per_cell`` markers each, as a particle tree + stops splitting at its leaf capacity. Markers outside the domain (and in the + notch of an L) are not counted. + """ + if len(coordinates) != hierarchy.ndim: + raise ValueError( + f"marker_tags takes {hierarchy.ndim} coordinate arrays, " + f"got {len(coordinates)}" + ) + if levels < 0: + raise ValueError("levels must not be negative") + points = np.stack([np.ravel(np.asarray(c, dtype=float)) for c in coordinates]) + if any(hierarchy.periodic): + points = points.copy() + hierarchy.wrap(points) + tags = {} + for level in range(levels): + edges = [ + hierarchy.node_positions(level, axis) for axis in range(points.shape[0]) + ] + counts, _ = np.histogramdd(points.T, bins=edges) + mine = np.ascontiguousarray(counts) + everyone = np.empty_like(mine) + hierarchy.comm.Allreduce(mine, everyone, op=MPI.SUM) + tags[level] = (everyone > per_cell) & _domain_cells(hierarchy, level) + return tags + + @sp.profile("patchwork.gradient_tags", tags=PROFILE_TAGS) @method( equations={ @@ -535,6 +581,140 @@ def new_boxes( return boxes +def _refine(mask: np.ndarray, ratio: int) -> np.ndarray: + """The fine cells of every true coarse cell: ``mask`` repeated ``ratio`` times per axis.""" + for axis in range(mask.ndim): + mask = np.repeat(mask, ratio, axis=axis) + return mask + + +def _blocks(mask: np.ndarray, size: int) -> np.ndarray: + """Which aligned blocks of ``size`` cells per axis hold a true cell (a partial last block counts).""" + padded = np.zeros([-(-n // size) * size for n in mask.shape], dtype=bool) + padded[tuple(slice(0, n) for n in mask.shape)] = mask + return _coarsen(padded, size) + + +def _block_cells(blocks: np.ndarray, size: int, shape: tuple[int, ...]) -> np.ndarray: + """The cells of the true blocks, cut to ``shape``.""" + cells = _refine(blocks, size) + return cells[tuple(slice(0, n) for n in shape)] + + +@method( + equations={ + "blocks": r"B^{k}_{\mathbf m} = \prod_{d} [\, m_d b,\ (m_d + 1) b \,) \text{ (cells of level } k\text{)}, \quad \text{refined} \iff B^{k}_{\mathbf m} \text{ holds a tag of level } k - 1", + "children": r"B^{k+1}_{\mathbf m'} \subset B^{k}_{\mathbf m} \iff \lfloor \mathbf m' / r \rfloor = \mathbf m \quad (2^d \text{ children for } r = 2)", + }, + assumptions=( + "each patch is one block of `block_size` cells of its level, aligned to multiples of `block_size`; the last block of a level may be shorter, and a block that crosses the edge of the domain or a forbidden cell is cut into rectangles of its allowed cells", + "a level is refined, with a margin of `nesting` cells, wherever a finer block needs it, so the blocks are properly nested (a balanced tree)", + ), + references=( + "[MacNeice et al., Comput. Phys. Commun. 126, 330 (2000)](https://doi.org/10.1016/S0010-4655(99)00501-9)", + "[Burstedde, Wilcox and Ghattas, SIAM J. Sci. Comput. 33, 1103 (2011)](https://doi.org/10.1137/100791634)", + ), +) +def quadtree_boxes( + hierarchy: AMRHierarchy, + tags: Mapping[int, np.ndarray], + *, + block_size: int, + buffer: int, + nesting: int, + min_patch_size: int = 1, + forbid: Any = None, +) -> dict[int, list[IndexBox]]: + """The boxes of every refined level as the blocks of a quadtree (an octree in 3D). + + Every level is cut into aligned blocks of ``block_size`` cells per axis. + A block of level ``k + 1`` is a patch when a tag of level ``k``, grown by + ``buffer`` cells, lies under it, or when a finer block needs it: each block + keeps ``nesting`` cells of the level below between itself and that level's + edge (the edge of the domain excepted), so the level below is refined + around it too. With a refinement ratio of two, the blocks of level ``k + 1`` + under a block of level ``k`` are its four children (eight in 3D): the + patches are the nodes of a tree, all of one size, and the tree is balanced. + + A block that crosses the edge of the domain (the notch of an L), a + forbidden cell (``forbid`` as for `AMRHierarchy.regrid`) or the margin + the level below needs is cut into rectangles of its allowed cells, which may + then be narrower than ``block_size``; ``min_patch_size`` widens those + pieces as `cluster` does. ``block_size`` is in cells of the new level and + must be a multiple of the refinement ratio. + """ + ratio = hierarchy.refinement_ratio + periodic = hierarchy.periodic + if int(block_size) != block_size or block_size < ratio or block_size % ratio: + raise ValueError( + f"block_size must be a multiple of the refinement ratio {ratio}, " + f"got {block_size}" + ) + if buffer < 0 or nesting < 0: + raise ValueError("buffer and nesting must not be negative") + if min_patch_size < 1: + raise ValueError("min_patch_size must be at least 1") + size = int(block_size) // ratio # a block of level k + 1, in cells of level k + levels = [level for level, values in tags.items() if values.any()] + top = max(levels) + 1 if levels else 0 + # top down: the blocks each level needs, for its own tags and the finer blocks + refined: dict[int, np.ndarray] = {} # level k + 1 -> its blocks, over level k + margin: np.ndarray | None = None # cells of level k the finer blocks need + for level in range(top - 1, -1, -1): + domain = _domain_cells(hierarchy, level) + need = _grow( + tags.get(level, np.zeros(domain.shape, dtype=bool)), + buffer, + periodic, + outside=False, + ) + if margin is not None: + need |= _coarsen(margin, ratio) + need &= domain + refined[level + 1] = _blocks(need, size) + cells = _block_cells(refined[level + 1], size, domain.shape) & domain + margin = _grow(cells, nesting, periodic, outside=False) + # bottom up: each needed block, cut to the cells where its level may go + boxes: dict[int, list[IndexBox]] = {} + covered = _domain_cells(hierarchy, 0) + min_size = -(-min_patch_size // ratio) + for level in range(top): + domain = _domain_cells(hierarchy, level) + allowed = _shrink(covered | ~domain, nesting, periodic) & covered + forbidden = _forbidden_cells(hierarchy, forbid, level + 1) + if forbidden is not None: + allowed &= ~_coarsen(forbidden, ratio) + found: list[IndexBox] = [] + for index in zip(*np.nonzero(refined[level + 1]), strict=True): + block = tuple( + (int(m) * size, min((int(m) + 1) * size, n)) + for m, n in zip(index, domain.shape, strict=True) + ) + inside = allowed[tuple(slice(lo, hi) for lo, hi in block)] + if inside.all(): + parts = [block] + elif inside.any(): + parts = [ + tuple( + (lo + a, lo + b) + for (lo, _), (a, b) in zip(block, part, strict=True) + ) + for part in cluster(inside, 1.0, None, inside, min_size) + ] + else: + continue + found.extend(parts) + if not found: + break + boxes[level + 1] = [ + tuple((lo * ratio, hi * ratio) for lo, hi in box) for box in sorted(found) + ] + covered = np.zeros(hierarchy.level_shape(level + 1), dtype=bool) + for box in boxes[level + 1]: + covered[tuple(slice(lo, hi) for lo, hi in box)] = True + return boxes + + @sp.profile("patchwork.regrid_transfer", tags=PROFILE_TAGS) def transfer(old: AMRHierarchy, new: AMRHierarchy, name: str) -> None: """Fill field ``name`` of ``new`` from ``old``, level by level (collective). diff --git a/src/patchwork/tests/unit/test_mpi.py b/src/patchwork/tests/unit/test_mpi.py index 2866592..55b5217 100644 --- a/src/patchwork/tests/unit/test_mpi.py +++ b/src/patchwork/tests/unit/test_mpi.py @@ -44,6 +44,7 @@ def test_patches_on_some_ranks_give_what_one_rank_gives(ranks: int) -> None: [ "test_halos.py", "test_regrid.py", + "test_quadtree.py", "test_markers.py", "test_reflux.py", "test_line_patches.py", diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py new file mode 100644 index 0000000..d91051b --- /dev/null +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -0,0 +1,217 @@ +"""Quadtree regridding (``regrid(method="quadtree")``) and tagging by marker counts. + +Runs serially and under ``mpirun -n N python -m pytest`` (see ``test_mpi.py``). +""" + +from __future__ import annotations + +import numpy as np +import pytest +from maybempi import MPI + +from patchwork import AMRHierarchy, function_tags, marker_tags, quadtree_boxes +from patchwork.mesh.regrid import combine_tags + +WORLD = MPI.COMM_WORLD +SIZE = WORLD.Get_size() + + +def ring(x, y): + return np.abs(np.hypot(x - 0.5, y - 0.5) - 0.3) < 0.03 + + +def boxes_of(mesh, level): + return sorted(patch.box for patch in mesh.patches_at_level(level)) + + +def covered(mesh, level): + cells = np.zeros(mesh.level_shape(level), dtype=bool) + for box in boxes_of(mesh, level): + cells[tuple(slice(lo, hi) for lo, hi in box)] = True + return cells + + +@pytest.mark.parametrize("block_size", [4, 8, 16]) +def test_quadtree_patches_are_aligned_blocks_whose_parents_are_blocks( + block_size, +) -> None: + mesh = AMRHierarchy(base_shape=(32, 32)) + tags = function_tags(mesh, ring, levels=3) + new = mesh.regrid(tags, method="quadtree", block_size=block_size) + assert new.max_level == 3 + for level in range(1, new.max_level + 1): + for box in boxes_of(new, level): + for lo, hi in box: # one whole, aligned block of its level + assert lo % block_size == 0 + assert hi - lo == block_size + if level == 1: + continue + # inside one block of the level below: the patches form a tree + parents = [ + parent + for parent in boxes_of(new, level - 1) + if all( + 2 * plo <= lo and hi <= 2 * phi + for (lo, hi), (plo, phi) in zip(box, parent, strict=True) + ) + ] + assert len(parents) == 1 + # every tag of the level below is covered + assert np.all( + covered(new, level)[np.repeat(np.repeat(tags[level - 1], 2, 0), 2, 1)] + ) + + +def test_quadtree_blocks_far_away_stay_when_a_tag_goes() -> None: + mesh = AMRHierarchy(base_shape=(32, 32)) + + def blobs(both): + def tag(x, y): + near = np.hypot(x - 0.2, y - 0.2) < 0.06 + far = np.hypot(x - 0.8, y - 0.8) < 0.06 + return near | far if both else near + + return tag + + one = mesh.regrid( + function_tags(mesh, blobs(False), levels=2), method="quadtree", block_size=8 + ) + two = mesh.regrid( + function_tags(mesh, blobs(True), levels=2), method="quadtree", block_size=8 + ) + for level in (1, 2): + near = [ + b for b in boxes_of(two, level) if b[0][1] <= one.level_shape(level)[0] // 2 + ] + assert near == boxes_of(one, level) + + +def test_quadtree_moves_a_linear_field_exactly() -> None: + mesh = AMRHierarchy(base_shape=(16, 16)) + mesh.allocate_field("u", centering="node") + mesh.allocate_field("c") + + def plane(x, y): + return 1.0 + 2.0 * x - 3.0 * y + + for patch in mesh.local_patches: + patch.field("u").local[...] = plane(*patch.local_node_coordinates(mesh, "u")) + patch.field("c").local[...] = plane(*patch.local_cell_centers(mesh, "c")) + for tag in (lambda x, y: x < 0.4, lambda x, y: y > 0.7): + mesh = mesh.regrid( + function_tags(mesh, tag, levels=2), method="quadtree", block_size=4 + ) + assert mesh.max_level == 2 + for patch in mesh.local_patches: + x, y = patch.local_node_coordinates(mesh, "u") + np.testing.assert_allclose(patch.field("u").local, plane(x, y), atol=1e-12) + x, y = patch.local_cell_centers(mesh, "c") + np.testing.assert_allclose(patch.field("c").local, plane(x, y), atol=1e-12) + + +def test_quadtree_blocks_are_cut_at_the_edge_of_an_l_and_at_forbidden_cells() -> None: + mesh = AMRHierarchy( + base_shape=(16, 16), + base_boxes=[((0, 8), (0, 16)), ((8, 16), (8, 16))], # an L of area 3/4 + ) + tags = {0: np.ones((16, 16), dtype=bool)} + new = mesh.regrid(tags, method="quadtree", block_size=12, nesting=0) + inside = np.zeros((32, 32), dtype=bool) + inside[:16, :] = True + inside[16:, 16:] = True + assert np.array_equal(covered(new, 1), inside) + + forbid = {1: np.zeros((32, 32), dtype=bool)} + forbid[1][:, 30:] = True + new = mesh.regrid(tags, method="quadtree", block_size=12, nesting=0, forbid=forbid) + assert np.array_equal(covered(new, 1), inside & ~forbid[1]) + + +def test_quadtree_keeps_the_nesting_margin_and_periodic_axes() -> None: + mesh = AMRHierarchy(base_shape=(16, 16), periodic=(True, False)) + tags = function_tags( + mesh, lambda x, y: (x < 0.05) & (np.abs(y - 0.5) < 0.05), levels=2 + ) + new = mesh.regrid(tags, method="quadtree", block_size=4, nesting=2) + level1 = covered(new, 1) + # the level-2 blocks at x = 0 need level 1 on both sides of the seam + assert level1[0].any() and level1[-1].any() + assert new.max_level == 2 + + +@pytest.mark.parametrize("ndim", [1, 3]) +def test_quadtree_in_one_and_three_dimensions(ndim) -> None: + mesh = AMRHierarchy(base_shape=(8,) * ndim) + tags = {0: np.zeros((8,) * ndim, dtype=bool)} + tags[0][(3,) * ndim] = True + new = mesh.regrid(tags, method="quadtree", block_size=4) + for box in boxes_of(new, 1): + assert all(lo % 4 == 0 and hi - lo == 4 for lo, hi in box) + assert covered(new, 1)[(6,) * ndim] + + +def test_quadtree_boxes_is_usable_on_its_own() -> None: + mesh = AMRHierarchy(base_shape=(16, 16)) + tags = combine_tags(mesh, {0: np.eye(16, dtype=bool)}) + boxes = quadtree_boxes(mesh, tags, block_size=8, buffer=0, nesting=0) + assert boxes == { + 1: [ + ((0, 8), (0, 8)), + ((8, 16), (8, 16)), + ((16, 24), (16, 24)), + ((24, 32), (24, 32)), + ] + } + assert quadtree_boxes(mesh, {}, block_size=8, buffer=0, nesting=0) == {} + + +def test_quadtree_checks_its_arguments() -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + tags = {0: np.ones((8, 8), dtype=bool)} + with pytest.raises(ValueError, match="method"): + mesh.regrid(tags, method="octopus") + with pytest.raises(ValueError, match="max_patch_size"): + mesh.regrid(tags, method="quadtree", max_patch_size=8) + for size in (1, 3, 2.5): + with pytest.raises(ValueError, match="block_size"): + mesh.regrid(tags, method="quadtree", block_size=size) + with pytest.raises(ValueError, match="negative"): + mesh.regrid(tags, method="quadtree", buffer=-1) + with pytest.raises(ValueError, match="min_patch_size"): + mesh.regrid(tags, method="quadtree", min_patch_size=0) + + +def test_marker_tags_count_the_markers_of_every_rank() -> None: + mesh = AMRHierarchy(base_shape=(4, 4), periodic=(True, False)) + rank = WORLD.Get_rank() + # each rank holds a share of 9 markers in cell (1, 2), 3 in cell (3, 0) + x = np.array([0.3] * 9 + [0.9] * 3) + y = np.array([0.6] * 9 + [0.1] * 3) + mine = slice(rank, None, SIZE) + tags = marker_tags( + mesh, x[mine] + 1.0, y[mine], per_cell=4, levels=2 + ) # wrapped in x + expected = np.zeros((4, 4), dtype=bool) + expected[1, 2] = True + assert np.array_equal(tags[0], expected) + assert tags[1].sum() == 1 and tags[1][2, 4] # level 1: all 9 in one cell still + assert marker_tags(mesh, x[mine], y[mine], per_cell=9, levels=1)[0].sum() == 0 + with pytest.raises(ValueError, match="coordinate"): + marker_tags(mesh, x, per_cell=1, levels=1) + with pytest.raises(ValueError, match="levels"): + marker_tags(mesh, x, y, per_cell=1, levels=-1) + + +def test_marker_tags_skip_the_notch_of_an_l() -> None: + mesh = AMRHierarchy( + base_shape=(4, 4), base_boxes=[((0, 2), (0, 4)), ((2, 4), (2, 4))] + ) + x, y = np.full(10, 0.8), np.full(10, 0.2) # in the notch + assert not marker_tags(mesh, x, y, per_cell=1, levels=1)[0].any() + + +def test_quadtree_adds_no_level_where_every_cell_is_forbidden() -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + tags = {0: np.ones((8, 8), dtype=bool)} + new = mesh.regrid(tags, method="quadtree", block_size=4, forbid=lambda x, y: x > -1) + assert new.max_level == 0 diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb new file mode 100644 index 0000000..5eb019c --- /dev/null +++ b/tutorials/13_quadtree_patches.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0", + "metadata": {}, + "source": [ + "# Quadtree patches\n", + "\n", + "`regrid` places patches in one of two ways. The default, `method=\"cluster\"`, covers the\n", + "tagged cells with few rectangles fitted to them (the Berger-Rigoutsos algorithm, see\n", + "[Regridding](/patchwork/examples/06-regridding/)). `method=\"quadtree\"` cuts every level into\n", + "aligned square blocks of `block_size` cells and makes a patch of each block that holds a tag:\n", + "the blocks of a level are the children of those of the level below, so the patches are the\n", + "nodes of a quadtree (an octree in 3D), all of one size.\n", + "\n", + "Both give an ordinary hierarchy: halos, regridding of the fields, markers, deposits and the\n", + "solvers work on either. They differ in how many patches there are, how many cells are\n", + "refined, and how much the mesh changes when the tags change a little." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1", + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "from patchwork import (\n", + " AMRHierarchy,\n", + " NodalPoisson,\n", + " function_tags,\n", + " marker_tags,\n", + " plot_patches,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "2", + "metadata": {}, + "source": [ + "## Clusters and blocks\n", + "\n", + "The same tags, a ring refined by three levels, placed both ways:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3", + "metadata": {}, + "outputs": [], + "source": [ + "mesh = AMRHierarchy(base_shape=(32, 32))\n", + "\n", + "\n", + "def ring(x, y):\n", + " return np.abs(np.hypot(x - 0.5, y - 0.5) - 0.3) < 0.03\n", + "\n", + "\n", + "tags = function_tags(mesh, ring, levels=3)\n", + "meshes = {\n", + " \"cluster\": mesh.regrid(tags, max_patch_size=32),\n", + " \"quadtree\": mesh.regrid(tags, method=\"quadtree\", block_size=16),\n", + "}\n", + "\n", + "\n", + "def cells(mesh, level):\n", + " return sum(\n", + " int(np.prod([hi - lo for lo, hi in patch.box]))\n", + " for patch in mesh.patches_at_level(level)\n", + " )\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)\n", + "for ax, (method, new) in zip(axes, meshes.items(), strict=True):\n", + " plot_patches(new, ax=ax, show_grid=False)\n", + " ax.set_title(f\"{method}: {len(new.patches)} patches\")\n", + " for level in range(1, new.max_level + 1):\n", + " print(\n", + " f\"{method:8s} level {level}: {len(new.patches_at_level(level)):3d} patches, \"\n", + " f\"{cells(new, level):6d} cells\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "4", + "metadata": {}, + "source": [ + "The clusters follow the ring closely with few, unequal rectangles. The quadtree refines whole\n", + "blocks, so it covers more cells, but every patch is a square of 16 x 16 cells: one kernel\n", + "size for every patch, and patches that are easy to share out between ranks.\n", + "\n", + "## The blocks form a tree\n", + "\n", + "A block of level $k + 1$ is `block_size` cells of its level wide, half a block of level $k$\n", + "(refinement ratio 2), and its corners are on multiples of `block_size`. So each block lies in\n", + "exactly one block of the level below, its parent, and each parent has four children. Where a\n", + "block is refined, the level below is refined around it as well, with a margin of `nesting`\n", + "cells, so neighbouring blocks differ by at most one level: the tree is balanced." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5", + "metadata": {}, + "outputs": [], + "source": [ + "tree = meshes[\"quadtree\"]\n", + "child = tree.patches_at_level(3)[0]\n", + "parent = next(\n", + " patch\n", + " for patch in tree.patches_at_level(2)\n", + " if all(\n", + " 2 * lo <= clo and chi <= 2 * hi\n", + " for (clo, chi), (lo, hi) in zip(child.box, patch.box, strict=True)\n", + " )\n", + ")\n", + "print(\"block of level 3:\", child.box, \" its parent on level 2:\", parent.box)" + ] + }, + { + "cell_type": "markdown", + "id": "6", + "metadata": {}, + "source": [ + "A block at the edge of the domain or of a forbidden region (`forbid`) is cut to the cells\n", + "it may cover, so a patch can be narrower than `block_size` there, as in the notch of an L.\n", + "\n", + "## Refining by the number of markers\n", + "\n", + "`marker_tags` tags the cells that hold more than `per_cell` markers, on every level. A\n", + "particle tree stops splitting a box when it holds few enough particles; regridding with these\n", + "tags stops refining where the cells hold few enough markers. The markers are counted over all\n", + "ranks, so each rank passes its own. Here a dense beam and a wider cloud on a uniform\n", + "background:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7", + "metadata": {}, + "outputs": [], + "source": [ + "rng = np.random.default_rng(3)\n", + "\n", + "\n", + "def markers(n, cx, cy):\n", + " x = np.concatenate(\n", + " [\n", + " rng.normal(cx, 0.04, n),\n", + " rng.normal(0.7, 0.1, n // 2),\n", + " rng.uniform(0, 1, n // 4),\n", + " ]\n", + " )\n", + " y = np.concatenate(\n", + " [\n", + " rng.normal(cy, 0.04, n),\n", + " rng.normal(0.35, 0.06, n // 2),\n", + " rng.uniform(0, 1, n // 4),\n", + " ]\n", + " )\n", + " inside = (x > 0) & (x < 1) & (y > 0) & (y < 1)\n", + " return x[inside], y[inside]\n", + "\n", + "\n", + "x, y = markers(40_000, 0.3, 0.6)\n", + "base = AMRHierarchy(base_shape=(32, 32))\n", + "base.allocate_field(\"rho\", centering=\"node\")\n", + "mesh = base\n", + "for _ in range(3): # a level can only be tagged once it exists: one more each time\n", + " mesh = mesh.regrid(\n", + " marker_tags(mesh, x, y, per_cell=20, levels=3), method=\"quadtree\", block_size=16\n", + " )\n", + "\n", + "fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)\n", + "ax.plot(x[::10], y[::10], \",\", color=\"0.5\")\n", + "plot_patches(mesh, ax=ax, show_grid=False)\n", + "ax.set_title(f\"{len(mesh.patches)} patches, {mesh.max_level} levels\")" + ] + }, + { + "cell_type": "markdown", + "id": "8", + "metadata": {}, + "source": [ + "The mesh is a hierarchy like any other: deposit the markers' charge on it and solve for the\n", + "potential (grounded faces)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9", + "metadata": {}, + "outputs": [], + "source": [ + "charge = np.full(x.size, 1.0 / x.size)\n", + "mx, my, mq = mesh.migrate(x, y, charge, name=\"rho\")\n", + "mesh.deposit(mx, my, mq, \"rho\")\n", + "mesh.accumulate_halos(\"rho\")\n", + "\n", + "solver = NodalPoisson(mesh)\n", + "density = solver.nodes.from_patches(\"rho\") / solver.nodes.volumes\n", + "solver.solve(density, potential=\"phi\")\n", + "print(f\"total charge {solver.nodes.from_patches('rho').sum():.6f}\")\n", + "fig, ax = plot_patches(mesh, field=\"phi\", show_grid=False)" + ] + }, + { + "cell_type": "markdown", + "id": "10", + "metadata": {}, + "source": [ + "## Following a moving beam\n", + "\n", + "The beam moves to the right, and the mesh is regridded after every step. Between two regrids\n", + "the clusters are recut wherever the tags change, even by a few cells, while the quadtree\n", + "adds and removes blocks only where the beam has come or gone and keeps the others as they\n", + "are: the same patches, on the same ranks, with their fields copied rather than\n", + "interpolated. Kept patches are grey, new ones red:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "11", + "metadata": {}, + "outputs": [], + "source": [ + "from matplotlib.patches import Rectangle\n", + "\n", + "\n", + "def draw(ax, mesh, previous):\n", + " for patch in mesh.patches:\n", + " if patch.level == 0:\n", + " continue\n", + " (i0, i1), (j0, j1) = patch.box\n", + " xs = mesh.node_positions(patch.level, 0)\n", + " ys = mesh.node_positions(patch.level, 1)\n", + " kept = (patch.level, patch.box) in previous\n", + " ax.add_patch(\n", + " Rectangle(\n", + " (xs[i0], ys[j0]),\n", + " xs[i1] - xs[i0],\n", + " ys[j1] - ys[j0],\n", + " fill=not kept,\n", + " facecolor=\"tab:red\",\n", + " edgecolor=\"0.4\" if kept else \"tab:red\",\n", + " alpha=0.6 if kept else 0.35,\n", + " lw=0.8,\n", + " )\n", + " )\n", + " ax.set_xlim(0, 1)\n", + " ax.set_ylim(0, 1)\n", + " ax.set_aspect(\"equal\")\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)\n", + "for ax, (method, options) in zip(\n", + " axes, [(\"cluster\", {}), (\"quadtree\", {\"block_size\": 8})], strict=True\n", + "):\n", + " mesh, previous, kept = base, set(), []\n", + " for step in range(12):\n", + " x, y = markers(40_000, 0.25 + 0.04 * step, 0.6)\n", + " tags = marker_tags(mesh, x, y, per_cell=20, levels=3)\n", + " new = mesh.regrid(tags, method=method, **options)\n", + " boxes = {(patch.level, patch.box) for patch in new.patches if patch.level}\n", + " if step > 3: # once all levels are there\n", + " kept.append(len(boxes & previous) / len(boxes))\n", + " if step == 11:\n", + " draw(ax, new, previous)\n", + " mesh, previous = new, boxes\n", + " refined = sum(cells(mesh, level) for level in range(1, mesh.max_level + 1))\n", + " ax.set_title(\n", + " f\"{method}: {len(boxes)} patches, {refined} refined cells,\\n\"\n", + " f\"{np.mean(kept):.0%} of the patches kept per regrid\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "12", + "metadata": {}, + "source": [ + "The few new blocks far from the beam come from the uniform background: its count per cell\n", + "fluctuates around `per_cell` there, so a block or two switches on or off. With fewer\n", + "markers per cell than `per_cell` in the background they would not appear.\n", + "\n", + "## Which one to use\n", + "\n", + "- `\"cluster\"` refines the fewest cells with the fewest patches: the choice when the tags\n", + " change slowly and the per-patch overhead matters.\n", + "- `\"quadtree\"` refines more cells, in more and smaller patches, but they are all of one size\n", + " and a regrid leaves most of them untouched: the choice when the tags change every few\n", + " steps, as with markers that move, and for spreading many equal patches over ranks\n", + " (`placement=\"balanced\"`).\n", + "\n", + "`block_size` sets the balance: small blocks follow the tags as closely as clusters do, with\n", + "many patches; large blocks give few patches and refine more cells." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From b7b1d5b443014ffe1c7367fc621e1241141a4fb9 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:03:04 +0000 Subject: [PATCH 2/6] docs: README.md as quarto renders it. --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b57212d..6540a9f 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,10 @@ A hierarchy can also be the axisymmetric r–z plane `regrid` places the patches itself: tag the cells that need finer cells (by a field’s change across a cell, a function of the position, or by -hand), and it covers them with properly nested patches (Berger-Rigoutsos clustering, or the blocks of a quadtree with -`method="quadtree"`) and moves the fields over; `marker_tags` tags the cells -that hold too many markers. +hand), and it covers them with properly nested patches (Berger-Rigoutsos +clustering, or the blocks of a quadtree with `method="quadtree"`) and +moves the fields over; `marker_tags` tags the cells that hold too many +markers. Markers live on the patches too: `locate` finds the finest patch of each point (a compiled kernel with the `pyccel` extra), `owner` and `migrate` From e74d2d895d5cc1a3b4a69250642bb392cb8db2e5 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:47:22 +0000 Subject: [PATCH 3/6] feat: Morton placement, a cheaper regrid transfer, and the quadtree benchmark. --- benchmarks/quadtree/README.md | 16 +++ benchmarks/quadtree/bench_quadtree.py | 162 ++++++++++++++++++++++ benchmarks/quadtree/run.py | 129 +++++++++++++++++ src/patchwork/__init__.py | 2 + src/patchwork/mesh/__init__.py | 2 + src/patchwork/mesh/hierarchy.py | 34 +++-- src/patchwork/mesh/regrid.py | 68 +++++++-- src/patchwork/tests/unit/test_quadtree.py | 51 ++++++- 8 files changed, 445 insertions(+), 19 deletions(-) create mode 100644 benchmarks/quadtree/README.md create mode 100644 benchmarks/quadtree/bench_quadtree.py create mode 100644 benchmarks/quadtree/run.py diff --git a/benchmarks/quadtree/README.md b/benchmarks/quadtree/README.md new file mode 100644 index 0000000..f5c1c7f --- /dev/null +++ b/benchmarks/quadtree/README.md @@ -0,0 +1,16 @@ +# Quadtree patches against clustered ones + +`bench_quadtree.py` runs a particle-in-cell cycle on a mesh that follows a moving beam of +markers: tag (`marker_tags`), regrid, migrate, deposit, build the solver, solve, exchange +the halos and gather, each a scope-profiler region. `run.py` runs it for clustered patches +(`method="cluster"`, with and without `max_patch_size`) and quadtree blocks of 8, 16 and 32 +cells, and prints a table; under MPI it compares `placement="balanced"` with +`placement="morton"` (without the solve, which the LU backend does not distribute). + +```sh +python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve +python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid +python benchmarks/quadtree/run.py --out /tmp/quadtree --steps 40 --base 128 # any option of bench_quadtree.py +``` + +`RESULTS.md` has the numbers of the last run. diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py new file mode 100644 index 0000000..0e32870 --- /dev/null +++ b/benchmarks/quadtree/bench_quadtree.py @@ -0,0 +1,162 @@ +"""Quadtree patches against clustered ones in a particle-in-cell cycle. + +A beam of markers (a Gaussian of width ``--width``, ``--markers`` of them, on a uniform +background) moves across the unit square on a ``--base`` x ``--base`` base, and every step + +- ``tag``: `marker_tags` (more than ``--per-cell`` markers per cell, ``--levels`` levels); +- ``regrid``: `regrid` with ``--method`` (``cluster`` or ``quadtree`` with ``--block-size``) + and ``--placement`` (``balanced`` or ``morton``); +- ``migrate``, ``deposit``: the markers to their patches' ranks, cloud-in-cell deposit and + `accumulate_halos`; +- ``solver``, ``solve``: a new `NodalPoisson` on the new mesh and its solve (serial only, + or with ``--solve`` where the LU backend is enough); +- ``halos``: `exchange_halos` of the potential (or of the charge without a solve); +- ``gather``: `interpolate` at the markers. + +Each part is a scope-profiler region (``quadtree_bench.``); run with + + scope-profiler run -o prof.h5 benchmarks/quadtree/bench_quadtree.py --method quadtree + mpiexec -n 4 scope-profiler run -o prof.h5 benchmarks/quadtree/bench_quadtree.py \\ + --placement morton --no-solve + +and read the times with ``scope-profiler inspect prof.h5 --sort total``. Rank 0 also prints +one JSON line with the mesh: patches, refined cells, the share of patches a regrid keeps, +and the cells per rank. +""" + +from __future__ import annotations + +import argparse +import json + +import numpy as np +import scope_profiler as sp +from maybempi import MPI + +from patchwork import AMRHierarchy, NodalPoisson, marker_tags + + +def beam(rng, count: int, width: float, centre: tuple[float, float]): + """Markers of a Gaussian beam on a uniform background (a fifth of them), in the unit square.""" + dense = count * 4 // 5 + x = np.concatenate( + [rng.normal(centre[0], width, dense), rng.uniform(0, 1, count - dense)] + ) + y = np.concatenate( + [rng.normal(centre[1], width, dense), rng.uniform(0, 1, count - dense)] + ) + inside = (x > 0) & (x < 1) & (y > 0) & (y < 1) + return x[inside], y[inside] + + +def refined_cells(mesh) -> int: + return sum( + int(np.prod([hi - lo for lo, hi in patch.box])) + for patch in mesh.patches + if patch.level + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--method", choices=["cluster", "quadtree"], default="quadtree") + parser.add_argument("--block-size", type=int, default=16) + parser.add_argument("--max-patch-size", type=int, default=None) + parser.add_argument( + "--placement", choices=["balanced", "morton"], default="balanced" + ) + parser.add_argument("--base", type=int, default=64) + parser.add_argument("--levels", type=int, default=3) + parser.add_argument("--markers", type=int, default=200_000) + parser.add_argument("--per-cell", type=float, default=20.0) + parser.add_argument("--width", type=float, default=0.06) + parser.add_argument("--steps", type=int, default=20) + parser.add_argument("--speed", type=float, default=0.01, help="beam shift per step") + parser.add_argument("--no-solve", dest="solve", action="store_false") + parser.add_argument("--seed", type=int, default=0) + args = parser.parse_args() + + comm = MPI.COMM_WORLD + rank, size = comm.Get_rank(), comm.Get_size() + rng = np.random.default_rng(args.seed + rank) + options = ( + {"method": "quadtree", "block_size": args.block_size} + if args.method == "quadtree" + else {"method": "cluster", "max_patch_size": args.max_patch_size} + ) + mesh = AMRHierarchy( + base_shape=(args.base, args.base), + placement=args.placement, + comm=comm, + ) + mesh.allocate_field("rho", centering="node") + if args.solve: + mesh.allocate_field("phi", centering="node") + + def markers(step: int): + x, y = beam( + rng, args.markers // size, args.width, (0.25 + args.speed * step, 0.5) + ) + return x, y, np.full(x.size, 1.0 / args.markers) + + # build the levels on the first beam, one level per regrid, untimed + x, y, q = markers(0) + for _ in range(args.levels): + mesh = mesh.regrid( + marker_tags(mesh, x, y, per_cell=args.per_cell, levels=args.levels), + **options, + ) + + kept, patches, cells = [], [], [] + previous = {(p.level, p.box) for p in mesh.patches if p.level} + for step in range(1, args.steps + 1): + x, y, q = markers(step) + with sp.region("quadtree_bench.tag"): + tags = marker_tags(mesh, x, y, per_cell=args.per_cell, levels=args.levels) + with sp.region("quadtree_bench.regrid"): + mesh = mesh.regrid(tags, **options) + boxes = {(p.level, p.box) for p in mesh.patches if p.level} + kept.append(len(boxes & previous) / max(len(boxes), 1)) + previous = boxes + patches.append(len(boxes)) + cells.append(refined_cells(mesh)) + with sp.region("quadtree_bench.migrate"): + mx, my, mq = mesh.migrate(x, y, q, name="rho") + with sp.region("quadtree_bench.deposit"): + mesh.deposit(mx, my, mq, "rho") + mesh.accumulate_halos("rho") + field = "rho" + if args.solve: + with sp.region("quadtree_bench.solver"): + solver = NodalPoisson(mesh) + with sp.region("quadtree_bench.solve"): + density = solver.nodes.from_patches("rho") / solver.nodes.volumes + solver.solve(density, potential="phi") + field = "phi" + with sp.region("quadtree_bench.halos"): + mesh.exchange_halos(field) + with sp.region("quadtree_bench.gather"): + mesh.interpolate(mx, my, field) + + load = mesh.cells_on_rank + if rank == 0: + print( + json.dumps( + { + "method": args.method, + "block_size": args.block_size + if args.method == "quadtree" + else None, + "placement": args.placement, + "ranks": size, + "patches": float(np.mean(patches)), + "refined_cells": float(np.mean(cells)), + "kept": float(np.mean(kept)), + "load_imbalance": max(load) / (sum(load) / len(load)), + } + ) + ) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py new file mode 100644 index 0000000..5d8998f --- /dev/null +++ b/benchmarks/quadtree/run.py @@ -0,0 +1,129 @@ +"""Run `bench_quadtree.py` for several meshes and placements and print a table of the times. + + python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve + python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid + +Every configuration runs ``--repeats`` times under ``scope-profiler run``; the table gives +the median over the repeats of the mean time per step of each region (ms), and the mesh of +the JSON line of the run: patches, refined cells, the share of patches a regrid keeps and +the load imbalance (largest cells per rank over the mean). Profiles are written to ``--out``. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).parent +BENCH = HERE / "bench_quadtree.py" +PROFILER = Path(sys.executable).with_name("scope-profiler") +PARTS = ("tag", "regrid", "migrate", "deposit", "solver", "solve", "halos", "gather") + +#: (label, arguments) of the meshes compared +MESHES = [ + ("cluster", ["--method", "cluster"]), + ("cluster, max 16", ["--method", "cluster", "--max-patch-size", "16"]), + ("quadtree 8", ["--method", "quadtree", "--block-size", "8"]), + ("quadtree 16", ["--method", "quadtree", "--block-size", "16"]), + ("quadtree 32", ["--method", "quadtree", "--block-size", "32"]), +] + + +def run_once(arguments: list[str], ranks: int, output: Path) -> tuple[dict, dict]: + """One profiled run: the JSON line of the mesh and the mean ms per step of each part.""" + command = [str(PROFILER), "run", "-o", str(output), str(BENCH), *arguments] + if ranks > 1: + command = ["mpiexec", "-n", str(ranks), "--oversubscribe", *command] + env = os.environ | { + "OMPI_ALLOW_RUN_AS_ROOT": "1", + "OMPI_ALLOW_RUN_AS_ROOT_CONFIRM": "1", + "OMP_NUM_THREADS": "1", + } + result = subprocess.run( + command, capture_output=True, text=True, env=env, check=True + ) + mesh = next( + json.loads(line) + for line in result.stdout.splitlines() + if line.startswith("{") and '"method"' in line + ) + inspected = subprocess.run( + [str(PROFILER), "inspect", str(output), "--json", "--top", "50"], + capture_output=True, + text=True, + check=True, + ) + regions = json.loads(inspected.stdout)["regions"]["items"] + times = {} + for region in regions: + name = region["name"] + if name.startswith("quadtree_bench."): + # the slowest rank's mean per call + times[name.split(".", 1)[1]] = ( + 1e3 * region["max"] if ranks > 1 else 1e3 * region["avg"] + ) + return mesh, times + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--ranks", type=int, default=1) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--placements", nargs="+", default=None) + args, bench = parser.parse_known_args() + args.out.mkdir(parents=True, exist_ok=True) + placements = args.placements or ( + ["balanced", "morton"] if args.ranks > 1 else ["balanced"] + ) + extra = list(bench) + ([] if args.ranks == 1 else ["--no-solve"]) + + header = [ + "mesh", + "placement", + "patches", + "refined", + "kept", + "imbalance", + *PARTS, + "total", + ] + print("| " + " | ".join(header) + " |") + print("|" + "---|" * len(header)) + for label, arguments in MESHES: + for placement in placements: + runs = [] + for repeat in range(args.repeats): + name = f"{label.replace(', ', '_').replace(' ', '')}_{placement}_{args.ranks}_{repeat}.h5" + runs.append( + run_once( + [*arguments, "--placement", placement, *extra], + args.ranks, + args.out / name, + ) + ) + mesh = runs[0][0] + times = { + part: float(np.median([t.get(part, 0.0) for _, t in runs])) + for part in PARTS + } + total = sum(times.values()) + cells = [ + f"{mesh['patches']:.0f}", + f"{mesh['refined_cells']:.0f}", + f"{mesh['kept']:.0%}", + f"{mesh['load_imbalance']:.2f}", + *(f"{times[part]:.1f}" if times[part] else "-" for part in PARTS), + f"{total:.1f}", + ] + print(f"| {label} | {placement} | " + " | ".join(cells) + " |", flush=True) + + +if __name__ == "__main__": + main() diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index df91035..97e3893 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -19,6 +19,7 @@ graded_nodes, gradient_tags, marker_tags, + morton_ranks, plot_patches, quadtree_boxes, ) @@ -91,6 +92,7 @@ "graded_nodes", "gradient_tags", "marker_tags", + "morton_ranks", "plot_patches", "quadtree_boxes", "solve_nodal_poisson", diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index 898391e..a50e190 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -16,6 +16,7 @@ function_tags, gradient_tags, marker_tags, + morton_ranks, quadtree_boxes, ) @@ -29,6 +30,7 @@ "graded_nodes", "gradient_tags", "marker_tags", + "morton_ranks", "plot_patches", "quadtree_boxes", ] diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 232a98a..ca73b1b 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -299,10 +299,15 @@ class AMRHierarchy: on several, over which mpiarray splits its fields. ``placement`` says where a patch goes that is added without ``ranks``: ``"all"`` puts it on every rank, ``"balanced"`` on the one rank that holds the fewest cells so - far, or a function ``placement(level, box)`` that returns the ranks (as - ``ranks`` of `add_patch` takes them). With ``max_cells_per_rank``, a - ``"balanced"`` patch with more cells than that is split over as many of - the least loaded ranks as it needs (at most all of them). + far, ``"morton"`` along a Morton (Z-order) curve when `regrid` places the + patches (each level's patches, in the order of the curve, cut into + pieces of about equal cells, one piece per rank, so that neighbouring + patches tend to share a rank; a patch added by `add_patch` goes where + ``"balanced"`` would put it), or a function ``placement(level, box)`` that + returns the ranks (as ``ranks`` of `add_patch` takes them). With + ``max_cells_per_rank``, a ``"balanced"`` patch with more cells than that is + split over as many of the least loaded ranks as it needs (at most all of + them); a ``"morton"`` patch stays on one rank. The domain is the rectangle of ``base_shape`` cells, or with ``base_boxes`` the union of those boxes of base cells: an L, a T, a rectangle with a notch. @@ -477,9 +482,10 @@ def __init__( ) self.geometry = geometry self.comm = mpa.default_comm() if comm is None else comm - if not callable(placement) and placement not in ("all", "balanced"): + if not callable(placement) and placement not in ("all", "balanced", "morton"): raise ValueError( - f"placement must be 'all', 'balanced' or a function, got {placement!r}" + "placement must be 'all', 'balanced', 'morton' or a function, " + f"got {placement!r}" ) if max_cells_per_rank is not None and int(max_cells_per_rank) < 1: raise ValueError("max_cells_per_rank must be at least 1") @@ -1046,7 +1052,7 @@ def regrid( are dropped, as are those that would need patches too close to it. New patches are placed by ``placement`` (default: this hierarchy's), - the largest first. Collective over ``comm``; this hierarchy is left as + the largest first, or along a Morton curve with ``"morton"``. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ from patchwork.mesh.regrid import ( @@ -1101,9 +1107,17 @@ def regrid( geometry=self.geometry, axis_nodes=self.axis_nodes, ) - for level in sorted(boxes): - for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): - new.add_patch(level, box) + if new.placement == "morton": + from patchwork.mesh.regrid import morton_ranks + + for level in sorted(boxes): + ranks = morton_ranks(boxes[level], self.comm.Get_size()) + for box, rank in zip(boxes[level], ranks, strict=True): + new.add_patch(level, box, ranks=rank) + else: + for level in sorted(boxes): + for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): + new.add_patch(level, box) for name, spec in self._field_specs.items(): if spec["conservative"]: self.restrict(name) diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index cb48c0d..1208422 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -33,6 +33,7 @@ import itertools from typing import TYPE_CHECKING, Any +import cunumpy as xp import mpiarray as mpa import numpy as np import scope_profiler as sp @@ -50,7 +51,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, Mapping + from collections.abc import Callable, Mapping, Sequence from patchwork.mesh.hierarchy import AMRHierarchy, IndexBox @@ -715,6 +716,48 @@ def quadtree_boxes( return boxes +@method( + equations={ + "key": r"k(\mathbf i) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b(i_d)\, 2^{bD + d} \quad \text{(the lower corner of a patch)}", + "ranks": r"r(B) = \min\left(R - 1, \left\lfloor R\, \frac{C_{ list[int]: + """The rank of each box of one level: the boxes along a Morton curve, cut into ``size`` pieces. + + The boxes are ordered by the Morton (Z-order) key of their lower corner, + which keeps boxes that are close in space close in the order, and the + order is cut where the running count of cells passes ``k / size`` of all + cells: each rank gets a run of neighbouring boxes with about the same + number of cells. Returns the ranks in the order of ``boxes``. + """ + if size < 1: + raise ValueError(f"size must be at least 1, got {size}") + cells = [int(np.prod([hi - lo for lo, hi in box])) for box in boxes] + corners = np.array([[lo for lo, _ in box] for box in boxes], dtype=np.uint64) + if corners.size and corners.shape[1] > 1: + keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D + else: # 1D: the curve is the axis + keys = corners.reshape(-1) + order = sorted(range(len(boxes)), key=lambda n: (int(keys[n]), boxes[n])) + total = sum(cells) + ranks = [0] * len(boxes) + before = 0 + for n in order: + middle = before + cells[n] / 2 + ranks[n] = min(size - 1, int(size * middle / total)) if total else 0 + before += cells[n] + return ranks + + @sp.profile("patchwork.regrid_transfer", tags=PROFILE_TAGS) def transfer(old: AMRHierarchy, new: AMRHierarchy, name: str) -> None: """Fill field ``name`` of ``new`` from ``old``, level by level (collective). @@ -743,9 +786,10 @@ def new_field(patch: Any) -> Any: for patch in new.patches_at_level(level): own = points.own(patch) origin = tuple(lo for lo, _ in own) - covered = np.zeros([hi - lo for lo, hi in own], dtype=bool) + # the old patches near this one (a bin index, not every pair) + mine = [] for previous in ( - old.patches_at_level(level) if level <= old.max_level else () + old_points.near(level, own) if level <= old.max_level else () ): theirs = old_points.own(previous) their_origin = tuple(lo for lo, _ in theirs) @@ -758,11 +802,19 @@ def new_field(patch: Any) -> Any: tuple(-d - o for d, o in zip(shift, their_origin, strict=True)), ) target = _shift(part, tuple(-o for o in origin)) - copies.append( - (old_field(previous), source, new_field(patch), target) - ) - covered[tuple(slice(s, e) for s, e in target)] = True - if level == 0: + mine.append((old_field(previous), source, new_field(patch), target)) + # the last copy of a point wins: drop the copies that later ones overwrite + # entirely (an old patch with the same box makes its neighbours' shared + # nodes redundant), so that a kept patch costs one copy, not one per neighbour + covered = np.zeros([hi - lo for lo, hi in own], dtype=bool) + kept = [] + for copy in reversed(mine): + where = tuple(slice(s, e) for s, e in copy[3]) + if not covered[where].all(): + kept.append(copy) + covered[where] = True + copies.extend(reversed(kept)) + if level == 0 or covered.all(): continue index = tuple( values + o diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index d91051b..18d5503 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -9,7 +9,13 @@ import pytest from maybempi import MPI -from patchwork import AMRHierarchy, function_tags, marker_tags, quadtree_boxes +from patchwork import ( + AMRHierarchy, + function_tags, + marker_tags, + morton_ranks, + quadtree_boxes, +) from patchwork.mesh.regrid import combine_tags WORLD = MPI.COMM_WORLD @@ -215,3 +221,46 @@ def test_quadtree_adds_no_level_where_every_cell_is_forbidden() -> None: tags = {0: np.ones((8, 8), dtype=bool)} new = mesh.regrid(tags, method="quadtree", block_size=4, forbid=lambda x, y: x > -1) assert new.max_level == 0 + + +def test_morton_ranks_follow_the_z_curve_with_equal_cells() -> None: + # sixteen 2 x 2 blocks of a 8 x 8 level: the Z curve visits the quadrants in turn + boxes = [ + ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(4) for j in range(4) + ] + ranks = morton_ranks(boxes, 4) + for box, rank in zip(boxes, ranks, strict=True): + (i0, _), (j0, _) = box + assert rank == 2 * (i0 >= 4) + (j0 >= 4) or rank == (i0 >= 4) + 2 * (j0 >= 4) + assert sorted(ranks) == [r for r in range(4) for _ in range(4)] + # unequal boxes: the cells per rank differ by at most one box + boxes = [((0, 8), (0, 8)), ((8, 10), (0, 2)), ((8, 10), (2, 4)), ((10, 12), (0, 2))] + cells = [64, 4, 4, 4] + ranks = morton_ranks(boxes, 2) + load = [ + sum(c for c, r in zip(cells, ranks, strict=True) if r == k) for k in range(2) + ] + assert sum(load) == 76 and max(load) - min(load) <= 64 + assert morton_ranks(boxes, 1) == [0, 0, 0, 0] + assert morton_ranks([], 3) == [] + with pytest.raises(ValueError, match="size"): + morton_ranks(boxes, 0) + + +def test_regrid_places_the_blocks_along_the_morton_curve() -> None: + mesh = AMRHierarchy(base_shape=(16, 16), placement="morton") + mesh.allocate_field("u", centering="node") + tags = function_tags(mesh, ring, levels=2) + new = mesh.regrid(tags, method="quadtree", block_size=8) + assert new.placement == "morton" + for level in (1, 2): + patches = new.patches_at_level(level) + expected = morton_ranks([p.box for p in patches], SIZE) + assert [p.ranks for p in patches] == [(r,) for r in expected] + # the next regrid keeps the placement; a patch added by hand is balanced + again = new.regrid(tags, method="quadtree", block_size=8, fill_halos=True) + assert again.placement == "morton" + added = again.add_patch(3, ((40, 48), (40, 48))) + assert len(added.ranks) == 1 + with pytest.raises(ValueError, match="morton"): + AMRHierarchy(base_shape=(4, 4), placement="hilbert") From 566690308acddd06f5be8d5c4dda7b651d457ea4 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:47:38 +0000 Subject: [PATCH 4/6] Docstrings of the quadtree benchmark. --- benchmarks/quadtree/bench_quadtree.py | 4 +++- benchmarks/quadtree/run.py | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py index 0e32870..7113df3 100644 --- a/benchmarks/quadtree/bench_quadtree.py +++ b/benchmarks/quadtree/bench_quadtree.py @@ -1,4 +1,4 @@ -"""Quadtree patches against clustered ones in a particle-in-cell cycle. +r"""Quadtree patches against clustered ones in a particle-in-cell cycle. A beam of markers (a Gaussian of width ``--width``, ``--markers`` of them, on a uniform background) moves across the unit square on a ``--base`` x ``--base`` base, and every step @@ -50,6 +50,7 @@ def beam(rng, count: int, width: float, centre: tuple[float, float]): def refined_cells(mesh) -> int: + """The cells of the patches above the base level.""" return sum( int(np.prod([hi - lo for lo, hi in patch.box])) for patch in mesh.patches @@ -58,6 +59,7 @@ def refined_cells(mesh) -> int: def main() -> None: + """Run the cycle and print the mesh of the run as one JSON line.""" parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--method", choices=["cluster", "quadtree"], default="quadtree") parser.add_argument("--block-size", type=int, default=16) diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py index 5d8998f..db9efa4 100644 --- a/benchmarks/quadtree/run.py +++ b/benchmarks/quadtree/run.py @@ -72,6 +72,7 @@ def run_once(arguments: list[str], ranks: int, output: Path) -> tuple[dict, dict def main() -> None: + """Run every configuration and print the table.""" parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--ranks", type=int, default=1) From 7e602560aac6d098ca7c0eec70cdf3dec7bcd243 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:55:48 +0000 Subject: [PATCH 5/6] Morton placement over all levels, with the base level's load counted. --- src/patchwork/mesh/hierarchy.py | 16 ++++-- src/patchwork/mesh/regrid.py | 70 +++++++++++++++-------- src/patchwork/tests/unit/test_quadtree.py | 37 ++++++------ 3 files changed, 78 insertions(+), 45 deletions(-) diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index ca73b1b..044aa1e 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -300,9 +300,10 @@ class AMRHierarchy: where a patch goes that is added without ``ranks``: ``"all"`` puts it on every rank, ``"balanced"`` on the one rank that holds the fewest cells so far, ``"morton"`` along a Morton (Z-order) curve when `regrid` places the - patches (each level's patches, in the order of the curve, cut into - pieces of about equal cells, one piece per rank, so that neighbouring - patches tend to share a rank; a patch added by `add_patch` goes where + patches (`morton_ranks`: the patches of all levels in the order of the + curve, cut into runs of about equal cells with the base level counted, + one run per rank, so that neighbouring patches and the patches over them + tend to share a rank; a patch added by `add_patch` goes where ``"balanced"`` would put it), or a function ``placement(level, box)`` that returns the ranks (as ``ranks`` of `add_patch` takes them). With ``max_cells_per_rank``, a ``"balanced"`` patch with more cells than that is @@ -1110,9 +1111,14 @@ def regrid( if new.placement == "morton": from patchwork.mesh.regrid import morton_ranks + ranks = morton_ranks( + boxes, + self.comm.Get_size(), + ratio=self.refinement_ratio, + load=new.cells_on_rank, # the base level + ) for level in sorted(boxes): - ranks = morton_ranks(boxes[level], self.comm.Get_size()) - for box, rank in zip(boxes[level], ranks, strict=True): + for box, rank in zip(boxes[level], ranks[level], strict=True): new.add_patch(level, box, ranks=rank) else: for level in sorted(boxes): diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 1208422..81a5df6 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -718,44 +718,66 @@ def quadtree_boxes( @method( equations={ - "key": r"k(\mathbf i) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b(i_d)\, 2^{bD + d} \quad \text{(the lower corner of a patch)}", - "ranks": r"r(B) = \min\left(R - 1, \left\lfloor R\, \frac{C_{ list[int]: - """The rank of each box of one level: the boxes along a Morton curve, cut into ``size`` pieces. - - The boxes are ordered by the Morton (Z-order) key of their lower corner, - which keeps boxes that are close in space close in the order, and the - order is cut where the running count of cells passes ``k / size`` of all - cells: each rank gets a run of neighbouring boxes with about the same - number of cells. Returns the ranks in the order of ``boxes``. +def morton_ranks( + boxes: Mapping[int, Sequence[IndexBox]], + size: int, + *, + ratio: int = 2, + load: Sequence[float] | None = None, +) -> dict[int, list[int]]: + """The rank of each box: the boxes of all levels along a Morton curve, cut into ``size`` runs. + + ``boxes`` maps a level to its boxes. Every box gets the Morton (Z-order) + key of its lower corner in cells of the finest level, so that boxes close + in space are close on the curve whatever their level, and a box comes + before the finer boxes at the same corner. Walking the curve, a rank takes + boxes until its cells, with the ``load`` it already has (the cells of the + base level, say), reach an equal share of all cells; then the next rank + goes on. Returns, per level, the ranks in the order of ``boxes[level]``. """ if size < 1: raise ValueError(f"size must be at least 1, got {size}") - cells = [int(np.prod([hi - lo for lo, hi in box])) for box in boxes] - corners = np.array([[lo for lo, _ in box] for box in boxes], dtype=np.uint64) - if corners.size and corners.shape[1] > 1: + weights = [0.0] * size if load is None else [float(w) for w in load] + if len(weights) != size: + raise ValueError(f"load needs {size} values, got {len(weights)}") + items = [ + (level, n, box) for level in sorted(boxes) for n, box in enumerate(boxes[level]) + ] + result: dict[int, list[int]] = {level: [0] * len(boxes[level]) for level in boxes} + if not items: + return result + top = max(level for level, _, _ in items) + corners = np.array( + [[lo * ratio ** (top - level) for lo, _ in box] for level, _, box in items], + dtype=np.uint64, + ) + if corners.shape[1] > 1: keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D else: # 1D: the curve is the axis keys = corners.reshape(-1) - order = sorted(range(len(boxes)), key=lambda n: (int(keys[n]), boxes[n])) - total = sum(cells) - ranks = [0] * len(boxes) - before = 0 - for n in order: - middle = before + cells[n] / 2 - ranks[n] = min(size - 1, int(size * middle / total)) if total else 0 - before += cells[n] - return ranks + cells = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] + share = (sum(weights) + sum(cells)) / size + rank = 0 + for k in sorted(range(len(items)), key=lambda k: (int(keys[k]), items[k][0])): + while rank < size - 1 and weights[rank] + cells[k] / 2 > share: + rank += 1 + level, n, _ = items[k] + result[level][n] = rank + weights[rank] += cells[k] + return result @sp.profile("patchwork.regrid_transfer", tags=PROFILE_TAGS) diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 18d5503..8c5d2fd 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -228,23 +228,23 @@ def test_morton_ranks_follow_the_z_curve_with_equal_cells() -> None: boxes = [ ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(4) for j in range(4) ] - ranks = morton_ranks(boxes, 4) + ranks = morton_ranks({1: boxes}, 4)[1] for box, rank in zip(boxes, ranks, strict=True): (i0, _), (j0, _) = box - assert rank == 2 * (i0 >= 4) + (j0 >= 4) or rank == (i0 >= 4) + 2 * (j0 >= 4) - assert sorted(ranks) == [r for r in range(4) for _ in range(4)] - # unequal boxes: the cells per rank differ by at most one box - boxes = [((0, 8), (0, 8)), ((8, 10), (0, 2)), ((8, 10), (2, 4)), ((10, 12), (0, 2))] - cells = [64, 4, 4, 4] - ranks = morton_ranks(boxes, 2) - load = [ - sum(c for c, r in zip(cells, ranks, strict=True) if r == k) for k in range(2) - ] - assert sum(load) == 76 and max(load) - min(load) <= 64 - assert morton_ranks(boxes, 1) == [0, 0, 0, 0] - assert morton_ranks([], 3) == [] + assert rank == (i0 >= 4) + 2 * (j0 >= 4) # the first axis is the lowest bit + # a rank that holds the base already takes fewer patches + loaded = morton_ranks({1: boxes}, 2, load=[32, 0])[1] + assert loaded.count(0) == 4 and loaded.count(1) == 12 + # a patch and the finer patch over it are neighbours on the curve + levels = {1: [((0, 4), (0, 4)), ((4, 8), (4, 8))], 2: [((0, 4), (0, 4))]} + assert morton_ranks(levels, 2) == {1: [0, 1], 2: [0]} + assert morton_ranks({1: boxes}, 1)[1] == [0] * 16 + assert morton_ranks({}, 3) == {} + assert morton_ranks({1: [((0, 4),), ((4, 8),)]}, 2) == {1: [0, 1]} # 1D with pytest.raises(ValueError, match="size"): - morton_ranks(boxes, 0) + morton_ranks({1: boxes}, 0) + with pytest.raises(ValueError, match="load"): + morton_ranks({1: boxes}, 2, load=[1.0]) def test_regrid_places_the_blocks_along_the_morton_curve() -> None: @@ -253,10 +253,15 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: tags = function_tags(mesh, ring, levels=2) new = mesh.regrid(tags, method="quadtree", block_size=8) assert new.placement == "morton" + boxes = {level: [p.box for p in new.patches_at_level(level)] for level in (1, 2)} + base = AMRHierarchy(base_shape=(16, 16), placement="morton").cells_on_rank + expected = morton_ranks(boxes, SIZE, load=base) for level in (1, 2): patches = new.patches_at_level(level) - expected = morton_ranks([p.box for p in patches], SIZE) - assert [p.ranks for p in patches] == [(r,) for r in expected] + assert [p.ranks for p in patches] == [(r,) for r in expected[level]] + # the cells per rank differ by less than the largest patch + load = new.cells_on_rank + assert max(load) - min(load) <= max(256, max(base)) # the next regrid keeps the placement; a patch added by hand is balanced again = new.regrid(tags, method="quadtree", block_size=8, fill_halos=True) assert again.placement == "morton" From 6ad46a78d5dfe11c72a745de0bcc22df8c3ceebe Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 05:02:53 +0000 Subject: [PATCH 6/6] Quadtree benchmark results, Morton placement in the tutorial and the changelog. --- CHANGELOG.md | 5 +++ benchmarks/quadtree/RESULTS.md | 65 +++++++++++++++++++++++++++++ benchmarks/quadtree/run.py | 32 +++++++------- tutorials/13_quadtree_patches.ipynb | 61 +++++++++++++++++++++++++++ 4 files changed, 147 insertions(+), 16 deletions(-) create mode 100644 benchmarks/quadtree/RESULTS.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c67d66b..3b6b634 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). allowed cells. `quadtree_boxes` gives the boxes on their own. More cells are refined than with clusters, but all patches have one size and a regrid keeps most of them. Tutorial "Quadtree patches". +- `placement="morton"`: `regrid` puts the patches on the ranks along a Morton curve + (`morton_ranks`), all levels on one curve keyed in cells of the finest level, cut into runs + of about equal cells with the base level's cells counted. +- Benchmark `benchmarks/quadtree`: clusters against quadtree blocks in a particle-in-cell + cycle, serially and under MPI with both placements (`RESULTS.md`). - `marker_tags(hierarchy, x, y, per_cell=..., levels=...)`: tag the cells that hold more than `per_cell` markers, counted over all ranks. - Graded axes: `AMRHierarchy(axis_nodes=...)` takes, per axis, `None` (uniform) or the diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md new file mode 100644 index 0000000..117534c --- /dev/null +++ b/benchmarks/quadtree/RESULTS.md @@ -0,0 +1,65 @@ +# Results + +2026-11-25, a cloud container with 4 cores (Intel Xeon, 2.1 GHz), one thread per rank, +`bench_quadtree.py` defaults: a 64 x 64 base, 3 levels, 200,000 markers (four fifths in a +Gaussian beam of width 0.06 moving by 0.01 per step), `per_cell=20`, 20 timed steps. Times +are the median of 3 runs of the mean ms per step; under MPI on the rank where the part is +largest. "kept" is the share of the patches of a regrid that were there before it. + +## Serial, with the solve + +| mesh | patches | refined cells | kept | tag | regrid | migrate | deposit | solver | solve | halos | gather | total | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| cluster | 8 | 27,864 | 0% | 73.9 | 10.3 | 22.0 | 57.8 | 114.1 | 6.2 | 4.7 | 31.2 | 320 | +| cluster, `max_patch_size=16` | 134 | 27,864 | 2% | 73.2 | 98.6 | 43.6 | 132.7 | 133.8 | 13.1 | 100.0 | 78.2 | 673 | +| quadtree, block 8 | 386 | 24,714 | 92% | 70.6 | 277.0 | 64.9 | 231.4 | 179.7 | 23.4 | 295.5 | 131.4 | 1274 | +| quadtree, block 16 | 121 | 30,925 | 91% | 72.4 | 75.3 | 40.0 | 126.4 | 135.1 | 12.4 | 94.5 | 74.6 | 631 | +| quadtree, block 32 | 49 | 50,330 | 94% | 72.3 | 26.0 | 31.2 | 88.6 | 204.6 | 13.0 | 43.0 | 53.5 | 532 | + +## 4 ranks, without the solve + +| mesh | placement | imbalance | tag | regrid | migrate | deposit | halos | gather | total | +|---|---|---|---|---|---|---|---|---|---| +| cluster | balanced | 2.18 | 30.6 | 7.5 | 13.3 | 59.9 | 4.4 | 18.8 | 135 | +| cluster | morton | 2.19 | 32.0 | 7.6 | 12.4 | 57.5 | 4.8 | 23.0 | 137 | +| cluster, `max_patch_size=16` | balanced | 1.01 | 24.2 | 51.7 | 19.1 | 53.9 | 97.5 | 15.8 | 262 | +| cluster, `max_patch_size=16` | morton | 1.01 | 29.9 | 46.3 | 18.4 | 61.7 | 101.4 | 20.1 | 278 | +| quadtree, block 8 | balanced | 1.00 | 27.5 | 214.2 | 32.2 | 91.2 | 296.3 | 24.8 | 686 | +| quadtree, block 8 | morton | 1.00 | 30.7 | 189.0 | 30.9 | 95.9 | 273.5 | 25.3 | 645 | +| quadtree, block 16 | balanced | 1.02 | 24.6 | 39.4 | 17.8 | 60.5 | 96.6 | 16.6 | 256 | +| quadtree, block 16 | morton | 1.02 | 27.4 | 47.1 | 19.6 | 56.8 | 95.9 | 18.1 | 265 | +| quadtree, block 32 | balanced | 1.02 | 29.3 | 24.6 | 18.0 | 58.1 | 47.1 | 15.5 | 193 | +| quadtree, block 32 | morton | 1.02 | 25.5 | 17.3 | 14.5 | 49.7 | 36.3 | 15.2 | 158 | + +Imbalance: the largest cells per rank over the mean (the base level counted). + +## What they say + +- **The cost follows the number of patches, not how they are placed.** Regrid, halos, + deposit and gather grow with the patches: 8 clusters take 320 ms per step, 386 blocks of 8 + cells 1274 ms. At about the same number of patches the quadtree is as fast as clusters + (block 16, 121 patches: 631 ms; clusters cut to 16 cells, 134 patches: 673 ms), its + regrid a little faster since most of its patches are copied, not interpolated. +- **What the quadtree keeps is not reused yet.** 91-94% of its patches survive a regrid, + but the hierarchy is new, so the halo schedules (`build_schedule`, most of "halos"), the + composite node numbering and the solver are built again from scratch. Reusing them for + kept patches is where the quadtree could win; picnic's solver already reuses the grids and + probed operators of kept boxes (see picnic's `adaptive_rebuild_cost.py --method quadtree`). +- **Large blocks refine many cells**: blocks of 32 cover 50,330 cells for the 27,864 the + clusters need; the solver setup grows with them (205 ms against 114 ms). +- **Morton and balanced placement are within the noise on one node** (about 10% between + repeats). Morton keeps neighbouring patches and the patches over them on one rank, which + saves messages between nodes; within a node the messages are cheap and the halo time is + the schedule, built in Python. The few large clusters cannot be balanced by either (2.2). +- On four ranks tagging and gathering take about half as long as serially, but the deposit + does not get faster (58 ms serially, 50-96 ms on the slowest rank): the placements balance + cells, and the beam's patches hold most markers. Marker-weighted cuts of the Morton curve + are patchwork step 8e. + +## Fixed on the way + +The regrid's transfer compared every new patch with every old one of its level, and copied +the nodes a new patch shares with its old neighbours although an old patch with the same box +already had them. With the bin index of the halo schedules and without the copies that a +later one overwrites, the regrid of the 386-block mesh went from 866 ms to 277 ms per step +(serial), with the same values. diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py index db9efa4..4bd7d42 100644 --- a/benchmarks/quadtree/run.py +++ b/benchmarks/quadtree/run.py @@ -4,7 +4,8 @@ python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid Every configuration runs ``--repeats`` times under ``scope-profiler run``; the table gives -the median over the repeats of the mean time per step of each region (ms), and the mesh of +the median over the repeats of the mean time per step of each region (ms; under MPI on the +rank where it is largest), and the mesh of the JSON line of the run: patches, refined cells, the share of patches a regrid keeps and the load imbalance (largest cells per rank over the mean). Profiles are written to ``--out``. """ @@ -53,21 +54,20 @@ def run_once(arguments: list[str], ranks: int, output: Path) -> tuple[dict, dict for line in result.stdout.splitlines() if line.startswith("{") and '"method"' in line ) - inspected = subprocess.run( - [str(PROFILER), "inspect", str(output), "--json", "--top", "50"], - capture_output=True, - text=True, - check=True, - ) - regions = json.loads(inspected.stdout)["regions"]["items"] - times = {} - for region in regions: - name = region["name"] - if name.startswith("quadtree_bench."): - # the slowest rank's mean per call - times[name.split(".", 1)[1]] = ( - 1e3 * region["max"] if ranks > 1 else 1e3 * region["avg"] - ) + times: dict[str, float] = {} + for rank in range(ranks): # the slowest rank's mean per step of each part + inspected = subprocess.run( + [str(PROFILER), "inspect", str(output), "--json", "--top", "50"] + + (["--ranks", str(rank)] if ranks > 1 else []), + capture_output=True, + text=True, + check=True, + ) + for region in json.loads(inspected.stdout)["regions"]["items"]: + name = region["name"] + if name.startswith("quadtree_bench."): + part = name.split(".", 1)[1] + times[part] = max(times.get(part, 0.0), 1e3 * region["avg"]) return mesh, times diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb index 5eb019c..be9d882 100644 --- a/tutorials/13_quadtree_patches.ipynb +++ b/tutorials/13_quadtree_patches.ipynb @@ -289,6 +289,67 @@ "cell_type": "markdown", "id": "12", "metadata": {}, + "source": [ + "## Placing the blocks on ranks\n", + "\n", + "Under MPI, `placement=\"morton\"` puts the patches of a regrid on the ranks along a Morton\n", + "(Z-order) curve (`morton_ranks`): the patches of all levels in the order of the curve, keyed\n", + "by their lower corner in cells of the finest level, cut into runs of about equal cells, the\n", + "base level's cells counted. Neighbouring patches, and a patch and the patches over it, then\n", + "tend to share a rank, which saves messages between ranks. Here the ranks four processes would\n", + "give the patches of the beam's mesh:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13", + "metadata": {}, + "outputs": [], + "source": [ + "from patchwork import morton_ranks\n", + "\n", + "boxes = {\n", + " level: [patch.box for patch in mesh.patches_at_level(level)]\n", + " for level in range(1, mesh.max_level + 1)\n", + "}\n", + "ranks = morton_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", + "colours = plt.get_cmap(\"tab10\").colors\n", + "\n", + "fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)\n", + "for level in sorted(boxes):\n", + " xs, ys = mesh.node_positions(level, 0), mesh.node_positions(level, 1)\n", + " for ((i0, i1), (j0, j1)), rank in zip(boxes[level], ranks[level], strict=True):\n", + " ax.add_patch(\n", + " Rectangle(\n", + " (xs[i0], ys[j0]),\n", + " xs[i1] - xs[i0],\n", + " ys[j1] - ys[j0],\n", + " facecolor=colours[rank],\n", + " edgecolor=\"k\",\n", + " alpha=0.25,\n", + " lw=0.6,\n", + " )\n", + " )\n", + "ax.set_xlim(0, 1)\n", + "ax.set_ylim(0, 1)\n", + "ax.set_aspect(\"equal\")\n", + "cells = [\n", + " sum(\n", + " (hi0 - lo0) * (hi1 - lo1)\n", + " for level in boxes\n", + " for ((lo0, hi0), (lo1, hi1)), r in zip(boxes[level], ranks[level], strict=True)\n", + " if r == rank\n", + " )\n", + " for rank in range(4)\n", + "]\n", + "ax.set_title(f\"refined cells per rank: {cells} (rank 0 also has the base)\")" + ] + }, + { + "cell_type": "markdown", + "id": "14", + "metadata": {}, "source": [ "The few new blocks far from the beam come from the uniform background: its count per cell\n", "fluctuates around `per_cell` there, so a block or two switches on or off. With fewer\n",