|
Sparse Linear Algebra 0.3.0
Sparse Linear Algebra
|
Most matrices of estimation, control, and simulation problems are mostly zeros, and their structure is known before the program runs: a diagonal noise, a triangular transition, a banded stencil. Ordinary dense linear algebra stores and multiplies those zeros anyway, and ordinary sparse linear algebra discovers them at run time, with memory allocations and indirections. This library is a C++ compile-time sparsity pattern linear algebra: the positions of the stored elements are part of the matrix type. Every other element is a structural zero, occupying no memory and costing no operation. Each operation computes the pattern of its result, and the exact arithmetic terms it needs, at compile time. There is no memory allocation, no exception, no input-output, and every operation is constexpr, freestanding, and real-time.
See INSTALL.md for installation instructions. Only the include/ folder is the library: cmake --install and the release packages deliver it, with its CMake package configuration, and nothing else. The support/, sample/, test/, and benchmark/ folders are development examples and tooling, not part of the delivered library.
| Use Case | Sample |
|---|---|
| Constant velocity prediction | Usage example: sample/constant_velocity.cpp. |
| Heat diffusion stencil | Usage example: sample/heat_diffusion.cpp. |
The library is the compile-time sparsity layer between the application and the C++ language, without dependency.
Link against the CMake target fcarouge-sparse-linear-algebra::slinalg.
Include the library header in your sources:
For forward declarations only, include instead:
The library is header-only and has no dependency. A single-header amalgamation, sparse_linear_algebra.h, is also published.
Every public class, function, type, and constant of the library at a glance, detailed in the reference below.
The sparse_matrix class, its operations, and the sparsity_pattern concept live in the fcarouge namespace, and the 0_o structural zero literal in the fcarouge::literals namespace. The patterns and their algebra live in the fcarouge::sparse namespace. Import them with a using-declaration or namespace alias as your project's style prefers.
Compile-time sparsity pattern matrix. Stores the elements of the pattern in place, in row-major order. Every other element is a structural zero: it reads as a zero, and a write to it does not compile.
Also documented in the fcarouge/sparse_linear_algebra.hpp header.
| Template Parameter | Definition |
|---|---|
| Type | The type of the stored elements. |
| Pattern | The sparsity pattern of the matrix. |
| Member Variable | Definition |
|---|---|
| structure | Static. The sparsity pattern of the matrix. |
| rows | Static. The std::size_t count of rows. |
| columns | Static. The std::size_t count of columns. |
| rank | Static. The std::size_t number of dimensions: 0 for a singleton, 1 for a row or column vector, 2 otherwise. A property of the shape, not the linear algebra rank of the matrix. |
| values | The std::array of the stored elements, zero-initialized, in row-major order. |
| Member Function | Definition |
|---|---|
| (default constructor) | Construct a zero matrix. |
| (explicit constructor) | Construct from every stored element, in row-major order. Type holds each one exactly, and there is at least one. |
| (explicit constructor) | Construct from every row, each a braced list of every column: each stored element a value Type holds exactly, each structural zero the `0_o` literal. |
| (conversion constructor) | Implicitly convert from a matrix of the same shape, whose stored positions this pattern all stores, and whose element type Type holds every value of exactly. |
| at<Row, Column>() | Access the stored element at the compile-time position, by reference. Only for a stored element. |
| at<Row, Column>() const | Read the element at the compile-time position, by constant value. A structural zero reads as Type{}. |
| operator[row, column] const | Read the element at the run-time position, by constant value. A structural zero reads as Type{}. |
| operator[row, column] | Access the element at the run-time position, by reference. Only without a structural zero. |
| operator[std::integral_constant<std::size_t, Row>, std::integral_constant<std::size_t, Column>] | Access the stored element at the compile-time position, by reference. Only for a stored element. The generic access of a linear algebra library by compile-time position. |
| operator[std::integral_constant<std::size_t, Row>, std::integral_constant<std::size_t, Column>] const | Read the element at the compile-time position, by constant value. A structural zero reads as Type{}. The generic read of a linear algebra library by compile-time position. |
The positions of the stored elements of a matrix. A structural type, usable as a template argument, of strictly ascending row-major positions: two equal patterns are one and the same type of matrix. Its constructors establish that order, and its class template arguments are deduced from them.
| Template Parameter | Definition |
|---|---|
| Rows | The count of rows of the matrix. |
| Columns | The count of columns of the matrix. |
| Count | The count of stored elements of the matrix. |
| Member Variable | Definition |
|---|---|
| rows | The count of rows. |
| columns | The count of columns. |
| stored | The count of stored elements: the values in memory. |
| constants | The count of structural constants: the positions reading no stored element, the structural zeros. |
| positions | The std::array of the stored positions, in row-major order. A position has a row and a column. |
| Member Function | Definition |
|---|---|
| (constructor) | Construct from the shape of the matrix, shape<R, C>, and the stored positions or a predicate: see Patterns. Not default-constructible, and not an aggregate. |
| lower_bound(position) | The index of the first stored position not before the given one. |
| index_of(row, column) | The index of the stored element at the given position, or absent for a structural zero. |
| stores(row, column) | Whether the given position is a stored element. |
| operator== | Whether two patterns, of any sizes, store the same positions of the same shape. |
A pattern is constructed at compile time from the shape of its matrix, shape<R, C>, and its stored positions, or a predicate selecting them. The count of stored elements is deduced, as are the counts of rows and columns: pattern{shape<2, 3>, {{0, 2}, {1, 0}}} is a pattern<2, 3, 2>.
| Pattern | Example | Definition |
|---|---|---|
| pattern{shape<R, C>} | No position. | |
| pattern{shape<R, C>, {{i, j}, ...}} | The listed positions, in any order. A duplicate or out-of-range position does not compile. | |
| pattern{shape<R, C>, predicate} | The positions satisfying a stateless predicate of a row and a column. | |
| dense<R, C> | Every position: a matrix without structural zeros. | |
| zero<R, C> | No position: the zero matrix. | |
| banded<R, C, L, U> | The L sub-diagonals, the main diagonal, and the U super-diagonals. | |
| diagonal<N> | The main diagonal of a square matrix. | |
| tridiagonal<N> | The three central diagonals of a square matrix. | |
| lower_triangular<N> | The main diagonal and below of a square matrix. | |
| upper_triangular<N> | The main diagonal and above of a square matrix. |
The examples draw the stored positions filled and the structural zeros empty: the listed positions {{0, 1}, {1, 4}, {2, 0}, {2, 3}, {3, 5}}, the predicate (i + j) % 3 == 0, and the band banded<6, 6, 1, 2>.
The operations use these compile-time computations to find which positions of their result are stored. Each is a variable template of the fcarouge::sparse namespace, which you can also use directly, for example in a static_assert.
| Variable | Example | Definition |
|---|---|---|
| pattern_union<Lhs, Rhs> | The positions stored by either pattern. It is the pattern of a sum or a difference. Both patterns have the same shape. | |
| pattern_intersection<Lhs, Rhs> | The positions stored by both patterns. Both patterns have the same shape. | |
| pattern_transpose<Pattern> | The pattern with its rows and columns swapped. | |
| pattern_product<Lhs, Rhs> | The pattern of the matrix product Lhs * Rhs. A position is stored when at least one elementary product adds to it, even if the values could cancel out at run time. | |
| product_term_count<Lhs, Rhs> | The count of elementary products of the matrix product Lhs * Rhs. The example shows the count reaching each position. | |
| structural_rank<Pattern> | The most stored positions that can be picked with no two in the same row or column. When a square pattern's structural rank is below its size, every matrix of that pattern is singular, whatever its values. | |
| pattern_quotient<Lhs, Rhs> | The pattern of the division Lhs / Rhs: the x solving x * Rhs = Lhs. Rhs is square, of full structural rank. A position is stored when solving the equation reaches it. | |
| pattern_cholesky<Pattern> | The pattern of the lower triangular factor L of a symmetric positive definite matrix, A = L * transposed(L). Pattern is structurally symmetric and stores its diagonal. A position is stored when the elimination reaches it. The order of the rows and columns decides the fill-in: the example fills the whole lower triangle, and the same arrow with its dense row and column last fills nothing. | |
| is_subset_of<Inner, Outer> | Whether Outer stores every position that Inner stores. Patterns of different shapes are not subsets. | |
| is_structurally_symmetric<Pattern> | Whether the pattern is square and is its own mirror image across the main diagonal. It is about positions only: a matrix of this pattern may still have different values at mirrored positions. |
The examples draw the stored positions filled and the structural zeros empty. The dots mark the positions the structural rank picks, and the dashed line is the main diagonal.
The value of a structural zero in a construction from every row, so that the declaration reads as the matrix. A value at a structural zero, even 0., does not compile, nor does 0_o at a stored element. The literal is a zero only, 0_o or 0._o: 1_o does not compile.
A structural zero has nothing to refer to. A read is by constant value, and a write that would be lost does not compile, whatever the value and the element type: neither an assignment nor a modifying member function of an element of a class type reaches a read. A pattern without a structural zero is an ordinary dense storage.
| Access | Stored Element | Structural Zero |
|---|---|---|
| Read: at<i, j>(), operator[i, j] | Yes. | Yes, by constant value. A zero of the element type. |
| Write: at<i, j>() = value | Yes. | Does not compile. |
| Write: operator[i, j] = value | Without a structural zero only: its position is only known at run time. | Does not compile. |
| Construction from the stored elements | Yes, in row-major order. | Takes no value. |
| Construction from every row | Yes, of a value Type holds exactly. | Yes, 0_o. |
| Conversion from a matrix of a narrower pattern | Yes. | Yes, zero. |
The rejections of the writes and of the constructions are compile errors, which a requires expression detects. To ask whether a position can be written, use decltype(value)::structure.stores(i, j).
The operations below are supported, each as a function or an operator of the fcarouge namespace, found by argument-dependent lookup on sparse_matrix. K is the count of stored elements, R and C the counts of rows and columns, and T the `product_term_count`. Each result pattern is computed at compile time. The algorithms mirror the names of the C++26 standard linear algebra library, std::linalg, and return their results by value.
| Operation | Result Pattern | Run-Time Complexity |
|---|---|---|
| +, binary - | The union of the patterns, of the same shape. | O(K) of the result. |
| Unary - | The same pattern. | O(K). |
| *, of matrices and vectors | The structural product of the patterns. | O(K + T) of the result. |
| *, /, by a scalar Type holds exactly | The same pattern. | O(K). |
| /, of matrices, the quotient x of x * rhs = lhs | The structural quotient of the patterns, by a square denominator of full structural rank. | O(K + T) of the operands, the result, and the terms coupling the blocks of the denominator's block triangular form, plus O(B³) for each irreducible diagonal block of B unknowns, which is eliminated dense, with partial pivoting. A diagonal or a triangular denominator is a substitution. |
| == | Not applicable. Compares every position of the same shape: a structural zero equals a stored zero. | O(K) of the union. |
| transposed | The transposed pattern. Returns a matrix, not a view. | O(K). |
| dot | Not applicable. Returns an element. Vectors of the same size, of any orientation. | O(K), of the elements stored by both vectors. |
| matrix_frob_norm | Not applicable. Returns an element. Floating-point elements only. | O(K). |
| matrix_one_norm | Not applicable. Returns an element, the largest absolute column sum. | O(K + C). |
| matrix_inf_norm | Not applicable. Returns an element, the largest absolute row sum. | O(K + R). |
| Construction from every row | The pattern of the matrix. | O(R * C). |
| Read of an element at a run-time position | Not applicable. Returns an element. | O(log K). O(1) without a structural zero. |
| Access of an element at a compile-time position | Not applicable. Returns an element. | O(1). |
The following are not supported yet:
| Concept | Definition |
|---|---|
| sparsity_pattern | Concept of a compile-time sparsity pattern. |
A matrix formats every element, structural zeros included, so the format does not depend on the pattern: a singleton as its element, a row vector as a list of elements, a column vector or a matrix as a list of rows. Hosted implementation only.
The library serves fixed-size computations whose structure is known at compile time and whose budget is tight: embedded, real-time, safety-critical, or high-rate software, where a dense computation wastes most of its operations on zeros and a run-time sparse computation is not an option.
In theory there is no difference between theory and practice, while in practice there is. The following engineering tradeoffs have been selected for this library implementation:
The library's patterns, pattern algebra, and matrix are stable in practice but not yet frozen. The longer-term ambition is to be the compile-time sparse storage beneath typed linear algebra facades, where dimensional and semantic type safety meets structural sparsity, and beneath state estimation filters.
Toward version 1.0:
The pattern is in the type, not in the object. A run-time sparse format stores its indexes beside its values and pays an indirection for each element. A compile-time pattern stores nothing but its values: the indexes, the result patterns, and the exact list of elementary products of each operation are constants of the program, computed once, by the compiler. The run-time code reads none of the pattern itself, only the tables it needs: a run-time read of a pattern, a template parameter object, would place all of it in the program, every position included.
A structural zero has nothing to refer to. A reference to a structural zero would either write to nowhere, silently losing a value, or need a run-time check. Element writes are therefore compile-time positions only, and a run-time position is read by constant value: a read by value alone would still take the assignment of an element of a class type, to a temporary, and lose it. A pattern without structural zeros is an ordinary dense storage, with every element addressable.
A structural zero is not a stored zero. It is a property of the type: the product of a structural zero and an infinity is never computed. A stored zero is a value, which may become non-zero, and multiplies as any other value.
Construction states the structure. A value given for a structural zero, even a zero, is a defect: it says the author expected an element there. The 0_o literal makes the intent explicit and checks it at compile time, at no run-time cost.
The cost of an operation follows its count of stored elements and of elementary products, not its shape. See the benchmarks.
The embedded footprint reports the flash, RAM, and worst-case stack sizes of the operations of dense, tridiagonal, and diagonal patterns on a bare-metal Arm Cortex-M4 target.
The library is used in projects:
Your project link here!
The library is designed, developed, and tested with the help of third-party tools and services acknowledged and thanked here:
Thank you to everyone who has contributed code, tests, or documentation!
See CONTRIBUTORS.md for the full, credited list, CHANGELOG.md for notable changes, and CONTRIBUTING.md to join.
Become a sponsor today! Support this project with coffee and infrastructure!
Your group logo and link here!
Your name and link here!
Thanks everyone!
Need help integrating, tuning, or extending sparse linear algebra in your product? Commercial support, consulting, training, and custom development are available. Get in touch.

SparseLinearAlgebra is public domain:
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to https://unlicense.org