Mustafa Alhussain
Mustafa Alhussain

Reputation: 11

How can I count number of iterations that ran for sparse linear solver in SciPy

I'm trying to use scipy.sparse.linalg.cg to solve linear system. I want to know how many iteration ran to achieve the specific tolerance?

Upvotes: 1

Views: 741

Answers (2)

Brian Knight
Brian Knight

Reputation: 11

scipy.sparse.linalg.cg takes a optional argument of callback, which evaluates at each iteration of the conjugate gradient algorithm and takes the current vector as an argument. By using a nonlocal variable reference you can extract the total number of iterations as follows

iters = 0

def nonlocal_iterate(arr):
    nonlocal iters
    iters+=1

x, info = scipy.sparse.linalg.cg(A, b, callback=nonlocal_iterate)

Upvotes: 1

Léonard
Léonard

Reputation: 2630

So far, there is not way you can get this value explicitly. From the Conjugate Gradient documentation of Scipy, it is mentioned that the output of the function comes with the solution and with an integer info, where you can only know the number of iteration when the convergence to tolerance was not achieved:

0 : successful exit

>0 : convergence to tolerance not achieved, number of iterations

<0 : illegal input or breakdown

A solution would be to increase the tolerance (or max number of iteration) until the convergence is reached and the function returns 0 for the info variable.

Upvotes: 0

Related Questions