Skip to content
Projects

patchwork.mesh

The mesh layer: the patch hierarchy and what moves data between its patches.

hierarchy (AMRHierarchy, Patch, IndexBox: patches, fields, marker location and migration), halos (halo exchange and restriction), regrid (tagging, clustering, regridding), accumulate (deposit accumulation across patch edges), reflux (flux registers), grading (the nodes of graded axes) and plotting. It knows nothing of the spaces (patchwork.spaces) or the solvers (patchwork.solvers) built on it.

Attributes

NameDescription
IndexBoxNo description.

Classes

NameDescription
AMRHierarchyA 1D or 2D nested patch hierarchy with mpiarray-backed fields.
FluxRegisterMatches the fluxes of coarse and fine levels at their interfaces (refluxing).
PatchOne rectangular patch; its box uses level-local, half-open cell indices.

Functions

NameDescription
box_costsThe cost of each new box and of each rank's base patches.
clusterCover the tagged cells with boxes (the Berger-Rigoutsos algorithm).
curve_ranksThe rank of each box: the boxes of all levels along a space-filling curve, cut into size runs.
function_tagsTag the cells of levels 0 .. levels - 1 where function is true.
graded_nodesThe nodes of [lower, upper] whose cells follow the size spacing.
gradient_tagsTag the cells across which field name changes by more than threshold.
knapsack_ranksThe rank of each box: the largest cost first, each to the rank with the least so far.
marker_countsThe number of markers in every cell of levels 0 .. levels - 1, over all ranks.
marker_tagsTag the cells of levels 0 .. levels - 1 that hold more than per_cell markers.
plot_patchesPlot patch extents and cell grids, optionally colored by a field.
quadtree_boxesThe boxes of every refined level as the blocks of a quadtree (an octree in 3D).

Modules

  • accumulateScatter-add of a node-centered deposit: every node's charge goes to one copy.
  • gradingGraded axes: node positions whose spacing follows a given local cell size.
  • halosHalo exchange between patches, and restriction from fine patches to coarse ones.
  • hierarchyBlock-structured adaptive mesh hierarchy and mpiarray-backed patch fields.
  • plottingMatplotlib plots for AMR patch layouts and patch-local fields.
  • refluxConservative explicit time steps on a patch hierarchy: refluxing.
  • regridRegridding: patches where tagged cells say the mesh needs to be finer.

IndexBoxattributemodule attribute#

IndexBox = tuple[tuple[int, int], ...]

AMRHierarchyclass#

class AMRHierarchy(base_shape: tuple[int, ...], bounds: Sequence[Sequence[float] | None] | None = None, *, refinement_ratio: int = 2, periodic: Sequence[bool] | None = None, base_boxes: Sequence[Sequence[Sequence[int]]] | None = None, placement: str | Callable[[int, IndexBox], Any] = 'all', max_cells_per_rank: int | None = None, base_ranks: Sequence[int | Sequence[int] | None] | None = None, comm: Any = None, geometry: str = 'cartesian', axis_nodes: Sequence[Any] | None = None)

A 1D or 2D nested patch hierarchy with mpiarray-backed fields.

The number of dimensions is that of base_shape: (nx,) cells for a line (a uniform 1D grid is a hierarchy of one level), (nx, ny) for a plane. Boxes, bounds, periodic and point coordinates then have one entry per axis, and everything below works the same way in both.

Patch coordinates are integer cell bounds on their own refinement level. A child patch’s bounds must align with the parent level and lie within the patches of that level. The refinement ratio is two by default. Fields are cell-centered, or node-centered (one value per cell corner, see allocate_field). periodic flags the axes on which the last cell neighbours the first; the node-centered solver (NodalPoisson) uses it. Without an MPI launcher, mpiarray supplies a serial communicator and the same interface works with a single process.

Under MPI every rank builds the same hierarchy, with the same calls in the same order. Each patch then lives on some of the ranks of comm and has a communicator of its own for them: a small patch on one rank, a large one on several, over which mpiarray splits its fields. placement says where a patch goes that is added without ranks: "all" puts it on every rank, "balanced" on the one rank that holds the fewest cells so far, "morton" or "hilbert" along that space-filling curve when regrid places the patches (curve_ranks: the patches of all levels in the order of the curve, cut into runs of about equal cells with the base level counted, one run per rank, so that neighbouring patches and the patches over them tend to share a rank; the Hilbert curve has no jumps, so its runs are more compact; a patch added by add_patch goes where "balanced" would put it), or a function placement(level, box) that returns the ranks (as ranks of add_patch takes them). With max_cells_per_rank, a "balanced" patch with more cells than that is split over as many of the least loaded ranks as it needs (at most all of them); a patch placed along a curve stays on one rank.

The domain is the rectangle of base_shape cells, or with base_boxes the union of those boxes of base cells: an L, a T, a rectangle with a notch. The boxes are the patches of level zero. Where the domain does not fill the rectangle, its edge is a boundary like the rectangle’s own faces.

geometry is "cartesian", a plane (x, y), or "cylindrical", the axisymmetric plane (r, z) of a body of revolution: the first axis is the radius (bounds[0][0] >= 0, not periodic), and a cell is a ring of volume 2 pi r dr dz (cell_volumes). integral, restrict and the conservative interpolation of regrid then weight cells by their volumes. Fields are per unit length along z in the Cartesian plane and totals over the ring in r–z; in 1D they are per unit area of the planes normal to x. The r–z plane is 2D only.

Numerics

levels

hL=h0rL,r≥2 on every axis and levelh_L = \frac{h_0}{r^L}, \qquad r \ge 2 \text{ on every axis and level}

nesting

loL≡hiL≡0(modr),[loLr,hiLr)⊂⋃patches of L−1box\mathrm{lo}_L \equiv \mathrm{hi}_L \equiv 0 \pmod r, \qquad \Big[\tfrac{\mathrm{lo}_L}{r}, \tfrac{\mathrm{hi}_L}{r}\Big) \subset \bigcup_{\text{patches of } L-1} \text{box}

ring volume

V=2πrc Δr Δz,rc=12(r0+r1)V = 2\pi r_c\,\Delta r\,\Delta z, \qquad r_c = \tfrac12 (r_0 + r_1)

radial face

Ar=2πrf ΔzA_r = 2\pi r_f\,\Delta z

axial face

Az=π(r12−r02)=2πrc ΔrA_z = \pi (r_1^2 - r_0^2) = 2\pi r_c\,\Delta r

plane

V=Δx Δy,A=Δy or Δx (2D);V=Δx,A=1 (1D)V = \Delta x\,\Delta y, \quad A = \Delta y \text{ or } \Delta x \ \text{(2D)}; \qquad V = \Delta x, \quad A = 1 \ \text{(1D)}

Assumptions:

  • one refinement ratio rr for all axes and levels; patch boxes half open, in cells of their level
  • proper nesting by a margin is not required by add_patch; regrid enforces it
  • in (r,z)(r, z): 2D, r0≥0r_0 \ge 0, the radius not periodic; the ring volumes and areas are exact, so the faces of a cell close it and fine faces add up to the coarse one

axis_nodesattributeinstance attribute#

axis_nodes: tuple[Any, ...] = tuple(graded)

base_shapeattributeinstance attribute#

base_shape = tuple((int(n) for n in base_shape))

boundsattributeinstance attribute#

bounds = tuple((tuple((float(x) for x in axis)) for axis in bounds_pairs))

commattributeinstance attribute#

comm = mpa.default_comm() if comm is None else comm

geometryattributeinstance attribute#

geometry = geometry

max_cells_per_rankattributeinstance attribute#

max_cells_per_rank = None if max_cells_per_rank is None else int(max_cells_per_rank)

periodicattributeinstance attribute#

periodic = tuple((bool(flag) for flag in periodic))

placementattributeinstance attribute#

placement = placement

refinement_ratioattributeinstance attribute#

refinement_ratio = int(refinement_ratio)

cells_on_rankproperty#

cells_on_rank: tuple[float, ...]

Cells of all patches held by every rank (a patch on several ranks is shared).

cylindricalproperty#

cylindrical: bool

Whether the hierarchy is the axisymmetric r–z plane.

field_namesproperty#

field_names: tuple[str, ...]

Names allocated throughout the hierarchy.

gradedproperty#

graded: bool

Whether an axis is graded (axis_nodes): its cells differ in size.

local_patchesproperty#

local_patches: tuple[Patch, ...]

The patches this rank holds a part of, ordered as patches.

lower_boundproperty#

lower_bound: tuple[float, ...]

Physical lower (lower-left) corner of the domain.

max_levelproperty#

max_level: int

Finest level currently present.

ndimproperty#

ndim: int

Number of dimensions: 1, 2 or 3.

on_axisproperty#

on_axis: bool

Whether a cylindrical domain reaches the axis (its radius starts at 0).

patchesproperty#

patches: tuple[Patch, ...]

All patches, ordered by level and then lower corner.

upper_boundproperty#

upper_bound: tuple[float, ...]

Physical upper (upper-right) corner of the domain.

accumulate_halosmethod#

def accumulate_halos(name: str) -> None

Bring deposited charge to the composite nodes: the scatter-add after deposit.

For a node-centered field, in two steps. First each patch adds the halos of its blocks into the neighbouring blocks (mpiarray’s accumulate_halos; at the edges of the patch they are dropped). Then the charge of every copy of a node goes to one: the node is held by every patch that has it as a corner, and by the two copies of a node on a periodic seam (the upper one, at the end of the axis, is the owner there); the owner copy is that of the finest patch that holds it, the one CompositeNodes.from_patches reads, and the last of the patches of that level in the order of patches. The other copies end up zero. So the total is kept, and from_patches returns what CompositeNodes.deposit gives for the same markers, to round-off.

This is the whole of the scatter-add of a bilinear deposit: a marker’s cell is in one patch, so its corners are nodes of that patch and no halo reaches over a coarse-fine edge. A deposit of a higher B-spline degree folds its stencil at the patch edges for the same reason, so it too leaves nothing in the dropped halos (but CompositeNodes.deposit has no such degree to compare with). (The charge on a hanging node is passed to its coarse neighbours by NodalPoisson.solve.) Cell-centered fields are not supported. Collective; the schedule is built at the first call and kept until a patch is added.

add_patchmethod#

def add_patch(level: int, box: Sequence[Sequence[int]], ranks: int | Sequence[int] | None = None) -> Patch

Add a non-overlapping, properly nested fine patch.

box is half-open and measured in cells at level. Bounds must align to the cells of the level below, and the patch must lie within the patches of that level (it may span several that touch).

ranks are the ranks of the hierarchy’s communicator that hold the patch: one rank or several, over which its fields are split. Without it, placement decides. Under MPI every rank adds the same patches in the same order.

allocate_fieldmethod#

def allocate_field(name: str, *, dtype: Any = float, halo: int = 1, split: Any = 0, centering: str = 'cell', conservative: bool = False) -> None

Allocate a named zero-filled field on every existing patch.

A patch’s arrays exist on the ranks that hold it. The default splits them over those ranks along the first axis (which then needs at least one cell per rank). Use split=None to replicate them instead. With centering="node" the values sit on the cell corners: a patch of (nx, ny) cells holds (nx + 1, ny + 1) of them, and patches that touch or nest share the nodes they have in common.

A conservative field is an amount per area, such as a density, whose integral (integral) regrid keeps: it is restricted before a regrid, and the cells of new patches are filled from the level below so that the fine cells of a coarse cell keep its mean. It must be cell-centered.

cell_sizesmethod#

def cell_sizes(level: int, axis: int, i: Any) -> Any

Physical sizes along axis of the cells of level with index i there.

cell_volumesmethod#

def cell_volumes(level: int, *index: Any) -> Any

Volumes of the cells of level with indices index (one array per axis).

The arrays broadcast against each other, as do the sizes. dx on a line (per unit area), dx * dy in the plane, dx dy dz in 3D; 2 pi r dr dz in r–z, with r the cell’s mid-radius (the exact volume of the ring). dx and the others are the physical sizes of the cells (cell_sizes), which differ along a graded axis.

centeringmethod#

def centering(name: str) -> str

"cell" or "node": where the values of field name sit.

depositmethod#

def deposit(*arguments: Any, name: str | None = None, reset: bool = True, splines: Any = 1, times: dict | None = None) -> None

Deposit the charge of markers on the node-centered field name, patch by patch.

deposit(x, charge, name) in 1D, deposit(x, y, charge, name) in 2D. Each marker spreads its charge over the corners of its cell (two in 1D, four in 2D), in the finest patch that holds it, with linear or bilinear (cloud-in-cell) weights: the same weights as CompositeNodes.deposit, whose transposed interpolation the field gather is, and of interpolate. With mpifield’s built-in splines the markers of all patches are deposited at once into a buffer of the blocks: the cloud-in-cell weights by one bincount, degrees 2 and 3 in one compiled call (scatter_blocks, with mpifield’s spline_cell); another shape runs its own kernels patch by patch. The values are charges, not a density. The markers must be on the ranks that owner gives (use migrate), so that the corners fall in the block or its halo, and the field needs a halo of at least one node. The corners in the halo, and the nodes that several patches share, are not yet where the composite mesh wants them: follow with accumulate_halos. With reset the field is zeroed first, halos included. Collective (the check of the owners).

splines is the B-spline degree of the shape (1, the cloud-in-cell weights above, 2 or 3), or an mpifield.Splines: the marker spreads its charge over (p + 1) nodes per axis, and the field needs a halo of at least mpifield.splines(p).halo nodes (2 from degree 2 on). Where the stencil would reach past the edge of the marker’s patch it folds onto the patch’s edge nodes, so the total is kept; such charge stays on the patch.

times, a dict, collects the seconds spent on the markers of every patch, added to the value of its (level, box): costs measured on this rank, for regrid and rebalance (sum them over the ranks first).

Numerics

cloud in cell

q00=q(1−ξ)(1−η),q10=q ξ(1−η),q01=q(1−ξ) η,q11=q ξη,ξ=x−xihx, η=y−yjhyq_{00} = q(1-\xi)(1-\eta), \quad q_{10} = q\,\xi(1-\eta), \quad q_{01} = q(1-\xi)\,\eta, \quad q_{11} = q\,\xi\eta, \qquad \xi = \frac{x - x_i}{h_x}, \ \eta = \frac{y - y_j}{h_y}

line

q0=q(1−ξ),q1=q ξq_0 = q(1-\xi), \qquad q_1 = q\,\xi

splines

qk=q∏dBp(rd−kd),rd=xd−xd,0hd(degree p; p=1 above)q_{\mathbf k} = q \prod_d B_p(r_d - k_d), \qquad r_d = \frac{x_d - x_{d,0}}{h_d} \quad (\text{degree } p; \ p = 1 \text{ above})

gather

E(x)=∑corners cwc(x) Ec(the transpose: interpolate)E(\mathbf{x}) = \sum_{\text{corners } c} w_c(\mathbf{x})\,E_c \quad (\text{the transpose: } \texttt{interpolate})

Assumptions:

  • each marker in the finest patch that holds it; the values are charges, not a density
  • a marker gathers the field of its own patch, which may jump at a coarse-fine edge
  • the halos and the copies of shared nodes are summed afterwards (accumulate_halos)
  • from degree 2 on a stencil folds onto the edge nodes of the marker’s patch where it would reach past them (at coarse-fine edges, walls and periodic seams alike): the charge is kept, the shape there is not the spline’s

Built from:

  • patchwork.mesh.accumulate.Accumulation
  • mpifield.splines.Splines

exchange_halosmethod#

def exchange_halos(name: str, *, level: int | None = None, below: str | None = None) -> None

Fill the halo of every patch of field name from the rest of the hierarchy.

From the patches of the same level the halo overlaps (across periodic faces too), else by bilinear interpolation of the level below, and between the ranks of each patch. Halo points outside the domain are left for the boundary conditions. Collective over comm; the schedule is built at the first call and kept until a patch is added. See HaloExchange.

With level, only the halos of the patches of that level are filled. With below, the values interpolated from the level below are those of field below (of the same centering) instead: for a level that takes several time steps for one of the level below (subcycling), a field that holds the level below at the time in between.

face_areasmethod#

def face_areas(level: int, axis: int, *index: Any) -> Any

Areas of the faces of level normal to axis, one index array per axis.

Along axis the index numbers the faces (face i is the lower face of cell i), along the others the cells the faces belong to; the arrays broadcast. 1 on a line (per unit area), the product of the other cell sizes in the plane (per unit length out of it) and in 3D; in r–z, 2 pi r dz for a radial face at r and 2 pi r dr for an axial face of a cell of mid-radius r, so that the faces of a cell close it (cell_volumes) and the faces of the fine cells over a coarse face add up to it.

gathermethod#

def gather(patch: Patch, name: str, root: int | None = None) -> Any

The whole of field name of patch as a NumPy array.

Collective over the hierarchy’s communicator: every rank calls it, whether it holds the patch or not. The array is returned on every rank, or with root on that rank only (None on the others).

integralmethod#

def integral(name: str) -> float

The integral of field name over the domain, from the finest values.

Cell-centered: the sum of value times area (in r–z: times volume, cell_volumes) over the cells that no finer patch covers. Node-centered: the trapezoidal rule over those cells (Cartesian only). Collective over comm; the same value on every rank.

interpolatemethod#

def interpolate(*arguments: Any, name: str | None = None, splines: Any = 1, times: dict | None = None) -> Any

Interpolate the node-centered field name at markers, each in its own patch.

interpolate(x, name) in 1D, interpolate(x, y, name) in 2D. Each marker reads the corners of its cell in the finest patch that holds it, with the linear or bilinear weights of deposit, of which this is the transpose: for a field computed patch by patch, such as an electric field that jumps at a coarse-fine edge, every marker sees the field of its own patch. The markers must be on the ranks that owner gives (use migrate) and the halos filled (exchange_halos), since a cell’s upper corners may be in the halo. A marker outside the domain gets zero. Returns an array of the shape of x. Collective (the check of the owners).

splines is the B-spline degree of the weights (1, 2 or 3) or an mpifield.Splines, as for deposit, whose transpose this is for the same degree, the fold at the patch edges included.

times collects the seconds spent per patch, as in deposit.

level_shapemethod#

def level_shape(level: int) -> tuple[int, ...]

Number of cells in the full domain at a refinement level.

locatemethod#

def locate(*coordinates: Any) -> Any

The finest patch that holds each point: its index in patches.

locate(x) in 1D, locate(x, y) in 2D, locate(x, y, z) in 3D: arrays of the same shape (physical coordinates); the result has that shape and is -1 for a point outside the domain, such as one in the notch of an L. Cells are half open, so a point on the edge between two patches belongs to the one that starts there; the upper faces of the domain, though, belong to the last cell. On a periodic axis a point outside the domain is wrapped back into it first. Local to every rank (every rank holds the whole hierarchy); no communication.

logical_pointsmethod#

def logical_points(coordinates: Sequence[Any]) -> tuple[Any, ...]

The logical coordinates of points given by one physical array per axis.

migratemethod#

def migrate(*points_and_arrays: Any, name: str, outside: str = 'error') -> tuple[Any, ...]

Send markers to the ranks that hold their patches; returns what this rank gets.

migrate(x, *arrays, name=...) in 1D, migrate(x, y, *arrays, name=...) in 2D: the positions of this rank’s markers (1D arrays) and any other per-marker data, with one row per marker (velocities as v.T if they are stored (3, n)). Each marker goes to owner of field name, with mpiarray.migrate. Returns the positions and arrays of the markers now on this rank, as given: those that stayed and those that arrived, ordered by the rank they came from. Call it again on the hierarchy regrid returns to move the markers whose patch changed ranks.

A marker outside the domain raises ValueError on every rank with outside="error", or is dropped with outside="drop". Collective.

node_gridmethod#

def node_grid(patch: Patch) -> Any

The nodes of patch as an mpifield.BlockGrid: all of them, no halo.

The grid is in logical coordinates (to_logical): on a graded axis a kernel takes the markers’ logical positions, and a gradient it computes is per unit of the logical coordinate (multiply by its derivative, cell_sizes).

For compiled kernels that run on a patch’s node array, such as a push that gathers each marker’s field in its own patch. No axis is periodic: a patch holds every node, both images of a periodic seam too.

node_positionsmethod#

def node_positions(level: int, axis: int) -> Any

Physical positions of the nodes of level along axis: n + 1 values.

n is the number of cells of the level along the axis. On a uniform axis x_0 + i h; on a graded axis (axis_nodes) the base nodes, and between them the nodes of finer levels evenly spaced (the map from the logical to the physical coordinate is linear in every base cell). Kept per level and axis.

ownermethod#

def owner(*points: Any, name: str | None = None) -> Any

The rank that should hold each marker: -1 outside the domain.

owner(x, name) in 1D, owner(x, y, name) in 2D. A marker belongs to the rank that holds the block of field name in which the lower (left) corner of its cell lies, in the finest patch that holds it (see locate). That block is the one deposit writes into: the other corners of the cell are in its halo, which accumulate_halos hands on. The same for a cell-centered and a node-centered field, since cell (i, j) starts at node (i, j). Collective the first time for a field (until a patch is added), as the ranks tell each other their blocks; the same result on every rank for the same points.

patches_at_levelmethod#

def patches_at_level(level: int) -> tuple[Patch, ...]

Patches on one level.

physical_pointsmethod#

def physical_points(coordinates: Sequence[Any]) -> tuple[Any, ...]

The physical coordinates of points given by one logical array per axis.

rebalancemethod#

def rebalance(cost: Mapping[Any, Any] | None = None, *, placement: str = 'morton', fill_halos: bool = False) -> AMRHierarchy

The same patches placed again by cost; fields moved.

Every refined patch goes to a rank along a space-filling curve (placement "morton" or "hilbert", curve_ranks) or by the greedy knapsack ("balanced", knapsack_ranks), weighed by its cells plus the cost of its leaf cells, or by measured costs per patch, 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 the same way. Collective over comm.

regridmethod#

def regrid(tags: Mapping[int, Any], *, method: str = 'cluster', block_size: int = 16, efficiency: float = 0.7, buffer: int = 1, nesting: int = 1, max_patch_size: int | None = None, min_patch_size: int = 1, forbid: Any = None, placement: str | Callable[[int, IndexBox], Any] | None = None, cost: Mapping[Any, Any] | None = None, fill_halos: bool = False, fields: Sequence[str] | None = None) -> AMRHierarchy

A new hierarchy with patches over the tagged cells, and the fields moved to it.

tags maps a level to booleans of that level’s shape (level_shape): the cells that need the next finer level. Make them with gradient_tags, function_tags or by hand; each rank may tag 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. 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 stays as it is. The levels above the last tagged one are dropped.

Every field is moved: a point takes the value of an old patch of the same level that has it, else the bilinear interpolation of the new level below. A conservative field (see allocate_field) is first restricted on this hierarchy, and its new cells are filled so that the fine cells of a coarse cell keep its mean: its integral is the same before and after. Halos are not filled unless fill_halos (then exchange_halos runs for every field of the new hierarchy). fields names the fields whose values are moved (default: all); the others are allocated on the new hierarchy and zero, which saves the transfer of a field that is computed again right after the regrid, such as a charge deposited from the markers or a potential solved for.

min_patch_size is the shortest side a patch may have, in cells of its own level (rounded up to whole cells of the level below): a patch that would be narrower is widened where there is room, so that no patch is one cell wide. forbid keeps patches off places a code cannot handle, such as a periodic seam: a mapping from a level (1 and up) to booleans of that level’s shape (level_shape), true where no patch of that level may cover a cell, or a function of the cell centres (x, y) of a level that returns such booleans and is used for every refined level. Tags that would need a forbidden cell 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 with "balanced", or along a space-filling curve with "morton" or "hilbert". With these three, cost weighs the patches by more than their cells (box_costs): 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, or a mapping from a patch (level, box) to a measured cost (deposit(..., times=...)). "balanced" with a cost is the greedy knapsack (knapsack_ranks): the most even, without locality. Collective over comm; this hierarchy is left as it is, except for the restriction of conservative fields.

Numerics

grow

T~L=growb(TL∪coarsenr(growm(T~L+1)))∩ΩL,L=Lmax,…,0\tilde T_L = \mathrm{grow}_{b}\Big(T_L \cup \mathrm{coarsen}_r\big(\mathrm{grow}_{m}(\tilde T_{L+1})\big)\Big) \cap \Omega_L, \qquad L = L_\mathrm{max}, \dots, 0

allowed

AL=shrinkm(⋃new boxes of L)∖{cells with forbidden fine cells}\mathcal{A}_L = \mathrm{shrink}_{m}\big(\textstyle\bigcup \text{new boxes of } L\big) \setminus \{\text{cells with forbidden fine cells}\}

boxes

BL+1=r⋅cluster(T~L∩AL)B_{L+1} = r \cdot \mathrm{cluster}\big(\tilde T_L \cap \mathcal{A}_L\big)

transfer

unew={uoldon an old patch of the levelI(uL−1new)elseu^\mathrm{new} = \begin{cases} u^\mathrm{old} & \text{on an old patch of the level} \\ \mathcal{I}(u^\mathrm{new}_{L-1}) & \text{else} \end{cases}

Assumptions:

  • bb = buffer, mm = nesting (cells of the level below; the domain’s edge does not count as an edge)
  • I\mathcal{I} the bilinear (renormalised) interpolation, or for a conservative field the conservative fill after a restriction
  • the base level is kept; levels above the last tagged one are dropped
  • halos stay zero unless fill_halos

References:

Built from:

  • patchwork.mesh.regrid.cluster
  • patchwork.mesh.halos.conservative_from_below

restrictmethod#

def restrict(name: str, *, level: int | None = None) -> None

Give the points of field name under finer patches the fine values.

The mean of the fine cells (cell-centered) or the coinciding fine node (node-centered), finest level first. With level, only the points of that level under the next finer one (a level that has caught up with the finer ones when they subcycle). Collective over comm; call exchange_halos after it for the halos. See Restriction.

spacingmethod#

def spacing(level: int = 0) -> tuple[float, ...]

Cell spacing at a refinement level, per axis.

to_logicalmethod#

def to_logical(axis: int, physical: Any) -> Any

The logical coordinate along axis of a physical one: to_physical inverted.

physical is returned as given on a uniform axis. On a graded axis the base cell is found by bisection of the sorted base nodes; beyond the domain as to_physical.

to_physicalmethod#

def to_physical(axis: int, logical: Any) -> Any

The physical coordinate along axis of a logical one (arrays of any shape).

The logical coordinate is the uniform one that patches, levels and the kernels use: x_0 + i h at node i of a level; both share the bounds. On a uniform axis the two are the same and logical is returned as given; on a graded axis the map is linear between the base nodes and continuous. Beyond the domain it continues the end cells, or on a periodic axis maps a point whole periods beyond it to the point as many periods beyond.

wrapmethod#

def wrap(points: Any) -> None

Move points (ndim, k) beyond a periodic face back into the domain, in place.

Only the points outside the domain along a periodic axis are touched.

wrappedmethod#

def wrapped(points: Any) -> Any

points (ndim, k) moved into the domain along its periodic axes.

The array itself if no point is beyond a periodic face, else a wrapped copy (see wrap).

FluxRegisterclass#

class FluxRegister(hierarchy: AMRHierarchy, cells: CompositeCells | None = None)

Matches the fluxes of coarse and fine levels at their interfaces (refluxing).

Built for one hierarchy (after a regrid, build one for the new hierarchy, with no step under way). One register serves any number of fields: it keeps what it records per field name. See the module docstring.

The coarse–fine faces are the faces between two leaf cells of different levels (CompositeCells): a level need not be properly nested in the one below, and periodic axes and domains that are not rectangles are covered. Under MPI the coarse and fine cells of a face may be on different ranks: reflux sums the records over the hierarchy’s communicator (one allreduce of a value per coarse face).

Attributes

NameDescription
hierarchyThe patch hierarchy.
num_facesThe number of coarse faces on the edges of finer levels.

Numerics

balance

Vi uin+1−uinΔt=−∑f∈∂iAf Ff nf,i,nf,i=±1V_i\,\frac{u_i^{n+1} - u_i^n}{\Delta t} = -\sum_{f\in\partial i} A_f\,F_f\,n_{f,i}, \qquad n_{f,i} = \pm 1

register

δf=∑fine steps∑fine facess AF−s AcFc,s=Δt (default)\delta_f = \sum_{\text{fine steps}} \sum_{\text{fine faces}} s\,A F - s\,A_c F_c, \qquad s = \Delta t \text{ (default)}

reflux

uc+=∓δfVc(− for the face above the cell, + below), then restrictu_c \mathrel{+}= \mp\frac{\delta_f}{V_c} \quad (- \text{ for the face above the cell, } + \text{ below}), \text{ then restrict}

Assumptions:

  • the fluxes are the caller’s: flux densities along the axis, per block, from its own cells and halo
  • coarse-fine faces are those between leaf cells of different levels: proper nesting is not needed
  • the integral then changes only through the domain’s faces, to round-off, in the plane and in (r,z)(r, z)
  • subcycling: a finer level takes rr steps of Δt/r\Delta t / r, then reflux(level=); scale =Δt/2= \Delta t / 2 per stage of Heun

References:

Built from:

  • patchwork.mesh.halos.Restriction

hierarchyattributeinstance attribute#

hierarchy = hierarchy

num_facesattributeinstance attribute#

num_faces = int(unique.size)

refluxmethod#

def reflux(name: str, *, level: int | None = None) -> None

Correct the coarse cells next to finer levels, and restrict onto them.

Each coarse leaf cell on the edge of a finer level takes, for each of its faces there, the recorded sum of the fine fluxes instead of its own flux (divided by its volume), and the records of those faces are cleared. Then the cells under the finer patches take the mean of their fine cells. With level, for the coarse cells of that level only (when the finer levels have caught up with it), and the restriction onto that level only. Collective over the hierarchy’s communicator.

resetmethod#

def reset(name: str | None = None) -> None

Clear the records of field name (of every field without it).

updatemethod#

def update(name: str, fluxes: Fluxes, dt: float, *, level: int | None = None, scale: float | None = None) -> None

Advance field name by the divergence of face fluxes, and record them.

For every patch this rank holds (of level only, if given), the cells of its block take u -= dt / V * sum(A F n) with the flux densities fluxes(patch) (see Fluxes). The fluxes through coarse–fine faces are recorded times scale (default dt) for reflux. A multi-stage method records each stage with its weight: the two stages of Heun’s method (SSP-RK2) with scale=dt / 2.

Local to this rank: no communication. The fluxes of a face that two patches of the same level, or two ranks of one patch, share must agree (as they do when computed alike from the values the halos give).

Patchclassdataclass#

class Patch(level: int, box: IndexBox, ranks: tuple[int, ...] = (0), comm: Any = field(default=None, repr=False, compare=False), _fields: dict[str, DistributedArray] = field(default_factory=dict, repr=False))

One rectangular patch; its box uses level-local, half-open cell indices.

A patch lives on some of the ranks of its hierarchy: ranks, the same on every rank. On those ranks comm is the patch’s own communicator, over which mpiarray splits its fields; on the others it is None and the patch holds no data (is_local is false).

boxattributeinstance attribute#

box: IndexBox

commattributeclass attributeinstance attribute#

comm: Any = field(default=None, repr=False, compare=False)

levelattributeinstance attribute#

level: int

ranksattributeclass attributeinstance attribute#

ranks: tuple[int, ...] = (0)

field_namesproperty#

field_names: tuple[str, ...]

Names of allocated fields on this patch.

is_localproperty#

is_local: bool

Whether this rank holds a part of the patch.

node_shapeproperty#

node_shape: tuple[int, ...]

Number of nodes (cell corners) along each axis: one more than cells.

shapeproperty#

shape: tuple[int, ...]

Number of cells along each axis.

fieldmethod#

def field(name: str) -> DistributedArray

Get an allocated field by name, on a rank that holds the patch.

local_cell_centersmethod#

def local_cell_centers(hierarchy: AMRHierarchy, name: str | None = None) -> tuple[Any, ...]

Coordinates of this rank’s cells of the cell-centered field name.

One array per axis of the shape of field(name).local, for filling it. Without name, of the first cell-centered field allocated.

local_node_coordinatesmethod#

def local_node_coordinates(hierarchy: AMRHierarchy, name: str) -> tuple[Any, ...]

Coordinates of this rank’s nodes of the node-centered field name.

One array per axis (x, or x and y) of the shape of field(name).local, for filling it.

node_coordinatesmethod#

def node_coordinates(hierarchy: AMRHierarchy) -> tuple[Any, ...]

Coordinates of the nodes of the whole patch along each axis (1D arrays).

physical_boundsmethod#

def physical_bounds(hierarchy: AMRHierarchy) -> PhysicalBounds

Physical interval (1D) or rectangle (2D) occupied by this patch.

box_costsfunction#

def box_costs(hierarchy: AMRHierarchy, boxes: Mapping[int, Sequence[IndexBox]], cost: Mapping[Any, Any]) -> tuple[dict[int, list[float]], list[float]]

The cost of each new box and of each rank’s base patches.

cost is one of two things:

  • a mapping from 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 box costs its cells plus the cost of its leaf cells, the cells no finer box covers, since that is where their markers deposit and gather;
  • a mapping from a patch, (level, box), to its cost, e.g. the seconds measured with deposit(..., times=...) and interpolate(..., times=...): a box costs its own value, and a box without one the mean cost per cell of those that have one.

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 curve_ranks and knapsack_ranks.

clusterfunction#

def cluster(tags: np.ndarray, efficiency: float = 0.7, max_size: int | None = None, allowed: np.ndarray | None = None, min_size: int = 1) -> list[IndexBox]

Cover the tagged cells with boxes (the Berger-Rigoutsos algorithm).

A box is kept when at least efficiency of its cells are tagged, it holds no cell that allowed forbids, and it is at most max_size cells long on each axis. Otherwise it is cut: at a gap in the tagged cells (a row, column or plane without tags; a cell in 1D), else where the number of tagged cells per row or column bends most (a zero crossing of its second difference), else in the middle of its longest side. Each part shrinks to the tagged cells in it. In 1D the boxes are intervals, in 3D boxes.

Parameters

NameTypeDefaultDescription
tagsnp.ndarrayrequiredBooleans, one per cell: a 1D, 2D or 3D array.
efficiencyfloat0.7The smallest fraction of tagged cells in a box, in (0, 1].
max_sizeint | NoneNoneThe longest side of a box, in cells; default: no limit.
allowednp.ndarray | NoneNoneBooleans of the shape of tags: where boxes may go. Tagged cells that are not allowed are dropped.
min_sizeint1The shortest side a box should have, in cells. A shorter box is widened, one row or column at a time, into cells that are allowed and that no other box has, as far as there is room: it stays shorter where there is none (the shape of tags or the allowed region is narrower).

Returns

list[IndexBox]
Half-open boxes ((i0, i1),), ((i0, i1), (j0, j1)) or
list[IndexBox]
((i0, i1), (j0, j1), (k0, k1)) that do not overlap and cover every
list[IndexBox]
allowed tagged cell.

Numerics

efficiency

keep B  ⟺  #{tagged cells in B}∣B∣≥efficiency and B⊂A,chopped into ⌈n/max_size⌉ parts per axis\text{keep } B \iff \frac{\#\{\text{tagged cells in } B\}}{|B|} \ge \texttt{efficiency} \text{ and } B \subset \mathcal{A}, \quad \text{chopped into } \lceil n / \texttt{max\_size} \rceil \text{ parts per axis}

signature

Σk=#{tagged cells in row (or column) k}\Sigma_k = \#\{\text{tagged cells in row (or column) } k\}

inflection

Δk2=Σk+2−2Σk+1+Σk,cut at k+2 where ∣Δk+12−Δk2∣ is largest among sign changes\Delta^2_k = \Sigma_{k+2} - 2\Sigma_{k+1} + \Sigma_k, \qquad \text{cut at } k + 2 \text{ where } |\Delta^2_{k+1} - \Delta^2_k| \text{ is largest among sign changes}

Assumptions:

  • cut at an empty row or column nearest the middle, else at the strongest inflection (sides of at least 4 cells), else in the middle of the longest side
  • every part shrinks to its tagged cells; boxes shorter than min_size are widened into free allowed cells
  • the boxes are disjoint and cover every allowed tagged cell

References:

curve_ranksfunction#

def curve_ranks(boxes: Mapping[int, Sequence[IndexBox]], size: int, *, curve: str = 'morton', 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 space-filling curve, cut into size runs.

boxes maps a level to its boxes. Every box gets the key of its lower corner, in cells of the finest level, on the curve: "morton" (the Z-order curve) or "hilbert" (without the Z’s jumps, so that the run of a rank is more compact). Boxes close in space are close on the curve whatever their level, and a box comes before the finer boxes at the same corner. Walking the curve, a rank takes boxes until its cost, with the load it already has (the cells of the base level, say), reaches an equal share of all costs; then the next rank goes on. The cost of a box is its cells, or weights (per level, one per box, in the units of load; see box_costs). Returns, per level, the ranks in the order of boxes[level].

Numerics

morton

k(B)=∑b∑d=0D−1bitb(rL−ℓ id) 2bD+d(the lower corner i of B on level ℓ, in cells of the finest level L)k(B) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b\big(r^{L - \ell}\, i_d\big)\, 2^{bD + d} \quad \text{(the lower corner } \mathbf i \text{ of } B \text{ on level } \ell\text{, in cells of the finest level } L\text{)}

hilbert

k(B)=H(rL−ℓ i),H the Hilbert index (Skilling’s construction): consecutive keys are neighbouring cellsk(B) = H\big(r^{L - \ell}\, \mathbf i\big), \quad H \text{ the Hilbert index (Skilling's construction): consecutive keys are neighbouring cells}

ranks

along the curve, rank q takes boxes while wq+cB/2≤T,T=1R(∑qwq0+∑BcB)\text{along the curve, rank } q \text{ takes boxes while } w_q + c_B/2 \le T, \quad T = \frac{1}{R}\Big(\sum_q w_q^{0} + \sum_B c_B\Big)

Assumptions:

  • the patches of all refined levels on one curve, a coarse patch before the finer ones at the same corner, so that a patch and the patches over it tend to share a rank
  • the cost cBc_B of a box is its cells, or its weight (box_costs); the load a rank already has (the base level) counts
  • a patch stays on one rank

References:

function_tagsfunction#

def function_tags(hierarchy: AMRHierarchy, function: Callable[..., Any], levels: int) -> dict[int, np.ndarray]

Tag the cells of levels 0 .. levels - 1 where function is true.

function(x) in 1D, function(x, y) in 2D, gets the coordinates of the cell centres of a whole level and returns booleans; cells outside the domain are never tagged. The tags of level k ask for patches on level k + 1, so levels is the number of refined levels wanted.

graded_nodesfunction#

def graded_nodes(lower: float, upper: float, spacing: Callable[[np.ndarray], Any] | Sequence[Sequence[float]], *, cells: int | None = None, through: Sequence[float] = ()) -> np.ndarray

The nodes of [lower, upper] whose cells follow the size spacing.

spacing is the local cell size [m]: a vectorised function of x, or a sequence of (x, dx) pairs, linear between them and constant beyond. The number of cells is the integral of 1 / dx over the interval, rounded (at least one), or cells if given (the sizes are then scaled to fit). The nodes are those where that integral reaches whole cells, so two neighbouring cells differ by about the change of dx over a cell. The first and last node are lower and upper; the result is the axis_nodes entry of an AMRHierarchy with that many base cells.

through are positions that must be nodes, such as the faces of electrodes or the edges of apertures, so that the surfaces fall on the mesh instead of cutting cells: every stretch between two of them (and the ends) is graded on its own, with at least one cell. Not with cells.

Numerics

count

s(x)=∫x0xdξΔx(ξ),N=max⁡(1,round⁡s(x1))s(x) = \int_{x_0}^{x} \frac{d\xi}{\Delta x(\xi)}, \qquad N = \max\big(1, \operatorname{round} s(x_1)\big)

nodes

s(xi)=iN s(x1),i=0,…,Ns(x_i) = \frac{i}{N}\, s(x_1), \qquad i = 0, \dots, N

Assumptions:

  • Δx>0\Delta x > 0; between the given (x,Δx)(x, \Delta x) pairs linear, beyond them constant
  • ss integrated by the trapezoidal rule on a fine sampling and inverted linearly; the cells follow Δx\Delta x to a factor s(x1)/Ns(x_1) / N, and two neighbours differ by about Δx′\Delta x'
  • with nodes required at given positions, every stretch between them on its own

gradient_tagsfunction#

def gradient_tags(hierarchy: AMRHierarchy, name: str, threshold: float) -> dict[int, np.ndarray]

Tag the cells across which field name changes by more than threshold.

Cell-centered: a cell is tagged where its value differs by more than threshold from one of its neighbours (two in 1D, four in 2D). Node-centered: where the values at its corners span more than threshold. The change is per cell of each level, so a finer level, with smaller cells, sees a smaller change: tagging stops once the cells resolve the field.

Every existing level is tagged, from the data each rank holds, comparing only points of the same patch: where a patch is split over ranks, the halos between its blocks are filled first (update_halos, collective over the patch’s ranks). The tags are combined over the ranks by AMRHierarchy.regrid.

Numerics

cells

tag i  ⟺  max⁡j∈N(i)∣ui−uj∣>τ(two neighbours in 1D, four in 2D)\text{tag } i \iff \max_{j \in N(i)} |u_i - u_j| > \tau \quad \text{(two neighbours in 1D, four in 2D)}

nodes

tag K  ⟺  max⁡p∈Kϕp−min⁡p∈Kϕp>τ\text{tag } K \iff \max_{p \in K} \phi_p - \min_{p \in K} \phi_p > \tau

Assumptions:

  • the change per cell of each level: tagging stops once the cells resolve the field
  • only points of one patch are compared; the tags are combined over the ranks by regrid

knapsack_ranksfunction#

def knapsack_ranks(boxes: Mapping[int, Sequence[IndexBox]], size: int, *, load: Sequence[float] | None = None, weights: Mapping[int, Sequence[float]] | None = None) -> dict[int, list[int]]

The rank of each box: the largest cost first, each to the rank with the least so far.

The greedy solution of cutting the boxes into size sets of equal cost, what placement="balanced" does with cells, here with the weights of box_costs and the load the ranks already have. Balances better than a curve, but neighbouring boxes may land on different ranks. Returns, per level, the ranks in the order of boxes[level].

Numerics

greedy

cB1≥cB2≥…,r(Bk)=arg⁡min⁡qwq (the lowest such rank),wr(Bk)+=cBkc_{B_1} \ge c_{B_2} \ge \dots, \qquad r(B_k) = \arg\min_q w_q \text{ (the lowest such rank)}, \quad w_{r(B_k)} \mathrel{+}= c_{B_k}

Assumptions:

  • the greedy (longest processing time first) solution of the knapsack-like partition: the largest cost at most 4/3 of the best possible
  • no locality: neighbouring patches may land on any ranks

References:

marker_countsfunction#

def marker_counts(hierarchy: AMRHierarchy, *coordinates: Any, levels: int) -> dict[int, np.ndarray]

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.

marker_tagsfunction#

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.

plot_patchesfunction#

def plot_patches(hierarchy: AMRHierarchy, *, field: str | None = None, show_grid: bool = True, ax: Any = None, cmap: str = 'viridis', root: int = 0, grid_linewidth: float | None = None, grid_alpha: float | None = None, transpose: bool = False, scale: float = 1.0, mask_covered: bool = True, colors: Sequence[Any] | None = None, labels: Sequence[str | None] | None = None, title: str | None = None) -> tuple[Any, Any] | None

Plot patch extents and cell grids, optionally colored by a field.

With show_grid=False and no field only the patch outlines are drawn, e.g. over an image that is already on ax. grid_linewidth and grid_alpha set the cell lines of every level; by default they are thin and faint, more so on the base level, which suits a large figure. A small one, e.g. an animation’s frames, may need stronger lines.

transpose draws the hierarchy’s second axis horizontally (e.g. x of an (r, x) cylindrical hierarchy), scale multiplies the coordinates (1e3 for millimetres from metres). Without field, the cells of a coarser level under a finer patch are hidden; mask_covered=False keeps them, so every level’s grid shows in full. colors and labels give each level its colour and legend entry (None leaves a level out of the legend; by default tab10 and “level n”; the entries are the labels of the plotted artists, so a later ax.legend() keeps them), title the axes’ title ("" for none).

A 1D hierarchy is drawn as a line plot: without field one bar per patch at the height of its level (with its cell edges if show_grid); with field the values of every patch against x, the finer patches on top and shaded over their extent.

When field is provided, each patch field is gathered collectively and plotted on root only. Call this function on every rank in the patch communicator. Layout-only plots are also returned on root only. Matplotlib is imported only when this function is called.

Returns (figure, axes) on the plotting rank and None elsewhere.

quadtree_boxesfunction#

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.

Numerics

blocks

Bmk=∏d[ mdb, (md+1)b ) (cells of level k),refined  ⟺  Bmk holds a tag of level k−1B^{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

Bm′k+1⊂Bmk  ⟺  ⌊m′/r⌋=m(2d children for r=2)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: