Skip to content

Commit bb78b3e

Browse files
authored
Merge pull request #3003 from devitocodes/no-incr-inject
api: introduce nearset neighboor interpolation and assignment injection for it
2 parents e26adc2 + 3c52121 commit bb78b3e

3 files changed

Lines changed: 172 additions & 29 deletions

File tree

‎devito/operations/interpolators.py‎

Lines changed: 65 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
from devito.types import CustomDimension, Eq, Evaluable, Inc, SubFunction, Symbol
2222
from devito.types.utils import DimensionTuple
2323

24-
__all__ = ['LinearInterpolator', 'PrecomputedInterpolator', 'SincInterpolator']
24+
__all__ = ['LinearInterpolator', 'NearestInterpolator',
25+
'PrecomputedInterpolator', 'SincInterpolator']
2526

2627

2728
def check_radius(func):
@@ -163,20 +164,23 @@ class Injection(UnevaluatedSparseOperation):
163164
Evaluates to a list of Eq objects.
164165
"""
165166

166-
__rargs__ = ('field', 'expr', 'implicit_dims') + UnevaluatedSparseOperation.__rargs__
167+
__rargs__ = ('field', 'expr', 'increment', 'implicit_dims') + \
168+
UnevaluatedSparseOperation.__rargs__
167169

168-
def __new__(cls, field, expr, implicit_dims, interpolator):
170+
def __new__(cls, field, expr, increment, implicit_dims, interpolator):
169171
obj = super().__new__(cls, interpolator)
170172

171173
# TODO: unused now, but will be necessary to compute the adjoint
172174
obj.field = field
173175
obj.expr = expr
176+
obj.increment = increment
174177
obj.implicit_dims = implicit_dims
175178

176179
return obj
177180

178181
def operation(self, **kwargs):
179182
return self.interpolator._inject(expr=self.expr, field=self.field,
183+
increment=self.increment,
180184
implicit_dims=self.implicit_dims)
181185

182186
def __repr__(self):
@@ -353,6 +357,20 @@ def _interp_idx(self, variables, implicit_dims=None, subdomain=None,
353357

354358
return idx_subs, temps
355359

360+
def _local_accumulator(self, expr, idx_subs, implicit_dims=None, subdomain=None):
361+
"""
362+
Generate a local accumulator for the interpolation/injection operation.
363+
"""
364+
# Accumulate point-wise contributions into a temporary
365+
rhs = Symbol(name=f'sum{self.sfunction.name}', dtype=self.sfunction.dtype)
366+
summands = [Eq(rhs, 0., implicit_dims=implicit_dims)]
367+
# Substitute coordinate base symbols into the interpolation coefficients
368+
weights = self._weights(subdomain=subdomain)
369+
summands.extend([Inc(rhs, (weights * expr).xreplace(idx_subs),
370+
implicit_dims=implicit_dims)])
371+
372+
return summands, rhs
373+
356374
@check_radius
357375
@check_coords
358376
def interpolate(self, expr, increment=False, self_subs=None, implicit_dims=None):
@@ -376,7 +394,7 @@ def interpolate(self, expr, increment=False, self_subs=None, implicit_dims=None)
376394

377395
@check_radius
378396
@check_coords
379-
def inject(self, field, expr, implicit_dims=None):
397+
def inject(self, field, expr, increment=True, implicit_dims=None):
380398
"""
381399
Generate equations injecting an arbitrary expression into a field.
382400
@@ -391,7 +409,7 @@ def inject(self, field, expr, implicit_dims=None):
391409
injection expression, but that should be honored when constructing
392410
the operator.
393411
"""
394-
return Injection(field, expr, implicit_dims, self)
412+
return Injection(field, expr, increment, implicit_dims, self)
395413

396414
def _interpolate(self, expr, increment=False, self_subs=None, implicit_dims=None):
397415
"""
@@ -425,22 +443,18 @@ def _interpolate(self, expr, increment=False, self_subs=None, implicit_dims=None
425443
idx_subs, temps = self._interp_idx(variables, implicit_dims=implicit_dims,
426444
subdomain=subdomain)
427445

428-
# Accumulate point-wise contributions into a temporary
429-
rhs = Symbol(name=f'sum{self.sfunction.name}', dtype=self.sfunction.dtype)
430-
summands = [Eq(rhs, 0., implicit_dims=implicit_dims)]
431-
# Substitute coordinate base symbols into the interpolation coefficients
432-
weights = self._weights(subdomain=subdomain)
433-
summands.extend([Inc(rhs, (weights * expr).xreplace(idx_subs),
434-
implicit_dims=implicit_dims)])
435-
446+
# Local scalar for accumulation over radius
447+
summands, rhs = self._local_accumulator(expr, idx_subs,
448+
implicit_dims=implicit_dims,
449+
subdomain=subdomain)
436450
# Write/Incr `self`
437451
lhs = self.sfunction.subs(self_subs)
438452
ecls = Inc if increment else Eq
439453
last = [ecls(lhs, rhs, implicit_dims=implicit_dims)]
440454

441455
return temps + summands + last
442456

443-
def _inject(self, field, expr, implicit_dims=None):
457+
def _inject(self, field, expr, increment=True, implicit_dims=None):
444458
"""
445459
Generate equations injecting an arbitrary expression into a field.
446460
@@ -494,9 +508,10 @@ def _inject(self, field, expr, implicit_dims=None):
494508
# Move all temporaries inside inner loop to improve parallelism
495509
# Can only be done for inject as interpolation needs a summing temp
496510
# that wouldn't allow collapsing
497-
implicit_dims = implicit_dims + tuple(r.parent for r in
498-
self._rdim(subdomain=subdomain,
499-
shifts=shifts))
511+
with suppress(AttributeError):
512+
implicit_dims = implicit_dims + tuple(r.parent for r in
513+
self._rdim(subdomain=subdomain,
514+
shifts=shifts))
500515

501516
# List of indirection indices for all adjacent grid points
502517
idx_subs, _temps = self._interp_idx(list(g_fields) + variables,
@@ -505,8 +520,9 @@ def _inject(self, field, expr, implicit_dims=None):
505520

506521
w = self._weights(subdomain=subdomain, shifts=shifts)
507522
temps.extend(_temps)
508-
eqns.extend([Inc(f.xreplace(idx_subs), (w * e).xreplace(idx_subs),
509-
implicit_dims=implicit_dims)
523+
ecls = Inc if increment else Eq
524+
eqns.extend([ecls(f.xreplace(idx_subs), (w * e).xreplace(idx_subs),
525+
implicit_dims=implicit_dims)
510526
for f, e in zip(g_fields, g_exprs, strict=True)])
511527

512528
return filter_ordered(temps) + eqns
@@ -713,6 +729,36 @@ def _arg_defaults(self, coords=None, sfunc=None, origin=None):
713729
return args
714730

715731

732+
class NearestInterpolator(LinearInterpolator):
733+
"""
734+
Nearest neighbor interpolation scheme.
735+
736+
Gridpoints and per-dim `(1-frac, frac)` weights are precomputed on the
737+
host in fp64 (see `_arg_defaults`) and passed to the kernel as int32/fp
738+
SubFunctions. The generated C only indexes those tables and never sees
739+
`(c-o)/h` or `floor` on fp32.
740+
"""
741+
742+
_name = 'nearest'
743+
744+
def _local_accumulator(self, expr, idx_subs, implicit_dims=None, subdomain=None):
745+
return [], expr.xreplace(idx_subs)
746+
747+
@memoized_meth
748+
def _rdim(self, subdomain=None, shifts=None):
749+
return DimensionTuple(*[0 for _ in self._cdim], getters=self._gdims)
750+
751+
@memoized_meth
752+
def _weights(self, subdomain=None, shifts=None):
753+
return sympy.S.One
754+
755+
def _gridpoints(self, shifts=None):
756+
return self._generate_coeffs(tuple(shifts) if shifts else None)[0]
757+
758+
def _coeffs(self, shifts=None):
759+
return []
760+
761+
716762
class PrecomputedInterpolator(WeightedInterpolator):
717763
"""
718764
Concrete implementation of WeightedInterpolator implementing a Precomputed

‎devito/types/sparse.py‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from devito.finite_differences import generate_fd_shortcuts
1010
from devito.mpi import MPI, SparseDistributor
1111
from devito.operations import (
12-
LinearInterpolator, PrecomputedInterpolator, SincInterpolator
12+
LinearInterpolator, NearestInterpolator, PrecomputedInterpolator, SincInterpolator
1313
)
1414
from devito.symbolics import indexify, retrieve_function_carriers
1515
from devito.tools import (
@@ -34,8 +34,9 @@
3434
]
3535

3636

37-
_interpolators = {'linear': LinearInterpolator, 'sinc': SincInterpolator}
38-
_default_radius = {'linear': 1, 'sinc': 4}
37+
_interpolators = {'linear': LinearInterpolator, 'sinc': SincInterpolator,
38+
'nearest': NearestInterpolator}
39+
_default_radius = {'linear': 1, 'sinc': 4, 'nearest': 0}
3940

4041

4142
class SparseSubFunction(SubFunction):
@@ -380,6 +381,8 @@ def _pos_symbols(self, shifts=None):
380381
@cached_property
381382
def _point_increments(self):
382383
"""Index increments in each Dimension for each point symbol."""
384+
if self.r == 0:
385+
return ((0,) * self.grid.dim,)
383386
return tuple(product(range(-self.r+1, self.r+1), repeat=self.grid.dim))
384387

385388
@cached_property
@@ -439,11 +442,14 @@ def interpolate(self, *args, **kwargs):
439442
"""
440443
return self.interpolator.interpolate(*args, **kwargs)
441444

442-
def inject(self, *args, **kwargs):
445+
def inject(self, *args, increment=True, **kwargs):
443446
"""
444447
Implement an injection operation from a sparse point onto the grid
445448
"""
446-
return self.interpolator.inject(*args, **kwargs)
449+
if not increment and self.interpolation != 'nearest':
450+
raise ValueError("Assignment injection is only supported"
451+
"for nearest-neighbor interpolation")
452+
return self.interpolator.inject(*args, increment=increment, **kwargs)
447453

448454
def guard(self, expr=None):
449455
"""
@@ -982,6 +988,8 @@ def __interp_setup__(self, interpolation='linear', r=None, **kwargs):
982988
raise ValueError("'sinc' interpolator requires a radius of at most 10")
983989
elif interpolation == 'linear' and self._radius != 1:
984990
self._radius = 1
991+
elif interpolation == 'nearest':
992+
self._radius = 0
985993

986994
@cached_property
987995
def _coordinate_symbols(self):
@@ -1135,7 +1143,7 @@ def interpolate(self, expr, u_t=None, p_t=None, increment=False, implicit_dims=N
11351143
return super().interpolate(expr, increment=increment, self_subs=subs,
11361144
implicit_dims=implicit_dims)
11371145

1138-
def inject(self, field, expr, u_t=None, p_t=None, implicit_dims=None):
1146+
def inject(self, field, expr, increment=True, u_t=None, p_t=None, implicit_dims=None):
11391147
"""
11401148
Generate equations injecting an arbitrary expression into a field.
11411149
@@ -1153,14 +1161,17 @@ def inject(self, field, expr, u_t=None, p_t=None, implicit_dims=None):
11531161
An ordered list of Dimensions that do not explicitly appear in the
11541162
injection expression, but that should be honored when constructing
11551163
the operator.
1164+
increment: bool, optional
1165+
If Flalse, generate assignment (Eq) rather than increment (Inc).
11561166
"""
11571167
# Apply optional time symbol substitutions to field and expr
11581168
if u_t is not None:
11591169
field = field.subs({field.time_dim: u_t})
11601170
if p_t is not None:
11611171
expr = expr.subs({self.time_dim: p_t})
11621172

1163-
return super().inject(field, expr, implicit_dims=implicit_dims)
1173+
return super().inject(field, expr, increment=increment,
1174+
implicit_dims=implicit_dims)
11641175

11651176
@property
11661177
def forward(self):

‎tests/test_interpolation.py‎

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
SparseFunction, SparseTimeFunction, SubDomain, TimeFunction, VectorFunction,
1212
switchconfig
1313
)
14-
from devito.operations.interpolators import LinearInterpolator, SincInterpolator
14+
from devito.operations.interpolators import (
15+
LinearInterpolator, SincInterpolator, _cell_indices
16+
)
1517
from devito.tools import as_tuple
1618
from examples.seismic import (
1719
AcquisitionGeometry, Receiver, RickerSource, TimeAxis, demo_model
@@ -48,11 +50,12 @@ def unit_box_time(name='a', shape=(11, 11), space_order=1):
4850
return a
4951

5052

51-
def points(grid, ranges, npoints, name='points'):
53+
def points(grid, ranges, npoints, name='points', interpolation='linear'):
5254
"""Create a set of sparse points from a set of coordinate
5355
ranges for each spatial dimension.
5456
"""
55-
points = SparseFunction(name=name, grid=grid, npoint=npoints)
57+
points = SparseFunction(name=name, grid=grid, npoint=npoints,
58+
interpolation=interpolation)
5659
for i, r in enumerate(ranges):
5760
points.coordinates.data[:, i] = np.linspace(r[0], r[1], npoints)
5861
return points
@@ -524,6 +527,89 @@ def test_inject_staggered_mixed(self):
524527
# Should be a single loop nest with 3 injections
525528
assert_structure(op, ['p_p,rp_px,rp_py,rp_pz'], 'p_prp_pxrp_py,rp_pz')
526529

530+
def test_assign_not_supported(self):
531+
grid = Grid((11, 11, 11))
532+
a = Function(name='a', grid=grid, space_order=2)
533+
p = SparseFunction(name="p", grid=grid, nt=10, npoint=1)
534+
535+
with pytest.raises(ValueError):
536+
p.inject(a, expr=1., increment=False)
537+
538+
539+
# ---------------------------------------------------------------------------
540+
# Nearest interpolation / injection
541+
# ---------------------------------------------------------------------------
542+
543+
544+
class TestNearest:
545+
546+
"""Tests for NearestSparseFunction / NearestSparseTimeFunction."""
547+
548+
@pytest.mark.parametrize('shape, coords', SHAPE_COORDS)
549+
def test_nearest_interpolation(self, shape, coords, npoints=20):
550+
"""Test interpolation with NearestSparseFunction which uses nearest
551+
neighbour interpolation.
552+
"""
553+
a = unit_box(shape=shape)
554+
p = points(a.grid, ranges=coords, npoints=npoints, interpolation='nearest')
555+
# nearest grdpoint
556+
xcoords = _cell_indices(p.coordinates.data, a.grid, None,
557+
a.grid.spacing, a.grid.origin)[:, 0] * a.grid.spacing[0]
558+
559+
expr = p.interpolate(a)
560+
op = Operator(expr)
561+
562+
op(a=a)
563+
assert np.allclose(p.data[:], xcoords, rtol=1e-6)
564+
565+
@pytest.mark.parametrize('shape, coords, result', SHAPE_COORDS_INJECT)
566+
def test_nearest_injection(self, shape, coords, result, npoints=19):
567+
"""Test injection with NearestSparseFunction which uses nearest
568+
neighbour injection.
569+
"""
570+
a = unit_box(shape=shape)
571+
a.data[:] = 0.
572+
p = points(a.grid, ranges=coords, npoints=npoints, interpolation='nearest')
573+
574+
expr = p.inject(a, Float(1.))
575+
576+
op = Operator(expr)
577+
578+
op(a=a)
579+
580+
d64 = np.array([.1]*a.grid.dim, dtype=np.float64)
581+
o64 = np.array([0]*a.grid.dim, dtype=np.float64)
582+
indices = _cell_indices(p.coordinates.data, a.grid, None,
583+
d64, o64)
584+
pos, pcount = np.unique(indices, return_counts=True, axis=0)
585+
586+
assert np.sum(a.data) == npoints
587+
for p, pc in zip(pos, pcount, strict=True):
588+
assert a.data[tuple(p)] == pc
589+
590+
@pytest.mark.parametrize('shape, coords, result', SHAPE_COORDS_INJECT)
591+
def test_nearest_injection_assign(self, shape, coords, result, npoints=19):
592+
a = unit_box(shape=shape)
593+
a.data[:] = 0.
594+
p = points(a.grid, ranges=coords, npoints=npoints, interpolation='nearest')
595+
596+
expr = p.inject(a, Float(1.), increment=False)
597+
598+
op = Operator(expr)
599+
600+
op(a=a)
601+
602+
d64 = np.array([.1]*a.grid.dim, dtype=np.float64)
603+
o64 = np.array([0]*a.grid.dim, dtype=np.float64)
604+
indices = _cell_indices(p.coordinates.data, a.grid, None,
605+
d64, o64)
606+
pos, _ = np.unique(indices, return_counts=True, axis=0)
607+
608+
assert np.sum(a.data) == len(pos)
609+
for i in indices:
610+
assert a.data[tuple(i)] == 1
611+
612+
527613
# ---------------------------------------------------------------------------
528614
# Precomputed interpolation / injection
529615
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)