Issue with compute_gradient: Invalid Type Conversion in FEniCS

Hi,

I am working with FEniCS and dolfin-adjoint, and I encountered an error while trying to compute the gradient of a functional. The error message I am receiving is:

Invalid type conversion: f_53 can not be converted to any UFL type.

The forward problem is implemented as follows:

u_bc = DirichletBC(V, u_bc_expr, boundary)

u = TrialFunction(V)
v = TestFunction(V)

F = k * dot(grad(u), grad(v)) * dx - f_expr * v * dx
a, L = lhs(F), rhs(F)

u_sol = Function(V)

A, b = assemble_system(a, L, u_bc)
solve(A, u_sol.vector(), b)

After solving the forward problem, I am trying to compute the sensitivity of the loss with respect to k by calculating the gradient:

neum_output_func = k_func * dot(grad(u_output), n)
neum_exact_func = k_exact_func * dot(grad(target_u), n)

diff_neum_func = neum_output_func - neum_exact_func

L = assemble(0.5 * inner(diff_neum_func, diff_neum_func) * ds)

control_k = Control(k_func)

dLdk = compute_gradient(L, control_k)

The error occurs when trying to compute the gradient using compute_gradient(L, control_k).

I am using the following versions:

* dolfin-adjoint: 2019.1.0
* fenics-dijitso: 2019.2.0.dev0
* fenics-dolfin: 2019.2.0.64.dev0
* fenics-ffc: 2019.2.0.dev0
* fenics-fiat: 2019.2.0.dev0
* fenics-ufl: 2024.2.0
* fenics-ufl-legacy: 2022.3.0

Question:

Could you help me understand why this error occurs? It seems like there might be a mismatch or compatibility issue with the UFL types, but I’m not sure how to resolve it.
Also, could this problem be caused by the version differences between dolfin-adjoint, fenics-dolfin, and fenics-ufl? Would using compatible versions of these packages help resolve the issue? Any advice or guidance would be greatly appreciated.

Thank you!

Best regards, Dabin Park

You would have to give a reproducible example.

However, looking at the versions you are using:

You shouldn’t have dolfin-adjoint 2019.1.0 and fenics-ufl 2024.2.0 in the same environment.
If you install dolfin-adjoint that should be compatible with ufl-legacy, install any version >= 2023.1.0:

you can get 2023.3.0 from pypi: Releases · dolfin-adjoint/dolfin-adjoint · GitHub

Hello,

I was able to resolve the issue I mentioned earlier, and I just wanted to thank you for your detailed explanation and help.

Thanks again!