Debian Codegraph @

python/demo/undocumented/optimization/demo_optimization.py

raw
1 # Copyright (C) 2008 Anders Logg
2 #
3 # This file is part of DOLFIN.
4 #
5 # DOLFIN is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # DOLFIN is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
17 #
18 # First added: 2008-10-17
19 # Last changed: 2012-11-12
20
21
22 from dolfin import *
23 import matplotlib.pyplot as plt
24
25
26 # Create mesh
27 mesh = UnitSquareMesh(16, 16)
28
29 # Define function spaces
30 P1 = FunctionSpace(mesh, "CG", 1)
31 P0 = FunctionSpace(mesh, "DG", 0)
32
33 # Define test and trial functions
34 v1 = TestFunction(P1)
35 w1 = TrialFunction(P1)
36 w0 = TestFunction(P0)
37
38 # Define functions
39 u = Function(P1)
40 z = Function(P1)
41 f = Constant(1.0)
42 p = Function(P0)
43 u0 = Expression("x[0]*(1.0 - x[0])*x[1]*(1.0 - x[1])", degree=2)
44
45 # Dirichlet boundary
46 class DirichletBoundary(SubDomain):
47 def inside(self, x, on_boundary):
48 return on_boundary
49
50 # Boundary condition
51 bc = DirichletBC(P1, u0, DirichletBoundary())
52
53 # Goal functional
54 J = (u - u0)*(u - u0)*dx(mesh)
55
56 # Forward problem
57 problem = (inner(grad(v1), p*grad(w1))*dx, v1*f*dx)
58
59 # Adjoint problem
60 adjoint = (inner(grad(w1), p*grad(v1))*dx, -2*v1*(u - u0)*dx)
61
62 # Update of parameter
63 gradient = -inner(grad(z), w0*grad(u))*dx
64 px = p.vector()
65
66 # Set initial value for parameter
67 px[:] = 1.0
68
69 # Iterate until convergence
70 for i in range(100):
71
72 # Solve forward problem
73 A = assemble(problem[0])
74 b = assemble(problem[1])
75 bc.apply(A, b)
76 solve(A, u.vector(), b)
77
78 # Solve adjoint problem
79 A = assemble(adjoint[0])
80 b = assemble(adjoint[1])
81 bc.apply(A, b)
82 solve(A, z.vector(), b)
83
84 # Update parameter
85 dp = assemble(gradient)
86 dp *= 100.0
87 px -= dp
88
89 # Print value of functional
90 jval = assemble(J)
91 print("J = ", jval)
92 print(u.vector().max())
93
94 # Plot solution and parameter
95 plt.figure(); plot(u, title="Solution")
96 plt.figure(); plot(z, title="Adjoint")
97 plt.figure(); plot(p, title="Parameter")
98 plt.figure(); plot(u0, mesh=mesh, title="Target")
99 plt.show()