funsim / moola

GNU Lesser General Public License v3.0
20 stars 6 forks source link

Can't use constant controls #12

Open augustjohansson opened 5 years ago

augustjohansson commented 5 years ago

It's not possible to use controls that are constant variables, but this works if one uses minimize(). Here's an example:

from fenics import *
from fenics_adjoint import *
import moola

mesh = UnitSquareMesh(10, 10)

# Control
k = Constant(0.1)
control = Control(k)
k_exact = Constant(2.0)

# State discretization
V = FunctionSpace(mesh, "CG", 1)
u = Function(V, name="State")
v = TestFunction(V)

# State data
x = SpatialCoordinate(mesh)
d = sin(pi*x[0])*sin(pi*x[1])
f = -div(k_exact*grad(d))

# State PDE
F = inner(k*grad(u), grad(v))*dx - f*v*dx
bc = DirichletBC(V, Constant(0.0), "on_boundary")
solve(F == 0, u, bc)

# Goal functional
J = assemble((0.5*inner(u-d, u-d))*dx)
rJ = ReducedFunctional(J, control)

# Solve using moola doesn't work
problem = MoolaOptimizationProblem(rJ)
k_moola = moola.DolfinPrimalVector(k)
solver = moola.BFGS(problem, k_moola)
solution = solver.solve()
k_opt = solution["control"].data

# # Solve using minimize works
# k_opt = minimize(rJ)

print("k_opt", k_opt.values()
funsim commented 5 years ago

Good catch. Feel free to create a PR :+1: