Copying a function in dolfinx

Dear FEniCS community,

I’m trying to create a copy of a dolfinx.fem.Function object:

from mpi4py import MPI
from ufl import FiniteElement
from dolfinx.mesh import create_rectangle
from dolfinx.fem import FunctionSpace, Function

mesh = create_rectangle(MPI.COMM_WORLD, [[0, 0],[1, 1]], [10, 10])
scalar_element = FiniteElement("P", mesh.ufl_cell(), 2)
V = FunctionSpace(mesh, scalar_element)
func = Function(V)
func.interpolate(lambda x: x[0]*x[1])
copy = func.copy()

However, this raises an AttributeError:

Traceback (most recent call last):
  File "/root/test.py", line 12, in <module>
    copy = func.copy()
  File "/usr/local/dolfinx-real/lib/python3.8/dist-packages/dolfinx/fem/function.py", line 345, in copy
    self._cpp_object.vector.copy())
AttributeError: 'dolfinx.cpp.fem.Function_float64' object has no attribute 'vector'

How can I create a copy of my functiction? I need it to store intermediate results that are required for chekpointing for coupling with preCICE. I got this error with the latest Docker image.

For now you can make a workaround as follows:

func = Function(V)
copy = Function(V)
copy.x.array[:] = func.x.array

There is an issue registered on github, and a proposed fix is added in: Fix function copy option by jorgensd · Pull Request #1916 · FEniCS/dolfinx · GitHub

3 Likes