Consider the following based on the nonlinear Poisson demo. Instead of plotting you could print out a functional of u
:
from dolfin import *
class Problem(NonlinearProblem):
def __init__(self, a, L, bcs):
NonlinearProblem.__init__(self)
self.a = a
self.L = L
self.bcs = bcs
def F(self, b, x):
assembler = SystemAssembler(self.a, self.L, self.bcs)
assembler.assemble(b, x)
def J(self, A, x):
assembler = SystemAssembler(self.a, self.L, self.bcs)
assembler.assemble(A)
class CustomSolver(NewtonSolver):
def __init__(self, u):
self.u = u
NewtonSolver.__init__(self)
def update_solution(self, x, dx, relaxation, problem, k):
x.axpy(-1.0, dx)
plot(self.u)
interactive()
# Create mesh and define function space
mesh = UnitSquareMesh(32, 32)
V = FunctionSpace(mesh, "CG", 1)
# Define boundary condition
g = Constant(1.0)
bc = DirichletBC(V, g, "on_boundary")
# Define variational problem
u = Function(V)
v = TestFunction(V)
f = Constant(10.0)
F = inner((1 + u**2)*grad(u), grad(v))*dx - f*v*dx
J = derivative(F, u)
problem = Problem(J, F, [bc])
solver = CustomSolver(u)
solver.solve(problem, u.vector())
# Plot solution and solution gradient
plot(u, title="Solution")
interactive()