Expand description
Linear algebra: sparse matrices, eigensolvers (ARPACK, LAPACK), BLAS helpers and spectral embeddings of graphs.
This module covers six igraph C headers:
| C header | Rust | What it offers |
|---|---|---|
igraph_sparsemat.h | SparseMat, SparseLu, SparseQr, SparseMatIter | Owned sparse matrices (CXSparse), triplet and column-compressed formats, arithmetic, triangular/LU/QR/Cholesky solvers, ARPACK on sparse matrices |
igraph_arpack.h | arpack_rssolve, arpack_rnsolve, ArpackOptions, ArpackStorage | Matrix-free eigensolvers driven by a Rust closure computing y = A x |
igraph_eigen.h | eigen_matrix_symmetric, eigen_matrix, Graph::eigen_adjacency | A unified front-end choosing between LAPACK and ARPACK |
igraph_lapack.h | lapack_dgesv, lapack_dgetrf, lapack_dgetrs, lapack_dsyevr, lapack_dgeev, lapack_dgeevx, lapack_dgehrd | Dense linear systems and eigenproblems |
igraph_blas.h | blas_dgemv, blas_dgemv_array, blas_dgemm, blas_ddot, blas_dnrm2 | Dense matrix products, dot products and norms |
igraph_embedding.h | Graph::adjacency_spectral_embedding, Graph::laplacian_spectral_embedding, dim_select | Spectral embeddings of graphs and dimensionality selection |
Dense matrices are the crate’s Matrix (column-major, like
igraph and LAPACK); vectors are plain Rust slices and Vecs. Complex numbers
are Complex (igraph’s igraph_complex_t, with re and
im accessors).
§Safety net around the C library
The C routines wrapped here trust their callers a lot: a wrong vector length
reads out of bounds, and an invalid argument handed to the bundled LAPACK
or BLAS makes it terminate the process. The wrappers therefore validate
every dimension, index and range on the Rust side and report problems as
ErrorKind::InvalidValue errors; a few
igraph quirks (present in both igraph 1.0.0 and 1.0.1: the linear algebra
sources did not change in 1.0.1) are worked around and documented on the
affected functions (e.g. SparseMat::transpose of non-square triplet matrices,
SparseMat::max, blas_dgemm with beta != 0, 2 × 2 problems in
arpack_rssolve). One cannot be worked around: the last ARPACK error
is a process-wide C variable, so arpack_last_error is unsafe; use
the thread-safe ArpackError::from_error instead.
igraph’s ARPACK is not re-entrant (its iteration state lives in
thread-local statics): every ARPACK-based function of the crate (those of
this module, and eigenvector centrality, hub and authority scores,
eigenvector centralization, PageRank with the ARPACK algorithm and
leading eigenvector communities) refuses to run nested inside another
ARPACK run on the same thread (from its matrix-vector closure, or from a
progress or interruption handler called by it), with an
ErrorKind::Failure error (see
arpack_rssolve). Also note that ARPACK starts from A v0, not from
the start vector v0: null vectors of singular operators can be missed,
shift the operator instead (see arpack_rssolve).
igraph_arpack_options_get_default is not wrapped: it hands out a mutable
pointer to igraph’s shared default options; use
ArpackOptions::default() (igraph_arpack_options_init)
instead.
§Related functionality in other modules
| Need | Where |
|---|---|
| Adjacency matrix of a graph, dense or sparse | Graph::get_adjacency, Graph::get_adjacency_sparse (conversion) |
| Laplacian matrix of a graph, dense or as triplets | Graph::get_laplacian, Graph::get_laplacian_sparse (structural) |
| Stochastic (random-walk) matrix | Graph::get_stochastic, Graph::get_stochastic_sparse (conversion) |
| A graph from a (sparse) adjacency matrix | Graph::adjacency, Graph::sparse_adjacency, Graph::sparse_weighted_adjacency (constructors) |
| Spectral centralities (ARPACK/PRPACK inside) | Graph::eigenvector_centrality, Graph::hub_and_authority_scores, Graph::pagerank (centrality) |
| Spectral community detection | Graph::community_leading_eigenvector (community) |
| Spectral layouts | Graph::layout_mds (layout) |
| Seeding the random start vectors of ARPACK | rng::seed (per thread) |
§Example: the spectrum of a path graph
The Laplacian of the path on n vertices has eigenvalues
2 - 2 cos(pi k / n), k = 0, ..., n - 1. Here we take it from the
structural module as sparse triplets, load it into a SparseMat,
compute its two largest eigenvalues with ARPACK and check the smallest
one with a dense LAPACK solver.
use igraph::linalg::*;
use igraph::prelude::*;
use igraph::structural::LaplacianNormalization;
use std::f64::consts::PI;
let n = 10;
let path = Graph::ring(n, false, false, false).unwrap();
let triplets: Vec<(usize, usize, f64)> = path
.get_laplacian_sparse(NeighborMode::All, LaplacianNormalization::Unnormalized, None)
.unwrap()
.into_iter()
.map(|(i, j, x)| (i as usize, j as usize, x))
.collect();
let lap = SparseMat::from_triplets(n, n, &triplets).unwrap().compress().unwrap();
assert!(lap.is_symmetric().unwrap());
// ARPACK, largest algebraic eigenvalues (the random start vector comes
// from this thread's igraph RNG: seed it for reproducible iterations).
rng::seed(42).unwrap();
let opts = ArpackOptions::default().with_nev(2).with_which(ArpackWhich::LargestAlgebraic);
let top = lap.arpack_rssolve(&opts, SparseSolveMethod::Lu).unwrap();
for (k, value) in top.values.iter().enumerate() {
let expected = 2.0 - 2.0 * (PI * (n - 1 - k) as f64 / n as f64).cos();
assert!((value - expected).abs() < 1e-8);
}
// LAPACK on the dense copy: the smallest eigenvalue is 0.
let dense = lap.to_dense().unwrap();
let low = lapack_dsyevr(&dense, &SymmetricRange::Select(0..1), 1e-12).unwrap();
assert!(low.values[0].abs() < 1e-10);Structs§
- Arpack
Info - Statistics reported by ARPACK after a successful run (the output fields
of
igraph_arpack_options_t). - Arpack
NonSymmetric Result - Result of the non-symmetric ARPACK solvers.
- Arpack
Options - Options of the ARPACK eigensolvers (a safe subset of
igraph_arpack_options_t). - Arpack
Storage - Preallocated working memory for repeated ARPACK runs
(
igraph_arpack_storage_t), freed on drop (igraph_arpack_storage_destroy). - Arpack
Symmetric Result - Result of the symmetric ARPACK solvers.
- Complex
Eigen - Eigenvalues and eigenvectors of a general real matrix.
- Dgeev
Result - Eigenvalues and eigenvectors of a general real matrix computed by
lapack_dgeev, in LAPACK’s packed real format. - Dgeevx
Result - Output of
lapack_dgeevx. - Dgesv
Result - The solution of a linear system computed by
lapack_dgesv. - Dsyevr
Result - Eigenvalues and eigenvectors computed by
lapack_dsyevr. - LuFactors
- An LU factorization
A = P L Ucomputed bylapack_dgetrf. - Sparse
Elements - The elements of a sparse matrix as returned by
SparseMat::getelements(the raw CXSparse arrays). - Sparse
Lu - A sparse LU factorization, see
SparseMat::lu. It owns igraph’s symbolic and numeric decompositions and frees them on drop (igraph_sparsemat_symbolic_destroy,igraph_sparsemat_numeric_destroy). - Sparse
MatIter - Iterator over the stored entries of a
SparseMat, seeSparseMat::iter. - Sparse
Qr - A sparse QR factorization of a square matrix, see
SparseMat::qr. - Spectral
Embedding - A spectral embedding of the vertices of a graph.
- Symmetric
Eigen - Eigenvalues and eigenvectors of a real symmetric matrix.
Enums§
- Arpack
Error - Error conditions reported by ARPACK (
igraph_arpack_error_t), seeArpackError::from_errorandarpack_error_to_string. - Arpack
Mode - The kind of eigenproblem ARPACK solves (the
modefield ofigraph_arpack_options_t). - Arpack
Which - Which eigenvalues ARPACK should compute (the
whichfield ofigraph_arpack_options_t). - Dgeevx
Balance - Balancing performed by
lapack_dgeevx(igraph_lapack_dgeevx_balance_t). - Eigen
Algorithm - Which numerical library
eigen_matrix_symmetric,eigen_matrixandGraph::eigen_adjacencyuse (igraph_eigen_algorithm_t). - Eigen
Which - Which eigenvalues to compute (
igraph_eigen_which_t). - Embedding
Which - Which eigenvalues (singular values for directed graphs) the spectral
embeddings use (the admissible subset of
igraph_eigen_which_position_t). - Laplacian
Embedding Type - The Laplacian used by
Graph::laplacian_spectral_embedding(igraph_laplacian_spectral_embedding_type_t).Dis the degree (strength) matrix,Athe adjacency matrix. - Sparse
MatType - Storage format of a
SparseMat(igraph_sparsemat_type_t). - Sparse
Ordering - Fill-reducing ordering used by the sparse factorizations
(
SparseMat::cholsol,SparseMat::lusol,SparseMat::lu,SparseMat::qr); the integerorderargument of the C functions. - Sparse
Solve Method - How the linear systems of the shift-and-invert mode of
SparseMat::arpack_rssolveare solved (igraph_sparsemat_solve_t). - Symmetric
Range - Which eigenvalues
lapack_dsyevrcomputes (igraph_lapack_dsyev_which_tplus its parameters).
Functions§
- arpack_
error_ to_ string - Human readable description of an ARPACK error code
(
igraph_arpack_error_to_string). - arpack_
last_ ⚠error - The error code of the last ARPACK failure in the process
(
igraph_arpack_get_last_error). - arpack_
rnsolve - Eigenvalues and eigenvectors of a general (non-symmetric) linear
operator given as a Rust closure, with ARPACK’s implicitly restarted
Arnoldi method (
igraph_arpack_rnsolve). - arpack_
rssolve - Eigenvalues and eigenvectors of a symmetric linear operator given as
a Rust closure, with ARPACK’s implicitly restarted Lanczos method
(
igraph_arpack_rssolve). - arpack_
unpack_ complex - Rewrites the packed output of the non-symmetric ARPACK solver into a
regular form (
igraph_arpack_unpack_complex). - blas_
ddot - Dot product of two vectors of the same length (
igraph_blas_ddot). - blas_
dgemm - Matrix-matrix product
alpha * op(A) * op(B) + beta * C, whereop(X)isXor its transpose (igraph_blas_dgemm).cmay beNonewhenbetais zero (or to mean a zero matrix). - blas_
dgemv - Matrix-vector product
alpha * op(A) * x + beta * y, whereop(A)isAor its transpose (igraph_blas_dgemv); the result is returned as a new vector. Whenbetais zero,yonly provides the length. - blas_
dgemv_ array - In-place matrix-vector product
y <- alpha * op(A) * x + beta * yon plain slices (igraph_blas_dgemv_array). - blas_
dnrm2 - Euclidean norm of a vector (
igraph_blas_dnrm2), computed without undue overflow or underflow. - dense_
multiply - The dense product
a * bof a dense matrix with a sparse one (igraph_sparsemat_dense_multiply). - dim_
select - Dimensionality selection by profile likelihood (
igraph_dim_select). - eigen_
matrix - Selected eigenvalues and eigenvectors of a general real dense matrix
(
igraph_eigen_matrix); onlyEigenAlgorithm::Lapackis implemented by igraph 1.0.0 and 1.0.1. - eigen_
matrix_ symmetric - Selected eigenvalues and eigenvectors of a real symmetric dense
matrix (
igraph_eigen_matrix_symmetric), with LAPACK or ARPACK. - eigen_
symmetric_ fn - Selected eigenvalues and eigenvectors of a real symmetric operator
given by a matrix-vector product closure (
igraph_eigen_matrix_symmetricwith a callback), seearpack_rssolvefor the closure contract. With LAPACK the matrix is first formed by applying the closure to the unit vectors. - lapack_
dgeev - Eigenvalues and, optionally, left and/or right eigenvectors of a general
real square matrix (
igraph_lapack_dgeev). The eigenvectors are normalized to unit Euclidean norm with largest component real. - lapack_
dgeevx - Eigenvalues and left and right eigenvectors of a general real matrix,
“expert” version (
igraph_lapack_dgeevx): it also balances the matrix (seeDgeevxBalance) and computes reciprocal condition numbers of the eigenvalues. - lapack_
dgehrd - Reduces a general square matrix to upper Hessenberg form by an
orthogonal similarity transformation (
igraph_lapack_dgehrd): the resultH = Q' A Qhas zeros below the first subdiagonal and the same eigenvalues asA. - lapack_
dgesv - Solves the linear system
A X = Bfor a squareAand one or more right hand sides (the columns ofB), by LU decomposition with partial pivoting (igraph_lapack_dgesv). - lapack_
dgetrf - LU factorization with partial pivoting of a general
m×nmatrix,A = P L U(igraph_lapack_dgetrf), whereLis lower triangular (trapezoidal ifm > n) with unit diagonal andUis upper triangular (trapezoidal ifm < n). - lapack_
dgetrs - Solves
A X = BorA' X = B(transpose) using the LU factors of a squareAcomputed bylapack_dgetrf(igraph_lapack_dgetrs). No check is made for singularity. - lapack_
dsyevr - Selected eigenvalues and eigenvectors of a real symmetric matrix, with
LAPACK’s relatively robust representations algorithm
(
igraph_lapack_dsyevr). Only the upper triangle ofais used. - solve
- Solves
A x = bfor a single right hand side (vialapack_dgesv).
Type Aliases§
- Complex
- A complex number (
igraph_complex_t), withreandimaccessors andComplex::new. - Sparse
Mat - An owned sparse matrix of reals (
igraph_sparsemat_t), backed by the CXSparse library bundled with igraph.