Interpolate expression with complex litteral

Hello,

I am not sure why, but the following MWE does not work

import dolfinx, dolfinx.mesh
from dolfinx import fem
from mpi4py import MPI

mesh = dolfinx.mesh.create_unit_cube(MPI.COMM_WORLD, 5, 5, 5)
V = fem.FunctionSpace(mesh, ("CG", 1))

u = fem.Function(V)
u.vector.set(0.)

f = fem.Function(V)
expr = 1j * u

f.interpolate(fem.Expression(expr, V.element.interpolation_points))

which yields the following error

TypeError: can't convert complex to float

This is actually not a very big deal, as a trivial workaround would be the following

import dolfinx, dolfinx.mesh
from dolfinx import fem
from mpi4py import MPI

mesh = dolfinx.mesh.create_unit_cube(MPI.COMM_WORLD, 5, 5, 5)
V = fem.FunctionSpace(mesh, ("CG", 1))

u = fem.Function(V)
u.vector.set(0.)

im = fem.Function(V)
im.vector.set(1j)

f = fem.Function(V)
expr = im * u

f.interpolate(fem.Expression(expr, V.element.interpolation_points))

but still, I find it quite odd that the use of a complex litteral in an expression results in an error.
Is this intended?
Thanks!

Did you try specifying the dtype in the Expression constructor’s argument list?

Just tried to do so

f.interpolate(fem.Expression(expr, V.element.interpolation_points, dtype=np.complex128))

but the error persists. Anyway, from the Expression tooltip, dtype defaults to PETSc.ScalarType which is already set to np.complex128.

Could you try with dolfinx.fem.Constant(mesh, PETSc.ScalarType(1j))*u?

2 Likes

Yes it works using your code or even expr = dolfinx.fem.Constant(mesh, 1j)*u.