From 0ffee9a78c2454543dd408b2cec60fa83097a5d5 Mon Sep 17 00:00:00 2001 From: mloubout Date: Mon, 30 Nov 2026 22:28:31 -0500 Subject: [PATCH] Make the safe harmonic mean zero next to any zero point The safe harmonic mean drops a zero point instead of dividing by it, then guarded its final inversion by the reference point alone, so it was zero only when that point was. Next to a zero elsewhere in the stencil it came out at 4/3 or 2 times the nonzero value, e.g., a shear modulus on faces touching a fluid on one side of every fluid-solid contact. Guard it by the smallest of the points the mean reads instead: zero wherever it reads a zero, as the harmonic mean is, and still no division by zero. --- devito/types/basic.py | 18 +++++++++++++----- tests/test_differentiable.py | 27 ++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/devito/types/basic.py b/devito/types/basic.py index fc8940f5e9..cab0c08cb5 100644 --- a/devito/types/basic.py +++ b/devito/types/basic.py @@ -16,8 +16,8 @@ from devito.data import default_allocator from devito.parameters import configuration from devito.tools import ( - CustomDtype, Pickable, as_tuple, dtype_to_ctype, flatten, frozendict, memoized_meth, - sympy_mutex + CustomDtype, Pickable, as_tuple, dtype_to_ctype, filter_ordered, flatten, frozendict, + memoized_meth, sympy_mutex ) from devito.types.args import ArgProvider from devito.types.caching import Cached, Uncached @@ -1111,9 +1111,17 @@ def _evaluate(self, **kwargs): retval = retval._evaluate(**kwargs) retval = retval.subs(subs) - # If harmonic averaging, invert at the end - if self.is_harmonic: - retval = retval._inv(self.function.subs(subs), safe=self.is_harmonic_safe) + # If harmonic averaging, invert at the end. The safe mean drops a zero + # point instead of dividing by it, so it is zero only where the guard of + # this inversion is: the smallest point it reads, so that it is zero + # next to any zero, as the harmonic mean is + if self.is_harmonic_safe: + from devito.finite_differences.elementary import Min # noqa + from devito.symbolics import retrieve_functions # noqa + points = filter_ordered(retrieve_functions(retval)) + retval = retval._inv(Min(*points, evaluate=False), safe=True) + elif self.is_harmonic: + retval = retval._inv(self.function.subs(subs)) return retval diff --git a/tests/test_differentiable.py b/tests/test_differentiable.py index 6a3083a5ce..9083ed94bb 100644 --- a/tests/test_differentiable.py +++ b/tests/test_differentiable.py @@ -160,7 +160,32 @@ def test_avg_mode(ndim, io): for c, arg in zip(ndcoeffs.flatten(), args, strict=True))) assert sympy.simplify(b_avg.args[0] - expected) == 0 assert isinstance(b_avg, SafeInv) - assert b_avg.base == b + # Guarded by every point the mean reads + assert {str(i) for i in b_avg.base.args} == {str(b.subs(arg)) for arg in args} + + +@pytest.mark.parametrize('ndim', [2, 3]) +@pytest.mark.parametrize('io', [2, 4]) +def test_safe_harmonic_zero_neighbour(ndim, io): + """ + The safe harmonic mean is zero wherever it reads a zero, as the harmonic + mean is, and never divides by it. + """ + grid = Grid([8]*ndim) + v = Function(name='v', grid=grid, staggered=grid.dimensions, space_order=4) + b = Function(name='b', grid=grid, space_order=4, interp_order=io, + avg_mode='safe_harmonic') + b.data_with_halo[:] = 2. + b.data[(4,)*ndim] = 0. + + Operator(Eq(v, b)).apply() + + # Every point whose mean reads the zero one + zeros = {tuple(i) for i in np.argwhere(v.data == 0)} + assert zeros == set(product(range(4 - io//2, 4 + io//2), repeat=ndim)) + assert np.all(np.isfinite(v.data)) + if io == 2: + assert np.allclose(v.data[v.data != 0], 2.) def test_no_interp():