File: ode.cpp

package info (click to toggle)
quantlib 1.39-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 41,264 kB
  • sloc: cpp: 396,561; makefile: 6,539; python: 272; sh: 154; lisp: 86
file content (217 lines) | stat: -rw-r--r-- 7,624 bytes parent folder | download | duplicates (2)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2012 Peter Caspers
 Copyright (C) 2013 Klaus Spanderen

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include "toplevelfixture.hpp"
#include "utilities.hpp"
#include <ql/math/matrixutilities/expm.hpp>
#include <ql/math/ode/adaptiverungekutta.hpp>
#include <complex>

using namespace QuantLib;
using namespace boost::unit_test_framework;

using std::exp;
using std::sin;

BOOST_FIXTURE_TEST_SUITE(QuantLibTests, TopLevelFixture)

BOOST_AUTO_TEST_SUITE(OdeTests)

struct ode1 {
    Real operator()(Real x, Real y) const { return y; }
};

struct ode2 {
    std::complex<Real> operator()(Real x,
                                  const std::complex<Real>& y) {
        return std::complex<Real>(0.0,1.0)*y;
    }
};

struct ode3 {
    std::vector<Real> operator()(Real x, const std::vector<Real>& y) {
        std::vector<Real> r(2);
        r[0] = y[1]; r[1] = -y[0];
        return r;
    }
};

struct ode4 {
    std::vector<std::complex<Real> > operator()(
                                                const std::complex<Real>& x,
                                                const std::vector<std::complex<Real> >& y) {
        std::vector<std::complex<Real> > r(2);
        r[0] = y[1]; r[1] = -y[0];
        return r;
    }
};


BOOST_AUTO_TEST_CASE(testAdaptiveRungeKutta) {

    BOOST_TEST_MESSAGE("Testing adaptive Runge Kutta...");

    AdaptiveRungeKutta<Real> rk_real(1E-12,1E-4,0.0);
    AdaptiveRungeKutta<std::complex<Real> > rk_complex(1E-12,1E-4,0.0);
    Real tol1 = 5E-10, tol2 = 2E-12, tol3 = 2E-12, tol4 = 2E-12;

    // f'=f, f(0)=1
    AdaptiveRungeKutta<Real>::OdeFct1d ode1_ = ode1();
    Real y10=1;

    // f'=f, f(0)=i
    AdaptiveRungeKutta<std::complex<Real> >::OdeFct1d ode2_ = ode2();
    std::complex<Real> y20(0.0,1.0);

    // f''=-f, f(0)=0, f'(0)=1
    AdaptiveRungeKutta<Real>::OdeFct ode3_ = ode3();
    std::vector<Real> y30(2); y30[0] = 0.0; y30[1] = 1.0;

    // f''=-f, f(0)=1, f'(0)=i
    AdaptiveRungeKutta<std::complex<Real> >::OdeFct ode4_ = ode4();
    std::vector<std::complex<Real> > y40(2);
    y40[0] = 1.0;
    y40[1] = std::complex<Real>(0.0,1.0);

    Real x=0.0;
    Real y1 = y10;
    std::complex<Real> y2 = y20;
    std::vector<Real> y3 = y30;
    std::vector<std::complex<Real> > y4 = y40;

    while (x<5.0) {
        Real exact1 = exp(x);
        std::complex<Real> exact2 =
            std::exp(std::complex<Real>(0.0,x)) * std::complex<Real>(0.0,1.0);
        Real exact3 = sin(x);
        std::complex<Real> exact4 = std::exp(std::complex<Real>(0.0,x));

        if ( std::fabs( exact1 - y1 ) > tol1 )
            BOOST_FAIL("Error in ode #1: exact solution at x=" << x
                       << " is " << exact1
                       << ", numerical solution is " << y1
                       << " difference " << std::fabs(exact1-y1)
                       << " outside tolerance " << tol1);
        if ( abs( exact2 - y2 ) > tol2 )
            BOOST_FAIL("Error in ode #2: exact solution at x=" << x
                       << " is " << exact2
                       << ", numerical solution is " << y2
                       << " difference " << abs(exact2-y2)
                       << " outside tolerance " << tol2);
        if ( std::fabs( exact3 - y3[0] ) > tol3 )
            BOOST_FAIL("Error in ode #3: exact solution at x=" << x
                       << " is " << exact3
                       << ", numerical solution is " << y3[0]
                       << " difference " << std::fabs(exact3-y3[0])
                       << " outside tolerance " << tol3);
        if ( abs( exact4 - y4[0] ) > tol4 )
            BOOST_FAIL("Error in ode #4: exact solution at x=" << x
                       << " is " << exact4
                       << ", numerical solution is " << y4[0]
                       << " difference " << abs(exact4-y4[0])
                       << " outside tolerance " << tol4);
        x+=0.01;
        y1=rk_real(ode1_,y10,0.0,x);
        y2=rk_complex(ode2_,y20,0.0,x);
        y3=rk_real(ode3_,y30,0.0,x);
        y4=rk_complex(ode4_,y40,0.0,x);
    }
}


Real frobenuiusNorm(const Matrix& m) {
    return std::sqrt(DotProduct((m*transpose(m)).diagonal(),
                                Array(m.rows(), 1.0)));
}


BOOST_AUTO_TEST_CASE(testMatrixExponential) {
    BOOST_TEST_MESSAGE("Testing matrix exponential based on ode...");

    // Reference results are taken from
    // http://www.millersville.edu/~bikenaga/linear-algebra/matrix-exponential/matrix-exponential.html

    Matrix m(3, 3);
    m[0][0] = 5; m[0][1] =-6; m[0][2] =-6;
    m[1][0] =-1; m[1][1] = 4; m[1][2] = 2;
    m[2][0] = 3; m[2][1] =-6; m[2][2] =-4;

    const Real tol = 1e-12;

    for (Real t=0.01; t < 11; t+=t) {
        const Matrix calculated = Expm(m, t, tol);

        Matrix expected(3, 3);
        expected[0][0] = -3*std::exp(t)+4*std::exp(2*t);
        expected[0][1] =  6*std::exp(t)-6*std::exp(2*t);
        expected[0][2] =  6*std::exp(t)-6*std::exp(2*t);
        expected[1][0] =    std::exp(t)-  std::exp(2*t);
        expected[1][1] = -2*std::exp(t)+3*std::exp(2*t);
        expected[1][2] = -2*std::exp(t)+2*std::exp(2*t);
        expected[2][0] = -3*std::exp(t)+3*std::exp(2*t);
        expected[2][1] =  6*std::exp(t)-6*std::exp(2*t);
        expected[2][2] =  6*std::exp(t)-5*std::exp(2*t);

        Matrix diff = calculated - expected;
        Real relDiffNorm = frobenuiusNorm(diff)/frobenuiusNorm(expected);

        if ( std::fabs(relDiffNorm) > 100*tol) {
            BOOST_FAIL("Failed to reproduce expected matrix exponential."
                    << "\n rel. difference norm: " << relDiffNorm
                    << "\n tolerance           : " << 100*tol);
        }

        const Matrix negativeTime = Expm((-1)*m, -t, tol);
        diff = negativeTime - expected;
        relDiffNorm = frobenuiusNorm(diff)/frobenuiusNorm(expected);

        if ( std::fabs(relDiffNorm) > 100*tol) {
            BOOST_FAIL("Failed to reproduce expected matrix exponential."
                    << "\n rel. difference norm: " << relDiffNorm
                    << "\n tolerance           : " << 100*tol);
        }

    }
}

BOOST_AUTO_TEST_CASE(testMatrixExponentialOfZero) {
    BOOST_TEST_MESSAGE("Testing matrix exponential of a zero matrix "
                       "based on ode...");

    Matrix m(3, 3, 0.0);

    constexpr double tol = 100*QL_EPSILON;
    constexpr double t=1.0;
    const Matrix calculated = Expm(m, t);

    for (Size i=0; i < calculated.rows(); ++i) {
        for (Size j=0; j < calculated.columns(); ++j) {
            const Real kroneckerDelta = (i==j)? 1.0 : 0.0;
            if (std::fabs(calculated[i][j] -kroneckerDelta) > tol) {
                BOOST_FAIL("Failed to reproduce expected matrix exponential."
                        << "\n tolerance           : " << tol);
            }
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()