Coverage Report

Created: 2025-08-28 06:30

/src/quantlib/ql/math/matrixutilities/expm.cpp
Line
Count
Source (jump to first uncovered line)
1
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3
/*
4
 Copyright (C) 2013 Klaus Spanderen
5
6
 This file is part of QuantLib, a free-software/open-source library
7
 for financial quantitative analysts and developers - http://quantlib.org/
8
9
 QuantLib is free software: you can redistribute it and/or modify it
10
 under the terms of the QuantLib license.  You should have received a
11
 copy of the license along with this program; if not, please email
12
 <quantlib-dev@lists.sf.net>. The license is also available online at
13
 <http://quantlib.org/license.shtml>.
14
15
 This program is distributed in the hope that it will be useful, but WITHOUT
16
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17
 FOR A PARTICULAR PURPOSE.  See the license for more details.
18
*/
19
20
/*! \file expm.cpp
21
    \brief matrix exponential
22
*/
23
24
25
#include <ql/math/matrixutilities/expm.hpp>
26
#include <ql/math/ode/adaptiverungekutta.hpp>
27
#include <algorithm>
28
#include <numeric>
29
#include <utility>
30
31
namespace QuantLib {
32
33
    namespace {
34
        class MatrixVectorProductFct {
35
          public:
36
0
            explicit MatrixVectorProductFct(Matrix m) : m_(std::move(m)) {}
37
38
            // implements x = M*y
39
0
            std::vector<Real> operator()(Real t, const std::vector<Real>& y) {
40
41
0
                std::vector<Real> result(m_.rows());
42
0
                for (Size i=0; i < result.size(); i++) {
43
0
                    result[i] = std::inner_product(y.begin(), y.end(),
44
0
                                                   m_.row_begin(i), Real(0.0));
45
0
                }
46
0
                return result;
47
0
            }
48
          private:
49
            const Matrix m_;
50
        };
51
    }
52
53
0
    Matrix Expm(const Matrix& M, Real t, Real tol) {
54
0
        const Size n = M.rows();
55
0
        QL_REQUIRE(n == M.columns(), "Expm expects a square matrix");
56
57
0
        AdaptiveRungeKutta<> rk(tol);
58
0
        AdaptiveRungeKutta<>::OdeFct odeFct = MatrixVectorProductFct(M);
59
60
0
        Matrix result(n, n);
61
0
        for (Size i=0; i < n; ++i) {
62
0
            std::vector<Real> x0(n, 0.0);
63
0
            x0[i] = 1.0;
64
65
0
            const std::vector<Real> r = rk(odeFct, x0, 0.0, t);
66
0
            std::copy(r.begin(), r.end(), result.column_begin(i));
67
0
        }
68
0
        return result;
69
0
    }
70
}