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..6540a9f 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,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. +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 +}