def J(f): u_1 = Function(V) u_1.vector()[:] = 1 a = u_1 * u * v * dx + dt * f * inner(grad(u), grad(v)) * dx L = u_1 * v * dx # Time loop t = dt while t <= T: solve(a == L, u_, bc) u_1.assign(u_) t += dt return assemble(u_1**2 * dx)
def test_solver_ident_zeros(): """ Test using ident zeros to restrict half of the domain """ from fenics_adjoint import (UnitSquareMesh, Function, assemble, solve, project, Expression, DirichletBC) mesh = UnitSquareMesh(10, 10) cf = MeshFunction("size_t", mesh, mesh.topology().dim(), 0) top_half().mark(cf, 1) ff = MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0) top_boundary().mark(ff, 1) dx = Measure("dx", domain=mesh, subdomain_data=cf) V = FunctionSpace(mesh, "CG", 1) u, v = TrialFunction(V), TestFunction(V) a = inner(grad(u), grad(v)) * dx(1) w = Function(V) with stop_annotating(): w.assign(project(Expression("x[0]", degree=1), V)) rhs = w**3 * v * dx(1) A = assemble(a, keep_diagonal=True) A.ident_zeros() b = assemble(rhs) bc = DirichletBC(V, Constant(1), ff, 1) bc.apply(A, b) uh = Function(V) solve(A, uh.vector(), b, "umfpack") J = assemble(inner(uh, uh) * dx(1)) Jhat = ReducedFunctional(J, Control(w)) with stop_annotating(): w1 = project(Expression("x[0]*x[1]", degree=2), V) results = taylor_to_dict(Jhat, w, w1) assert (min(results["R0"]["Rate"]) > 0.95) assert (min(results["R1"]["Rate"]) > 1.95) assert (min(results["R2"]["Rate"]) > 2.95)