aboutsummaryrefslogtreecommitdiff
path: root/src/cholesky.cpp
blob: f65d9ce54d463e8bcfe692266c8eeb5a0eb185ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
export module linalgebra:cholesky;
import std;
import :error;
import :vector;
import :matrix;
import :triangular_solve;

export namespace linalgebra {

struct CholeskyResult {
    Matrix L;
};

CholeskyResult cholesky_factor(const Matrix& A, double tolerance = 1e-12);

Vector cholesky_solve(const CholeskyResult& chol, const Vector& b);

}  // namespace linalgebra

namespace linalgebra {

CholeskyResult cholesky_factor(const Matrix& A, double tolerance) {
    if (A.rows() != A.cols()) {
        std::ostringstream oss;
        oss << "cholesky_factor requires a square matrix, got " << A.rows() << "x" << A.cols();
        throw DimensionMismatchError(oss.str());
    }

    const std::size_t n = A.rows();

    for (std::size_t i = 0; i < n; ++i) {
        for (std::size_t j = i + 1; j < n; ++j) {
            if (std::abs(A(i, j) - A(j, i)) > tolerance) {
                throw LinAlgError("cholesky_factor requires a symmetric matrix");
            }
        }
    }

    Matrix L = Matrix::zeros(n, n);

    for (std::size_t j = 0; j < n; ++j) {
        double sum = A(j, j);
        for (std::size_t k = 0; k < j; ++k) {
            sum -= L(j, k) * L(j, k);
        }

        if (sum <= tolerance) {
            std::ostringstream oss;
            oss << "cholesky_factor: matrix is not positive definite (diagonal became "
                << sum << " at step " << j << ")";
            throw LinAlgError(oss.str());
        }

        L(j, j) = std::sqrt(sum);

        for (std::size_t i = j + 1; i < n; ++i) {
            double s = A(i, j);
            for (std::size_t k = 0; k < j; ++k) {
                s -= L(i, k) * L(j, k);
            }
            L(i, j) = s / L(j, j);
        }
    }

    return CholeskyResult{std::move(L)};
}

Vector cholesky_solve(const CholeskyResult& chol, const Vector& b) {
    const std::size_t n = chol.L.rows();

    if (b.size() != n) {
        std::ostringstream oss;
        oss << "cholesky_solve: rhs size " << b.size()
            << " does not match factorization size " << n;
        throw DimensionMismatchError(oss.str());
    }

    const Vector y = forward_substitution(chol.L, b);
    return backward_substitution(transpose(chol.L), y);
}

}  // namespace linalgebra