Return relative residual from Newton solver

Hello,

I currently have a custom Newton solver as designed following: Set krylov linear solver paramters in newton solver - #3 by nate,

If i need to access the relative residual after each (converged) newton iteration in python as a variable, how does one go about achieving this?

I have tried inspecting the returned values from the solver call:

r = newton_solver.solve(nonlinear_problem, u.vector())
print(r) 

Which gives me (1, True) each time (The True I assumed being whether the solver converged or not. Not entirely sure what the ‘1’ is). Is there a way I could access the relative residual in this way, e.g. something like
r = newton_solver.get_relative_residual()?

Thanks,

You can overwrite dolfin::nls::NewtonSolver::converged. E.g. modify the CustomSolver in your link with the following

class CustomSolver(NewtonSolver):
    def __init__(self):
        NewtonSolver.__init__(self, mesh.mpi_comm(),
                              PETScKrylovSolver(), PETScFactory.instance())

    def solver_setup(self, A, P, problem, iteration):
        self.linear_solver().set_operator(A)

        PETScOptions.set("ksp_type", "gmres")
        PETScOptions.set("ksp_monitor")
        PETScOptions.set("pc_type", "ilu")

        self.linear_solver().set_from_options()

    def converged(self, r, problem, iteration):
        if iteration == 0:
            self.r0 = r.norm("l2")
        print(f"Iteration {iteration}, relative residual {r.norm('l2')/self.r0:.6e}")
        return super().converged(r, problem, iteration)
2 Likes