Getting the number of iterations of scipy's gmres iterative method
Asked Answered
M

1

5

I want to know how many iterations scipy.sparse.linalg.gmres is taking to converge, but there doesn't seem to be an argument for that. There is a maxiter argument that one could set to terminate the method, but nothing that shows the number of iterations it's taking. Can someone help me with this?

Mclin answered 4/11, 2015 at 1:14 Comment(2)
Usually, this is not something people care about. You can use the callback argument to give a function that counts the cycles for you, though.Uncommitted
Possible duplicate of Retrieving number of iterations that ran for sparse linear solver in SciPyJarman
J
7

To illustrate @cel's comment, you could implement a simple counter class like this:

class gmres_counter(object):
    def __init__(self, disp=True):
        self._disp = disp
        self.niter = 0
    def __call__(self, rk=None):
        self.niter += 1
        if self._disp:
            print('iter %3i\trk = %s' % (self.niter, str(rk)))

You would use it like this:

import numpy as np
from scipy.sparse.linalg import gmres

A = np.random.randn(10, 10)
b = np.random.randn(10)

counter = gmres_counter()

x, info = gmres(A, b, callback=counter)
# iter   1        rk = 0.999558746968
# iter   2        rk = 0.960490282387
# iter   3        rk = 0.945887432101
# iter   4        rk = 0.931790454216
# iter   5        rk = 0.877655067142
# iter   6        rk = 0.739596963239
# iter   7        rk = 0.677886023198
# iter   8        rk = 0.52015135005
# iter   9        rk = 0.168298366785
# iter  10        rk = 9.22692033803e-16

print(counter.niter)
# 10
Jarman answered 5/11, 2015 at 2:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.