How to use fenics_adjoint with Quadrilateral elements

Hi, I am new to fenics and I am trying to get the gradient of my objective function. It all works fine with triangular elements but the moment I use quad elements, the code breaks.

Please see the code example below:

from dolfin import *              # core FEniCS API
from dolfin_adjoint import *
#from dolfin_adjoint import *      # adjoint API (overloads solve, assemble, etc.)

# ——— setup quad mesh, spaces ———
n    = 32
# mesh = UnitSquareMesh.create(n, n, CellType.Type.quadrilateral)
mesh = UnitSquareMesh(n,n)
dx   = Measure("dx", domain=mesh)

V = FunctionSpace(mesh, "CG", 1)   # state space
A = FunctionSpace(mesh, "DG", 0)   # control space

# ——— control and state solve ———
b = Function(A, name="control")
b.assign(Constant(1.0))

u = Function(V, name="state")
v = TestFunction(V)
F = inner(grad(u), grad(v))*dx - b*v*dx
bc = DirichletBC(V, Constant(0.0), "on_boundary")
solve(F == 0, u, bc)

# ——— assemble J ———
J = assemble(u*b*dx)

# ——— 1) Gradient *vector* w.r.t. b ———
grad_vec = compute_gradient(J, Control(b))


grad_fun = Function(A, name="dJ/db")
grad_fun.assign(grad_vec)

# ——— inspect ———
print("First 10 entries of ∂J/∂b:", grad_fun.vector().get_local()[:10])
print("Value at (0.2,0.3)         :", grad_fun(0.2, 0.3))

This breaks in the solve function if I use :

mesh = UnitSquareMesh.create(n, n, CellType.Type.quadrilateral)

Even when I change my imports to :

import fenics as fe
import fenics_adjoint as fa

And import the modules as:

fa.Function(), fa.Control etc, I get some automatic differentiation related error. Could you help me out please on how to use fenics_adjoint properly with Quad elements?

If you use mesh = Mesh(UnitSquareMesh.create(n, n, CellType.Type.quadrilateral)) it will work, as then the mesh is overloaded by dolfin-adjoint. The problem is that UnitSquareMesh.create is not overloaded by dolfin-adjoint.

You will get issues with the line

as this function is not implemented for quad grids in legacy dolfin.

Side-note
Please note that I modified your post with

```python
# add code here
```

so that it formats correctly on the website. Please try to use this syntax in the future.

Thanks for the help, It worked!! dolfin_adjoint’s overloading of dolfin functions get really confusing sometimes, could you provide some source which can help?
Thanks!

It’s one of the “issues” with the legacy from dolfin_adjoint import * (wildcard import approach).

The next iteration of DOLFIN-adjoint (DOLFINx-adjoint) will be way clearer on what is overloaded, and what is not.