File: gaussianquadratures.cpp

package info (click to toggle)
quantlib 1.40-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 41,768 kB
  • sloc: cpp: 398,987; makefile: 6,574; python: 214; sh: 150; lisp: 86
file content (463 lines) | stat: -rw-r--r-- 16,385 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2005, 2016 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
 <https://www.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/types.hpp>
#include <ql/math/matrix.hpp>
#include <ql/math/randomnumbers/mt19937uniformrng.hpp>
#include <ql/math/distributions/normaldistribution.hpp>
#include <ql/math/integrals/gaussianquadratures.hpp>
#include <ql/math/integrals/momentbasedgaussianpolynomial.hpp>
#include <ql/math/integrals/gausslaguerrecosinepolynomial.hpp>
#include <ql/experimental/math/gaussiannoncentralchisquaredpolynomial.hpp>

#include <boost/math/distributions/non_central_chi_squared.hpp>

#ifndef TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE
//#define TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE
#endif

#ifdef TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE
    #if BOOST_VERSION < 105300
        #error This boost version is too old to support boost multi precision
    #endif

    #include <boost/multiprecision/cpp_dec_float.hpp>
#endif

using namespace QuantLib;
using namespace boost::unit_test_framework;

BOOST_FIXTURE_TEST_SUITE(QuantLibTests, TopLevelFixture)

BOOST_AUTO_TEST_SUITE(GaussianQuadraturesTests)

template <class T>
void testSingle(const T& I, const std::string& tag,
                const boost::function<Real(Real)>& f, Real expected) {
    Real calculated = I(f);
    if (std::fabs(calculated-expected) > 1.0e-4) {
        BOOST_ERROR("integrating" << tag << "\n"
                    << "    calculated: " << calculated << "\n"
                    << "    expected:   " << expected);
    }
}

// test functions

Real inv_exp(Real x) {
    return std::exp(-x);
}

Real x_inv_exp(Real x) {
    return x*std::exp(-x);
}

Real x_normaldistribution(Real x) {
    return x*NormalDistribution()(x);
}

Real x_x_normaldistribution(Real x) {
    return x*x*NormalDistribution()(x);
}

Real inv_cosh(Real x) {
    return 1/std::cosh(x);
}

Real x_inv_cosh(Real x) {
    return x/std::cosh(x);
}

Real x_x_nonCentralChiSquared(Real x) {
    return x * x * boost::math::pdf(
            boost::math::non_central_chi_squared_distribution<Real>(4.0,1.0),x);
}

Real x_sin_exp_nonCentralChiSquared(Real x) {
    return x * std::sin(0.1*x) * std::exp(0.3*x) * boost::math::pdf(
            boost::math::non_central_chi_squared_distribution<Real>(1.0,1.0),x);
}

template <class T>
void testSingleJacobi(const T& I) {
    testSingle(I, "f(x) = 1",
               [](Real x) -> Real { return 1.0; }, 2.0);
    testSingle(I, "f(x) = x",
               [](Real x) -> Real { return x; }, 0.0);
    testSingle(I, "f(x) = x^2",
               [](Real x) -> Real{ return x * x; }, 2/3.);
    testSingle(I, "f(x) = sin(x)",
               [](Real x) -> Real { return std::sin(x); }, 0.0);
    testSingle(I, "f(x) = cos(x)",
               [](Real x) -> Real { return std::cos(x); },
               std::sin(1.0)-std::sin(-1.0));
    testSingle(I, "f(x) = Gaussian(x)",
               NormalDistribution(),
               CumulativeNormalDistribution()(1.0)
               -CumulativeNormalDistribution()(-1.0));
}

template <class T>
void testSingleLaguerre(const T& I) {
    testSingle(I, "f(x) = exp(-x)",
               inv_exp, 1.0);
    testSingle(I, "f(x) = x*exp(-x)",
               x_inv_exp, 1.0);
    testSingle(I, "f(x) = Gaussian(x)",
               NormalDistribution(), 0.5);
}

void testSingleTabulated(const boost::function<Real(Real)>& f,
                         const std::string& tag,
                         Real expected, Real tolerance) {
    const Size order[] = { 6, 7, 12, 20 };
    TabulatedGaussLegendre quad;
    for (unsigned long i : order) {
        quad.order(i);
        Real realised = quad(f);
        if (std::fabs(realised-expected) > tolerance) {
            BOOST_ERROR(" integrating " << tag << "\n"
                        << "    order " << i << "\n"
                        << "    realised: " << realised << "\n"
                        << "    expected: " << expected);
        }
    }
}

template <class mp_float>
class MomentBasedGaussLaguerrePolynomial
    : public MomentBasedGaussianPolynomial<mp_float> {
  public:
    mp_float moment(Size i) const override {
        if (i == 0)
            return mp_float(1.0);
        else
            return mp_float(i)*moment(i-1);
    }

    Real w(Real x) const override { return std::exp(-x); }
};


BOOST_AUTO_TEST_CASE(testJacobi) {
    BOOST_TEST_MESSAGE("Testing Gauss-Jacobi integration...");

    testSingleJacobi(GaussLegendreIntegration(16));
    testSingleJacobi(GaussChebyshevIntegration(130));
    testSingleJacobi(GaussChebyshev2ndIntegration(130));
    testSingleJacobi(GaussGegenbauerIntegration(50,0.55));
}

BOOST_AUTO_TEST_CASE(testLaguerre) {
     BOOST_TEST_MESSAGE("Testing Gauss-Laguerre integration...");

     testSingleLaguerre(GaussLaguerreIntegration(16));
     testSingleLaguerre(GaussLaguerreIntegration(150,0.01));

     testSingle(GaussLaguerreIntegration(16, 1.0), "f(x) = x*exp(-x)",
                x_inv_exp, 1.0);
     testSingle(GaussLaguerreIntegration(32, 0.9), "f(x) = x*exp(-x)",
                x_inv_exp, 1.0);
}

BOOST_AUTO_TEST_CASE(testHermite) {
     BOOST_TEST_MESSAGE("Testing Gauss-Hermite integration...");

     testSingle(GaussHermiteIntegration(16), "f(x) = Gaussian(x)",
                NormalDistribution(), 1.0);
     testSingle(GaussHermiteIntegration(16,0.5), "f(x) = x*Gaussian(x)",
                x_normaldistribution, 0.0);
     testSingle(GaussHermiteIntegration(64,0.9), "f(x) = x*x*Gaussian(x)",
                x_x_normaldistribution, 1.0);
}

BOOST_AUTO_TEST_CASE(testHyperbolic) {
     BOOST_TEST_MESSAGE("Testing Gauss hyperbolic integration...");

     testSingle(GaussHyperbolicIntegration(16), "f(x) = 1/cosh(x)",
                inv_cosh, M_PI);
     testSingle(GaussHyperbolicIntegration(16), "f(x) = x/cosh(x)",
                x_inv_cosh, 0.0);
}

BOOST_AUTO_TEST_CASE(testTabulated) {
     BOOST_TEST_MESSAGE("Testing tabulated Gauss-Laguerre integration...");

     testSingleTabulated([](Real x) -> Real { return x; }, "f(x) = x",
                         0.0,       1.0e-13);
     testSingleTabulated([](Real x) -> Real { return x * x; }, "f(x) = x^2",
                         (2.0/3.0), 1.0e-13);
     testSingleTabulated([](Real x) -> Real { return x * x * x; }, "f(x) = x^3",
                         0.0,       1.0e-13);
     testSingleTabulated([](Real x) -> Real { return x * x * x * x; }, "f(x) = x^4",
                         (2.0/5.0), 1.0e-13);
}

BOOST_AUTO_TEST_CASE(testMomentBasedGaussianPolynomial) {
     BOOST_TEST_MESSAGE("Testing moment-based Gaussian polynomials...");

     GaussLaguerrePolynomial g;

     std::vector<ext::shared_ptr<GaussianOrthogonalPolynomial> > ml;
     ml.push_back(
         ext::make_shared<MomentBasedGaussLaguerrePolynomial<Real> >());

#ifdef TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE
     ml.push_back(
         ext::make_shared<MomentBasedGaussLaguerrePolynomial<
             boost::multiprecision::number<
                 boost::multiprecision::cpp_dec_float<20> > > >());
#endif

     const Real tol = 1e-12;
     for (auto& k : ml) {

         for (Size i=0; i < 10; ++i) {
             const Real diffAlpha = std::fabs(k->alpha(i) - g.alpha(i));
             const Real diffBeta = std::fabs(k->beta(i) - g.beta(i));

             if (diffAlpha > tol) {
                 BOOST_ERROR("failed to reproduce alpha for Laguerre quadrature"
                             << "\n    calculated: " << k->alpha(i) << "\n    expected  : "
                             << g.alpha(i) << "\n    diff      : " << diffAlpha);
             }
             if (i > 0 && diffBeta > tol) {
                 BOOST_ERROR("failed to reproduce beta for Laguerre quadrature"
                             << "\n    calculated: " << k->beta(i) << "\n    expected  : "
                             << g.beta(i) << "\n    diff      : " << diffBeta);
             }
         }
     }
}

BOOST_AUTO_TEST_CASE(testGaussLaguerreCosinePolynomial) {
    BOOST_TEST_MESSAGE("Testing Gauss-Laguerre-Cosine quadrature...");

    const GaussianQuadrature quadCosine(
            16, GaussLaguerreCosinePolynomial<Real>(0.2));

    testSingle(quadCosine, "f(x) = exp(-x)",
               inv_exp, 1.0);
    testSingle(quadCosine, "f(x) = x*exp(-x)",
               x_inv_exp, 1.0);

    const GaussianQuadrature quadSine(
            16, GaussLaguerreSinePolynomial<Real>(0.2));

    testSingle(quadSine, "f(x) = exp(-x)",
               inv_exp, 1.0);
    testSingle(quadSine, "f(x) = x*exp(-x)",
               x_inv_exp, 1.0);
}

BOOST_AUTO_TEST_CASE(testNonCentralChiSquared) {
    BOOST_TEST_MESSAGE(
        "Testing Gauss non-central chi-squared integration...");

    testSingle(
        GaussianQuadrature(2, GaussNonCentralChiSquaredPolynomial(4.0, 1.0)),
        "f(x) = x^2 * nonCentralChiSquared(4, 1)(x)",
        x_x_nonCentralChiSquared, 37.0);

    testSingle(
        GaussianQuadrature(14, GaussNonCentralChiSquaredPolynomial(1.0, 1.0)),
        "f(x) = x * sin(0.1*x)*exp(0.3*x)*nonCentralChiSquared(1, 1)(x)",
        x_sin_exp_nonCentralChiSquared, 17.408092);
}

BOOST_AUTO_TEST_CASE(testNonCentralChiSquaredSumOfNodes) {
    BOOST_TEST_MESSAGE(
        "Testing Gauss non-central chi-squared sum of nodes...");

    // Walter Gautschi, How and How not to check Gaussian Quadrature Formulae
    // https://www.cs.purdue.edu/homes/wxg/selected_works/section_08/084.pdf

    // Expected results have been calculated with a multi precision library
    // following the description of test #4 in the paper above.
    // Using QuantLib's own determinant function will not work here
    // as it supports only double precision.

    const Real expected[] = {
        47.53491786730293,
        70.6103295419633383,
        98.0593406849441607,
        129.853401537905341,
        165.96963582663912,
        206.389183233992043
    };

    const Real nu=4.0;
    const Real lambda=1.0;
    const GaussNonCentralChiSquaredPolynomial orthPoly(nu, lambda);

    const Real tol = 1e-5;

    for (Size n = 4; n < 10; ++n) {
         const Array x = GaussianQuadrature(n, orthPoly).x();
         const Real calculated = std::accumulate(x.begin(), x.end(), Real(0.0));


         if (std::fabs(calculated - expected[n-4]) > tol) {
             BOOST_ERROR("failed to reproduce rule of sum"
                         << "\n    calculated: " << calculated
                         << "\n    expected:   " << expected[n-4]
                         << "\n    diff    :   " << calculated - expected[n-4]);
         }
    }
}


BOOST_AUTO_TEST_CASE(testMultiDimensionalGaussIntegration) {
    BOOST_TEST_MESSAGE("Testing multi-dimensional Gaussian quadrature...");

    const auto normal = [](const Array& x) -> Real {
        return std::exp(-DotProduct(x, x));
    };

    for (Size n=1; n < 5; ++n) {
        std::vector<Size> ns(n);
        std::iota(ns.begin(), ns.end(), Size(1));

        MultiDimGaussianIntegration quad(
            ns,
            [](const Size n) {
               return ext::make_shared<GaussHermiteIntegration>(n);
            }
        );

        constexpr double tol = 1e4*QL_EPSILON;

        const Real calculated = quad(normal);
        const Real expected = std::sqrt(std::pow(M_PI, Real(n)));
        const Real diff = std::abs(expected-calculated);
        if (diff > tol) {
            BOOST_ERROR("failed to reproduce multi dimensional Gaussian quadrature"
                        << std::setprecision(12)
                        << "\n    calculated: " << calculated
                        << "\n    expected:   " << expected
                        << "\n    diff:       " << diff);
        }
    }

    // testing some Gaussian Integrals
    // https://en.wikipedia.org/wiki/Gaussian_integral
    MersenneTwisterUniformRng rng(1234);
    const std::vector<Size> ns = {20, 28, 16, 22};
    const std::vector<Real> tols = {1e-8, 1e-6, 1e-2, 5e-2};
    for (Size n=1; n < 5; ++n) {
        // create symmetric positive-definite matrix
        Matrix a(n, n);
        for (Size i=0; i < n; ++i)
            for (Size j=0; j < n; ++j)
                a[i][j] = (i==j) ? (i+1) : rng.nextReal();

        const Matrix A = a*transpose(a);
        const Matrix invA = inverse(A);
        const Real det_2piA = std::sqrt(determinant(M_TWOPI*invA));

        const MultiDimGaussianIntegration quad(
            std::vector<Size>(ns.begin(), ns.begin()+n),
            [](const Size n) { return ext::make_shared<GaussHermiteIntegration>(n); }
        );

        const Real calculated = quad(
            [&A](const Array& x) -> Real { return std::exp(-0.5*DotProduct(x, A*x)); }
        );

        const Real expected = det_2piA;
        const Real diff = std::abs(calculated - expected);
        if (diff > tols[n-1]) {
            BOOST_ERROR("failed to reproduce multi dimensional Gaussian quadrature"
                        << "\n    dimensions: " << n
                        << std::setprecision(12)
                        << "\n    calculated: " << calculated
                        << "\n    expected:   " << expected
                        << "\n    diff:       " << diff
                        << "\n    tolerance:  " << tols[n-1]);
        }
    }


    Matrix a(3, 3);
    for (Size i=0; i < 3; ++i)
        for (Size j=0; j < 3; ++j)
            a[i][j] = (i==j) ? (i+1) : rng.nextReal();

    const Matrix A = a*transpose(a);
    const Matrix invA = inverse(A);
    const Real sqrt_det_2piA = std::sqrt(determinant(M_TWOPI*invA));

    const MultiDimGaussianIntegration quadHigh(
        std::vector<Size>({22, 18, 26}),
        [](const Size n) { return ext::make_shared<GaussHermiteIntegration>(n); }
    );
    const MultiDimGaussianIntegration quad2(
        std::vector<Size>(3, 2),
        [](const Size n) { return ext::make_shared<GaussHermiteIntegration>(n); }
    );

    for (Size i=0; i < 3; ++i)
        for (Size j=0; j < 3; ++j) {
            const Real expected = sqrt_det_2piA*invA[i][j];

            Real calculated = quadHigh(
                [&A, i, j](const Array& x) -> Real {
                    return x[i]*x[j]*std::exp(-0.5*DotProduct(x, A*x));
                }
            );

            Real diff = std::abs(calculated - expected);
            Real tol = 1e-4;
            if (diff > tol) {
                BOOST_ERROR("failed to reproduce multi dimensional Gaussian quadrature"
                            << std::setprecision(12)
                            << "\n    calculated: " << calculated
                            << "\n    expected:   " << expected
                            << "\n    diff:       " << diff
                            << "\n    tolerance:  " << tol);
            }

            Matrix inva = inverse(transpose(a));
            calculated = quad2(
                [&inva, i, j](const Array& x) -> Real {
                    const Array f = M_SQRT2*inva*x;
                    return f[i]*f[j]*std::exp(-DotProduct(x, x));
                }
            );

            calculated *= determinant(M_SQRT2*inva);
            diff = std::abs(calculated - expected);
            tol = QL_EPSILON*1e4;
            if (diff > tol) {
                BOOST_ERROR("failed to reproduce multi dimensional Gaussian quadrature"
                            << std::setprecision(12)
                            << "\n    calculated: " << calculated
                            << "\n    expected:   " << expected
                            << "\n    diff:       " << diff
                            << "\n    tolerance:  " << tol);
            }
        }
}


BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()