Callbacks on Newton solver

Hi, I’m fairly new to FEniCS and just implemented my first non-trivial solver involving a coupled Navier-Stokes system. I’d like to get some insight into the numerics of newton iterations; e.g. check the condition number or examine the structure of the matrix at each iteration. Is there a way to set some kind of callback on the NewtonSolver and/or the NonlinearSolver?

You can create a custom nonlinear problem instance that allows arbitrary code to execute while forming the residual and/or Jacobian. See the following example:

from dolfin import *

mesh = UnitSquareMesh(10,10)
V = FunctionSpace(mesh,"Lagrange",1)
u = Function(V)
v = TestFunction(V)
x = SpatialCoordinate(mesh)
f = x[0]*x[1]
res = (1.0+u*u)*inner(grad(u),grad(v))*dx + inner(u,v)*dx - inner(f,v)*dx
Dres = derivative(res,u)

class CustomNonlinearProblem(NonlinearProblem):
    def F(self,b,x):

        #########################################
        print("Executing arbitrary Python code.")
        #########################################
        
        return assemble(res,tensor=b)
    def J(self,A,x):
        return assemble(Dres,tensor=A)

problem = CustomNonlinearProblem()
solver = PETScSNESSolver()
solver.solve(problem,u.vector())

I just wanted to add that, to me, it feels wrong to define res and Dres globally and then use those global variables in the CustomNonlinearProblem class.
Just for - in my opinion - cleaner code I would set the linear and bilinear forms as attributes supplied to the __init__ method as done here:

For this kind of reply I would really like to have something like a comment function as known from stackoverflow…

Thank you both, this is helpful appears promising. One detail I wasn’t clear on is that I’m currently using NonlinearVariationalProblem and NonlinearVariationalSolver, neither of which provides as many points for overriding/extension. That said, from your example it seems I could just as easily have formulated my problem in terms of NonlinearProblem and NonlinearSolver. What exactly is the relationship between these classes and their Variational counterparts?

I think the “variational” versions are just intended as a convenience for the most common case.