Possible bug in `derivative_cb_post` of `ReducedFunctional`
Issue #65
resolved
Hi there,
When printing out the current control values through derivative_cb_post
, it seems all control values m
are accidentally set to be m[-1]
. eval_cb_post
does not have this problem.
from dolfin import *
from dolfin_adjoint import *
set_log_level(ERROR)
# Create mesh
nx = 9
mesh = UnitSquareMesh(nx, nx)
# Define function space
V = FunctionSpace(mesh, "CG", 1)
# Define a source dependent on three controls (c, d and e)
# 'f = c - d**2 - e**2'
class SourceExpression(Expression):
def __init__(self, c, d, e, derivative=None):
self.c = c
self.d = d
self.e = e
self.derivative = derivative
def eval(self, value, x):
if self.derivative is None:
value[0] = float(self.c) - float(self.d)**2 - float(self.e)**2
elif self.derivative == self.c:
value[0] = 1.0
elif self.derivative == self.d:
value[0] = -2.0*float(self.d)
elif self.derivative == self.e:
value[0] = -2.0*float(self.e)
def forward(f):
"""
forward model
"""
u = Function(V, name='State')
v = TestFunction(V)
F = inner(grad(u), grad(v)) * dx - f * v *dx
bc = DirichletBC(V, 0.0, "on_boundary")
solve(F == 0, u, bc)
return u
def derivative_cb(j, dj, m):
"""
output after each derivative evaluation
"""
print "<<<< grad"
print 'j = ', j
print 'dj = ', [float(va) for va in dj]
print 'm = ', [float(va) for va in m]
print ">>>>"
def eval_cb(j, m):
"""
output after each function evaluation
"""
print "<<<< eval"
print 'j = ', j
print 'm = ', [float(va) for va in m]
print ">>>>"
c = Constant(2.0)
d = Constant(3.0)
e = Constant(4.0)
f = SourceExpression(c, d, e)
f.dependencies = c, d, e
# Provide the derivative coefficients
f.user_defined_derivatives = {c: SourceExpression(c, d, e, derivative=c),
d: SourceExpression(c, d, e, derivative=d),
e: SourceExpression(c, d, e, derivative=e)}
# run forward model once
u = forward(f)
# define target functional
J = Functional(-inner(u, u) * dx)
# define controls
controls = [Control(j) for j in f.dependencies]
# create ReducedFunctional object
rf = ReducedFunctional(J, controls,
derivative_cb_post=derivative_cb, eval_cb_post=eval_cb)
# minimize
f_opt = minimize(rf, bounds=((0.0, 0.0, 0.0), (10.0, 10.0, 10.0)), tol=1.0e-10)
print float(f_opt[0]), float(f_opt[1]), float(f_opt[2])
Comments (3)
-
-
reporter Thanks, Simon. I just pulled the dev-dolfin-adjoint version at quay.io, and the code works fine now.
-
- changed status to resolved
- Log in to comment
It might be an issue with an old dolfin-adjoint version?
I am running dolfin and dolfin-adjoint master and get the following output. Is this what you expect?
Not that I had to change the script slightly to get it to work on dolfin master: