Copy of solution Function

Hi all,

I am solving a weak formulation repeatedly. Therefore, I use the same PETSc solver. In order to use the solutions separately I want to copy the solution uh into a new function. However, when I try this in the Docker image (I use v0.3.0) I get an error which I don’t understand:

  File "/usr/local/lib/python3.9/dist-packages/IPython/core/interactiveshell.py", line 3457, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-8c2428ca2963>", line 6, in <module>
    runfile('/opt/project/old/mwe.py', wdir='/opt/project')
  File "/opt/.pycharm_helpers/pydev/_pydev_bundle/pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "/opt/.pycharm_helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/opt/project/old/mwe.py", line 31, in <module>
    uh.copy()
  File "/usr/local/dolfinx-complex/lib/python3.8/dist-packages/dolfinx/fem/function.py", line 289, in copy
    return Function(self.function_space,
  File "/usr/local/dolfinx-complex/lib/python3.8/dist-packages/dolfinx/fem/function.py", line 192, in __init__
    self._cpp_object = cpp.fem.Function(V._cpp_object, x)
TypeError: __init__(): incompatible constructor arguments. The following argument types are supported:
    1. dolfinx.cpp.fem.Function(arg0: dolfinx::fem::FunctionSpace)
    2. dolfinx.cpp.fem.Function(arg0: dolfinx::fem::FunctionSpace, arg1: dolfinx::la::Vector<std::complex<double>, std::allocator<std::complex<double> > >)
Invoked with: <dolfinx.cpp.fem.FunctionSpace object at 0x7f5573333930>, <petsc4py.PETSc.Vec object at 0x7f5552681950>
Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,
<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic
conversions are optional and require extra headers to be included
when compiling your pybind11 module.

To aid my problem, I have constructed an MWE below.

import dolfinx.fem
from dolfinx import FunctionSpace, Function, fem, Constant
from mpi4py import MPI
from ufl import TrialFunction, TestFunction, dx, inner

mesh = dolfinx.UnitSquareMesh(MPI.COMM_WORLD, 8, 8, dolfinx.cpp.mesh.CellType.triangle)
V = FunctionSpace(mesh, ("CG", 1))
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(mesh, 4)
uh = Function(V)

a = inner(u, v) * dx
L = inner(f, v) * dx

problem = fem.LinearProblem(a, L, u=uh)
problem.solve()

uh.copy()

To solve this, I could deep copy the underlying petsc vector and build a new Function based on this copy myself, but I’d think my MWE above should work fine. Can anyone give me a push in the right direction?

Many thanks in advance!

  • Wouter

See: Copying a function in dolfinx - #2 by dokken