Peano
Loading...
Searching...
No Matches
dense-linear-algebra.h
Go to the documentation of this file.
1#ifndef APPARENT_HORIZON_FINDER_DENSE_LINEAR_ALGEBRA_H_
2#define APPARENT_HORIZON_FINDER_DENSE_LINEAR_ALGEBRA_H_
3
4#include <cmath>
5#include <cstddef>
6#include <stdexcept>
7#include <utility>
8#include <vector>
9
10// Small dense linear solve for the spectral Newton-Raphson step (the dense N x N system
11// J delta a = -R). N is small (e.g. 81 at lmax = 8), so a plain Gaussian
12// elimination with partial pivoting is fine.
13
14namespace exahype2::ccz4::ahf {
15
23inline std::vector<double> SolveLinearSystem(std::vector<std::vector<double>> A,
24 std::vector<double> b) {
25 // Checks for A
26 const std::size_t n = b.size();
27 if (A.size() != n) {
28 throw std::invalid_argument("SolveLinearSystem: matrix/vector size mismatch");
29 }
30 for (const std::vector<double>& row : A) {
31 if (row.size() != n) {
32 throw std::invalid_argument("SolveLinearSystem: matrix is not square");
33 }
34 }
35
36// Gaussian elimination with partial pivoting.
37 for (std::size_t col = 0; col < n; ++col) {
38 // Partial pivot: pick the largest-magnitude entry in this column.
39 std::size_t pivot = col;
40 double best = std::abs(A[col][col]);
41 for (std::size_t row = col + 1; row < n; ++row) {
42 const double candidate = std::abs(A[row][col]);
43 if (candidate > best) {
44 best = candidate;
45 pivot = row;
46 }
47 }
48 if (!(best > 0.0)) {
49 throw std::runtime_error("SolveLinearSystem: singular matrix");
50 }
51 if (pivot != col) {
52 std::swap(A[pivot], A[col]);
53 std::swap(b[pivot], b[col]);
54 }
55
56 // Eliminate below the pivot.
57 for (std::size_t row = col + 1; row < n; ++row) {
58 const double factor = A[row][col] / A[col][col];
59 if (factor != 0.0) {
60 for (std::size_t c = col; c < n; ++c) {
61 A[row][c] -= factor * A[col][c];
62 }
63 b[row] -= factor * b[col];
64 }
65 }
66 }
67
68 // Back-substitution.
69 std::vector<double> x(n, 0.0);
70 for (std::size_t i = n; i-- > 0;) {
71 double sum = b[i];
72 for (std::size_t c = i + 1; c < n; ++c) {
73 sum -= A[i][c] * x[c];
74 }
75 x[i] = sum / A[i][i];
76 }
77 return x;
78}
79
80} // namespace exahype2::ccz4::ahf
81
82#endif // APPARENT_HORIZON_FINDER_DENSE_LINEAR_ALGEBRA_H_
std::vector< double > SolveLinearSystem(std::vector< std::vector< double > > A, std::vector< double > b)
Solve the dense square system A x = b by Gaussian elimination with partial pivoting.