russell_sparse/
lib.rs

1//! Russell - Rust Scientific Library
2//!
3//! `russell_sparse`: Solvers for large sparse linear systems (wraps MUMPS and UMFPACK)
4//!
5//! **Important:** This crate depends on external libraries (non-Rust). Thus, please check the [Installation Instructions on the GitHub Repository](https://github.com/cpmech/russell).
6//!
7//! # Introduction
8//!
9//! This crate implements three storage formats for sparse matrices (see the figure below):
10//!
11//! * [NumCooMatrix] (COO) -- COOrdinates matrix, also known as a sparse triplet.
12//! * [NumCscMatrix] (CSC) -- Compressed Sparse Column matrix
13//! * [NumCsrMatrix] (CSR) -- Compressed Sparse Row matrix
14//!
15//! ![Sparse-Matrix](https://raw.githubusercontent.com/cpmech/russell/main/russell_sparse/data/figures/sparse-matrix.svg)
16//!
17//! Additionally, to unify the handling of the above data structures, the library implements:
18//!
19//! * [NumSparseMatrix] -- Either a COO, CSC, or CSR matrix. We recommend using `NumSparseMatrix` solely, if possible.
20//!
21//! For convenience, this crate defines the following type aliases for Real and Complex matrices (with double precision):
22//!
23//! * [CooMatrix], [CscMatrix], [CsrMatrix], [SparseMatrix] -- For real numbers represented by `f64`
24//! * [ComplexCooMatrix], [ComplexCscMatrix], [ComplexCsrMatrix], [ComplexSparseMatrix] -- For complex numbers represented by [russell_lab::Complex64]
25//!
26//! The COO matrix is the best when we need to update the values of the matrix because it has easy access to the triples (i, j, aij). For instance, the repetitive access is the primary use case for codes based on the finite element method (FEM) for approximating partial differential equations. Moreover, the COO matrix allows storing duplicate entries; for example, the triple `(0, 0, 123.0)` can be stored as two triples `(0, 0, 100.0)` and `(0, 0, 23.0)`. Again, this is the primary need for FEM codes because of the so-called assembly process where elements add to the same positions in the "global stiffness" matrix. Nonetheless, the duplicate entries must be summed up at some stage for the linear solver (e.g., MUMPS, UMFPACK). These linear solvers also use the more memory-efficient storage formats CSC and CSR. The following is the default input for these solvers:
27//!
28//! * [MUMPS](https://mumps-solver.org) -- requires a COO matrix as input internally
29//! * [UMFPACK](https://github.com/DrTimothyAldenDavis/SuiteSparse) -- requires a CSC matrix as input internally
30//!
31//! Nonetheless, the implemented interface to the above linear solvers takes a [SparseMatrix] as input, which will automatically be converted from COO to CSC or COO to CSR, as appropriate.
32//!
33//! The best way to use a COO matrix is to initialize it with the maximum possible number of non-zero values and repetitively call the [CooMatrix::put()] function to insert triples (i, j, aij) into the data structure. This procedure is computationally efficient. Later, we can create a Compressed Sparse Column (CSC) or a Compressed Sparse Row (CSC) matrix from the COO matrix. The CSC and CSR will sum up any duplicates in the COO matrix during the conversion process. To reinitialize the counter for "putting" entries into the triplet structure, we can call the [CooMatrix::reset()] function (e.g., to recreate the global stiffness matrix in FEM simulations).
34//!
35//! The three individual sparse matrix structures ([CooMatrix], [CscMatrix], and [CsrMatrix]) and the wrapping (unifying) structure SparseMatrix have functions to calculate the (sparse) matrix-vector product, which, albeit not computer optimized, are convenient for checking the solution to the linear problem A * x = b (see also the VerifyLinSys structure).
36//!
37//! We recommend using the [SparseMatrix] directly unless your computations need a more specialized interaction with the CSC or CSR formats. Also, the [SparseMatrix] returns "pointers" to the CSC and CSR structures (constant access and mutable access).
38//!
39//! We call the actual linear system solver implementation [Genie] because they work like "magic" after being "wrapped" via a C-interface. Note that these fantastic solvers are implemented in Fortran and C. You may easily access the linear solvers directly via the following structures:
40//!
41//! * [SolverMUMPS] -- thin wrapper to the MUMPS solver
42//! * [SolverUMFPACK] -- thin wrapper to the UMFPACK solver
43//!
44//! This library also provides a unifying Trait called [LinSolTrait], which the above structures implement. In addition, the [LinSolver] structure holds a "pointer" to one of the above structures and is a more convenient way to use the linear solvers in generic codes when we need to switch from solver to solver (e.g., for benchmarking). After allocating a [LinSolver], if needed, we can access the actual implementations (interfaces/thin wrappers) via the [LinSolver::actual] data member.
45//!
46//! The [LinSolTrait] has two main functions (that should be called in this order):
47//!
48//! * [LinSolTrait::factorize()] -- performs the initialization of the linear solver, if needed, analysis, and symbolic and numerical factorization of the coefficient matrix A from A * x = b
49//! * [LinSolTrait::solve()] -- find x from the linear system A * x = b after completing the factorization.
50//!
51//! If the **structure** of the coefficient matrix remains constant, but its values change during a simulation, we can repeatedly call `factorize` again to perform the factorization. However, if the structure changes, the solver must be **dropped** and another solver allocated to force the **initialization** process.
52//!
53//! We call the **structure** of the coefficient matrix A from A * x = b the set with the following characteristics:
54//!
55//! * `nrow` -- number of rows
56//! * `ncol` -- number of columns
57//! * `nnz` -- number of non-zero values
58//! * `symmetric` -- the [Sym] type
59//! * the locations of the non-zero values
60//!
61//! If neither the structure nor the values of the coefficient matrix change, we can call `solve` repeatedly if needed (e.g., in a simulation of linear dynamics using the FEM).
62//!
63//! The linear solvers have numerous configuration parameters; however, we can use the default parameters initially. The configuration parameters are collected in the [LinSolParams] structures, which is an input to the [LinSolTrait::factorize()]. The parameters include options such as [Ordering] and [Scaling].
64//!
65//! This library also provides functions to read and write Matrix Market files containing (huge) sparse matrices that can be used in performance benchmarking or other studies. The [read_matrix_market()] function reads a Matrix Market file and returns a [CooMatrix]. To write a Matrix Market file, we can use [CscMatrix::write_matrix_market()] (and similar), which automatically converts COO to CSC or COO to CSR, also performing the sum of duplicates. The `write_matrix_market` can also writs an SMAT file (almost like the Matrix Market format) without the header and with zero-based indices. The SMAT file can be given to the fantastic [Vismatrix](https://github.com/cpmech/vismatrix) tool to visualize the sparse matrix structure and values interactively; see the example below.
66//!
67//! ![doc-example-vismatrix](https://raw.githubusercontent.com/cpmech/russell/main/russell_sparse/data/figures/doc-example-vismatrix.png)
68//!
69//! # Examples
70//!
71//! ## Create CSR matrix from COO
72//!
73//! ```
74//! use russell_sparse::prelude::*;
75//! use russell_sparse::StrError;
76//!
77//! fn main() -> Result<(), StrError> {
78//!     // allocate a square matrix and store as COO matrix
79//!     // ┌          ┐
80//!     // │  1  0  2 │
81//!     // │  0  0  3 │
82//!     // │  4  5  6 │
83//!     // └          ┘
84//!     let (nrow, ncol, nnz) = (3, 3, 6);
85//!     let mut coo = CooMatrix::new(nrow, ncol, nnz, Sym::No)?;
86//!     coo.put(0, 0, 1.0)?;
87//!     coo.put(0, 2, 2.0)?;
88//!     coo.put(1, 2, 3.0)?;
89//!     coo.put(2, 0, 4.0)?;
90//!     coo.put(2, 1, 5.0)?;
91//!     coo.put(2, 2, 6.0)?;
92//!
93//!     // convert to CCR matrix
94//!     let csc = CscMatrix::from_coo(&coo)?;
95//!     let correct_v = &[
96//!         //                               p
97//!         1.0, 4.0, //      j = 0, count = 0, 1
98//!         5.0, //           j = 1, count = 2
99//!         2.0, 3.0, 6.0, // j = 2, count = 3, 4, 5
100//!              //                  count = 6
101//!     ];
102//!     let correct_i = &[
103//!         //                         p
104//!         0, 2, //    j = 0, count = 0, 1
105//!         2, //       j = 1, count = 2
106//!         0, 1, 2, // j = 2, count = 3, 4, 5
107//!            //              count = 6
108//!     ];
109//!     let correct_p = &[0, 2, 3, 6];
110//!
111//!     // check
112//!     assert_eq!(csc.get_col_pointers(), correct_p);
113//!     assert_eq!(csc.get_row_indices(), correct_i);
114//!     assert_eq!(csc.get_values(), correct_v);
115//!     Ok(())
116//! }
117//! ```
118//!
119//! ## Solving a tiny sparse linear system using LinSolver (Umfpack)
120//!
121//! ```
122//! use russell_lab::{vec_approx_eq, Vector};
123//! use russell_sparse::prelude::*;
124//! use russell_sparse::StrError;
125//!
126//! fn main() -> Result<(), StrError> {
127//!     // constants
128//!     let ndim = 3; // number of rows = number of columns
129//!     let nnz = 5; // number of non-zero values
130//!
131//!     // allocate the linear solver
132//!     let mut solver = LinSolver::new(Genie::Umfpack)?;
133//!
134//!     // allocate the coefficient matrix
135//!     let mut coo = CooMatrix::new(ndim, ndim, nnz, Sym::No)?;
136//!     coo.put(0, 0, 0.2)?;
137//!     coo.put(0, 1, 0.2)?;
138//!     coo.put(1, 0, 0.5)?;
139//!     coo.put(1, 1, -0.25)?;
140//!     coo.put(2, 2, 0.25)?;
141//!
142//!     // print matrix
143//!     let mut a = coo.as_dense();
144//!     let correct = "┌                   ┐\n\
145//!                    │   0.2   0.2     0 │\n\
146//!                    │   0.5 -0.25     0 │\n\
147//!                    │     0     0  0.25 │\n\
148//!                    └                   ┘";
149//!     assert_eq!(format!("{}", a), correct);
150//!
151//!     // call factorize
152//!     solver.actual.factorize(&coo, None)?;
153//!
154//!     // allocate two right-hand side vectors
155//!     let rhs1 = Vector::from(&[1.0, 1.0, 1.0]);
156//!     let rhs2 = Vector::from(&[2.0, 2.0, 2.0]);
157//!
158//!     // calculate the solution
159//!     let mut x1 = Vector::new(ndim);
160//!     solver.actual.solve(&mut x1, &rhs1, false)?;
161//!     let correct = vec![3.0, 2.0, 4.0];
162//!     vec_approx_eq(&x1, &correct, 1e-14);
163//!
164//!     // calculate the solution again
165//!     let mut x2 = Vector::new(ndim);
166//!     solver.actual.solve(&mut x2, &rhs2, false)?;
167//!     let correct = vec![6.0, 4.0, 8.0];
168//!     vec_approx_eq(&x2, &correct, 1e-14);
169//!     Ok(())
170//! }
171//! ```
172//!
173//! ## Solving a tiny sparse linear system using SolverUMFPACK
174//!
175//! ```
176//! use russell_lab::{vec_approx_eq, Vector};
177//! use russell_sparse::prelude::*;
178//! use russell_sparse::StrError;
179//!
180//! fn main() -> Result<(), StrError> {
181//!     // constants
182//!     let ndim = 5; // number of rows = number of columns
183//!     let nnz = 13; // number of non-zero values, including duplicates
184//!
185//!     // allocate solver
186//!     let mut umfpack = SolverUMFPACK::new()?;
187//!
188//!     // allocate the coefficient matrix
189//!     //  2  3  .  .  .
190//!     //  3  .  4  .  6
191//!     //  . -1 -3  2  .
192//!     //  .  .  1  .  .
193//!     //  .  4  2  .  1
194//!     let mut coo = CooMatrix::new(ndim, ndim, nnz, Sym::No)?;
195//!     coo.put(0, 0, 1.0)?; // << (0, 0, a00/2) duplicate
196//!     coo.put(0, 0, 1.0)?; // << (0, 0, a00/2) duplicate
197//!     coo.put(1, 0, 3.0)?;
198//!     coo.put(0, 1, 3.0)?;
199//!     coo.put(2, 1, -1.0)?;
200//!     coo.put(4, 1, 4.0)?;
201//!     coo.put(1, 2, 4.0)?;
202//!     coo.put(2, 2, -3.0)?;
203//!     coo.put(3, 2, 1.0)?;
204//!     coo.put(4, 2, 2.0)?;
205//!     coo.put(2, 3, 2.0)?;
206//!     coo.put(1, 4, 6.0)?;
207//!     coo.put(4, 4, 1.0)?;
208//!
209//!     // parameters
210//!     let mut params = LinSolParams::new();
211//!     params.verbose = false;
212//!     params.compute_determinant = true;
213//!
214//!     // call factorize
215//!     umfpack.factorize(&coo, Some(params))?;
216//!
217//!     // allocate x and rhs
218//!     let mut x = Vector::new(ndim);
219//!     let rhs = Vector::from(&[8.0, 45.0, -3.0, 3.0, 19.0]);
220//!
221//!     // calculate the solution
222//!     umfpack.solve(&mut x, &rhs, false)?;
223//!     println!("x =\n{}", x);
224//!
225//!     // check the results
226//!     let correct = vec![1.0, 2.0, 3.0, 4.0, 5.0];
227//!     vec_approx_eq(&x, &correct, 1e-14);
228//!
229//!     // analysis
230//!     let mut stats = StatsLinSol::new();
231//!     umfpack.update_stats(&mut stats);
232//!     let (mx, ex) = (stats.determinant.mantissa_real, stats.determinant.exponent);
233//!     println!("det(a) = {:?}", mx * f64::powf(10.0, ex));
234//!     println!("rcond  = {:?}", stats.output.umfpack_rcond_estimate);
235//!     Ok(())
236//! }
237//! ```
238
239/// Defines the error output as a static string
240pub type StrError = &'static str;
241
242mod aliases;
243mod complex_coo_matrix;
244mod complex_lin_solver;
245mod complex_solver_klu;
246mod complex_solver_umfpack;
247mod constants;
248mod coo_matrix;
249mod csc_matrix;
250mod csr_matrix;
251mod enums;
252mod lin_sol_params;
253mod lin_solver;
254mod numerical_jacobian;
255pub mod prelude;
256mod read_matrix_market;
257mod samples;
258mod solver_klu;
259mod solver_umfpack;
260mod stats_lin_sol;
261mod stats_lin_sol_mumps;
262mod verify_lin_sys;
263mod write_matrix_market;
264
265pub use aliases::*;
266pub use complex_lin_solver::*;
267pub use complex_solver_klu::*;
268pub use complex_solver_umfpack::*;
269use constants::*;
270pub use coo_matrix::*;
271pub use csc_matrix::*;
272pub use csr_matrix::*;
273pub use enums::*;
274pub use lin_sol_params::*;
275pub use lin_solver::*;
276pub use numerical_jacobian::*;
277pub use read_matrix_market::*;
278pub use samples::*;
279pub use solver_klu::*;
280pub use solver_umfpack::*;
281pub use stats_lin_sol::*;
282pub use stats_lin_sol_mumps::*;
283pub use verify_lin_sys::*;
284
285#[cfg(feature = "with_mumps")]
286mod complex_solver_mumps;
287
288#[cfg(feature = "with_mumps")]
289mod solver_mumps;
290
291#[cfg(feature = "with_mumps")]
292pub use complex_solver_mumps::*;
293
294#[cfg(feature = "with_mumps")]
295pub use solver_mumps::*;
296
297// run code from README file
298#[doc = include_str!("../README.md")]
299#[cfg(doctest)]
300pub struct ReadmeDoctest;