Algorithm Search⌘K

Algorithmadvanced

Berger-Colella adaptive mesh refinement

Also called Berger-Oliger AMR, block-structured AMR.

Covers regions that need resolution by nested finer grid patches, subcycled in time, with flux corrections at coarse-fine boundaries to keep conservation.

Time
Θ(W) worst
Space
Θ(M) extra
Where
M = the number of cells on all levels; W = the cell updates in one coarse step, the sum over levels l of r^l times the number of cells on level l
Properties
adaptiveconservativedeterministicexplicitsubcycling
Origin
M. J. Berger, J. Oliger, P. Colella, 1989

Berger-Colella adaptive mesh refinement (AMR) is a way to run an explicit finite volume scheme for a conservation law on a hierarchy of grids. Level 0 covers the domain. Each finer level l+1l + 1 is a union of rectangular patches, each with cells rr times smaller than those of level ll, placed only where an error indicator is large, such as near shocks and fronts. Each level takes rr time steps of size Δtl/r\Delta t_l/r for each step of the level below, so every level runs at the same Courant number. At a face between a coarse cell and a fine patch, the coarse scheme and the fine scheme compute different fluxes. A flux register stores both, and after the fine steps a refluxing step corrects the coarse cell next to the patch, so the composite scheme conserves mass, momentum and energy exactly. Berger and Oliger (1984) introduced the hierarchy and the subcycling. Berger and Colella (1989) added the refluxing and the proper nesting that make it a conservative shock-capturing method. Libraries such as Chombo, AMReX and SAMRAI use this design.

In plain words

A fine grid everywhere is expensive, and a shock or a flame front usually takes only a small part of the domain. So the method puts small fine grids on top of a coarse one, only where the solution has sharp features, and it moves them with those features. A fine grid takes several small time steps while the coarse grid takes one large step. Where a fine grid meets the coarse grid, the two grids calculate a different amount of material that crosses their common edge. The method records both amounts and, after the fine steps, corrects the coarse cell next to the edge, so that no material is created or lost.

The problem

Solve a hyperbolic conservation law ut+f(u)x=0u_t + f(u)_x = 0 with a conservative explicit scheme ui←ui−ΔtΔx(Fi+1/2−Fi−1/2)u_i \leftarrow u_i - \frac{\Delta t}{\Delta x}(F_{i+1/2} - F_{i-1/2}) to a given accuracy, with far fewer cells than a uniform grid at the finest resolution. The composite solution must be conservative: on a periodic domain the sum of u Δxu\,\Delta x over the finest cells that cover each point must stay constant. The Lax-Wendroff theorem needs conservation to get correct shock speeds.

The algorithm

The hierarchy has levels 0,…,L0, \dots, L with Δxl=Δx0/rl\Delta x_l = \Delta x_0/r^l and Δtl=Δt0/rl\Delta t_l = \Delta t_0/r^l. A patch of level l+1l + 1 covers whole cells of level ll. A cell of level ll under a patch of level l+1l + 1 is covered. Proper nesting means that every patch of level l+1l + 1 is inside level ll with at least one level-ll cell between them. One coarse step is ADVANCE(0,0)\text{ADVANCE}(0, 0):

  1. ADVANCE(l, θ)
  2. 1fill the ghost cells of each level-l patch from a level-l patch, else from level l-1 at (1-θ) old + θ new
  3. 2for each level-l patch do save u as old; compute the fluxes F; u_i ← u_i - (Δt_l/Δx_l)(F_(i+1/2) - F_(i-1/2))
  4. 3if l > 0 then add Δt_l F at the two ends of each patch to the fine flux register R
  5. 4if l < L then keep C ← Δt_l F at the faces where level-(l+1) patches start or end
  6. 5for k ← 0 to r-1 do ADVANCE(l+1, k/r)
  7. 6at each such face correct the uncovered level-l cell next to it by ∓(R - C)/Δx_l
  8. 7replace each covered level-l cell by the mean of its r fine cells
  9. REGRID (every K coarse steps)
  10. 8for l ← 0 to L-1 do tag level-l cells with large |Δu|, add a buffer, keep only properly nested cells
  11. 9make level-(l+1) patches from runs of tagged cells; fill them from old level-(l+1) data, else from level l

The sign in L6 is minus for the cell to the left of a patch and plus for the cell to the right. L7 is called average down. After L7 the covered cells hold the fine averages, so level 0 alone gives the composite total.

Example

One face by hand. Take ut+ux=0u_t + u_x = 0 on [0,1)[0, 1), periodic, with 8 coarse cells, r=2r = 2, Δt0=116\Delta t_0 = \tfrac1{16} (Courant number 12\tfrac12 on both levels), and u=1u = 1 for x<916x < \tfrac9{16}, else 00, sampled at cell centres. Tagging the cells next to jumps (with no buffer) gives the patches over coarse cells 3 and 4 and over coarse cells 7 and 0. The fine values over coarse cells 3 and 4 are 1,1,1,01, 1, 1, 0. Coarse cell 4 holds their mean 12\tfrac12 and coarse cell 5 holds 00. At face 5, the right end of the first patch:

  • coarse flux: C=Δt0 u4=116⋅12=132C = \Delta t_0\,u_4 = \tfrac1{16}\cdot\tfrac12 = \tfrac1{32}, and the coarse step gives u5=0−12(0−12)=14u_5 = 0 - \tfrac12(0 - \tfrac12) = \tfrac14;
  • first fine step: the last fine cell holds 00, so the flux is 00, and the cell becomes 0−12(0−1)=120 - \tfrac12(0 - 1) = \tfrac12;
  • second fine step: the flux is 12\tfrac12, so R=132(0+12)=164R = \tfrac1{32}(0 + \tfrac12) = \tfrac1{64};
  • refluxing: u5←14+(R−C)/Δx0=14+(164−132)⋅8=18u_5 \leftarrow \tfrac14 + (R - C)/\Delta x_0 = \tfrac14 + (\tfrac1{64} - \tfrac1{32})\cdot 8 = \tfrac18.

The amount 18⋅18=164\tfrac18\cdot\tfrac18 = \tfrac1{64} in cell 5 is now exactly what left the fine patch. Without refluxing cell 5 holds 14\tfrac14, which is 164\tfrac1{64} of extra mass, and the total 916\tfrac9{16} is not kept. The tests check these numbers in exact rational arithmetic.

Accuracy and cost (measurement). u0=e−200(x−0.3)2u_0 = e^{-200(x - 0.3)^2}, 32 cells on level 0, r=2r = 2, Courant number 12\tfrac12, T=0.25T = 0.25, tags where a neighbour differs by more than 0.02, buffer 2, regrid every step. L1L^1 error against the exact solution at the cell centres:

method finest Δx\Delta x cells at TT L1L^1 error
uniform, 32 cells 1/32 32 5.551e-2
AMR, levels 0 and 1 1/64 49 3.482e-2
uniform, 64 cells 1/64 64 3.482e-2
AMR, levels 0 to 2 1/128 73 1.995e-2
uniform, 128 cells 1/128 128 1.995e-2

AMR gets the error of the uniform fine grid with 57% of its cells, because the pulse stays inside the refined region and the coarse cells see only u≈0u \approx 0. With a box profile, 16 coarse cells and two finer levels, the total mass is 1364\tfrac{13}{64} exactly after 14 coarse steps with refluxing. Without refluxing it is off by 4.3×10−34.3\times10^{-3}, that is 2%.

Correctness

The proof is in proofs/correctness.md. It shows two facts. First, proper nesting makes every ghost value in L1 and every cell in L6 exist. Second, with refluxing, one call ADVANCE(l,θ)\text{ADVANCE}(l, \theta) changes the mass of each level-ll patch only by the level-ll fluxes at its two ends, so the composite mass is conserved exactly. Regridding also conserves mass, because it fills new fine cells either from old fine cells or with the value of the parent cell. When level 1 covers the whole domain, the method is the uniform fine scheme with rr steps per coarse step. When L=0L = 0, it is the single-grid scheme.

Proof: With proper nesting and refluxing, the Berger-Colella step is well defined, conservative and reduces to the uniform schemefull

Setting. The domain is periodic. Level ll has nl=n0rln_l = n_0r^l cells of width Δxl\Delta x_l and time step Δtl=Δt0/rl\Delta t_l = \Delta t_0/r^l. Level 0 is one patch that covers the domain. A patch QQ of level l+1l + 1 covers the level-ll cells clo,…,chi−1c_{lo}, \dots, c_{hi} - 1, so its two end faces are the level-ll faces cloc_{lo} and chic_{hi}. Patches of one level are disjoint, and two patches of one level are separated by at least one level-ll cell that they do not cover (they are maximal runs). The scheme on each patch is conservative: ui←ui−ΔtΔx(Fi+1/2−Fi−1/2)u_i \leftarrow u_i - \frac{\Delta t}{\Delta x}(F_{i+1/2} - F_{i-1/2}). For a patch PP of level ll write S(P)=∑i∈PΔxl uiS(P) = \sum_{i \in P}\Delta x_l\,u_i.

Invariant (A), averages. Every covered level-ll cell holds the mean of its rr cells on level l+1l + 1.

Invariant (N), proper nesting. For each patch of level l+1≥2l + 1 \ge 2 and each level-ll cell cc under it, the cells c−1c - 1, cc, c+1c + 1 are on level ll.

Lemma 1 (well defined). If (N) holds, every value used by L1 and L6 exists.

Proof. On level 0 the single patch covers the domain, so every ghost value is in it. Let l≥1l \ge 1 and let QQ be a patch of level ll that does not cover the whole domain. Its ghost cells lie in the level-(l−1)(l-1) cells clo−1c_{lo} - 1 and chic_{hi}. For l=1l = 1 these are on level 0. For l≥2l \ge 2 they are on level l−1l - 1 by (N), applied to the end cells cloc_{lo} and chi−1c_{hi} - 1 of QQ. That level has been advanced in the current step before QQ, so both its old and its new values exist, and L1 can interpolate between them. The cells corrected by L6 are the same two cells, so they exist too. They are not covered by level ll, because QQ is a maximal run. □\square

Lemma 2 (one patch). Let (A) and (N) hold before the call ADVANCE(l,θ)\text{ADVANCE}(l, \theta). For every patch PP of level ll, the call changes S(P)S(P) by exactly −(ΔtlFhi−ΔtlFlo)-(\Delta t_lF_{hi} - \Delta t_lF_{lo}), where FloF_{lo} and FhiF_{hi} are the fluxes that L2 computes at the two end faces of PP. After the call, (A) holds on level ll and below the cells of level ll.

Proof. By induction on L−lL - l. L2 changes S(P)S(P) by −∑iΔtl(Fi+1/2−Fi−1/2)-\sum_i\Delta t_l(F_{i+1/2} - F_{i-1/2}), which telescopes to −(ΔtlFhi−ΔtlFlo)-(\Delta t_lF_{hi} - \Delta t_lF_{lo}). If l=Ll = L, nothing else changes PP.

Let l<Ll < L. Fix a patch QQ of level l+1l + 1 inside PP, with end faces cloc_{lo} and chic_{hi} on level ll. Let CloC_{lo} and ChiC_{hi} be Δtl\Delta t_l times the level-ll fluxes at those faces (L4), and RloR_{lo} and RhiR_{hi} the sums of Δtl+1\Delta t_{l+1} times the level-(l+1)(l+1) end fluxes over the rr subcycles (L3). By the induction hypothesis applied rr times, S(Q)S(Q) changes by −(Rhi−Rlo)-(R_{hi} - R_{lo}), and (A) holds below QQ after the subcycles. Now count the changes of S(P)S(P) caused by QQ after L2.

  • L6 changes the cell to the left of face cloc_{lo} by −(Rlo−Clo)/Δxl-(R_{lo} - C_{lo})/\Delta x_l and the cell to the right of face chic_{hi} by +(Rhi−Chi)/Δxl+(R_{hi} - C_{hi})/\Delta x_l. These cells are in PP by (N) (or because PP is level 0). The change of S(P)S(P) is −(Rlo−Clo)+(Rhi−Chi)-(R_{lo} - C_{lo}) + (R_{hi} - C_{hi}).
  • L7 replaces the values of the covered cells. Before the step, by (A), their sum times Δxl\Delta x_l was S(Q)S(Q) before the step. L2 changed that sum by −(Chi−Clo)-(C_{hi} - C_{lo}), by telescoping over the covered cells. After L7 the sum is S(Q)S(Q) after the subcycles, which is S(Q)S(Q) before the step minus (Rhi−Rlo)(R_{hi} - R_{lo}). So L7 changes S(P)S(P) by −(Rhi−Rlo)+(Chi−Clo)-(R_{hi} - R_{lo}) + (C_{hi} - C_{lo}).

The two changes add up to zero. Different patches QQ touch different cells of PP, because they are separated by uncovered cells and each L6 cell is uncovered. So the total change of S(P)S(P) is the one from L2. L7 restores (A) on level ll. □\square

Theorem 1 (conservation). With refluxing, one coarse step keeps the composite mass M=∑Δx uM = \sum \Delta x\,u over the finest cells that cover each point. In rational arithmetic the equality is exact.

Proof. By (A) and induction from the finest level down, M=S(P0)M = S(P_0), where P0P_0 is the level-0 patch. The level-0 patch has no end faces on the periodic domain: its two end fluxes are the same face flux, so Lemma 2 gives S(P0)S(P_0) unchanged. After the step (A) holds, so M=S(P0)M = S(P_0) again. □\square

Lemma 3 (regridding). L8 and L9 keep (A), (N) and MM.

Proof. L8 keeps on level l≥1l \ge 1 only cells cc with c−1,c,c+1c - 1, c, c + 1 on level ll, so the new patches of level l+1l + 1 satisfy (N). Patches cover whole parent cells. The rr children of a parent cell are either all copied from an old fine patch, whose mean equals the parent by (A), or all set to the parent value. In both cases the mean of the children equals the parent, so (A) holds and the final average down changes nothing. The values of level 0 are not changed, so M=S(P0)M = S(P_0) is kept. □\square

Theorem 2 (reductions). If L=0L = 0, a coarse step is one step of the single-grid scheme. If level 1 covers the whole domain and L=1L = 1, the values of level 1 after one coarse step are those of rr steps of the uniform scheme with Δx1\Delta x_1 and Δt1\Delta t_1.

Proof. With L=0L = 0 only L1 and L2 run on one periodic patch. If the level-1 patch covers the domain, L1 takes every ghost value from the patch itself, so level 1 does rr periodic uniform steps. There are no end faces, so L6 does nothing, and L7 only changes level 0. □\square

Termination. A coarse step makes rlr^l calls on level ll for l=0,…,Ll = 0, \dots, L, each with finitely many cells, and the regrid makes one pass over each level. So each step ends after finitely many operations.

Remark (order). The proof gives conservation, not accuracy. The accuracy table on the main page is a measurement. The ghost values are first order in space and linear in time, which matches the first-order upwind scheme of the reference code.

■\blacksquare

Complexity

One coarse step does rlr^l steps on level ll, so the work is Θ(∑lrlNl)\Theta(\sum_l r^l N_l) flux evaluations, where NlN_l is the number of cells on level ll. A uniform grid at the finest level does rLr^L steps on rLN0r^L N_0 cells, so the gain is large when the fine levels cover a small fraction of the domain. Regridding costs Θ(∑lNl)\Theta(\sum_l N_l) in one dimension, plus the cost of clustering the tagged cells into rectangles in two and three dimensions. The flux registers take memory proportional to the number of coarse-fine faces. The reference code finds the patch of a cell by a linear search over the patches of its level, which is simple but slow when there are many patches. Production codes keep an index map or a box tree.

Properties

  • Conservative to rounding error (exactly in rational arithmetic), with refluxing.
  • Every level runs at the same Courant number, so the time step is not limited by the finest cells.
  • First order in time at coarse-fine boundaries with linear interpolation in time for the ghost cells. Second-order schemes need second-order interpolation in space and time to keep their order there.
  • Explicit and local: each patch is a uniform grid, so a fast uniform-grid kernel runs on it.
  • The hierarchy changes during the run, so the number of cells changes with the solution.

Variants and improvements

  • Berger-Oliger. The 1984 method allows rotated patches and does not correct the fluxes, so it is not conservative.
  • Clustering. In two and three dimensions the tagged cells are grouped into rectangles with an efficiency threshold, usually by the method of Berger and Rigoutsos (1991), which splits boxes at holes and inflection points of tag signatures.
  • Without subcycling. All levels take the finest time step. Refluxing becomes simpler, and the code becomes slower by a factor near rLr^L on the coarse levels.
  • Runge-Kutta time stepping. The flux register sums the stage fluxes with the weights of the Runge-Kutta method, so the corrected coarse flux matches the fine one.
  • Tree-based AMR. A quadtree or an octree refines single cells instead of patches, and a space-filling curve distributes the leaves over processors. The refluxing idea is the same.
  • Elliptic AMR. A composite Poisson solve couples the levels with multigrid and the same flux matching at coarse-fine faces.

When to use it

Use it for explicit shock-capturing on structured grids when the features that need resolution (shocks, contact discontinuities, flame fronts, collapsing clouds) cover a small part of the domain and move. It is the standard method in astrophysics, combustion and compressible flow codes. For problems where most of the domain needs the fine grid, a uniform grid is simpler and faster. For complex geometry, unstructured mesh adaptation or adaptive finite elements fit better.

Pitfalls

  • Forgetting the reflux. The scheme still looks correct but loses or creates mass at every coarse-fine face, and shock speeds become wrong.
  • Breaking proper nesting. If a level-(l+2)(l+2) patch touches the edge of level l+1l + 1, its ghost cells come from the wrong level and the reflux corrects a covered cell.
  • Ghost values without time interpolation. Using the new coarse value for all subcycles is first order and can make reflections at the patch edge.
  • Regridding that interpolates non-conservatively. New fine cells must have the parent value as their mean. Linear interpolation needs a limited, conservative slope.
  • Tags too close to the patch edge. Without a buffer the feature leaves the fine patch between regrids. The buffer must be at least the distance the feature moves between regrids.
  • Small patches. Many small patches mean many ghost cells and much overhead. Clustering trades a few extra cells for fewer, larger boxes.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

berger_colella_amr.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/berger-colella-amr/. The authors are listed in prov/64KT6D.jsonl.
"""Berger-Colella adaptive mesh refinement in one space dimension.

The equation is linear advection u_t + a u_x = 0 on the periodic domain [0, 1),
with the first-order upwind flux on every level. The hierarchy has levels
0, 1, ..., with refinement ratio r in space and time. Level 0 covers the
domain. A patch of level l + 1 covers a run of whole level-l cells, and it may
wrap around the periodic boundary. Values can be floats or Fractions; with
Fractions every step is exact.
"""

from fractions import Fraction


class Patch:
    """Cells lo, ..., hi - 1 of one level (taken modulo the number of cells)."""

    __slots__ = ("lo", "hi", "u", "old")

    def __init__(self, lo, hi, u):
        self.lo, self.hi, self.u, self.old = lo, hi, u, None


class Hierarchy:
    def __init__(self, f, n0, a, dt0, ratio=2, max_level=1, tol=0.1,
                 buffer=1, regrid_every=2, reflux=True):
        if n0 < 3 or ratio < 2 or max_level < 0 or buffer < 0:
            raise ValueError("bad hierarchy parameters")
        self.n0, self.a, self.dt0, self.r = n0, a, dt0, ratio
        self.max_level, self.tol, self.buffer = max_level, tol, buffer
        self.regrid_every, self.reflux = regrid_every, reflux
        one = Fraction(1) if isinstance(dt0, Fraction) else 1.0
        self.length = one
        self.t, self.steps = 0 * one, 0
        self.levels = [[Patch(0, n0, [f(self.centre(0, j)) for j in range(n0)])]]
        self.regrid(init=f)

    # geometry ---------------------------------------------------------------
    def n(self, l):
        return self.n0 * self.r ** l

    def dx(self, l):
        return self.length / self.n(l)

    def dt(self, l):
        return self.dt0 / self.r ** l

    def centre(self, l, j):
        return (j + self.length / 2) * self.dx(l)

    def finest(self):
        return len(self.levels) - 1

    def find(self, l, j):
        """Return (patch, offset) for cell j of level l, or None."""
        n = self.n(l)
        for p in self.levels[l]:
            k = (j - p.lo) % n
            if k < p.hi - p.lo:
                return p, k
        return None

    def flux(self, ul, ur):
        return self.a * ul if self.a >= 0 else self.a * ur

    # time stepping ----------------------------------------------------------
    def _ghost(self, l, j, theta):
        hit = self.find(l, j)
        if hit is not None:                                 # same-level neighbour
            p, k = hit
            return p.u[k]
        # @line L1: from level l - 1, linear in time between its old and new values
        q, k = self.find(l - 1, (j % self.n(l)) // self.r)
        return (1 - theta) * q.old[k] + theta * q.u[k]

    def _advance(self, l, theta, fine_reg):
        dt, dx = self.dt(l), self.dx(l)
        n = self.n(l)
        patches = self.levels[l]
        ext = [[self._ghost(l, p.lo - 1, theta)] + p.u + [self._ghost(l, p.hi, theta)]
               for p in patches]
        face_flux = {}
        for p, e in zip(patches, ext):
            m = p.hi - p.lo
            F = [self.flux(e[i], e[i + 1]) for i in range(m + 1)]
            p.old = p.u
            # @line L2: one upwind step on every patch of level l
            p.u = [p.old[i] - dt / dx * (F[i + 1] - F[i]) for i in range(m)]
            for i in range(m + 1):
                face_flux[(p.lo + i) % n] = F[i]
            if l > 0 and m < n:
                # @line L3: fine flux register at the two ends of the patch
                for face, Fi in ((p.lo, F[0]), (p.hi, F[m])):
                    cf = (face // self.r) % self.n(l - 1)
                    fine_reg[cf] = fine_reg.get(cf, 0) + dt * Fi
        if l == self.finest():
            return
        r, nf = self.r, self.n(l + 1)
        # @line L4: coarse fluxes at the faces where level l + 1 patches start or end
        ends = [(q.lo // r % n, q.hi // r % n) for q in self.levels[l + 1]
                if q.hi - q.lo < nf]
        coarse = {f: dt * face_flux[f] for pair in ends for f in pair}
        reg = {}
        for k in range(r):
            # @line L5: subcycle the finer level r times
            self._advance(l + 1, Fraction(k, r) if isinstance(dt, Fraction) else k / r, reg)
        if self.reflux:
            for left, right in ends:
                # @line L6: reflux the uncovered coarse cells next to the patch
                p, k = self.find(l, left - 1)
                p.u[k] -= (reg[left] - coarse[left]) / dx
                p, k = self.find(l, right)
                p.u[k] += (reg[right] - coarse[right]) / dx
        self._average_down(l)

    def _average_down(self, l):
        r = self.r
        for q in self.levels[l + 1]:
            for c in range(q.lo // r, q.hi // r):
                p, k = self.find(l, c)
                i = c * r - q.lo
                # @line L7: covered coarse cell = mean of its r fine cells
                p.u[k] = sum(q.u[i:i + r]) / r

    def step(self):
        self._advance(0, 0, {})
        self.t += self.dt0
        self.steps += 1
        if self.regrid_every and self.steps % self.regrid_every == 0:
            self.regrid()

    def run(self, steps):
        for _ in range(steps):
            self.step()
        return self

    # regridding -------------------------------------------------------------
    def _tags(self, l):
        n = self.n(l)
        tags = set()
        for p in self.levels[l]:
            m = p.hi - p.lo
            for k in range(m):
                j = (p.lo + k) % n
                for nb in (j - 1, j + 1):
                    hit = self.find(l, nb)
                    if hit is not None and abs(hit[0].u[hit[1]] - p.u[k]) > self.tol:
                        tags.add(j)
        grown = {(j + d) % n for j in tags for d in range(-self.buffer, self.buffer + 1)}
        if l > 0:
            grown = {j for j in grown
                     if all(self.find(l, j + d) is not None for d in (-1, 0, 1))}
        return grown

    def regrid(self, init=None):
        r = self.r
        for l in range(self.max_level):
            if l > self.finest():
                break
            n = self.n(l)
            # @line L8: tag, buffer, and keep only properly nested cells
            tags = self._tags(l)
            runs = cell_runs(tags, n)
            old = self.levels[l + 1] if l + 1 < len(self.levels) else []
            new = []
            for lo, hi in runs:
                vals = []
                for j in range(lo * r, hi * r):
                    if init is not None:
                        vals.append(init(self.centre(l + 1, j % self.n(l + 1))))
                        continue
                    hit = None
                    for q in old:
                        k = (j - q.lo) % self.n(l + 1)
                        if k < q.hi - q.lo:
                            hit = q.u[k]
                    if hit is None:
                        c, k = self.find(l, (j // r) % n)
                        hit = c.u[k]
                    vals.append(hit)
                # @line L9: new patch, filled from old fine data or from level l
                new.append(Patch(lo * r, hi * r, vals))
            if not new:
                del self.levels[l + 1:]
                break
            self.levels[l + 1:l + 2] = [new]
        del self.levels[self.max_level + 1:]
        for l in range(self.finest() - 1, -1, -1):
            self._average_down(l)

    # output -----------------------------------------------------------------
    def composite(self):
        """List of (left, width, value) for the finest cells covering [0, 1)."""
        out = []

        def walk(l, j):
            r = self.r
            if l < self.finest() and self.find(l + 1, j * r) is not None:
                for i in range(r):
                    walk(l + 1, j * r + i)
            else:
                p, k = self.find(l, j)
                out.append((j * self.dx(l), self.dx(l), p.u[k]))

        for j in range(self.n0):
            walk(0, j)
        return out

    def mass(self):
        return sum(w * v for _, w, v in self.composite())

    def cells(self):
        return len(self.composite())


def cell_runs(tags, n):
    """Maximal runs of tagged cells on a circle of n cells, as (lo, hi), hi <= lo + n."""
    if not tags:
        return []
    if len(tags) == n:
        return [(0, n)]
    start = next(j for j in range(n) if j in tags and (j - 1) % n not in tags)
    runs, j = [], start
    for _ in range(n):
        if j % n in tags and (j - 1) % n not in tags:
            lo = j
        if j % n in tags and (j + 1) % n not in tags:
            runs.append((lo % n, lo % n + (j - lo) + 1))
        j += 1
    return runs


def upwind_uniform(u, a, lam, steps):
    """Reference: single-grid periodic upwind with Courant number lam = a dt / dx."""
    m = len(u)
    for _ in range(steps):
        if a >= 0:
            u = [u[i] - lam * (u[i] - u[i - 1]) for i in range(m)]
        else:
            u = [u[i] - lam * (u[(i + 1) % m] - u[i]) for i in range(m)]
    return u
test_berger_colella_amr.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/berger-colella-amr/. The authors are listed in prov/64KT6D.jsonl.

import math
from fractions import Fraction

import pytest

from berger_colella_amr import Hierarchy, cell_runs, upwind_uniform


def box(x):
    return Fraction(1) if Fraction(3, 10) <= x < Fraction(1, 2) else Fraction(0)


def bump(x):
    return math.exp(-200 * (x - 0.3) ** 2)


def test_cell_runs_on_a_circle():
    assert cell_runs(set(), 8) == []
    assert cell_runs({2, 3, 4}, 8) == [(2, 5)]
    assert sorted(cell_runs({0, 1, 7, 4}, 8)) == [(4, 5), (7, 10)]
    assert cell_runs(set(range(8)), 8) == [(0, 8)]


def test_one_level_is_the_single_grid_upwind_scheme():
    n0 = 20
    h = Hierarchy(box, n0, 1, Fraction(1, 40), max_level=0)
    h.run(12)
    u0 = [box((j + Fraction(1, 2)) / n0) for j in range(n0)]
    assert [v for _, _, v in h.composite()] == upwind_uniform(u0, 1, Fraction(1, 2), 12)


@pytest.mark.parametrize("a", [1, -1])
def test_full_refinement_is_the_fine_grid_scheme_with_subcycling(a):
    # tol < 0 tags every cell, so level 1 covers the whole circle.
    n0, r = 10, 2
    h = Hierarchy(box, n0, a, Fraction(1, 20), ratio=r, max_level=1, tol=-1)
    h.run(5)
    assert h.levels[1][0].hi - h.levels[1][0].lo == n0 * r
    uf = [box((j + Fraction(1, 2)) / (n0 * r)) for j in range(n0 * r)]
    assert [v for _, _, v in h.composite()] == upwind_uniform(uf, a, a * Fraction(1, 2), 5 * r)


@pytest.mark.parametrize("a,levels", [(1, 1), (1, 2), (-1, 2)])
def test_refluxing_conserves_mass_exactly(a, levels):
    h = Hierarchy(box, 16, a, Fraction(1, 40), ratio=2, max_level=levels,
                  tol=Fraction(1, 10), regrid_every=2)
    m0 = h.mass()
    for _ in range(14):
        h.step()
        assert h.mass() == m0
    assert len(h.levels) == levels + 1


def test_without_refluxing_mass_is_not_conserved():
    h = Hierarchy(box, 16, 1, Fraction(1, 40), ratio=2, max_level=1,
                  tol=Fraction(1, 10), reflux=False)
    m0 = h.mass()
    h.run(6)
    assert h.mass() != m0


@pytest.mark.parametrize("reflux,u5", [(True, Fraction(1, 8)), (False, Fraction(1, 4))])
def test_flux_register_by_hand(reflux, u5):
    # Eight coarse cells, Courant number 1/2, u = 1 on [0, 9/16).
    def f(x):
        return Fraction(1) if x < Fraction(9, 16) else Fraction(0)
    h = Hierarchy(f, 8, 1, Fraction(1, 16), ratio=2, max_level=1,
                  tol=Fraction(1, 2), buffer=0, regrid_every=0, reflux=reflux)
    assert [(p.lo, p.hi) for p in h.levels[1]] == [(6, 10), (14, 18)]
    assert h.levels[1][0].u == [1, 1, 1, 0] and h.levels[0][0].u[4] == Fraction(1, 2)
    h.step()
    # Face 5: the coarse flux is 1/16 * 1/2, the two fine fluxes are 1/32 * (0 + 1/2).
    p, k = h.find(0, 5)
    assert p.u[k] == u5
    assert (h.mass() == Fraction(9, 16)) == reflux


def test_proper_nesting_after_regrids():
    h = Hierarchy(lambda x: bump(x), 32, 1.0, 1 / 64, ratio=2, max_level=2,
                  tol=0.02, buffer=1, regrid_every=2)
    for _ in range(20):
        h.step()
        for l in (1, 2):
            if l + 1 > len(h.levels) - 1:
                continue
            for q in h.levels[l + 1]:
                for c in range(q.lo // 2, q.hi // 2):
                    for d in (-1, 0, 1):
                        assert h.find(l, c + d) is not None


def test_amr_is_more_accurate_than_the_coarse_grid_with_fewer_cells_than_the_fine_grid():
    n0, T = 32, 0.25

    def err(cells):
        return sum(w * abs(v - bump(x + w / 2 - T)) for x, w, v in cells)

    steps = 16                                  # dt0 = T / steps, Courant number 1/2
    coarse = Hierarchy(bump, n0, 1.0, T / steps, max_level=0).run(steps)
    amr = Hierarchy(bump, n0, 1.0, T / steps, ratio=2, max_level=2, tol=0.02,
                    buffer=2, regrid_every=1).run(steps)
    e_c, e_a = err(coarse.composite()), err(amr.composite())
    uf = [bump((j + 0.5) / (4 * n0)) for j in range(4 * n0)]
    fine = upwind_uniform(uf, 1, 0.5, 4 * steps)
    e_f = sum(abs(v - bump((j + 0.5) / (4 * n0) - T)) / (4 * n0) for j, v in enumerate(fine))
    assert e_a < 0.5 * e_c
    assert e_a < 1.3 * e_f
    assert amr.cells() < 0.6 * 4 * n0


def test_rejects_bad_parameters():
    with pytest.raises(ValueError):
        Hierarchy(box, 2, 1, Fraction(1, 10))

History

Marsha Berger and Joseph Oliger (1984) gave AMR for hyperbolic equations: a recursive hierarchy of patches, which can be rotated, with subcycling and regridding from an error estimate. Berger and Colella (1989) restricted the patches to be aligned with the coarse grid, introduced proper nesting and the conservative flux correction, and computed shock reflection problems for the Euler equations. The patch-based design became the basis of most block-structured AMR codes in astrophysics, combustion and plasma physics.

References

  1. M. J. Berger and P. Colella, Local adaptive mesh refinement for shock hydrodynamics, Journal of Computational Physics 82(1) (1989) 64-84, the grid hierarchy with proper nesting, the conservative flux correction at coarse-fine boundaries, the integration algorithm with subcycling
  2. Marsha J. Berger and Joseph Oliger, Adaptive mesh refinement for hyperbolic partial differential equations, Journal of Computational Physics 53(3) (1984) 484-512, the recursive time step on a hierarchy of nested grids, regridding from an error estimate

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example