Search code examples
pythonscipylinear-algebraeigenvalue

scipy.sparse.linalg.eigs fails with abstract linear operator


The above mentioned function fails when I use an abstract / black-box linear operator. Here's a minimal example:

import numpy as np
import scipy.sparse.linalg as la

# Just generate an n X n matrix
n = 9
a = np.random.normal( size = n * n )
a = a.reshape( (n,n) )

# A is a black-box linear operator
def A(v):
    global a   
    return np.dot( a, v )

# If you don't define a shpae for A you get an error
A.shape = ( n,n )

# This works
success = la.eigs( a )

# This throws an error.
failure = la.eigs( A )    

This happens for python 3.2.2 with scipy 0.13.3 as well as for python 2.7.3 with scipy 0.16.0.

Error message:

File "/home/daon/.local/lib/python2.7/site-packages/scipy/sparse/linalg/eigen/arpack/arpack.py", line 1227, in eigs
    matvec = _aslinearoperator_with_dtype(A).matvec
  File "/home/daon/.local/lib/python2.7/site-packages/scipy/sparse/linalg/eigen/arpack/arpack.py", line 885, in _aslinearoperator_with_dtype
    m = aslinearoperator(m)
  File "/home/daon/.local/lib/python2.7/site-packages/scipy/sparse/linalg/interface.py", line 682, in aslinearoperator
    raise TypeError('type not understood')
 TypeError: type not understood

Solution

  • OK, this is embarassing: just define A differently:

    def f(v):
        global a   
        return np.dot( a, v )
    
    A = la.LinearOperator( a.shape, f )
    

    this makes everything work just fine.