I've got linear system to solve which consists of large, sparse matrices.
I've been using the scipy.sparse
library, and its linalg
sub-library to do this, but I can't get some of the linear solvers to work.
Here is a working example which reproduces the issue for me:
from numpy.random import random
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import spsolve, minres
N = 10
A = csc_matrix( random(size = (N,N)) )
A = (A.T).dot(A) # force the matrix to be symmetric, as required by minres
x = csc_matrix( random(size = (N,1)) ) # create a solution vector
b = A.dot(x) # create the RHS vector
# verify shapes and types are correct
print('A', A.shape, type(A))
print('x', x.shape, type(x))
print('b', b.shape, type(b))
# spsolve function works fine
sol1 = spsolve(A, b)
# other solvers throw a incompatible dimensions ValueError
sol2 = minres(A, b)
Running this produces the following error
raise ValueError('A and b have incompatible dimensions')
ValueError: A and b have incompatible dimensions
for the call to minres
, even though the dimensions clearly are compatible. Other solvers in scipy.sparse.linalg
, such as cg
, lsqr
and gmres
all throw an identical error.
This is being run on python 3.6.1 with SciPy 0.19.
Anyone have any idea what's going on here?
Thanks!
The Sparse Solvers library in the Accelerate framework handles the solution of systems of equations where the coefficient matrix is sparse. That is, most of the entries in the matrix are zero. The Sparse Solvers library provides a sparse counterpart to the dense factorizations and linear solvers that LAPACK provides.
The linalg. solve function is used to solve the given linear equations. It is used to evaluate the equations automatically and find the values of the unknown variables.
A sparse matrix is a matrix that is comprised of mostly zero values. Sparse matrices are distinct from matrices with mostly non-zero values, which are referred to as dense matrices. A matrix is sparse if many of its coefficients are zero.
Your usage is incompatible with the API!
spsolve on b
:
b : ndarray or sparse matrix
The matrix or vector representing the right hand side of the equation. If a vector, b.shape must be (n,) or (n, 1).
sparse b is allowed
minres on b
:
b : {array, matrix}
Right hand side of the linear system. Has shape (N,) or (N,1).
sparse b is not allowed here!
The same applies to the mentioned non-working solvers (where lsqr might be a bit different -> array_like vs. array).
This is not that uncommon as sparse rhs-vectors are not helping in many cases and a lot of numerical-optimization devs therefore drop support!
This works:
sol2 = minres(A, b.todense())
(you got my upvote and praise for the nice reproducible example!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With