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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 52 additions & 4 deletions devito/finite_differences/derivative.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
--------
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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'))
Expand All @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
27 changes: 18 additions & 9 deletions devito/finite_differences/finite_difference.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
-------
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
-------
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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:
Expand Down
18 changes: 15 additions & 3 deletions devito/finite_differences/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand All @@ -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:
Expand Down
108 changes: 107 additions & 1 deletion examples/userapi/09_fd_evaluation.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -575,7 +675,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 14,
"id": "c24",
"metadata": {
"execution": {
Expand Down Expand Up @@ -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')"
]
}
Expand Down
Loading
Loading