svMultiPhysics
Loading...
Searching...
No Matches
DenseLinearAlgebra.h
1// SPDX-FileCopyrightText: Copyright (c) Stanford University, The Regents of the University of California, and others.
2// SPDX-License-Identifier: BSD-3-Clause
3
4#ifndef SVMP_COMMON_MATH_DENSELINEARALGEBRA_H
5#define SVMP_COMMON_MATH_DENSELINEARALGEBRA_H
6
7#include <cstddef>
8#include <limits>
9#include <memory>
10#include <span>
11#include <string>
12#include <string_view>
13#include <vector>
14
15namespace svmp::math {
16
17// Dense solve, inverse, rank, and pseudo-inverse support for FE construction
18// utilities. Matrices are row-major: matrix[row * cols + col]. The
19// error_message_label argument on the routines below is used only to prefix the
20// diagnostic message of any exception they throw.
21
22/**
23 * @brief Largest absolute entry of a dense matrix.
24 * @ingroup SVMP_Math
25 * @param matrix Row-major matrix entries.
26 * @return Maximum of |entry| over all entries, or 0 for an empty matrix.
27 */
28[[nodiscard]] double dense_matrix_max_abs(std::span<const double> matrix) noexcept;
29
30/**
31 * @brief Scale-aware pivot tolerance for dense factorization.
32 * @ingroup SVMP_Math
33 *
34 * @details Proportional to machine epsilon scaled by the matrix size and
35 * magnitude; pivots below it are treated as rank-deficient.
36 *
37 * @param rows Row count.
38 * @param cols Column count.
39 * @param max_abs Largest absolute matrix entry (see dense_matrix_max_abs()).
40 * @param multiplier Safety factor applied to the epsilon-scaled tolerance.
41 * @return Pivot magnitude threshold.
42 */
43[[nodiscard]] double dense_matrix_pivot_tolerance(std::size_t rows,
44 std::size_t cols,
45 double max_abs,
46 double multiplier = double(64)) noexcept;
47
48/**
49 * @brief Scale-aware singular-value tolerance for rank decisions.
50 * @ingroup SVMP_Math
51 *
52 * @details Singular values at or below the returned tolerance are treated as
53 * zero when computing rank or a pseudo-inverse.
54 *
55 * @param rows Row count.
56 * @param cols Column count.
57 * @param largest_singular_value Largest singular value of the matrix.
58 * @param multiplier Safety factor applied to the epsilon-scaled tolerance.
59 * @return Singular-value threshold.
60 */
61[[nodiscard]] double dense_matrix_singular_value_tolerance(std::size_t rows,
62 std::size_t cols,
63 double largest_singular_value,
64 double multiplier = double(64)) noexcept;
65
66/** @brief Result of a rank-revealing pseudo-inverse. @ingroup SVMP_Math */
68 std::vector<double> inverse; ///< Row-major pseudo-inverse.
69 std::size_t rank{0}; ///< Numerical rank at the chosen tolerance.
70 double tolerance{0}; ///< Singular-value tolerance used.
71 double largest_singular_value{0}; ///< Largest singular value.
72 double smallest_retained_singular_value{0}; ///< Smallest singular value kept.
73};
74
75/** @brief SVD-based conditioning and rank diagnostics for a dense matrix. @ingroup SVMP_Math */
77 std::size_t rank{0}; ///< Numerical rank at @ref tolerance.
78 double tolerance{0}; ///< Singular-value tolerance used.
79 double largest_singular_value{0}; ///< Largest singular value.
80 double smallest_retained_singular_value{0}; ///< Smallest singular value kept.
81 double condition_estimate{std::numeric_limits<double>::infinity()}; ///< Condition estimate; infinite when rank-deficient.
82};
83
84/** @brief A dense inverse together with its diagnostics. @ingroup SVMP_Math */
86 std::vector<double> inverse; ///< Row-major inverse.
87 DenseMatrixDiagnostics diagnostics; ///< Conditioning/rank diagnostics of the input.
88 bool used_svd_fallback{false}; ///< True when an SVD fallback was used for a high-condition matrix.
89};
90
91/**
92 * @brief Condition estimate above which the inverse switches to an SVD fallback.
93 * @ingroup SVMP_Math
94 * @return The fallback condition-number threshold.
95 */
96[[nodiscard]] double dense_matrix_condition_fallback_threshold() noexcept;
97/**
98 * @brief Condition estimate above which validation rejects a dense inverse.
99 * @ingroup SVMP_Math
100 * @return The error condition-number threshold.
101 */
102[[nodiscard]] double dense_matrix_condition_error_threshold() noexcept;
103
104/**
105 * @brief LU factorization of a dense square matrix with a cached pivot summary.
106 * @ingroup SVMP_Math
107 *
108 * @details Produced by factor_dense_matrix(); move-only because it owns the Eigen
109 * factorization. @ref error_message_label prefixes the messages of exceptions
110 * thrown by the solve methods.
111 */
112struct DenseLUSolver {
113 struct Impl;
114
115 DenseLUSolver();
116 ~DenseLUSolver();
117 DenseLUSolver(DenseLUSolver&&) noexcept;
118 DenseLUSolver& operator=(DenseLUSolver&&) noexcept;
119 DenseLUSolver(const DenseLUSolver&) = delete;
120 DenseLUSolver& operator=(const DenseLUSolver&) = delete;
121
122 std::size_t n{0}; ///< Matrix dimension.
123 DenseMatrixDiagnostics diagnostics; ///< Pivot-derived diagnostics (rank, tolerance).
124 double pivot_tolerance{0}; ///< Scale-aware pivot tolerance used.
125 double min_pivot{0}; ///< Smallest pivot magnitude.
126 double max_pivot{0}; ///< Largest pivot magnitude.
127 std::string error_message_label; ///< Prefix for solve-time exception messages.
128 std::unique_ptr<Impl> impl; ///< Eigen factorization (pimpl).
129
130 /**
131 * @brief Whether the factorization is empty (n == 0).
132 * @return True when no matrix has been factored.
133 */
134 [[nodiscard]] bool empty() const noexcept { return n == 0; }
135
136 /**
137 * @brief Solve A x = rhs in place for a single right-hand side.
138 * @param rhs On entry the right-hand side; on return the solution (size n).
139 */
140 void solve_in_place(std::span<double> rhs) const;
141 /**
142 * @brief Solve A X = RHS in place for several right-hand sides.
143 * @param rhs Row-major block of size n * rhs_count (solutions on return).
144 * @param rhs_count Number of right-hand sides.
145 */
146 void solve_in_place(std::span<double> rhs, std::size_t rhs_count) const;
147 /**
148 * @brief Solve A x = rhs and return the solution.
149 * @param rhs Right-hand side of size n.
150 * @return Solution vector of size n.
151 */
152 [[nodiscard]] std::vector<double> solve(std::span<const double> rhs) const;
153};
154
155// Inverses and pseudo-inverses keep the same row-major convention for their
156// returned dimensions.
157
158/**
159 * @brief SVD-based rank and conditioning diagnostics for a dense matrix.
160 * @ingroup SVMP_Math
161 * @param matrix Row-major matrix of size rows * cols.
162 * @param rows Row count.
163 * @param cols Column count.
164 * @param error_message_label Prefix for the message of any exception thrown.
165 * @return Rank, tolerance, singular-value, and condition diagnostics.
166 * @throws CoreException If the matrix size is inconsistent or the matrix is empty.
167 */
168[[nodiscard]] DenseMatrixDiagnostics dense_matrix_diagnostics(
169 std::span<const double> matrix,
170 std::size_t rows,
171 std::size_t cols,
172 std::string_view error_message_label = "dense matrix");
173
174/**
175 * @brief LU-factor a dense square matrix.
176 * @ingroup SVMP_Math
177 * @param matrix Row-major n * n matrix (consumed).
178 * @param n Matrix dimension.
179 * @param error_message_label Prefix for the message of any exception thrown.
180 * @return The factorization.
181 * @throws CoreException If the size is inconsistent or the matrix is rank-deficient.
182 */
183[[nodiscard]] DenseLUSolver factor_dense_matrix(std::vector<double> matrix,
184 std::size_t n,
185 std::string_view error_message_label = "dense matrix");
186
187/**
188 * @brief Invert a dense square matrix.
189 * @ingroup SVMP_Math
190 * @param matrix Row-major n * n matrix (consumed).
191 * @param n Matrix dimension.
192 * @param error_message_label Prefix for the message of any exception thrown.
193 * @return Row-major inverse of size n * n.
194 * @throws CoreException If the size is inconsistent or the matrix is singular.
195 */
196[[nodiscard]] std::vector<double> invert_dense_matrix(std::vector<double> matrix,
197 std::size_t n,
198 std::string_view error_message_label = "dense matrix");
199
200/**
201 * @brief Invert a dense square matrix with diagnostics, using an SVD fallback for
202 * high-condition matrices.
203 * @ingroup SVMP_Math
204 * @param matrix Row-major n * n matrix (consumed).
205 * @param n Matrix dimension.
206 * @param error_message_label Prefix for the message of any exception thrown.
207 * @return Inverse plus diagnostics and whether the SVD fallback was used.
208 * @throws CoreException If the size is inconsistent or the matrix is rank-deficient.
209 */
210[[nodiscard]] DenseInverseResult invert_dense_matrix_with_diagnostics(
211 std::vector<double> matrix,
212 std::size_t n,
213 std::string_view error_message_label = "dense matrix");
214
215/**
216 * @brief Validate that a dense inverse has full rank and acceptable conditioning.
217 * @ingroup SVMP_Math
218 * @param result Result from invert_dense_matrix_with_diagnostics().
219 * @param expected_rank Required (full) rank.
220 * @param error_message_label Prefix for the message of any exception thrown.
221 * @param max_condition Largest acceptable condition estimate.
222 * @throws CoreException If the rank is below expected_rank or the condition exceeds max_condition.
223 */
225 const DenseInverseResult& result,
226 std::size_t expected_rank,
227 std::string_view error_message_label = "dense matrix",
228 double max_condition = dense_matrix_condition_error_threshold());
229
230/**
231 * @brief Numerical rank of a dense matrix from its singular values.
232 * @ingroup SVMP_Math
233 * @param matrix Row-major matrix of size rows * cols (consumed).
234 * @param rows Row count.
235 * @param cols Column count.
236 * @return Number of singular values above the scale-aware tolerance.
237 * @throws CoreException If the matrix size is inconsistent.
238 */
239[[nodiscard]] std::size_t dense_matrix_rank(std::vector<double> matrix,
240 std::size_t rows,
241 std::size_t cols);
242
243/**
244 * @brief Moore-Penrose pseudo-inverse via a rank-revealing SVD.
245 * @ingroup SVMP_Math
246 * @param matrix Row-major matrix of size rows * cols.
247 * @param rows Row count.
248 * @param cols Column count.
249 * @param error_message_label Prefix for the message of any exception thrown.
250 * @return Row-major pseudo-inverse (cols * rows) plus rank/tolerance diagnostics.
251 * @throws CoreException If the matrix size is inconsistent or the matrix is empty.
252 */
253[[nodiscard]] DensePseudoInverseResult rank_revealing_pseudo_inverse(
254 std::span<const double> matrix,
255 std::size_t rows,
256 std::size_t cols,
257 std::string_view error_message_label = "dense matrix");
258
259} // namespace svmp::math
260
261#endif // SVMP_COMMON_MATH_DENSELINEARALGEBRA_H
void validate_dense_inverse_diagnostics(const DenseInverseResult &result, std::size_t expected_rank, std::string_view error_message_label="dense matrix", double max_condition=dense_matrix_condition_error_threshold())
Validate that a dense inverse has full rank and acceptable conditioning.
Definition DenseLinearAlgebra.cpp:243
std::vector< double > invert_dense_matrix(std::vector< double > matrix, std::size_t n, std::string_view error_message_label="dense matrix")
Invert a dense square matrix.
Definition DenseLinearAlgebra.cpp:263
double dense_matrix_singular_value_tolerance(std::size_t rows, std::size_t cols, double largest_singular_value, double multiplier=double(64)) noexcept
Scale-aware singular-value tolerance for rank decisions.
Definition DenseLinearAlgebra.cpp:69
DenseMatrixDiagnostics dense_matrix_diagnostics(std::span< const double > matrix, std::size_t rows, std::size_t cols, std::string_view error_message_label="dense matrix")
SVD-based rank and conditioning diagnostics for a dense matrix.
Definition DenseLinearAlgebra.cpp:117
DenseLUSolver factor_dense_matrix(std::vector< double > matrix, std::size_t n, std::string_view error_message_label="dense matrix")
LU-factor a dense square matrix.
Definition DenseLinearAlgebra.cpp:157
double dense_matrix_condition_fallback_threshold() noexcept
Condition estimate above which the inverse switches to an SVD fallback.
Definition DenseLinearAlgebra.cpp:79
double dense_matrix_condition_error_threshold() noexcept
Condition estimate above which validation rejects a dense inverse.
Definition DenseLinearAlgebra.cpp:83
DenseInverseResult invert_dense_matrix_with_diagnostics(std::vector< double > matrix, std::size_t n, std::string_view error_message_label="dense matrix")
Invert a dense square matrix with diagnostics, using an SVD fallback for high-condition matrices.
Definition DenseLinearAlgebra.cpp:199
double dense_matrix_pivot_tolerance(std::size_t rows, std::size_t cols, double max_abs, double multiplier=double(64)) noexcept
Scale-aware pivot tolerance for dense factorization.
Definition DenseLinearAlgebra.cpp:59
DensePseudoInverseResult rank_revealing_pseudo_inverse(std::span< const double > matrix, std::size_t rows, std::size_t cols, std::string_view error_message_label="dense matrix")
Moore-Penrose pseudo-inverse via a rank-revealing SVD.
Definition DenseLinearAlgebra.cpp:298
std::size_t dense_matrix_rank(std::vector< double > matrix, std::size_t rows, std::size_t cols)
Numerical rank of a dense matrix from its singular values.
Definition DenseLinearAlgebra.cpp:273
double dense_matrix_max_abs(std::span< const double > matrix) noexcept
Largest absolute entry of a dense matrix.
Definition DenseLinearAlgebra.cpp:51
A dense inverse together with its diagnostics.
Definition DenseLinearAlgebra.h:85
bool used_svd_fallback
True when an SVD fallback was used for a high-condition matrix.
Definition DenseLinearAlgebra.h:88
std::vector< double > inverse
Row-major inverse.
Definition DenseLinearAlgebra.h:86
DenseMatrixDiagnostics diagnostics
Conditioning/rank diagnostics of the input.
Definition DenseLinearAlgebra.h:87
Definition DenseLinearAlgebra.cpp:42
std::unique_ptr< Impl > impl
Eigen factorization (pimpl).
Definition DenseLinearAlgebra.h:128
double pivot_tolerance
Scale-aware pivot tolerance used.
Definition DenseLinearAlgebra.h:124
bool empty() const noexcept
Whether the factorization is empty (n == 0).
Definition DenseLinearAlgebra.h:134
double max_pivot
Largest pivot magnitude.
Definition DenseLinearAlgebra.h:126
double min_pivot
Smallest pivot magnitude.
Definition DenseLinearAlgebra.h:125
DenseMatrixDiagnostics diagnostics
Pivot-derived diagnostics (rank, tolerance).
Definition DenseLinearAlgebra.h:123
std::string error_message_label
Prefix for solve-time exception messages.
Definition DenseLinearAlgebra.h:127
std::size_t n
Matrix dimension.
Definition DenseLinearAlgebra.h:122
SVD-based conditioning and rank diagnostics for a dense matrix.
Definition DenseLinearAlgebra.h:76
double tolerance
Singular-value tolerance used.
Definition DenseLinearAlgebra.h:78
std::size_t rank
Numerical rank at tolerance.
Definition DenseLinearAlgebra.h:77
double smallest_retained_singular_value
Smallest singular value kept.
Definition DenseLinearAlgebra.h:80
double condition_estimate
Condition estimate; infinite when rank-deficient.
Definition DenseLinearAlgebra.h:81
double largest_singular_value
Largest singular value.
Definition DenseLinearAlgebra.h:79
Result of a rank-revealing pseudo-inverse.
Definition DenseLinearAlgebra.h:67
double largest_singular_value
Largest singular value.
Definition DenseLinearAlgebra.h:71
double tolerance
Singular-value tolerance used.
Definition DenseLinearAlgebra.h:70
double smallest_retained_singular_value
Smallest singular value kept.
Definition DenseLinearAlgebra.h:72
std::size_t rank
Numerical rank at the chosen tolerance.
Definition DenseLinearAlgebra.h:69
std::vector< double > inverse
Row-major pseudo-inverse.
Definition DenseLinearAlgebra.h:68