Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
5 changes: 3 additions & 2 deletions README.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
3 changes: 3 additions & 0 deletions docs/src/content/docs/examples/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion src/patchwork/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
function_tags,
graded_nodes,
gradient_tags,
marker_tags,
plot_patches,
quadtree_boxes,
)
from patchwork.solvers import (
AMGBackend,
Expand Down Expand Up @@ -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",
]
12 changes: 10 additions & 2 deletions src/patchwork/mesh/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -20,7 +26,9 @@
"Patch",
"cluster",
"function_tags",
"gradient_tags",
"graded_nodes",
"gradient_tags",
"marker_tags",
"plot_patches",
"quadtree_boxes",
]
63 changes: 49 additions & 14 deletions src/patchwork/mesh/hierarchy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
188 changes: 184 additions & 4 deletions src/patchwork/mesh/regrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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={
Expand Down Expand Up @@ -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).
Expand Down
Loading