libitofin 0.52.1

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
Documentation
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
//! Orthogonal polynomials for Gaussian quadratures.
//!
//! Port of `ql/math/integrals/gaussianorthogonalpolynomial.{hpp,cpp}`. A
//! family of orthogonal polynomials is defined by the three-term recurrence
//!
//! ```text
//! P_{k+1}(x) = (x - alpha_k) P_k(x) - beta_k P_{k-1}(x)
//! ```
//!
//! together with the zeroth moment `mu_0 = integral of w(x) dx` of its weight
//! function `w`. References: Golub and Welsch, "Calculation of Gauss
//! quadrature rules", Math. Comput. 23 (1969); "Numerical Recipes in C", 2nd
//! edition.

use crate::errors::QlResult;
use crate::math::comparison::close_enough;
use crate::math::gammafunction::log_gamma;
use crate::require;
use crate::types::{Real, Size};

/// A family of orthogonal polynomials defining a Gaussian quadrature: the
/// recurrence coefficients `alpha_k`, `beta_k`, the weight function `w`, and
/// its zeroth moment `mu_0`.
///
/// Port of the `GaussianOrthogonalPolynomial` base class; the C++ virtuals
/// are the required methods here, with the concrete `value`/`weightedValue`
/// provided on top of them.
pub trait GaussianOrthogonalPolynomial {
    /// The zeroth moment of the weight function, `integral of w(x) dx`.
    fn mu_0(&self) -> Real;

    /// The recurrence coefficient `alpha_i`.
    fn alpha(&self, i: Size) -> Real;

    /// The recurrence coefficient `beta_i`.
    fn beta(&self, i: Size) -> Real;

    /// The weight function `w(x)`.
    fn w(&self, x: Real) -> Real;

    /// `ln(w(x))` (QuantLib's `logW`), used by the quadrature weights when
    /// `w(x)` under- or overflows; families override it with a form that
    /// stays finite in the tails.
    fn log_w(&self, x: Real) -> Real {
        self.w(x).ln()
    }

    /// The value of the monic polynomial `P_n(x)` via the three-term
    /// recurrence (iterative form of QuantLib's recursive `value`).
    fn value(&self, n: Size, x: Real) -> Real {
        let mut previous = 1.0;
        if n == 0 {
            return previous;
        }
        let mut current = x - self.alpha(0);
        for k in 1..n {
            let next = (x - self.alpha(k)) * current - self.beta(k) * previous;
            previous = current;
            current = next;
        }
        current
    }

    /// `sqrt(w(x)) * P_n(x)`.
    fn weighted_value(&self, n: Size, x: Real) -> Real {
        self.w(x).sqrt() * self.value(n, x)
    }
}

/// Gauss-Jacobi polynomial, weight `w(x) = (1-x)^alpha (1+x)^beta` on
/// `[-1, 1]`.
///
/// The Legendre, Chebyshev (both kinds) and Gegenbauer families are the
/// special cases exposed as constructors, replacing QuantLib's subclasses.
#[derive(Clone, Copy, Debug)]
pub struct GaussJacobiPolynomial {
    alpha: Real,
    beta: Real,
}

impl GaussJacobiPolynomial {
    /// A Jacobi polynomial family with weight exponents `alpha` and `beta`.
    ///
    /// # Errors
    ///
    /// Returns an error unless `alpha > -1`, `beta > -1` and
    /// `alpha + beta > -2`.
    pub fn new(alpha: Real, beta: Real) -> QlResult<Self> {
        require!(
            (alpha + beta).is_finite() && alpha + beta > -2.0,
            "alpha+beta must be bigger than -2"
        );
        require!(
            alpha.is_finite() && alpha > -1.0,
            "alpha must be bigger than -1"
        );
        require!(
            beta.is_finite() && beta > -1.0,
            "beta  must be bigger than -1"
        );
        Ok(GaussJacobiPolynomial { alpha, beta })
    }

    /// Gauss-Legendre polynomial: Jacobi with `alpha = beta = 0`, weight
    /// `w(x) = 1`.
    pub fn legendre() -> Self {
        GaussJacobiPolynomial {
            alpha: 0.0,
            beta: 0.0,
        }
    }

    /// Gauss-Chebyshev polynomial (first kind): Jacobi with
    /// `alpha = beta = -1/2`, weight `w(x) = (1-x^2)^(-1/2)`.
    pub fn chebyshev() -> Self {
        GaussJacobiPolynomial {
            alpha: -0.5,
            beta: -0.5,
        }
    }

    /// Gauss-Chebyshev polynomial (second kind): Jacobi with
    /// `alpha = beta = 1/2`, weight `w(x) = (1-x^2)^(1/2)`.
    pub fn chebyshev2nd() -> Self {
        GaussJacobiPolynomial {
            alpha: 0.5,
            beta: 0.5,
        }
    }

    /// Gauss-Gegenbauer polynomial: Jacobi with
    /// `alpha = beta = lambda - 1/2`, weight `w(x) = (1-x^2)^(lambda-1/2)`.
    ///
    /// # Errors
    ///
    /// Returns an error unless `lambda > -1/2`.
    pub fn gegenbauer(lambda: Real) -> QlResult<Self> {
        Self::new(lambda - 0.5, lambda - 0.5)
    }
}

impl GaussianOrthogonalPolynomial for GaussJacobiPolynomial {
    fn mu_0(&self) -> Real {
        // The gamma arguments are alpha+1, beta+1 and alpha+beta+2, all
        // strictly positive by construction, so log_gamma cannot fail.
        let log = log_gamma(self.alpha + 1.0).expect("alpha + 1 > 0 by construction")
            + log_gamma(self.beta + 1.0).expect("beta + 1 > 0 by construction")
            - log_gamma(self.alpha + self.beta + 2.0)
                .expect("alpha + beta + 2 > 0 by construction");
        (2.0 as Real).powf(self.alpha + self.beta + 1.0) * log.exp()
    }

    /// # Panics
    ///
    /// Panics where QuantLib throws: when the recurrence denominator vanishes
    /// and l'Hospital's rule cannot recover it (unreachable for parameters
    /// accepted by the constructors and `i >= 1`).
    fn alpha(&self, i: Size) -> Real {
        let i = i as Real;
        let mut num = self.beta * self.beta - self.alpha * self.alpha;
        let mut denom =
            (2.0 * i + self.alpha + self.beta) * (2.0 * i + self.alpha + self.beta + 2.0);

        if close_enough(denom, 0.0) {
            assert!(
                close_enough(num, 0.0),
                "can't compute a_k for jacobi integration"
            );
            num = 2.0 * self.beta;
            denom = 2.0 * (2.0 * i + self.alpha + self.beta + 1.0);
            assert!(
                !close_enough(denom, 0.0),
                "can't compute a_k for jacobi integration"
            );
        }

        num / denom
    }

    /// # Panics
    ///
    /// Panics where QuantLib throws: when the recurrence denominator vanishes
    /// and l'Hospital's rule cannot recover it (unreachable for parameters
    /// accepted by the constructors and `i >= 1`).
    fn beta(&self, i: Size) -> Real {
        let i = i as Real;
        let s = 2.0 * i + self.alpha + self.beta;
        let mut num = 4.0 * i * (i + self.alpha) * (i + self.beta) * (i + self.alpha + self.beta);
        let mut denom = s * s * (s * s - 1.0);

        if close_enough(denom, 0.0) {
            assert!(
                close_enough(num, 0.0),
                "can't compute b_k for jacobi integration"
            );
            num = 4.0 * i * (i + self.beta) * (2.0 * i + 2.0 * self.alpha + self.beta);
            denom = 2.0 * s;
            denom *= denom - 1.0;
            assert!(
                !close_enough(denom, 0.0),
                "can't compute b_k for jacobi integration"
            );
        }

        num / denom
    }

    fn w(&self, x: Real) -> Real {
        (1.0 - x).powf(self.alpha) * (1.0 + x).powf(self.beta)
    }
}

/// Generalized Gauss-Laguerre polynomial, weight `w(x; s) = x^s exp(-x)` on
/// `[0, inf)` with `s > -1`.
#[derive(Clone, Copy, Debug)]
pub struct GaussLaguerrePolynomial {
    s: Real,
}

impl GaussLaguerrePolynomial {
    /// A Laguerre polynomial family with weight exponent `s` (QuantLib
    /// defaults `s` to 0).
    ///
    /// # Errors
    ///
    /// Returns an error unless `s > -1`.
    pub fn new(s: Real) -> QlResult<Self> {
        require!(s.is_finite() && s > -1.0, "s must be bigger than -1");
        Ok(GaussLaguerrePolynomial { s })
    }
}

impl GaussianOrthogonalPolynomial for GaussLaguerrePolynomial {
    fn mu_0(&self) -> Real {
        log_gamma(self.s + 1.0)
            .expect("s + 1 > 0 by construction")
            .exp()
    }

    fn alpha(&self, i: Size) -> Real {
        2.0 * i as Real + 1.0 + self.s
    }

    fn beta(&self, i: Size) -> Real {
        let i = i as Real;
        i * (i + self.s)
    }

    fn w(&self, x: Real) -> Real {
        x.powf(self.s) * (-x).exp()
    }

    fn log_w(&self, x: Real) -> Real {
        self.s * x.ln() - x
    }
}

/// Generalized Gauss-Hermite polynomial, weight
/// `w(x; mu) = |x|^(2 mu) exp(-x^2)` on the real line with `mu > -1/2`.
#[derive(Clone, Copy, Debug)]
pub struct GaussHermitePolynomial {
    mu: Real,
}

impl GaussHermitePolynomial {
    /// A Hermite polynomial family with weight exponent `mu` (QuantLib
    /// defaults `mu` to 0).
    ///
    /// # Errors
    ///
    /// Returns an error unless `mu > -1/2`.
    pub fn new(mu: Real) -> QlResult<Self> {
        require!(mu.is_finite() && mu > -0.5, "mu must be bigger than -0.5");
        Ok(GaussHermitePolynomial { mu })
    }
}

impl GaussianOrthogonalPolynomial for GaussHermitePolynomial {
    fn mu_0(&self) -> Real {
        log_gamma(self.mu + 0.5)
            .expect("mu + 1/2 > 0 by construction")
            .exp()
    }

    fn alpha(&self, _i: Size) -> Real {
        0.0
    }

    fn beta(&self, i: Size) -> Real {
        if i.is_multiple_of(2) {
            i as Real / 2.0
        } else {
            i as Real / 2.0 + self.mu
        }
    }

    fn w(&self, x: Real) -> Real {
        x.abs().powf(2.0 * self.mu) * (-x * x).exp()
    }

    fn log_w(&self, x: Real) -> Real {
        2.0 * self.mu * x.abs().ln() - x * x
    }
}

/// Gauss hyperbolic polynomial, weight `w(x) = 1/cosh(x)` on the real line.
#[derive(Clone, Copy, Debug, Default)]
pub struct GaussHyperbolicPolynomial;

impl GaussianOrthogonalPolynomial for GaussHyperbolicPolynomial {
    fn mu_0(&self) -> Real {
        std::f64::consts::PI
    }

    fn alpha(&self, _i: Size) -> Real {
        0.0
    }

    fn beta(&self, i: Size) -> Real {
        use std::f64::consts::{FRAC_PI_2, PI};
        if i != 0 {
            FRAC_PI_2 * FRAC_PI_2 * i as Real * i as Real
        } else {
            PI
        }
    }

    fn w(&self, x: Real) -> Real {
        1.0 / x.cosh()
    }

    /// Uses `ln(cosh x) = |x| - ln 2 + ln_1p(exp(-2|x|))`, since `cosh`
    /// overflows above `|x|` of about 710.
    fn log_w(&self, x: Real) -> Real {
        let ax = x.abs();
        -(ax - std::f64::consts::LN_2 + (-2.0 * ax).exp().ln_1p())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The log-space weights (QuantLib v1.44 `logWeight` overrides,
    /// gaussianorthogonalpolynomial.cpp:74,100,194) must equal `ln(w(x))`
    /// wherever `w` does not underflow. The v1.44 quadrature oracles only use
    /// `s = 0` and `mu = 0`, and the far-tail nodes that take the log-space
    /// path contribute below 1e-15 to any integral, so a `log_w` that dropped
    /// its `s` or `mu` term would pass them; this pins the terms directly.
    #[test]
    fn log_weights_equal_the_log_of_the_weights() {
        fn check(family: &str, log_w: Real, w: Real, x: Real) {
            let expected = w.ln();
            assert!(
                (log_w - expected).abs() <= 1e-12 * expected.abs().max(1.0),
                "{family}: log_w({x}) = {log_w}, ln(w({x})) = {expected}"
            );
        }
        let xs = [0.3, 1.0, 2.0, 5.0, 10.0];
        for s in [0.5, 1.5] {
            let p = GaussLaguerrePolynomial::new(s).unwrap();
            for x in xs {
                check("laguerre", p.log_w(x), p.w(x), x);
            }
        }
        for mu in [0.5, 1.0] {
            let p = GaussHermitePolynomial::new(mu).unwrap();
            for x in xs.iter().flat_map(|&x| [x, -x]) {
                check("hermite", p.log_w(x), p.w(x), x);
            }
        }
        let p = GaussHyperbolicPolynomial;
        for x in xs.iter().flat_map(|&x| [x, -x]) {
            check("hyperbolic", p.log_w(x), p.w(x), x);
        }
    }

    // Monic Legendre recurrence: alpha_k = 0, beta_k = k^2 / (4k^2 - 1),
    // weight w(x) = 1 on [-1, 1], mu_0 = 2.
    struct MonicLegendre;

    impl GaussianOrthogonalPolynomial for MonicLegendre {
        fn mu_0(&self) -> Real {
            2.0
        }
        fn alpha(&self, _i: Size) -> Real {
            0.0
        }
        fn beta(&self, i: Size) -> Real {
            let k = i as Real;
            k * k / (4.0 * k * k - 1.0)
        }
        fn w(&self, _x: Real) -> Real {
            1.0
        }
    }

    #[test]
    fn recurrence_reproduces_monic_legendre_polynomials() {
        let p = MonicLegendre;
        for &x in &[-0.9, -0.3, 0.0, 0.5, 1.0] {
            let x: Real = x;
            assert!((p.value(0, x) - 1.0).abs() < 1e-15);
            assert!((p.value(1, x) - x).abs() < 1e-15);
            assert!((p.value(2, x) - (x * x - 1.0 / 3.0)).abs() < 1e-15);
            assert!((p.value(3, x) - (x * x * x - 0.6 * x)).abs() < 1e-15);
        }
    }

    #[test]
    fn weighted_value_scales_by_sqrt_of_weight() {
        let p = MonicLegendre;
        assert!((p.weighted_value(2, 0.5) - p.value(2, 0.5)).abs() < 1e-15);
    }

    #[test]
    fn jacobi_with_zero_exponents_matches_legendre_recurrence() {
        let jacobi = GaussJacobiPolynomial::legendre();
        let legendre = MonicLegendre;
        assert!((jacobi.mu_0() - 2.0).abs() < 1e-14);
        for i in 0..10 {
            assert!(jacobi.alpha(i).abs() < 1e-14);
            if i > 0 {
                assert!((jacobi.beta(i) - legendre.beta(i)).abs() < 1e-14);
            }
        }
    }

    #[test]
    fn jacobi_rejects_out_of_domain_exponents() {
        assert!(GaussJacobiPolynomial::new(-1.0, 0.0).is_err());
        assert!(GaussJacobiPolynomial::new(0.0, -1.0).is_err());
        assert!(GaussJacobiPolynomial::new(-0.999, -1.5).is_err());
        assert!(GaussJacobiPolynomial::gegenbauer(-0.5).is_err());
    }

    #[test]
    fn laguerre_and_hermite_reject_out_of_domain_exponents() {
        assert!(GaussLaguerrePolynomial::new(-1.0).is_err());
        assert!(GaussHermitePolynomial::new(-0.5).is_err());
    }
}