Using Armadillo with SuperLU
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Armadillo is very versatile C++ library for linear algebra, brough to R via the RcppArmadillo package. It has proven to be very useful and popular, and is (as of February 2017) used by well over 300 CRAN packages as indicated by the reverse depends / linking-to on its CRAN page. Several earlier posts here on the Rcpp Gallery also demonstrate different usage patterns.
Armadillo has a core focus on dense matrices, but continues to expand its capabilities for sparse matrices. Basic operation are supported directly via the templated header files, along with calls back into the default (dense) LAPACK and BLAS libraries we can access easily as R uses them.
Armadillo also supports dedicated sparse solvers via the
SuperLU package. However, this requires access to
the SuperLU library. Many Linux distributions ship
it, see e.g. the Debian package page and the
Ubuntu package page; there is also a
homebrew recipe for OS X /
macOS (or other systems using brew
). As of this writing, the version in the current Ubuntu
release is behind the version Debian. But it is the 5.2.* version that is in Debian that is also
required with current Armadillo versions 7.700.* so we prepared ‘backports’ via
Dirk’s PPA repo.)
Recently, a GitHub issue ticket asked how to use SuperLU along with RcppArmadillo. This post essentially repeats the main answer, which was spread out over multiple posts, in a single article.
In a nutshell, two things need to happen:
-
One needs to define the required variable
ARMA_USE_SUPERLU
which has to be done before the Armadillo headers are included. One possibility (shown below) is a#define
statement right in the code file. -
One needs to tell the linker to use the SuperLU library. This step is of course not perfectly portable, and does require that the library be installed. (A genuinely portable solution would either need to test for presence of SuperLU, or include its sources. Both aspects are beyond the scope of this post._
Now that R knows about this library, we can present the code requiring it:
This code snippet defines a function superLuDemo()
which we can call from R:
Done.
As the data generated here is random, we did not bother printing the (dense) result vector of length 1000.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.