diff --git a/CHANGELOG.md b/CHANGELOG.md index c83e853..68c2fab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,13 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - `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. +- Morton cuts weighted by cost: `regrid(..., placement="morton", cost=...)` weighs every patch + by its cells plus the cost of its leaf cells (`box_costs`), e.g. the markers of + `marker_counts` times what a marker costs against a cell; `rebalance(cost)` places the + patches of a hierarchy again by them and moves the fields. +- The halo geometry of every patch (its copies and interpolation weights) is kept on the + hierarchy and handed on by `regrid`: a patch with the same box and ranks and the same + patches within reach of its halo reuses it instead of finding it again. - 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 diff --git a/benchmarks/quadtree/README.md b/benchmarks/quadtree/README.md index f5c1c7f..b87df40 100644 --- a/benchmarks/quadtree/README.md +++ b/benchmarks/quadtree/README.md @@ -5,7 +5,8 @@ markers: tag (`marker_tags`), regrid, migrate, deposit, build the solver, solve, 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). +`placement="morton"`, by cells and weighted by the markers (`cost`, a marker costing a +tenth of a cell), without the solve, which the LU backend does not distribute. ```sh python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 117534c..92df15b 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -4,57 +4,73 @@ `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. +largest. "kept" is the share of the patches of a regrid that were there before it. "tag" +counts the markers on one level more than it tags, for the cost of `morton, markers`. ## Serial, with the solve +With the halo geometry of kept patches reused (patchwork 10c; the numbers in brackets are +the halos without it, from the first run of this benchmark). + | 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 | +| cluster | 8 | 27,864 | 0% | 106.2 | 10.7 | 20.3 | 55.6 | 113.7 | 5.9 | 8.1 (4.7) | 30.1 | 351 | +| cluster, `max_patch_size=16` | 134 | 27,864 | 2% | 101.5 | 85.5 | 38.7 | 130.8 | 124.3 | 12.5 | 120.7 (100.0) | 74.6 | 689 | +| quadtree, block 8 | 386 | 24,714 | 92% | 105.6 | 284.7 | 65.1 | 229.2 | 184.0 | 23.9 | 273.7 (295.5) | 134.7 | 1301 | +| quadtree, block 16 | 121 | 30,925 | 91% | 100.0 | 66.6 | 37.2 | 113.7 | 130.8 | 11.4 | 78.2 (94.5) | 68.2 | 606 | +| quadtree, block 32 | 49 | 50,330 | 94% | 102.1 | 30.4 | 29.4 | 84.9 | 199.4 | 12.1 | 28.4 (43.0) | 50.9 | 538 | ## 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 | +`morton, markers` weighs the Morton cuts by `cost`: the markers of `marker_counts`, a marker +costing a tenth of a cell. + +| mesh | placement | cells imbalance | markers imbalance | tag | regrid | migrate | deposit | halos | gather | total | +|---|---|---|---|---|---|---|---|---|---|---| +| cluster | balanced | 2.18 | 3.04 | 45.5 | 8.0 | 10.6 | 59.7 | 5.5 | 19.2 | 149 | +| cluster | morton | 2.19 | 3.04 | 46.4 | 9.8 | 10.9 | 62.1 | 5.6 | 23.6 | 159 | +| cluster | morton, markers | 2.19 | 3.04 | 46.7 | 9.5 | 10.1 | 53.1 | 5.6 | 19.8 | 145 | +| cluster, `max_patch_size=16` | balanced | 1.01 | 1.36 | 41.2 | 52.9 | 18.3 | 62.8 | 124.3 | 17.4 | 317 | +| cluster, `max_patch_size=16` | morton | 1.01 | 1.35 | 41.9 | 49.9 | 20.8 | 61.4 | 110.7 | 18.9 | 303 | +| cluster, `max_patch_size=16` | morton, markers | 1.11 | 1.22 | 40.5 | 55.3 | 19.3 | 60.7 | 128.7 | 17.2 | 322 | +| quadtree, block 8 | balanced | 1.00 | 1.31 | 40.8 | 215.3 | 28.7 | 92.6 | 395.5 | 23.4 | 796 | +| quadtree, block 8 | morton | 1.00 | 1.26 | 46.4 | 199.5 | 29.9 | 89.4 | 267.4 | 26.6 | 659 | +| quadtree, block 8 | morton, markers | 1.09 | 1.16 | 46.2 | 220.1 | 31.7 | 90.8 | 297.3 | 29.7 | 716 | +| quadtree, block 16 | balanced | 1.02 | 1.28 | 44.4 | 62.6 | 20.8 | 69.0 | 131.4 | 18.4 | 347 | +| quadtree, block 16 | morton | 1.02 | 1.35 | 46.9 | 63.2 | 27.2 | 63.2 | 105.0 | 20.5 | 326 | +| quadtree, block 16 | morton, markers | 1.13 | 1.24 | 48.6 | 67.4 | 21.0 | 68.1 | 104.0 | 18.0 | 327 | +| quadtree, block 32 | balanced | 1.02 | 1.28 | 42.6 | 23.3 | 16.4 | 58.0 | 44.9 | 13.9 | 199 | +| quadtree, block 32 | morton | 1.02 | 1.55 | 44.6 | 21.3 | 17.0 | 61.3 | 51.5 | 16.4 | 212 | +| quadtree, block 32 | morton, markers | 1.18 | 1.41 | 46.7 | 26.6 | 19.3 | 57.9 | 40.3 | 16.3 | 207 | -Imbalance: the largest cells per rank over the mean (the base level counted). +Imbalance: the largest cells (base level counted) or markers (after `migrate`) per rank over +the mean. ## 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`). + deposit and gather grow with the patches: 8 clusters take 351 ms per step, 386 blocks of 8 + cells 1301 ms. At about the same number of patches the quadtree is as fast as clusters + (block 16, 121 patches: 606 ms; clusters cut to 16 cells, 134 patches: 689 ms). +- **Reusing the halo geometry of kept patches saves 7-34% of the halos** (block 8: 296 → + 274 ms, block 16: 95 → 78 ms, block 32: 43 → 28 ms). Not more, for two reasons: about + a third of the patches still find their geometry again (kept patches whose neighbours or + coarse patches changed, and new ones), and building the `mpiarray.CopyPlan` of the + exchange from the copies is now the largest part (about 100 of 250 ms at 386 patches: + per-copy Python and a pickled `allgather`), and it is built for every new hierarchy. Next: + a cheaper `CopyPlan` in mpiarray (patchwork 8k). The clusters gain nothing, their patches are + recut every regrid, and pay a few ms for checking the signatures (8 clusters: 4.7 → 8.1 ms). - **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. + clusters need; the solver setup grows with them (199 ms against 114 ms). +- **Morton placement**: on one node within the noise of `balanced` for most meshes (about + 10% between repeats); the halos of blocks of 8 are faster with it (267 against 396 ms), + where the patches are small and many. +- **Weighing the cuts by the markers** (`morton, markers`) lowers the marker imbalance (blocks + of 8: 1.26 → 1.16, 16: 1.35 → 1.24, 32: 1.55 → 1.41, clusters cut to 16: 1.35 → 1.22) for a + higher cell imbalance (1.09-1.18), as asked. The step time does not change measurably on + four ranks: with 200,000 markers the deposit and gather take 60-120 ms against the cells' + halos and regrid. It pays where the markers dominate (many markers per cell, the push of a + real simulation, many nodes). The 7 clusters cannot be balanced by any cut (2.2, 3.0). ## Fixed on the way diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py index 7113df3..df60150 100644 --- a/benchmarks/quadtree/bench_quadtree.py +++ b/benchmarks/quadtree/bench_quadtree.py @@ -5,7 +5,8 @@ - ``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``); + and ``--placement`` (``balanced`` or ``morton``, with ``--marker-cost`` the Morton cuts + weighted by the markers: `marker_counts` times the cost of a marker against a cell); - ``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, @@ -33,7 +34,7 @@ import scope_profiler as sp from maybempi import MPI -from patchwork import AMRHierarchy, NodalPoisson, marker_tags +from patchwork import AMRHierarchy, NodalPoisson, marker_counts, marker_tags def beam(rng, count: int, width: float, centre: tuple[float, float]): @@ -67,6 +68,12 @@ def main() -> None: parser.add_argument( "--placement", choices=["balanced", "morton"], default="balanced" ) + parser.add_argument( + "--marker-cost", + type=float, + default=0.0, + help="what a marker costs against a cell: weighs the Morton cuts (with morton)", + ) 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) @@ -109,14 +116,22 @@ def markers(step: int): **options, ) - kept, patches, cells = [], [], [] + kept, patches, cells, held = [], [], [], [] 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) + counts = marker_counts(mesh, x, y, levels=args.levels + 1) + tags = { + level: counts[level] > args.per_cell for level in range(args.levels) + } + weigh = {} + if args.marker_cost and args.placement == "morton": + weigh["cost"] = { + level: args.marker_cost * found for level, found in counts.items() + } with sp.region("quadtree_bench.regrid"): - mesh = mesh.regrid(tags, **options) + mesh = mesh.regrid(tags, **options, **weigh) boxes = {(p.level, p.box) for p in mesh.patches if p.level} kept.append(len(boxes & previous) / max(len(boxes), 1)) previous = boxes @@ -124,6 +139,7 @@ def markers(step: int): cells.append(refined_cells(mesh)) with sp.region("quadtree_bench.migrate"): mx, my, mq = mesh.migrate(x, y, q, name="rho") + held.append(comm.allgather(mx.size)) with sp.region("quadtree_bench.deposit"): mesh.deposit(mx, my, mq, "rho") mesh.accumulate_halos("rho") @@ -155,6 +171,9 @@ def markers(step: int): "refined_cells": float(np.mean(cells)), "kept": float(np.mean(kept)), "load_imbalance": max(load) / (sum(load) / len(load)), + "marker_imbalance": float( + np.mean([max(h) / (sum(h) / len(h)) for h in held]) + ), } ) ) diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py index 4bd7d42..9447c53 100644 --- a/benchmarks/quadtree/run.py +++ b/benchmarks/quadtree/run.py @@ -7,7 +7,9 @@ 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``. +the load imbalance (largest cells per rank over the mean) and the marker imbalance (largest +markers per rank over the mean, after `migrate`). ``morton, markers`` weighs the Morton cuts +with the markers, a marker costing a tenth of a cell. Profiles are written to ``--out``. """ from __future__ import annotations @@ -26,6 +28,13 @@ PROFILER = Path(sys.executable).with_name("scope-profiler") PARTS = ("tag", "regrid", "migrate", "deposit", "solver", "solve", "halos", "gather") +#: the placements compared under MPI, and their arguments +PLACEMENTS = { + "balanced": ["--placement", "balanced"], + "morton": ["--placement", "morton"], + "morton, markers": ["--placement", "morton", "--marker-cost", "0.1"], +} + #: (label, arguments) of the meshes compared MESHES = [ ("cluster", ["--method", "cluster"]), @@ -81,7 +90,7 @@ def main() -> 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"] + list(PLACEMENTS) if args.ranks > 1 else ["balanced"] ) extra = list(bench) + ([] if args.ranks == 1 else ["--no-solve"]) @@ -92,6 +101,7 @@ def main() -> None: "refined", "kept", "imbalance", + "markers", *PARTS, "total", ] @@ -101,10 +111,11 @@ def main() -> None: for placement in placements: runs = [] for repeat in range(args.repeats): - name = f"{label.replace(', ', '_').replace(' ', '')}_{placement}_{args.ranks}_{repeat}.h5" + name = f"{label}_{placement}_{args.ranks}_{repeat}".replace(", ", "_") + name = name.replace(" ", "") + ".h5" runs.append( run_once( - [*arguments, "--placement", placement, *extra], + [*arguments, *PLACEMENTS[placement], *extra], args.ranks, args.out / name, ) @@ -120,6 +131,7 @@ def main() -> None: f"{mesh['refined_cells']:.0f}", f"{mesh['kept']:.0%}", f"{mesh['load_imbalance']:.2f}", + f"{mesh['marker_imbalance']:.2f}", *(f"{times[part]:.1f}" if times[part] else "-" for part in PARTS), f"{total:.1f}", ] diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index 97e3893..d40902b 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -14,10 +14,12 @@ FluxRegister, IndexBox, Patch, + box_costs, cluster, function_tags, graded_nodes, gradient_tags, + marker_counts, marker_tags, morton_ranks, plot_patches, @@ -87,10 +89,12 @@ "PetscSystem", "__version__", "cell_body", + "box_costs", "cluster", "function_tags", "graded_nodes", "gradient_tags", + "marker_counts", "marker_tags", "morton_ranks", "plot_patches", diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index a50e190..0db5ce8 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -12,9 +12,11 @@ from patchwork.mesh.plotting import plot_patches from patchwork.mesh.reflux import FluxRegister from patchwork.mesh.regrid import ( + box_costs, cluster, function_tags, gradient_tags, + marker_counts, marker_tags, morton_ranks, quadtree_boxes, @@ -25,10 +27,12 @@ "FluxRegister", "IndexBox", "Patch", + "box_costs", "cluster", "function_tags", "graded_nodes", "gradient_tags", + "marker_counts", "marker_tags", "morton_ranks", "plot_patches", diff --git a/src/patchwork/mesh/halos.py b/src/patchwork/mesh/halos.py index 81192e9..2ee124a 100644 --- a/src/patchwork/mesh/halos.py +++ b/src/patchwork/mesh/halos.py @@ -523,6 +523,40 @@ def error(spacing: float) -> float: ), problem=_halo_problem, ) +def _key(patch: Patch) -> tuple: + """A patch as its level, box and ranks: the same in the hierarchies a regrid makes.""" + return (patch.level, patch.box, patch.ranks) + + +def _within(points: _Points, level: int, box: Box) -> tuple: + """The keys of the patches of ``level`` that overlap ``box`` or one of its periodic images.""" + shifts = points.shifts(level) + return tuple( + _key(other) + for other in points.near(level, box) + if any( + _overlap(box, _shift(points.own(other), shift)) is not None + for shift in shifts + ) + ) + + +class _HaloRecord: + """The halo geometry of one patch, its fields named by patch keys. + + ``copies`` are ``(source, box, target, box)`` with each array a slot: + ``("field", key)``, ``("coarse", key)`` (the field interpolated from) or + ``("buffer", shape)``, the patch's buffer of coarse values; ``None`` where + this rank does not hold the array. ``interpolation`` is the buffer's shape, + the storage index, the buffer points and the weights of the halo points + interpolated from the level below, or ``None``. + """ + + def __init__(self, copies: list[tuple], interpolation: tuple | None) -> None: + self.copies = copies + self.interpolation = interpolation + + class HaloExchange: """Fill the halo of every patch of field ``name``; see the module docstring. @@ -598,6 +632,112 @@ def _coarse_fine( if interpolation is not None: self._interpolations.append(interpolation) + def _signature(self, points: _Points, patch: Patch) -> tuple: + """What a patch's halo geometry depends on: itself and the patches within reach. + + The patches of its level that may overlap its halo, and those of the level + below that may hold the coarse points of its interpolation, each as + ``(level, box, ranks)``. + """ + own = points.own(patch) + width = self._width + extended = tuple((lo - width, hi + width) for lo, hi in own) + same = _within(points, patch.level, extended) + if patch.level == 0: + return (_key(patch), same) + ratio = points.ratio + coarse = tuple((lo // ratio - 1, -(-hi // ratio) + 2) for lo, hi in extended) + return (_key(patch), same, _within(points, patch.level - 1, coarse)) + + def _record(self, points: _Points, patch: Patch, dtype: Any) -> _HaloRecord: + """The halo geometry of one patch, with its fields as patch keys.""" + slots: dict[int, tuple] = {} + own_field, coarse_field = self._field, self._coarse_field + + def field(other: Patch) -> Any: + array = own_field(other) + if array is not None: + slots[id(array)] = ("field", _key(other)) + return array + + def coarse(other: Patch) -> Any: + array = coarse_field(other) + if array is not None: + slots[id(array)] = ("coarse", _key(other)) + return array + + copies: list[tuple] = [] + self._field, self._coarse_field = field, coarse # type: ignore[method-assign] + try: + covered = self._same_level(points, patch, copies) + interpolations: list = [] + if patch.level > 0: + before = self._interpolations + self._interpolations = interpolations + try: + self._coarse_fine(points, patch, covered, dtype, copies) + finally: + self._interpolations = before + finally: + del self._field, self._coarse_field # back to the methods + buffer = None + interpolation = None + if interpolations: + (found,) = interpolations + buffer = found.buffer + slots[id(buffer)] = ("buffer", tuple(buffer.shape)) + interpolation = ( + tuple(buffer.shape), + found.index, + found.flat, + found.weights, + ) + else: + for _, _, target, _ in copies: # a buffer on a rank without points + if target is not None and id(target) not in slots: + buffer = target + slots[id(target)] = ("buffer", tuple(target.shape)) + template = [ + ( + None if source is None else slots[id(source)], + source_box, + None if target is None else slots[id(target)], + target_box, + ) + for source, source_box, target, target_box in copies + ] + return _HaloRecord(template, interpolation) + + def _bind( + self, record: _HaloRecord, patch: Patch, patches: dict, dtype: Any + ) -> None: + """The copies and the interpolation of a record, on this hierarchy's arrays.""" + buffer = None + + def resolve(slot: tuple | None) -> Any: + nonlocal buffer + if slot is None: + return None + kind, key = slot + if kind == "buffer": + if buffer is None: + buffer = mpa.zeros(key, dtype=dtype, split=None, comm=patch.comm) + return buffer + other = patches[key] + return self._field(other) if kind == "field" else self._coarse_field(other) + + for source, source_box, target, target_box in record.copies: + self._copies.append( + (resolve(source), source_box, resolve(target), target_box) + ) + if record.interpolation is not None: + shape, index, flat, weights = record.interpolation + if buffer is None: + buffer = mpa.zeros(shape, dtype=dtype, split=None, comm=patch.comm) + self._interpolations.append( + _Bilinear(self._field(patch), index, buffer, flat, weights) + ) + def __init__( self, hierarchy: AMRHierarchy, @@ -610,6 +750,12 @@ def __init__( With ``level``, only for the patches of that level; with ``below``, interpolating field ``below`` of the level below instead of ``name``. + + The geometry of each patch's halo (which points come from which patch, + and the interpolation weights) is kept on the hierarchy, by centering, + width and type, and handed on by `AMRHierarchy.regrid`: a patch with the + same box and ranks, and the same patches within reach of its halo, reuses + it instead of finding it again. """ spec = hierarchy._field_specs[name] self._hierarchy = hierarchy @@ -617,16 +763,28 @@ def __init__( self._below = name if below is None else below self._level = level self._width = int(spec["halo"]) - points = _Points(hierarchy, spec["centering"] == "node") - copies: list[tuple] = [] + nodal = spec["centering"] == "node" + points = _Points(hierarchy, nodal) + self._copies: list[tuple] = [] self._interpolations: list[_Bilinear] = [] + dtype = spec["dtype"] + kind = ("halo", nodal, self._width, np.dtype(dtype).str, repr(spec["split"])) + known = hierarchy._halo_records.get(kind, {}) + used: dict[tuple, _HaloRecord] = {} + patches = {_key(patch): patch for patch in hierarchy.patches} for patch in hierarchy.patches if self._width else (): if level is not None and patch.level != level: continue - covered = self._same_level(points, patch, copies) - if patch.level > 0: - self._coarse_fine(points, patch, covered, spec["dtype"], copies) - self._plan = mpa.CopyPlan(copies, comm=hierarchy.comm) + signature = self._signature(points, patch) + record = known.get(signature) + if record is None: + record = self._record(points, patch, dtype) + used[signature] = record + self._bind(record, patch, patches, dtype) + # keep the records of this mesh (all of them after a full build) + hierarchy._halo_records[kind] = used if level is None else {**known, **used} + self._plan = mpa.CopyPlan(self._copies, comm=hierarchy.comm) + del self._copies def execute(self) -> None: """Fill the halos. Collective over the hierarchy's communicator.""" diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 044aa1e..822de85 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -501,6 +501,9 @@ def __init__( self._cells_on_rank = [0.0] * self.comm.Get_size() # halo exchanges and restrictions, by kind and field; rebuilt after add_patch self._schedules: dict[tuple[str, str], Any] = {} + # the halo geometry of each patch, kept across add_patch and regrid (halos.py) + if not hasattr(self, "_halo_records"): + self._halo_records: dict[tuple, dict] = {} # which patch owns each cell of every level, rebuilt after add_patch (locate) self._locators: tuple[Any, ...] | None = None self._field_specs: dict[str, dict[str, Any]] = {} @@ -968,6 +971,63 @@ def restrict(self, name: str, *, level: int | None = None) -> None: self._schedule("restrict", name, Restriction).execute(level=level) + def _rebuilt( + self, + boxes: Mapping[int, Sequence[IndexBox]], + placement: Any, + cost: Mapping[int, Any] | None, + fill_halos: bool, + ) -> AMRHierarchy: + """A hierarchy with this base and the refined ``boxes``, with the fields moved over.""" + from patchwork.mesh.regrid import transfer + + base = self.patches_at_level(0) + new = AMRHierarchy.__new__(AMRHierarchy) + new._communicators = self._communicators + new._halo_records = dict(self._halo_records) # the kept patches reuse theirs + new.__init__( # type: ignore[misc] + self.base_shape, # type: ignore[arg-type] + self.bounds, # type: ignore[arg-type] + refinement_ratio=self.refinement_ratio, + periodic=self.periodic, + base_boxes=[patch.box for patch in base], + base_ranks=[patch.ranks for patch in base], + placement=self.placement if placement is None else placement, + max_cells_per_rank=self.max_cells_per_rank, + comm=self.comm, + geometry=self.geometry, + axis_nodes=self.axis_nodes, + ) + if new.placement == "morton": + from patchwork.mesh.regrid import box_costs, morton_ranks + + weights, load = None, list(new.cells_on_rank) # the base level + if cost is not None: + weights, load = box_costs(new, boxes, cost) + ranks = morton_ranks( + boxes, + self.comm.Get_size(), + ratio=self.refinement_ratio, + load=load, + weights=weights, + ) + for level in sorted(boxes): + for box, rank in zip(boxes[level], ranks[level], 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) + new.allocate_field(name, **spec) + transfer(self, new, name) + if fill_halos: + for name in new.field_names: + new.exchange_halos(name) + return new + @sp.profile("patchwork.mesh.regrid", tags=PROFILE_TAGS) @method( equations={ @@ -1003,6 +1063,7 @@ def regrid( min_patch_size: int = 1, forbid: Any = None, placement: str | Callable[[int, IndexBox], Any] | None = None, + cost: Mapping[int, Any] | None = None, fill_halos: bool = False, ) -> AMRHierarchy: """A new hierarchy with patches over the tagged cells, and the fields moved to it. @@ -1053,18 +1114,23 @@ 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, or along a Morton curve with ``"morton"``. Collective over ``comm``; this hierarchy is left as + the largest first, or along a Morton curve with ``"morton"``. With + ``"morton"``, ``cost`` weighs the patches by more than their cells: a + mapping from a level to a per-cell cost of that level's shape, in units + of one cell (the markers of `marker_counts` times what a marker costs + against a cell), counted in the patch where the cell is a leaf + (`box_costs`), so that a rank with a dense beam gets fewer cells. 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, - quadtree_boxes, - transfer, - ) + from patchwork.mesh.regrid import combine_tags, new_boxes, quadtree_boxes if method not in ("cluster", "quadtree"): raise ValueError(f"method must be 'cluster' or 'quadtree', got {method!r}") + if ( + cost is not None + and (self.placement if placement is None else placement) != "morton" + ): + raise ValueError("cost weighs the patches of placement='morton' only") if method == "quadtree" and max_patch_size is not None: raise ValueError( "max_patch_size does not apply to method='quadtree': " @@ -1092,47 +1158,26 @@ def regrid( min_patch_size=min_patch_size, forbid=forbid, ) - base = self.patches_at_level(0) - new = AMRHierarchy.__new__(AMRHierarchy) - new._communicators = self._communicators - new.__init__( # type: ignore[misc] - self.base_shape, # type: ignore[arg-type] - self.bounds, # type: ignore[arg-type] - refinement_ratio=self.refinement_ratio, - periodic=self.periodic, - base_boxes=[patch.box for patch in base], - base_ranks=[patch.ranks for patch in base], - placement=self.placement if placement is None else placement, - max_cells_per_rank=self.max_cells_per_rank, - comm=self.comm, - geometry=self.geometry, - axis_nodes=self.axis_nodes, - ) - if new.placement == "morton": - from patchwork.mesh.regrid import morton_ranks + return self._rebuilt(boxes, placement, cost, fill_halos) - 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): - for box, rank in zip(boxes[level], ranks[level], 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) - new.allocate_field(name, **spec) - transfer(self, new, name) - if fill_halos: - for name in new.field_names: - new.exchange_halos(name) - return new + @sp.profile("patchwork.rebalance", tags=PROFILE_TAGS) + def rebalance( + self, cost: Mapping[int, Any] | None = None, *, fill_halos: bool = False + ) -> AMRHierarchy: + """The same patches placed again along the Morton curve, by ``cost``; fields moved. + + Every refined patch goes to a rank by `morton_ranks`, weighed by its + cells plus the ``cost`` of its leaf cells as in `regrid` (`box_costs`; + without ``cost`` by its cells). The base level stays where it is. Every + field is copied to the patches' new ranks; send the markers after them + with `migrate`. The new hierarchy places its regrids along the curve as + well (``placement="morton"``). Collective over ``comm``. + """ + boxes = { + level: [patch.box for patch in self.patches_at_level(level)] + for level in range(1, self.max_level + 1) + } + return self._rebuilt(boxes, "morton", cost, fill_halos) def integral(self, name: str) -> float: """The integral of field ``name`` over the domain, from the finest values. diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 81a5df6..2be6e38 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -96,23 +96,23 @@ def function_tags( return tags -def marker_tags( - hierarchy: AMRHierarchy, *coordinates: Any, per_cell: float, levels: int +def marker_counts( + hierarchy: AMRHierarchy, *coordinates: Any, 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. + """The number of markers in every cell of levels ``0 .. levels - 1``, over all ranks. + + ``marker_counts(x, ...)`` in 1D, ``marker_counts(x, y, ...)`` in 2D: the + positions of this rank's markers (arrays of one shape). Every level is + counted whole, whether a patch covers a cell or not, and the counts are + added over the ranks (collective over ``comm``): every rank gets the same + arrays, of the levels' shapes (`AMRHierarchy.level_shape`). Markers + outside the domain (and in the notch of an L) are not counted. The counts + make the tags of `marker_tags` and, scaled to the cost of a marker, the + ``cost`` of `AMRHierarchy.regrid`. """ if len(coordinates) != hierarchy.ndim: raise ValueError( - f"marker_tags takes {hierarchy.ndim} coordinate arrays, " + f"marker counts take {hierarchy.ndim} coordinate arrays, " f"got {len(coordinates)}" ) if levels < 0: @@ -121,17 +121,32 @@ def marker_tags( if any(hierarchy.periodic): points = points.copy() hierarchy.wrap(points) - tags = {} + counts = {} 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) + found, _ = np.histogramdd(points.T, bins=edges) + mine = np.ascontiguousarray(found) everyone = np.empty_like(mine) hierarchy.comm.Allreduce(mine, everyone, op=MPI.SUM) - tags[level] = (everyone > per_cell) & _domain_cells(hierarchy, level) - return tags + counts[level] = np.where(_domain_cells(hierarchy, level), everyone, 0.0) + return counts + + +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, counted + by `marker_counts` (collective over ``comm``, the same tags on every + rank). 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. + """ + counts = marker_counts(hierarchy, *coordinates, levels=levels) + return {level: found > per_cell for level, found in counts.items()} @sp.profile("patchwork.gradient_tags", tags=PROFILE_TAGS) @@ -737,6 +752,7 @@ def morton_ranks( *, ratio: int = 2, load: Sequence[float] | None = None, + weights: Mapping[int, 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. @@ -746,13 +762,16 @@ def morton_ranks( 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]``. + goes on. ``weights`` (per level, one per box) replaces the cells of a box + by its cost, in the units of ``load``: with `box_costs`, the cells plus the + markers on them. 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}") - 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)}") + loads = [0.0] * size if load is None else [float(w) for w in load] + if len(loads) != size: + raise ValueError(f"load needs {size} values, got {len(loads)}") items = [ (level, n, box) for level in sorted(boxes) for n, box in enumerate(boxes[level]) ] @@ -768,18 +787,70 @@ def morton_ranks( keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D else: # 1D: the curve is the axis keys = corners.reshape(-1) - cells = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] - share = (sum(weights) + sum(cells)) / size + if weights is None: + costs = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] + else: + for level in boxes: + if len(weights[level]) != len(boxes[level]): + raise ValueError(f"weights of level {level} need one value per box") + costs = [float(weights[level][n]) for level, n, _ in items] + share = (sum(loads) + sum(costs)) / 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: + while rank < size - 1 and loads[rank] + costs[k] / 2 > share: rank += 1 level, n, _ = items[k] result[level][n] = rank - weights[rank] += cells[k] + loads[rank] += costs[k] return result +def box_costs( + hierarchy: AMRHierarchy, + boxes: Mapping[int, Sequence[IndexBox]], + cost: Mapping[int, Any], +) -> tuple[dict[int, list[float]], list[float]]: + """The cost of each new box and of each rank's base patches: cells plus the cost of the leaf cells. + + ``cost`` maps a level to a per-cell cost of that level's shape, in units of + one cell (``0.5 * marker_counts(...)[level]`` if a marker costs half a cell; + a missing level costs nothing beyond its cells). A cell's cost goes to the + box where it is a leaf, not covered by a finer box, since that is where its + markers deposit and gather. ``hierarchy`` holds the base level (the patches + of level 0 with their ranks). Returns the weights of ``boxes`` per level and + the load of every rank from the base level, for `morton_ranks`. + """ + ratio = hierarchy.refinement_ratio + top = max(boxes, default=0) + leaf_cost = {} + for level in range(top + 1): + shape = hierarchy.level_shape(level) + values = cost.get(level) + if values is None: + values = np.zeros(shape) + values = np.asarray(values, dtype=float) + if values.shape != shape: + raise ValueError( + f"cost of level {level} has the shape {values.shape}, not {shape}" + ) + leaf = np.ones(shape, dtype=bool) + for box in boxes.get(level + 1, ()): + leaf[tuple(slice(lo // ratio, hi // ratio) for lo, hi in box)] = False + leaf_cost[level] = np.where(leaf, values, 0.0) + + def weight(level: int, box: IndexBox) -> float: + where = tuple(slice(lo, hi) for lo, hi in box) + cells = float(np.prod([hi - lo for lo, hi in box])) + return cells + float(leaf_cost[level][where].sum()) + + weights = {level: [weight(level, box) for box in boxes[level]] for level in boxes} + load = [0.0] * hierarchy.comm.Get_size() + for patch in hierarchy.patches_at_level(0): + for rank in patch.ranks: + load[rank] += weight(0, patch.box) / len(patch.ranks) + return weights, load + + @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_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 8c5d2fd..92f8a1b 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -269,3 +269,180 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: assert len(added.ranks) == 1 with pytest.raises(ValueError, match="morton"): AMRHierarchy(base_shape=(4, 4), placement="hilbert") + + +@pytest.mark.parametrize("centering", ["node", "cell"]) +def test_kept_patches_reuse_their_halo_geometry(centering, monkeypatch) -> None: + from patchwork.mesh import halos + + def blob(cx): + return lambda x, y: np.hypot(x - cx, y - 0.5) < 0.12 + + mesh = AMRHierarchy(base_shape=(32, 32), placement="morton") + mesh.allocate_field("u", centering=centering, halo=2) + for _ in range(2): + mesh = mesh.regrid( + function_tags(mesh, blob(0.4), levels=2), method="quadtree", block_size=4 + ) + mesh.exchange_halos("u") # the records of this mesh + + built = [] + record = halos.HaloExchange._record + monkeypatch.setattr( + halos.HaloExchange, + "_record", + lambda self, *args: built.append(args[1]) or record(self, *args), + ) + moved = mesh.regrid( + function_tags(mesh, blob(0.42), levels=2), method="quadtree", block_size=4 + ) + kept = {(p.level, p.box) for p in mesh.patches} & { + (p.level, p.box) for p in moved.patches + } + + def fill(hierarchy): + for patch in hierarchy.local_patches: + coordinates = ( + patch.local_node_coordinates(hierarchy, "u") + if centering == "node" + else patch.local_cell_centers(hierarchy, "u") + ) + patch.field("u").local[...] = ( + 1.0 + 2.0 * coordinates[0] - 3.0 * coordinates[1] + ) + + fill(moved) + moved.exchange_halos("u") + reused = len(moved.patches) - len(built) + assert 0 < reused <= len(kept) # only kept patches can reuse their geometry + # the same halos as a hierarchy that finds every patch's geometry again + fresh = moved.regrid( + function_tags(mesh, blob(0.42), levels=2), method="quadtree", block_size=4 + ) + fresh._halo_records.clear() + assert [(p.level, p.box) for p in fresh.patches] == [ + (p.level, p.box) for p in moved.patches + ] + fill(fresh) + fresh.exchange_halos("u") + for a, b in zip(moved.local_patches, fresh.local_patches, strict=True): + np.testing.assert_array_equal( + np.asarray(a.field("u").local_with_halos), + np.asarray(b.field("u").local_with_halos), + ) + + +def test_marker_weights_move_the_cuts_of_the_morton_curve() -> None: + from patchwork import box_costs, marker_counts + + boxes = { + 1: [((2 * i, 2 * i + 2), (0, 2)) for i in range(4)] + } # four boxes of 4 cells + assert morton_ranks(boxes, 2) == {1: [0, 0, 1, 1]} + # the first box costs as much as the other three: it gets a rank to itself + heavy = {1: [12.0, 4.0, 4.0, 4.0]} + assert morton_ranks(boxes, 2, weights=heavy) == {1: [0, 1, 1, 1]} + with pytest.raises(ValueError, match="weights"): + morton_ranks(boxes, 2, weights={1: [1.0]}) + + mesh = AMRHierarchy(base_shape=(8, 8)) + rank = WORLD.Get_rank() + # 64 markers in base cell (1, 1), shared out over the ranks + x = np.full(64, 0.19)[rank::SIZE] + y = np.full(64, 0.19)[rank::SIZE] + counts = marker_counts(mesh, x, y, levels=2) + assert counts[0][1, 1] == 64 and counts[0].sum() == 64 + assert counts[1][3, 3] == 64 + # level 1 covers base cells 0..3 x 0..1: the markers are on its leaf cells + new = {1: [((0, 8), (0, 4))]} + weights, load = box_costs(mesh, new, {0: counts[0], 1: counts[1]}) + assert weights == {1: [32.0 + 64.0]} + assert sum(load) == 64.0 # the base's cells; the markers are on the finer patch + with pytest.raises(ValueError, match="shape"): + box_costs(mesh, new, {0: np.zeros((3, 3))}) + + +def test_regrid_with_marker_costs_gives_the_dense_patches_fewer_cells() -> None: + from patchwork import box_costs, marker_counts + + mesh = AMRHierarchy(base_shape=(16, 16), placement="morton") + rng = np.random.default_rng(WORLD.Get_rank()) + x = np.concatenate([rng.normal(0.3, 0.04, 4000), rng.uniform(0, 1, 1000)]) % 1 + y = np.concatenate([rng.normal(0.3, 0.04, 4000), rng.uniform(0, 1, 1000)]) % 1 + for _ in range(2): + tags = marker_tags(mesh, x, y, per_cell=8 * SIZE, levels=2) + mesh = mesh.regrid(tags, method="quadtree", block_size=4) + counts = marker_counts(mesh, x, y, levels=3) + cost = {level: 0.5 * found for level, found in counts.items()} + plain = mesh.regrid(tags, method="quadtree", block_size=4) + weighted = mesh.regrid(tags, method="quadtree", block_size=4, cost=cost) + assert [(p.level, p.box) for p in weighted.patches] == [ + (p.level, p.box) for p in plain.patches + ] + + def costs(hierarchy): # cells plus half the markers of the leaf cells, per rank + boxes = { + level: [p.box for p in hierarchy.patches_at_level(level)] + for level in range(1, hierarchy.max_level + 1) + } + weights, load = box_costs(hierarchy, boxes, cost) + for level, values in weights.items(): + patches = hierarchy.patches_at_level(level) + for patch, value in zip(patches, values, strict=True): + load[patch.ranks[0]] += value + return load + + assert max(costs(weighted)) <= max(costs(plain)) + 1e-9 + with pytest.raises(ValueError, match="morton"): + AMRHierarchy(base_shape=(4, 4)).regrid({0: np.ones((4, 4), bool)}, cost=cost) + + +def test_rebalance_moves_the_patches_and_their_fields_to_the_weighted_ranks() -> None: + from patchwork import box_costs, marker_counts + + mesh = AMRHierarchy(base_shape=(16, 16), placement="balanced") + mesh.allocate_field("u", centering="node") + mesh.allocate_field("c") + mesh = mesh.regrid( + function_tags(mesh, ring, levels=2), method="quadtree", block_size=4 + ) + mesh = mesh.regrid( + function_tags(mesh, ring, levels=2), method="quadtree", block_size=4 + ) + + 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")) + x = np.full(100, 0.21)[WORLD.Get_rank() :: SIZE] + y = np.full(100, 0.5)[WORLD.Get_rank() :: SIZE] + cost = marker_counts(mesh, x, y, levels=3) + moved = mesh.rebalance(cost) + + assert moved.placement == "morton" + assert [(p.level, p.box) for p in moved.patches] == [ + (p.level, p.box) for p in mesh.patches + ] + boxes = { + level: [p.box for p in mesh.patches_at_level(level)] + for level in range(1, mesh.max_level + 1) + } + weights, load = box_costs(moved, boxes, cost) + expected = morton_ranks(boxes, SIZE, load=load, weights=weights) + for level in boxes: + ranks = [p.ranks for p in moved.patches_at_level(level)] + assert ranks == [(r,) for r in expected[level]] + for patch in moved.local_patches: + np.testing.assert_allclose( + patch.field("u").local, + plane(*patch.local_node_coordinates(moved, "u")), + atol=1e-12, + ) + np.testing.assert_allclose( + patch.field("c").local, + plane(*patch.local_cell_centers(moved, "c")), + atol=1e-12, + ) + assert mesh.rebalance().max_level == mesh.max_level # by cells alone diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb index be9d882..470002a 100644 --- a/tutorials/13_quadtree_patches.ipynb +++ b/tutorials/13_quadtree_patches.ipynb @@ -307,49 +307,88 @@ "metadata": {}, "outputs": [], "source": [ - "from patchwork import morton_ranks\n", + "from patchwork import box_costs, marker_counts, 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", + "def draw_ranks(ranks, title):\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", - " )\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)\")" + " ax.set_xlim(0, 1)\n", + " ax.set_ylim(0, 1)\n", + " ax.set_aspect(\"equal\")\n", + " ax.set_title(title)\n", + "\n", + "\n", + "def per_rank(ranks, values, base):\n", + " \"\"\"The sum of ``values`` per rank, with the base level's ``base`` on rank 0.\"\"\"\n", + " totals = [base, 0.0, 0.0, 0.0]\n", + " for level in boxes:\n", + " for value, rank in zip(values[level], ranks[level], strict=True):\n", + " totals[rank] += value\n", + " return [round(total) for total in totals]\n", + "\n", + "\n", + "cells = {\n", + " level: [np.prod([hi - lo for lo, hi in b]) for b in boxes[level]] for level in boxes\n", + "}\n", + "ranks = morton_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", + "draw_ranks(ranks, f\"cells per rank: {per_rank(ranks, cells, 1024)}\")" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, + "source": [ + "Equal cells are not equal work in a particle code: the ranks with the beam hold most of\n", + "the markers. With `cost`, `regrid(..., placement=\"morton\", cost=...)` weighs every patch by\n", + "its cells plus the cost of its leaf cells (a cell's markers deposit and gather on the finest\n", + "patch over it), here the counts of `marker_counts` at a tenth of a cell per marker.\n", + "`box_costs` gives these weights, and `rebalance(cost)` places the patches of an existing\n", + "hierarchy again by them and moves the fields (send the markers after them with `migrate`).\n", + "The ranks with the beam now get fewer cells and about the same cost:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "15", + "metadata": {}, + "outputs": [], + "source": [ + "counts = marker_counts(mesh, x, y, levels=mesh.max_level + 1)\n", + "cost = {level: 0.1 * found for level, found in counts.items()}\n", + "weights, (base,) = box_costs(mesh, boxes, cost) # one rank here: the base's cost\n", + "weighted = morton_ranks(boxes, 4, load=[base, 0, 0, 0], weights=weights)\n", + "print(\"cells per rank:\", per_rank(weighted, cells, 1024))\n", + "print(\"cost per rank, by cells: \", per_rank(ranks, weights, base))\n", + "print(\"cost per rank, by markers: \", per_rank(weighted, weights, base))\n", + "draw_ranks(weighted, \"the same patches, cut by cells plus markers\")" + ] + }, + { + "cell_type": "markdown", + "id": "16", + "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",