Sparse Linear Algebra 0.3.0
Sparse Linear Algebra
Loading...
Searching...
No Matches
François Carouge / 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.

using band = sparse_matrix<double, tridiagonal<3>>;
// Stores 7 of the 9 elements.
band value{{1.0, 2.0, 0_o}, //
{3.0, 4.0, 5.0}, //
{0_o, 6.0, 7.0}}; //
value.at<1, 2>() = 8.; // Writes a stored element.
// value.at<0, 2>() = 8.; // Does not compile: a structural zero.
std::println("{}", value * value); // Computes 17 of the 27 products.
// [[ 7, 10, 16],
// [15, 70, 88],
// [18, 66, 97]]

Pipeline Freestanding Sanitizer Format ClangTidy CppCheck Coverity Scan Doxygen Valgrind Public Domain License Scan OpenSSF Baseline Deploy Unit Test Code Coverage Deploy Doxygen Sponsor Discussions

Installation & Usage

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.

Samples

Use Case Sample
Constant velocity prediction Usage example: sample/constant_velocity.cpp.
Heat diffusion stencil Usage example: sample/heat_diffusion.cpp.

Reference

Layers

Where Sparse Linear Algebra sits in the technical stack: below the application and its optional typed or estimation libraries, building on the C++ language alone and storing arithmetic element types.

The library is the compile-time sparsity layer between the application and the C++ language, without dependency.

CMake

Link against the CMake target fcarouge-sparse-linear-algebra::slinalg.

Include

Include the library header in your sources:

Compile-time sparsity pattern linear algebra.

For forward declarations only, include instead:

Authoritative forward declaration header.

The library is header-only and has no dependency. A single-header amalgamation, sparse_linear_algebra.h, is also published.

Public API

The public API of Sparse Linear Algebra: the sparse_matrix class template, its member variables, construction, and element access, the sparse::pattern it is built on with its vocabulary and predefined patterns, the concept, the operations and the pattern algebra computing their result patterns, the structural zero literal, and the standard formatter.

Every public class, function, type, and constant of the library at a glance, detailed in the reference below.

Namespace

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.

Class Sparse Matrix

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.

Declaration

namespace fcarouge {
template <typename Type, auto Pattern>
requires sparsity_pattern<decltype(Pattern)>
class sparse_matrix;
}
Francois Carouge's projects namespace.
Definition benchmark.hpp:55

Template Parameters

Template Parameter Definition
Type The type of the stored elements.
Pattern The sparsity pattern of the matrix.

Member Variables

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 Functions

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.

Class Pattern

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.

Declaration

namespace fcarouge::sparse {
struct position;
inline constexpr std::size_t absent;
template <std::size_t Rows, std::size_t Columns, std::size_t Count>
struct pattern;
template <std::size_t Rows, std::size_t Columns>
struct shape_t;
template <std::size_t Rows, std::size_t Columns>
inline constexpr shape_t<Rows, Columns> shape;
}
Sparse linear algebra public namespace.
pattern(shape_t< Rows, Columns >) -> pattern< Rows, Columns, 0 >
Deduce the pattern without any stored position.
constexpr std::size_t absent
The index of a position a pattern does not store.
Definition pattern.hpp:130
constexpr shape_t< Rows, Columns > shape
The shape of a matrix, the first argument of the construction of a pattern, from which its counts of ...
Definition pattern.hpp:127

Template Parameters

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 Variables

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 Functions

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.

Patterns

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>} A 4 by 6 pattern without position. No position.
pattern{shape<R, C>, {{i, j}, ...}} A 4 by 6 pattern of five listed positions. The listed positions, in any order. A duplicate or out-of-range position does not compile.
pattern{shape<R, C>, predicate} A 4 by 6 pattern of the positions whose row and column sum to a multiple of three. The positions satisfying a stateless predicate of a row and a column.
dense<R, C> A dense 4 by 6 pattern: every position. Every position: a matrix without structural zeros.
zero<R, C> A zero 4 by 6 pattern: no position. No position: the zero matrix.
banded<R, C, L, U> A 6 by 6 banded pattern of one sub-diagonal and two super-diagonals. The L sub-diagonals, the main diagonal, and the U super-diagonals.
diagonal<N> A 6 by 6 diagonal pattern. The main diagonal of a square matrix.
tridiagonal<N> A 6 by 6 tridiagonal pattern. The three central diagonals of a square matrix.
lower_triangular<N> A 6 by 6 lower triangular pattern. The main diagonal and below of a square matrix.
upper_triangular<N> A 6 by 6 upper triangular pattern. 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>.

Pattern Algebra

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 union of a first row and a last column: the first row and the last column. 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 intersection of a lower and an upper triangular pattern: the diagonal. The positions stored by both patterns. Both patterns have the same shape.
pattern_transpose<Pattern> The transpose of a 2 by 3 pattern: a 3 by 2 pattern. The pattern with its rows and columns swapped.
pattern_product<Lhs, Rhs> The product of two tridiagonal patterns: a band of two sub-diagonals and two super-diagonals. 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 product of two 3 by 3 tridiagonal patterns: 17 elementary products. The count of elementary products of the matrix product Lhs * Rhs. The example shows the count reaching each position.
structural_rank<Pattern> A pattern of structural rank 2. 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 division of a row of one position by an upper triangular pattern: a full row. 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 Cholesky factor of an arrow pattern, of a dense first row and column: the whole lower triangle, filled in. 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> The diagonal pattern is a subset of the tridiagonal pattern. Whether Outer stores every position that Inner stores. Patterns of different shapes are not subsets.
is_structurally_symmetric<Pattern> A pattern that mirrors itself across its main diagonal, and one that does not. 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.

Structural Zero Literal

namespace fcarouge::literals {
template <char... Characters>
[[nodiscard]] consteval auto operator""_o() noexcept;
}

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.

using literals::operator""_o;
const sparse_matrix<double, lower_triangular<2>> value{{1., 0_o}, //
{2., 3.}}; //

Element Access

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).

Operations

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:

  • The std::linalg out-parameter algorithms: add, matrix_product, matrix_rank_1_update, matrix_vector_product, and scale.

Concepts

Concept Definition
sparsity_pattern Concept of a compile-time sparsity pattern.

Format

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.

const sparse_matrix<double, diagonal<2>> value{1., 2.5};
std::println("{}", value); // [[1, 0], [0, 2.5]]

More

Use Cases

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.

  • Estimation and filtering: diagonal noises, triangular or block transitions, and selection observation models of Kalman filters.
  • Guidance, navigation, and control: decoupled axes and cascaded loops whose gain and dynamics matrices are block or band structured.
  • Simulation: finite difference stencils, banded Jacobians, and explicit time integration.
  • Robotics: kinematic chains whose Jacobians only couple neighboring joints.
  • Linear algebra backend: a storage of fixed patterns beneath a typed linear algebra facade.

Selected Tradeoffs

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 sparsity pattern is structural and fixed at compile time: its indexes, the result patterns, and the terms of each operation are computed at compile time, into no storage per matrix but constant tables the run-time code walks, at the cost of compile time, and of elements cancelling out at run time staying stored.
  • A structural zero is never computed: unlike a dense computation, a non-finite operand does not propagate through it, and 0 * infinity is not a not-a-number value.
  • A sum of elementary products, of a matrix or a dot product, starts at its first product rather than at a zero: a negative zero product stays a negative zero, and no addition is spent on the zero. std::linalg::dot, as the reference BLAS, adds its products to T{} instead, and a sum of negative zero products is a positive zero there. A sum of no product is a positive zero, as the IEEE 754 reduction operations of no term (§9.4).
  • An element stored by one term only of a sum is copied, and of the right term only of a difference negated: a zero element keeps its sign, or flips it, where a dense computation adds it to, or subtracts it from, a positive zero.
  • A value converts implicitly only where nothing can be lost, and a lossy conversion does not compile: it is the user's decision, a named static_cast. A matrix converts only to a pattern storing all of its positions, never to a narrower one, which could lose an element. A matrix, a stored element, or a scalar factor converts only to an element type holding every value of its own type exactly: between arithmetic types, a floating-point type of no fewer digits and no narrower exponent range, or an integer type of no fewer digits, signed if the source is, float and int to double but not double or int to float, and a class type by its implicit, non-narrowing conversions, their constructor's argument included. A class value converted by its own conversion function, operator double() into a float element, escapes the check: the language does not see that conversion's result narrowed. The rule is by type, not by value: 0.5, a double, does not scale a float matrix, 0.5F does. A write through a reference to a stored element is an assignment of the language, not of the library, and converts as it does. Operands of two matrices of different element types do not mix: convert one first.
  • A matrix division eliminates each irreducible diagonal block of its denominator densely, with partial pivoting, a structural zero taking part as a zero: a diagonal or a triangular denominator computes no structural zero.
  • The library is freestanding, as its freestanding and bare-metal Cortex-M4 builds verify: no hosted-only standard header on a freestanding implementation, no exception, no run-time type information, and no memory allocation. At compile time and on a freestanding implementation, the Frobenius norm uses its own square root, not guaranteed identical to the last digit to std::sqrt.
  • The compile-time cost suits up to about ten thousand stored elements: the pattern operations and a dense product are verified at 100 x 100. A division by an irreducible denominator fills a dense quotient, verified up to a 48 x 48 tridiagonal denominator.

Roadmap & Vision

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:

  • Integrate as a typed linear algebra backend, with strong element types.
  • Solve: the determinant, and factorizations reused across divisions by the same matrix.
  • Interoperate with std::mdspan and the std::linalg out-parameter algorithms.
  • Compose block patterns from smaller patterns.
  • Stabilize the public API.

Lessons Learned

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.

Performance

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.

Projects

The library is used in projects:

Your project link here!

Resources

  1. D. Withopf, "Compile-time Is the New Constexpr: Leveraging Compile-time Sparsity for Vectors and Matrices," presented at C++Now, Aspen, CO, USA, May 2023. [Online]. Available: https://schedule.cppnow.org/session/2023/compile-time-is-the-new-constexpr-leveraging-compile-time-sparsity-for-vectors-and-matrices/
  2. M. Hoemmen, "std::linalg: Linear Algebra Coming to Standard C++" (WG21 P1673), presented at CppCon, Aurora, CO, USA, Oct. 2023. [Online]. Available: https://www.youtube.com/watch?v=-UXHMlAMXNk
  3. T. A. Davis, Direct Methods for Sparse Linear Systems. Philadelphia, PA, USA: SIAM, 2006.

Third Party Acknowledgement

The library is designed, developed, and tested with the help of third-party tools and services acknowledged and thanked here:

Contributors

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.

Sponsors

Become a sponsor today! Support this project with coffee and infrastructure!

Sponsor

Corporations & Institutions

Your group logo and link here!

Individuals

Your name and link here!

Thanks everyone!

Commercial Support & Consulting

Need help integrating, tuning, or extending sparse linear algebra in your product? Commercial support, consulting, training, and custom development are available. Get in touch.

License

Open Source Initiative Approved License

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