yixuan / RSpectra

R Interface to the Spectra Library for Large Scale Eigenvalue and SVD Problems
http://cran.r-project.org/package=RSpectra
80 stars 12 forks source link

Symmetric sparse matrices #24

Open dswatson opened 2 months ago

dswatson commented 2 months ago

Thanks for this great package! Was wondering if you could help with a issue.

The documentation suggests that eigs_sym() should be able to handle sparse matrix input, but there appears to be some subtleties to handling sparsity in symmetric matrices. Specifically, I get an error when I run this code:

# Create sparse, symmetric matrix
library(Matrix)
set.seed(1)
n <- 4
M <- matrix(0, nrow = n, ncol = n)
M[sample(n, 2), sample(n, 2)] <- rnorm(n)
A <- crossprod(M)
A <- as(A, 'sparseMatrix') # Note the class of A is dsCMatrix

# This works
e <- eigs(A, k = 2)

# This does not
e <- eigs_sym(A, k = 2)

The last line generates the following error:

Error in UseMethod("eigs_sym") : 
  no applicable method for 'eigs_sym' applied to an object of class "c('dsCMatrix', 'CsparseMatrix', 'dsparseMatrix', 'symmetricMatrix', 'dMatrix', 'sparseMatrix', 'Matrix')"

Interestingly, I do not get the same error when passing a dgeMatrix to eigs_sym. Hopefully this is an easy fix?

yixuan commented 2 months ago

Yeah, this is actually a design choice. eigs() tries to automatically detect the type of the matrix, and if it is dsCMatrix/dsRMatrix/dsyMatrix, it will directly call the symmetric solver. On the other hand, eigs_sym() in some sense "forces" the symmetry of the matrix, so I did not let it work on matrices that are already symmetric.

dswatson commented 2 months ago

That makes sense, thanks! Resolves my issue. Perhaps this could be a bit clearer in the documenation? Or maybe instead of an error, eigs_sym() could just run eigs() internally when the input is of class dsCMatrix?

yixuan commented 2 months ago

Yeah, good suggestion. This is actually documented in the help, but I agree that it can be made clearer.

image

I may change it in the next release.