Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the number of iterations of scipy's gmres iterative method

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?

like image 247
Sam K Avatar asked Nov 04 '15 01:11

Sam K


1 Answers

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
like image 82
ali_m Avatar answered Sep 20 '22 03:09

ali_m