Interpolate complex valued function thru Expression

Hi, I want to evaluate the gradient of the solution of my problem in a cartesian grid. I’m following the demo about computing the Von Mises stress, however, being my function complex, it doesn’t work.

That part of the code looks like this:

k_e = 200 
k_i = 0.025 

c_e = 900
c_i = 1000 

rho_e = 2700
rho_i = 1
#i = ScalarType(1j)
w = 1

TD = 2*k_e*( k_e - k_i) / (k_e + k_i ) * inner(grad(U),grad(V)) + 1j*w*(rho_i*c_i - rho_e*c_e)*inner(U,V)

H_grad = VectorFunctionSpace( mesh, ("Lagrange", 1))
TD_expr = Expression(TD, H_grad.element.interpolation_points())
TD = Function(H_grad)
TD.interpolate(TD_expr)

Where both U and V are complex valued fem functions (of ("Lagrange", 2) type) . I’m working with the complex slepc and everything is working fine until that part where I get a TypeError: can't convert complex to float on the line calling Expression.

I have also tried changing 1j by ScalarType(1j) without sucess. How should I approach this?

To be honest, I don’t need the full expression for the TD field, but only its real part, so if there is a workaround taking the real part of TD it would also work.

Thank you very much!

There are multiple issues in your code. Firstly, TD is a scalar value, not a vector value.

The second issue is that using complex numbers without wrapping them as a constant is not supported in FFCx.
A code that resolves your issues are:

from IPython import embed
import dolfinx
from ufl import inner, grad
from mpi4py import MPI

mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 10, 10)
F = dolfinx.fem.FunctionSpace(mesh, ("Lagrange", 2))
U = dolfinx.fem.Function(F)
V = dolfinx.fem.Function(F)


k_e = 200
k_i = 0.025

c_e = 900
c_i = 1000

rho_e = 2700
rho_i = 1
#i = ScalarType(1j)
w = 1

TD = 2*k_e*(k_e - k_i) / (k_e + k_i) * inner(grad(U), grad(V))  \
    + dolfinx.fem.Constant(mesh, 1j)*w*(rho_i*c_i - rho_e*c_e)*inner(U, V)
H_grad = dolfinx.fem.FunctionSpace(mesh, ("Lagrange", 1))
TD_expr = dolfinx.fem.Expression(TD, H_grad.element.interpolation_points())
TD = dolfinx.fem.Function(H_grad)
TD.interpolate(TD_expr)

Thank you, it “works” now (as in “it doesn’t throw any error and I’m able to plot things”) but I don’t get the expected results. I guess there is something wrong in my code.

Just to check, inner is performing conjugation in its second argument, right?

Thank you very much by the way

EDIT: sorry, you already answered that to me. Inner is indeed taking the conjugate of its second argument