Using Dolfin-adjoint for optimization problem without PDE constraint

This might not be the most elegant approach, but I would suggest using a immediate variable between your control and the function you would like to assemble over, as shown in the following example:

import numpy as np
import matplotlib.pyplot as plt
from dolfin import *
from dolfin_adjoint import *
import moola

n = 10
mesh = RectangleMesh(Point(-1,-1),Point(1,1), n, n)

V = FunctionSpace(mesh, "CG", 1)
u = Function(V)
v = TestFunction(V)
S0 = Constant(1)

bc = DirichletBC(V, 1, "on_boundary")

v = project(u, V, bcs=bc)
J = assemble((0.5*inner(grad(v), grad(v)) - v*S0)*dx)
J_hat = ReducedFunctional(J, Control(u))   
u_opt = minimize(J_hat, method = "L-BFGS-B", options = {"gtol": 1e-16, "ftol": 1e-16})
J_hat(u_opt)
fileY = File("temp.pvd");
fileY << v.block_variable.saved_output;
print(assemble(v*ds))
1 Like