diff --git a/devito/finite_differences/derivative.py b/devito/finite_differences/derivative.py index de2c0813e0..86e8f067a2 100644 --- a/devito/finite_differences/derivative.py +++ b/devito/finite_differences/derivative.py @@ -1,5 +1,5 @@ from collections import defaultdict -from collections.abc import Iterable +from collections.abc import Iterable, Mapping from contextlib import suppress from functools import cached_property from itertools import chain @@ -50,6 +50,12 @@ class Derivative(sympy.Derivative, Differentiable, Pickable): x0 : dict, optional Origin (where the finite-difference is evaluated at) for the finite-difference scheme, e.g. {x: x, y: y + h_y/2}. + fd_indices : tuple or dict of {Dimension: tuple}, optional + The stencil points, as offsets from `x0`, e.g. a one-sided stencil next to + a boundary. Each offset is a number of grid spacings, e.g. `(-1, 1)`, or a + multiple of the Dimension's spacing, e.g. `(-x.spacing, x.spacing)`. They + replace the points given by `fd_order` and `side`. A tuple can only be + given for a derivative along one Dimension. Examples -------- @@ -102,7 +108,7 @@ def _fd_priority(self): __rargs__ = ('expr', '*dims') __rkwargs__ = ('side', 'deriv_order', 'fd_order', 'transpose', '_ppsubs', - 'x0', 'method', 'weights', 'halo', 'subdomain') + 'x0', 'method', 'weights', 'halo', 'subdomain', 'fd_indices') def __new__(cls, expr, *dims, **kwargs): # Validate the input arguments `expr`, `dims` and `deriv_order` @@ -163,6 +169,7 @@ def __new__(cls, expr, *dims, **kwargs): obj._weights = cls._process_weights(**kwargs) obj._halo = cls._validate_halo(kwargs.get("halo")) obj._subdomain = kwargs.get("subdomain") + obj._fd_indices = cls._process_fd_indices(obj._dims, **kwargs) ppsubs = kwargs.get("subs", kwargs.get("_ppsubs", [])) processed = [] @@ -324,6 +331,34 @@ def _process_x0(cls, dims, **kwargs): return x0 + @classmethod + def _process_fd_indices(cls, dims, **kwargs): + fd_indices = kwargs.get('fd_indices') or {} + if not isinstance(fd_indices, Mapping): + if len(dims) != 1: + raise ValueError(f"fd_indices given as a tuple need a derivative along " + f"one Dimension, not {dims}") + fd_indices = {dims[0]: fd_indices} + + return frozendict({d: tuple(cls._process_fd_index(d, i) for i in v) + for d, v in fd_indices.items()}) + + @staticmethod + def _process_fd_index(dim, index): + """ + An offset of `fd_indices` in grid spacings, given either as a number of + grid spacings or as a multiple of `dim.spacing`. + """ + offset = sympy.sympify(index) + if offset.has(dim.spacing): + offset = sympy.expand(offset / dim.spacing) + if not offset.is_number: + raise ValueError(f"fd_indices along {dim} must be numbers or multiples " + f"of {dim.spacing}, not {index}") + # Use rationals, so that a half-point index lands exactly on a staggered + # point + return sympy.nsimplify(offset, rational=True) + @classmethod def _process_weights(cls, **kwargs): weights = kwargs.get('weights', kwargs.get('w')) @@ -339,6 +374,9 @@ def __call__(self, x0=None, fd_order=None, side=None, method=None, **kwargs): rkw = {} if 'halo' in kwargs: rkw['halo'] = kwargs['halo'] + if kwargs.get('fd_indices') is not None: + fd_indices = self._process_fd_indices(self.dims, **kwargs) + rkw['fd_indices'] = frozendict({**self.fd_indices, **fd_indices}) if side is not None: rkw['side'] = side if method is not None: @@ -504,6 +542,10 @@ def method(self): def weights(self): return self._weights + @property + def fd_indices(self): + return self._fd_indices + @property def T(self): """Transpose of the Derivative. @@ -674,14 +716,15 @@ def _eval_fd(self, expr, **kwargs): res = cross_derivative(expr, self.dims, self.fd_order, self.deriv_order, matvec=self.transpose, x0=x0_deriv, expand=expand, side=self.side, weights=self.weights, - subdomain=subdomain) + subdomain=subdomain, fd_indices=self.fd_indices) else: assert self.method == 'FD' res = generic_derivative(expr, self.dims[0], self.fd_order[0], self.deriv_order[0], weights=self.weights, side=self.side, matvec=self.transpose, x0=self.x0, expand=expand, - subdomain=subdomain) + subdomain=subdomain, + fd_indices=self.fd_indices.get(self.dims[0])) # Step 4: Apply substitutions for e in self._ppsubs: @@ -711,6 +754,11 @@ def _eval_expand_nest(self, **hints): if not isinstance(self.expr, self.__class__): return self + # Do not merge if either derivative has fd_indices: they would apply to the + # wrong derivative + if self.fd_indices or self.expr.fd_indices: + return self + # This is necessary as tools.abc.Reconstructable._rebuild will copy # all kwargs from the self object. Need to enssure that the nest is not # actually expanded if derivatives are incompatible. diff --git a/devito/finite_differences/finite_difference.py b/devito/finite_differences/finite_difference.py index 0f94304f97..6ccb129526 100644 --- a/devito/finite_differences/finite_difference.py +++ b/devito/finite_differences/finite_difference.py @@ -31,7 +31,8 @@ @check_input -def cross_derivative(expr, dims, fd_order, deriv_order, x0=None, side=None, **kwargs): +def cross_derivative(expr, dims, fd_order, deriv_order, x0=None, side=None, + fd_indices=None, **kwargs): """ Arbitrary-order cross derivative of a given expression. @@ -57,6 +58,8 @@ def cross_derivative(expr, dims, fd_order, deriv_order, x0=None, side=None, **kw expand : bool, optional, default=True If True, the derivative is fully expanded as a sum of products, otherwise an IndexSum is returned. + fd_indices : dict of {Dimension: tuple of numbers}, optional + The stencil points along each Dimension (see `generic_derivative`). Returns ------- @@ -96,9 +99,10 @@ def cross_derivative(expr, dims, fd_order, deriv_order, x0=None, side=None, **kw f(x + 2*h_x, y + 2*h_y)*g(x + 2*h_x, y + 2*h_y)/h_x)/h_y """ x0 = x0 or {} + fd_indices = fd_indices or {} for d, fd, dim in zip(deriv_order, fd_order, dims, strict=True): expr = generic_derivative(expr, dim=dim, fd_order=fd, deriv_order=d, x0=x0, - side=side, **kwargs) + side=side, fd_indices=fd_indices.get(dim), **kwargs) return expr @@ -129,7 +133,7 @@ def index_at(expr, dim): @check_input def generic_derivative(expr, dim, fd_order, deriv_order, matvec=direct, x0=None, coefficients='taylor', expand=True, weights=None, side=None, - subdomain=None): + subdomain=None, fd_indices=None): """ Arbitrary-order derivative of a given expression. @@ -159,6 +163,9 @@ def generic_derivative(expr, dim, fd_order, deriv_order, matvec=direct, x0=None, If given, `expr` is treated as zero outside `subdomain` (see `Derivative`'s `halo`): each stencil tap is multiplied by the indicator of `subdomain` at the point it reads. + fd_indices : tuple of numbers, optional + The stencil points, as offsets from `x0` in grid spacings. They replace + the points given by `fd_order` and `side`. Returns ------- @@ -170,16 +177,18 @@ def generic_derivative(expr, dim, fd_order, deriv_order, matvec=direct, x0=None, if deriv_order == 1 and fd_order == 2 and side is None: fd_order = 1 - # Zeroth order is the identity when `expr` already sits at `x0`, not a - # stencil centred there. - if deriv_order == 0 and (not x0 or index_at(expr, dim) == x0.get(dim)): + # A zeroth-order derivative of `expr` at its own point is `expr` itself, + # unless the stencil points are given + if deriv_order == 0 and fd_indices is None and \ + (not x0 or index_at(expr, dim) == x0.get(dim)): return expr # Enforce stable time coefficients coefficients = 'taylor' if dim.is_Time else expr.coefficients return make_derivative(expr, dim, fd_order, deriv_order, side, - matvec, x0, coefficients, expand, weights, subdomain) + matvec, x0, coefficients, expand, weights, subdomain, + fd_indices=fd_indices) # Backward compatibility @@ -188,7 +197,7 @@ def first_derivative(expr, dim, fd_order, **kwargs): def make_derivative(expr, dim, fd_order, deriv_order, side, matvec, x0, coefficients, - expand, weights=None, subdomain=None): + expand, weights=None, subdomain=None, fd_indices=None): # Always expand time derivatives to avoid issue with buffering and streaming. # Time derivative are almost always short stencils and won't benefit from # unexpansion in the rare case the derivative is not evaluated for time stepping. @@ -197,7 +206,7 @@ def make_derivative(expr, dim, fd_order, deriv_order, side, matvec, x0, coeffici # The stencil indices nweights, wdim, scale = process_weights(weights, expr, dim) indices, x0 = generate_indices(expr, dim, fd_order, side=side, matvec=matvec, - x0=x0, nweights=nweights) + x0=x0, nweights=nweights, fd_indices=fd_indices) # Finite difference weights corresponding to the indices. Computed via the # `coefficients` method (`taylor` or `symbolic`) if weights is None: diff --git a/devito/finite_differences/tools.py b/devito/finite_differences/tools.py index f517e4fd25..35d65ea9fe 100644 --- a/devito/finite_differences/tools.py +++ b/devito/finite_differences/tools.py @@ -255,7 +255,8 @@ def numeric_weights(function, deriv_order, indices, x0): coeff_priority = {'taylor': 1, 'standard': 1} -def generate_indices(expr, dim, order, side=None, matvec=None, x0=None, nweights=0): +def generate_indices(expr, dim, order, side=None, matvec=None, x0=None, nweights=0, + fd_indices=None): """ Indices for the finite-difference scheme. @@ -274,11 +275,24 @@ def generate_indices(expr, dim, order, side=None, matvec=None, x0=None, nweights finite difference. Defaults to `direct`. x0 : dict of {Dimension: Dimension or Expr or Number}, optional Origin of the scheme, ie. `x`, `x + .5 * x.spacing`, ... + fd_indices : tuple of numbers, optional + The stencil points, as offsets from `x0` in grid spacings. They replace + the points given by `order` and `side`. Consecutive points are a stencil + that can also be left unexpanded. Returns ------- An IndexSet, representing an ordered list of indices. """ + # Evaluation point + x0 = sympify((x0 or {}).get(dim) or expr.indices_ref[dim]) + + if fd_indices is not None: + if np.all(np.diff(fd_indices) == 1): + d = make_stencil_dimension(expr, 0, len(fd_indices) - 1) + return IndexSet(dim, expr=x0 + (fd_indices[0] + d)*dim.spacing), x0 + return IndexSet(dim, indices=[x0 + o*dim.spacing for o in fd_indices]), x0 + # Check size of input weights if nweights > 0: do, dw = order + 1 + order % 2, nweights @@ -290,8 +304,6 @@ def generate_indices(expr, dim, order, side=None, matvec=None, x0=None, nweights warning(f"Less weights ({nweights}) provided than the stencil size" f"({order + 1}) for order {order} scheme." f" Reducing order to {order}") - # Evaluation point - x0 = sympify((x0 or {}).get(dim) or expr.indices_ref[dim]) # If provided a pure number, assume it's a valid index if x0.is_Number: diff --git a/examples/userapi/09_fd_evaluation.ipynb b/examples/userapi/09_fd_evaluation.ipynb index 7d102542a2..e896819ba1 100644 --- a/examples/userapi/09_fd_evaluation.ipynb +++ b/examples/userapi/09_fd_evaluation.ipynb @@ -537,6 +537,105 @@ "an interpolation in `y` (since `fy` lives at `y + h_y/2`)." ] }, + { + "cell_type": "markdown", + "id": "c21a", + "metadata": {}, + "source": [ + "## Choosing the stencil points: `fd_indices`\n", + "\n", + "`x0` says where a derivative is evaluated; `fd_indices` says which points it\n", + "reads, as offsets from `x0` in grid spacings: `(-1, 1)` and\n", + "`(-x.spacing, x.spacing)` are the same points. They replace the points that\n", + "`fd_order` and `side` would give, and the Taylor weights are computed at them,\n", + "e.g. a one-sided stencil next to a boundary:" + ] + }, + { + "cell_type": "code", + "id": "c21b", + "metadata": {}, + "source": [ + "# NBVAL_IGNORE_OUTPUT\n", + "# Centred (default) vs. one-sided points, both evaluated at x\n", + "print('centred :', fn.dx.evaluate)\n", + "print('one-sided :', fn.dx(fd_indices=(0, 1, 2)).evaluate)" + ], + "execution_count": 11, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "centred : 0.0833333333*fn(x - 2*h_x, y)/h_x - 0.666666667*fn(x - h_x, y)/h_x + 0.666666667*fn(x + h_x, y)/h_x - 0.0833333333*fn(x + 2*h_x, y)/h_x\n", + "one-sided : -1.5*fn(x, y)/h_x + 2.0*fn(x + h_x, y)/h_x - 0.5*fn(x + 2*h_x, y)/h_x\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "id": "c21c", + "metadata": {}, + "source": [ + "On a staggered target, the offsets are from the target's point, so they are\n", + "half-integers when the argument sits half a cell away. A derivative of `fn`\n", + "onto `fx` (at `x + h_x/2`) that reads only `fn` at and right of `x`:" + ] + }, + { + "cell_type": "code", + "id": "c21d", + "metadata": {}, + "source": [ + "# NBVAL_IGNORE_OUTPUT\n", + "op = Operator(Eq(fx, fn.dx(fd_indices=(-.5, .5, 1.5, 2.5))))\n", + "print(updates(op)[-1])" + ], + "execution_count": 12, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Eq(fx[x + 4, y + 4], r0*(-0.958333333*fn[x + 4, y + 4] + 0.875*fn[x + 5, y + 4] + 0.125*fn[x + 6, y + 4] - 0.0416666667*fn[x + 7, y + 4]))\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "id": "c21e", + "metadata": {}, + "source": [ + "A dict gives the points per Dimension, e.g. for a cross derivative, and\n", + "`weights` can be given with them. The transpose `.T` reads the opposite\n", + "points, so it stays the adjoint of the forward stencil." + ] + }, + { + "cell_type": "code", + "id": "c21f", + "metadata": {}, + "source": [ + "# NBVAL_IGNORE_OUTPUT\n", + "print('cross :', fn.dxdy(fd_indices={x: (0, 1), y: (-1, 0)}).evaluate)\n", + "print('weights :', fn.dx(fd_indices=(0, 1), weights=(-1, 1)).evaluate)\n", + "print('transpose :', fn.dx(fd_indices=(0, 1, 2)).T.evaluate)" + ], + "execution_count": 13, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "cross : (-1/h_y)*(-fn(x, y - h_y)/h_x + fn(x + h_x, y - h_y)/h_x) + (-fn(x, y)/h_x + fn(x + h_x, y)/h_x)/h_y\n", + "weights : -fn(x, y)/h_x + fn(x + h_x, y)/h_x\n", + "transpose : -1.5*fn(x, y)/h_x - 0.5*fn(x - 2*h_x, y)/h_x + 2.0*fn(x - h_x, y)/h_x\n" + ] + } + ] + }, { "cell_type": "markdown", "id": "c22", @@ -553,6 +652,7 @@ "| `staggered=None` | Treated as `NODE`. **Does not** opt out of interpolation. |\n", "| `interp_order=0` | Function opts out of averaging - sampled directly at the target. |\n", "| Explicit `x0` on a derivative | Devito leaves it alone. |\n", + "| `fd_indices` on a derivative | Reads those points, as offsets from `x0`, with Taylor weights unless given. |\n", "\n", "For the `sym_opt={'interp-mode': ...}` choice that governs how products of\n", "staggered fields are projected onto a target, see\n", @@ -575,7 +675,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 14, "id": "c24", "metadata": { "execution": { @@ -614,6 +714,12 @@ "explicit_rhs = str(updates(Operator(Eq(fx, fn.dx(x0={x: x}))))[-1].rhs)\n", "assert default_rhs != explicit_rhs\n", "\n", + "# 5. `fd_indices` replaces the stencil points: a one-sided stencil reads only\n", + "# `fn` at and right of `x`.\n", + "one_sided = fn.dx(fd_indices=(0, 1, 2)).evaluate\n", + "assert {a.args[0] for a in one_sided.atoms(type(fn))} == \\\n", + " {x, x + x.spacing, x + 2*x.spacing}\n", + "\n", "print('all invariants hold')" ] } diff --git a/tests/test_derivatives.py b/tests/test_derivatives.py index c2b490fc1d..84a6a98ff0 100644 --- a/tests/test_derivatives.py +++ b/tests/test_derivatives.py @@ -1,6 +1,6 @@ import numpy as np import pytest -from sympy import Float, Symbol, diff, simplify, sympify +from sympy import Float, Rational, Symbol, diff, nsimplify, simplify, sympify from conftest import assert_structure from devito import ( @@ -622,6 +622,121 @@ def test_fd_adjoint(self, so, ndim, derivative, adjoint_name): b = np.dot(g_deriv.data.reshape(-1), f.data.reshape(-1)) assert np.isclose(1 - a/b, 0, atol=1e-5) + @pytest.mark.parametrize('staggered, fd_indices', [ + (False, (0, 1, 2)), + (False, (-1, 0, 1, 2)), + (True, (.5, 1.5, 2.5)), + (True, (-.5, .5, 1.5))]) + def test_given_fd_indices(self, staggered, fd_indices): + """ + A derivative with `fd_indices` reads only those points, and is exact to + their degree. + """ + grid = Grid(shape=(11,), extent=(10.,), dtype=np.float64) + x, = grid.dimensions + shift = Rational(1, 2) if staggered else 0 + f = Function(name='f', grid=grid, space_order=4, + staggered=x if staggered else None) + out = Function(name='out', grid=grid, space_order=4) + degree = len(fd_indices) - 1 + f.data[:] = (np.arange(11.) + float(shift))**degree + eq = Eq(out, f.dx(fd_indices=fd_indices)) + read = {a.args[0] for a in eq.evaluate.rhs.atoms(type(f))} + assert read <= {x + nsimplify(o)*x.spacing for o in fd_indices} + Operator(eq).apply() + inner = slice(2, -4) + assert np.allclose(out.data[inner], degree*np.arange(11.)[inner]**(degree - 1), + rtol=1e-10, atol=1e-10) + + @pytest.mark.parametrize('source, target, fd_indices, weights', [ + (False, False, (0, 1, 2), None), + (False, True, (-.5, .5, 1.5), None), + (True, False, (.5, 1.5, 2.5), None), + (False, True, (-.5, .5, 1.5), (-1., 2., -.5)), + (True, False, (.5,), (2.,))]) + def test_fd_indices_adjoint(self, source, target, fd_indices, weights): + """A derivative with `fd_indices` passes the dot test with its `.T`.""" + grid = Grid(shape=(21,), extent=(20.,), dtype=np.float64) + x, = grid.dimensions + rng = np.random.default_rng(0) + at = {False: (None, x), True: (x, x + x.spacing/2)} + f, f_out = (Function(name=n, grid=grid, space_order=4, staggered=at[k][0]) + for n, k in (('f', source), ('fo', target))) + g, g_out = (Function(name=n, grid=grid, space_order=4, staggered=at[k][0]) + for n, k in (('g', target), ('go', source))) + f.data[4:-6] = rng.standard_normal(11) + g.data[4:-6] = rng.standard_normal(11) + kwargs = {'fd_indices': fd_indices} if weights is None else \ + {'fd_indices': fd_indices, 'weights': weights} + Operator([Eq(f_out, f.dx(x0={x: at[target][1]}, **kwargs)), + Eq(g_out, g.dx(x0={x: 2*x - at[source][1]}, **kwargs).T)]).apply() + forward = np.dot(f_out.data, g.data) + backward = np.dot(f.data, g_out.data) + assert np.isclose(forward, backward, rtol=1e-12, atol=0) + + def test_fd_indices_tuple(self): + """A tuple of fd_indices is refused for a derivative along two Dimensions.""" + grid = Grid(shape=(11, 11)) + x, y = grid.dimensions + f = Function(name='f', grid=grid, space_order=4) + assert f.dx(fd_indices=(0, 1)).fd_indices == {x: (0, 1)} + with pytest.raises(ValueError, match='one Dimension'): + f.dxdy(fd_indices=(0, 1)) + + def test_fd_indices_spacing(self): + """fd_indices may be given in grid spacings or as multiples of the spacing.""" + grid = Grid(shape=(11, 11)) + x, y = grid.dimensions + hx, hy = x.spacing, y.spacing + f = Function(name='f', grid=grid, space_order=4) + assert f.dx(fd_indices=(-hx, hx)) == f.dx(fd_indices=(-1, 1)) + assert f.dx(fd_indices=(-hx/2, 1.5*hx)).fd_indices == \ + {x: (Rational(-1, 2), Rational(3, 2))} + d0 = f.dxdy(fd_indices={x: (0, hx), y: (-2*hy, 0)}) + d1 = f.dxdy(fd_indices={x: (0, 1), y: (-2, 0)}) + assert d0 == d1 + assert d0.evaluate == d1.evaluate + with pytest.raises(ValueError, match='multiples'): + f.dx(fd_indices=(-hy, hy)) + with pytest.raises(ValueError, match='multiples'): + f.dx(fd_indices=(0, 1 + hx)) + + def test_fd_indices_order_zero(self): + """ + A zeroth-order derivative with `fd_indices` reads those points, e.g. a + shift. + """ + grid = Grid(shape=(11,), extent=(10.,), dtype=np.float64) + x, = grid.dimensions + f = Function(name='f', grid=grid, space_order=4) + out = Function(name='out', grid=grid, space_order=4) + f.data[:] = np.arange(11.)**2 + Operator(Eq(out, f.diff((x, 0), x0={x: x}, fd_indices=(2,)))).apply() + assert np.allclose(out.data[:-2], f.data[2:], rtol=1e-12, atol=0) + + def test_fd_indices_cross(self): + """A dict of fd_indices gives the points along each Dimension.""" + grid = Grid(shape=(11, 11)) + x, y = grid.dimensions + f = Function(name='f', grid=grid, space_order=4) + deriv = f.dxdy(fd_indices={x: (0, 1), y: (-1, 0)}) + read = {a.args for a in deriv.evaluate.atoms(type(f))} + assert read == {(x + i*x.spacing, y + j*y.spacing) + for i in (0, 1) for j in (-1, 0)} + + def test_fd_indices_nested(self): + """ + A derivative of a derivative with fd_indices is not merged into one, and + calling it adds to its fd_indices. + """ + grid = Grid(shape=(11, 11)) + x, y = grid.dimensions + f = Function(name='f', grid=grid, space_order=4) + nested = f.dx(fd_indices=(0, 1)).dx + assert nested._eval_expand_nest() is nested + assert f.dxdy(fd_indices={x: (0, 1)})(fd_indices={y: (-1, 0)}).fd_indices == \ + {x: (0, 1), y: (-1, 0)} + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) @pytest.mark.parametrize('shift, ndim', [(None, 2), (.5, 2), (.5, 3), ((.5, .5, .5), 3)])