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
6 changes: 5 additions & 1 deletion firedrake/interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,9 +782,13 @@ def _loop_target_nodes(self, f: Function | Cofunction, value: float,
"""
target_mesh = self.target_mesh.unique()
for fk in f.subfunctions:
# Hold the temporary indexed dat strongly. For a Real space it has
# no loop index, so by default the assignment keeps only a weak
# reference and the garbage collector can free the dat before the
# loop runs.
op3.loop(
c := self._loop_index,
fk.dat[target_mesh.closure(c)].assign(value, mode),
fk.dat[target_mesh.closure(c)].assign(value, mode, _weakref=False),
eager=True,
)

Expand Down
21 changes: 21 additions & 0 deletions tests/firedrake/regression/test_interpolate.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import gc
from os.path import abspath, dirname, join
import numpy as np
import pytest
Expand Down Expand Up @@ -118,6 +119,26 @@ def test_subset_adjoint_interpolation():
assert np.allclose(result.dat.data_ro, expected.dat.data_ro)


def test_adjoint_interpolation_into_real_with_garbage_collection():
mesh = UnitSquareMesh(1, 1)
R = FunctionSpace(mesh, "R", 0)
v = TestFunction(R)
w = assemble(v * dx)

# Collect every generation after each allocation. The freeze empties the
# oldest generation, which CPython otherwise collects only rarely.
threshold = gc.get_threshold()
gc.freeze()
gc.set_threshold(1, 1, 1)
try:
result = assemble(interpolate(Constant(1.0), w))
finally:
gc.set_threshold(*threshold)
gc.unfreeze()
# w applied to the constant 1 is the area of the unit square.
assert np.isclose(result, 1.0)


@pytest.mark.skipcomplex
@pytest.mark.parametrize(
("access", "value"),
Expand Down
Loading