Skip to content

Instantly share code, notes, and snippets.

@funsim
Last active December 18, 2015 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funsim/5769594 to your computer and use it in GitHub Desktop.
Save funsim/5769594 to your computer and use it in GitHub Desktop.
from dolfin import *
from dolfin_adjoint import *
mesh = RectangleMesh(-1, -1, 1, 1, 20, 20)
V = FunctionSpace(mesh, "CG", 1)
u = Function(V, name="State")
m = Function(V, name="Control")
v = TestFunction(V)
F = (inner(grad(u), grad(v)) - m*v)*dx
bc = DirichletBC(V, 0.0, "on_boundary")
solve(F == 0, u, bc)
u_desired = Expression("exp(-1/(1-x[0]*x[0])-1/(1-x[1]*x[1]))")
J = Functional((0.5*inner(u-u_desired, u-u_desired))*dx)
reduced_functional = ReducedFunctional(J, SteadyParameter(m))
m_opt = minimize(reduced_functional, method = "L-BFGS-B", bounds =(0.0,0.5),
options = {"gtol": 1e-12,"ftol": 1e-12,"disp": True})
proj_error = project(u-u_desired,V)
save_file = File("optim_heat.pvd")
# desire solution
proj_udes = project(u_desired,V)
plot(u_desired, mesh, interactive=True, title="Desired")
# Actual solution
F_opt = replace(F, {m: m_opt})
solve(F_opt == 0, u, bc)
plot(u, interactive=True, title="Actual")
# L1 error
proj_error = project(u-u_desired,V)
plot(proj_error, interactive=True, title="L1-Error")
# Optimal forcing
plot(m_opt, interactive=True, title="Control")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment