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?