quad 0.1.2

Quadrature integration
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use ::rayon::prelude::*;

use crate::constants::*;
use crate::errors::QagError;
use crate::qag_integration_result::QagIntegrationResult;
use crate::qk15::qk15_quadrature;
use crate::qk21::qk21_quadrature;
use crate::qk31::qk31_quadrature;
use crate::qk41::qk41_quadrature;
use crate::qk51::qk51_quadrature;
use crate::qk61::qk61_quadrature;
use crate::semi_infinite_function::{double_infinite_function, semi_infinite_function};
use std::collections::{BinaryHeap, HashMap};
use std::sync::Arc;

#[derive(Clone)]
pub struct Qag {
    pub key: i32,
    pub limit: usize,
    pub points: Vec<f64>,
    pub number_of_thread: usize,
    pub more_info: bool,
}

///           f      : f64
///                     function
///
///           a      : f64
///                    lower limit of integration
///
///           b      : f64
///                    upper limit of integration
///
///           epsabs : f64
///                    absolute accuracy requested
///
///           epsrel : f64
///                    relative accuracy requested
///                    if  epsabs <= 0 && epsrel <= max(50*rel.mach.acc.,0.5d-28),
///                    the fn will return with result_state = Invalid.
///
///            key   : i32
///                    key for choice of local integration rule. A gauss-kronrod pair is used with:
///                          7 - 15 points if key < 2,
///                         10 - 21 points if key = 2,
///                         15 - 31 points if key = 3,
///                         20 - 41 points if key = 4,
///                         25 - 51 points if key = 5,
///                         30 - 61 points if key > 5.
///
///            limit : i32
///                    gives an upperbound on the number of subintervals in the partition
///                    of (a,b), limit >= 1.
///
///
///
///         On return : QagIntegratorResult :
///
///           QagIntegrationResult:
///           result : f64
///                    Approximation to the integral.
///
///           abserr : f64
///                    Estimate of the modulus of the absolute error,
///                    which should equal or exceed abs(i-result).
///
///           neval  : i32
///                    Number of integrand evaluations.
///
///           alist  : Vec<f64>
///                      Vector of dimension at least limit, the elements of which are the left
///                      end points of the subintervals in the partition of the given integration
///                      range (a,b).
///
///           blist  : Vec<f64>
///                      Vector of dimension at least limit, the elements of which are the right
///                      end points of the subintervals in the partition of the given integration
///                      range (a,b).
///
///           rlist  : Vec<f64>
///                      Vector of dimension at least limit, the elements of which are the integral
///                      approximations on the subintervals.
///
///            rlist  : Vec<f64>
///                      Vector of dimension at least limit, the elements of which are the moduli
///                      of the absolute error estimates on the subintervals.
///
///            iord   : Vec<usize>
///                      Vector of dimension at least limit, the elements of which are pointers to
///                      the error estimates over the subintervals, such that
///                      elist(iord(1)), ...,elist(iord(k)) form a decreasing sequence,
///                      with k = last if last <= (limit/2+2), and
///                      k = limit+1-last otherwise.
///
///            last    : usize
///                      number of subintervals actually produced in the
///                      subdivision process
///
///
///
///
///           ResultState =
///           Success :
///                    Normal and reliable termination of the routine. it is assumed that the
///                    requested accuracy has been achieved.
///           MaxIteration :
///                    The maximum number of steps has been executed. the integral is probably too
///                    difficult to be calculated by dqng.
///           Invalid :
///                     The input is invalid, because epsabs <= 0 &&
///                     epsrel < max(50 * rel.mach.acc.,0.5e-28).
///           BadTolerance :
///                     The occurrence of roundoff error is detected, which prevents the requested
///                     tolerance from being achieved.
///           BadFunction :
///                     Extremely bad integrand behaviour occurs at some points of the integration
///                     interval.
///
///
///           If ResultState != Succes =>    It is assumed that the requested accuracy has not
///           been achieved.
///
///
///

impl Qag {
    pub fn integrate(
        &self,
        fun: &FnVec,
        a: f64,
        b: f64,
        epsabs: f64,
        epsrel: f64,
    ) -> Result<QagIntegrationResult, QagError> {
        let f = &fun.components;
        if b == f64::INFINITY && a.is_finite()
            || a == f64::NEG_INFINITY && b.is_finite()
            || a == f64::NEG_INFINITY && b == f64::INFINITY
        {
            let points = points_transformed(self.points.clone(), a, b);
            let qag = Qag {
                key: self.key,
                limit: self.limit,
                points,
                number_of_thread: self.number_of_thread,
                more_info: self.more_info,
            };

            if b == f64::INFINITY && a.is_finite() {
                let f2 = FnVec {
                    components: Arc::new(|x: f64| semi_infinite_function(&**f, x, a, b)),
                };
                return qag.qintegrate(&f2, 0.0, 1.0, epsabs, epsrel);
            } else if a == f64::NEG_INFINITY && b.is_finite() {
                let f2 = FnVec {
                    components: Arc::new(|x: f64| semi_infinite_function(&**f, x, b, a)),
                };
                return qag.qintegrate(&f2, 0.0, 1.0, epsabs, epsrel);
            } else if a == f64::NEG_INFINITY && b == f64::INFINITY {
                let f2 = FnVec {
                    components: Arc::new(|x: f64| double_infinite_function(&**f, x)),
                };
                return qag.qintegrate(&f2, -1.0, 1.0, epsabs, epsrel);
            };
        }

        self.qintegrate(&fun, a, b, epsabs, epsrel)
    }

    pub fn qintegrate(
        &self,
        fun: &FnVec,
        a: f64,
        b: f64,
        epsabs: f64,
        epsrel: f64,
    ) -> Result<QagIntegrationResult, QagError> {
        if epsabs <= 0.0 && epsrel < 0.5e-28_f64.max(50.0 * EPMACH) {
            return Err(QagError::Invalid);
        }

        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(self.number_of_thread)
            .build()
            .unwrap();

        let mut initial_intervals = vec![];
        let mut points = self.points.clone();
        points.sort_by(|a, b| a.partial_cmp(b).unwrap());

        if points.is_empty() {
            initial_intervals.push((a, b));
        } else {
            let mut prev = a;
            for p in points {
                if p > a && p < b {
                    initial_intervals.push((prev, p));
                    prev = p;
                }
            }
            initial_intervals.push((prev, b));
        }

        let f = &fun.components;
        let n: usize = f(0.0).len();
        let mut neval = 0;
        let mut last = 1;
        let mut interval_cache = HashMap::new();
        let mut heap = BinaryHeap::new();
        let mut result = vec![0.0; n];
        let mut abserr = 0.0;
        let mut rounderr = 0.0;
        let mut iroff1 = 0;
        let mut iroff2 = 0;
        let mut keyf = self.key;
        if self.key <= 0 {
            keyf = 1;
        }
        if self.key >= 7 {
            keyf = 6;
        }

        for comp in initial_intervals {
            let (result_temp, abserr_temp, rounderr_temp) = match keyf {
                1 => qk15_quadrature(&**f, comp.0, comp.1),
                2 => qk21_quadrature(&**f, comp.0, comp.1),
                3 => qk31_quadrature(&**f, comp.0, comp.1),
                4 => qk41_quadrature(&**f, comp.0, comp.1),
                5 => qk51_quadrature(&**f, comp.0, comp.1),
                6 => qk61_quadrature(&**f, comp.0, comp.1),
                _ => (vec![0.0; n], 0.0, 0.0),
            };
            add_res(&mut result, &result_temp);
            abserr += abserr_temp;
            rounderr += rounderr_temp;
            heap.push(HeapItem::new((comp.0, comp.1), abserr_temp));
            interval_cache.insert((Myf64 { x: comp.0 }, Myf64 { x: comp.1 }), result_temp);
        }

        let mut errbnd = epsabs.max(epsrel * norm_vec(&result));

        if abserr + rounderr <= errbnd {
            if keyf != 1 {
                neval = (10 * keyf + 1) * (2 * last as i32 - 1);
            }
            if keyf == 1 {
                neval = 30 * last as i32 + 15;
            }
            abserr = abserr + rounderr;
            if self.more_info {
                return Ok(QagIntegrationResult::new_more_info(
                    result,
                    abserr,
                    neval,
                    last,
                    interval_cache,
                    heap,
                ));
            } else {
                return Ok(QagIntegrationResult::new(result, abserr));
            }
        }

        if self.limit == 1 {
            return Err(QagError::MaxIteration);
        }

        if abserr < rounderr {
            return Err(QagError::BadTolerance);
        }

        while last < self.limit {
            let mut to_process = vec![];
            let mut err_sum = 0.0;
            let mut old_result = vec![0.0; n];
            let max_new_divison = self.limit - last;

            while to_process.len() < 128.min(max_new_divison) && heap.len() != 0 {
                let old_interval = heap.pop().unwrap();
                let ((x, y), old_err) = (old_interval.interval, old_interval.err);
                if bad_function_flag(x, y) {
                    return Err(QagError::BadFunction);
                }
                let old_res = interval_cache
                    .remove(&(Myf64 { x }, Myf64 { x: y }))
                    .unwrap();
                err_sum += old_err;
                add_vec(&mut old_result, &old_res);
                to_process.push((x, y));
                if err_sum > abserr - errbnd / 8.0 {
                    break;
                }
            }

            last += to_process.len();

            let new_result: (Vec<_>, Vec<_>) = pool.install(|| {
                to_process
                    .par_iter()
                    .map(|comp| {
                        let mut result1 = vec![0.0; n];
                        let mut abserr1 = 0.0;
                        let mut rounderr1 = 0.0;

                        let mut result2 = vec![0.0; n];
                        let mut abserr2 = 0.0;
                        let mut rounderr2 = 0.0;

                        let a1 = comp.0;
                        let b1 = 0.5 * (comp.0 + comp.1);
                        let a2 = b1;
                        let b2 = comp.1;

                        match keyf {
                            1 => {
                                (result1, abserr1, rounderr1) = qk15_quadrature(&**f, a1, b1);
                                (result2, abserr2, rounderr2) = qk15_quadrature(&**f, a2, b2);
                            }
                            2 => {
                                (result1, abserr1, rounderr1) = qk21_quadrature(&**f, a1, b1);
                                (result2, abserr2, rounderr2) = qk21_quadrature(&**f, a2, b2);
                            }
                            3 => {
                                (result1, abserr1, rounderr1) = qk31_quadrature(&**f, a1, b1);
                                (result2, abserr2, rounderr2) = qk31_quadrature(&**f, a2, b2);
                            }
                            4 => {
                                (result1, abserr1, rounderr1) = qk41_quadrature(&**f, a1, b1);
                                (result2, abserr2, rounderr2) = qk41_quadrature(&**f, a2, b2);
                            }
                            5 => {
                                (result1, abserr1, rounderr1) = qk51_quadrature(&**f, a1, b1);
                                (result2, abserr2, rounderr2) = qk51_quadrature(&**f, a2, b2);
                            }
                            6 => {
                                (result1, abserr1, rounderr1) = qk61_quadrature(&**f, a1, b1);
                                (result2, abserr2, rounderr2) = qk61_quadrature(&**f, a2, b2);
                            }
                            _ => (),
                        }
                        (
                            (a1, b1, result1, abserr1, rounderr1),
                            (a2, b2, result2, abserr2, rounderr2),
                        )
                    })
                    .collect()
            });

            let mut new_res = vec![0.0; n];
            let mut new_abserr = 0.0;

            for k in 0..new_result.0.len() {
                add_vec(&mut new_res, &new_result.0[k].2);
                add_vec(&mut new_res, &new_result.1[k].2);
                new_abserr += new_result.0[k].3 + new_result.1[k].3;
                rounderr += new_result.0[k].4 + new_result.1[k].4;
                interval_cache.insert(
                    (
                        Myf64 {
                            x: new_result.0[k].0,
                        },
                        Myf64 {
                            x: new_result.0[k].1,
                        },
                    ),
                    new_result.0[k].2.clone(),
                );
                interval_cache.insert(
                    (
                        Myf64 {
                            x: new_result.1[k].0,
                        },
                        Myf64 {
                            x: new_result.1[k].1,
                        },
                    ),
                    new_result.1[k].2.clone(),
                );
                heap.push(HeapItem::new(
                    (new_result.0[k].0, new_result.0[k].1),
                    new_result.0[k].3,
                ));
                heap.push(HeapItem::new(
                    (new_result.1[k].0, new_result.1[k].1),
                    new_result.1[k].3,
                ));
            }
            if iroff1_flag(&old_result, &new_res, new_abserr, err_sum) {
                iroff1 += 1;
            }
            if last > 10 && new_abserr > err_sum {
                iroff2 += 1;
            }
            sub_vec(&mut result, &old_result);
            add_vec(&mut result, &new_res);
            abserr += new_abserr - err_sum;

            errbnd = epsabs.max(epsrel * norm_vec(&result));

            if abserr <= errbnd / 8.0 {
                break;
            }
            if abserr < rounderr || iroff1 >= IROFF1_THRESHOLD || iroff2 >= IROFF2_THRESHOLD {
                return Err(QagError::BadTolerance);
            }
        }

        if abserr > errbnd / 8.0 && last >= self.limit {
            return Err(QagError::MaxIteration);
        }

        if keyf != 1 {
            neval = (10 * keyf + 1) * (2 * last as i32 - 1);
        }
        if keyf == 1 {
            neval = 30 * last as i32 + 15;
        }

        abserr = abserr + rounderr;

        if self.more_info {
            return Ok(QagIntegrationResult::new_more_info(
                result,
                abserr,
                neval,
                last,
                interval_cache,
                heap,
            ));
        } else {
            return Ok(QagIntegrationResult::new(result, abserr));
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::constants::{FnVec, Myf64};
    use crate::errors::QagError;
    use crate::qag::Qag;
    use std::sync::Arc;

    #[test]
    fn max_iteration1() {
        let a = 0.0;
        let b = 10000.0;
        let epsrel = 0.0;
        let epsabs = 1.0e-2;
        let limit = 1;
        let key = 6;

        let qag = Qag {
            key,
            limit,
            points: vec![0.0; 0],
            number_of_thread: 8,
            more_info: true,
        };

        let f = FnVec {
            components: Arc::new(|x: f64| vec![x.sin(), x.cos()]),
        };
        let res = qag.integrate(&f, a, b, epsabs, epsrel);
        let error = res.unwrap_err();

        assert_eq!(error, QagError::MaxIteration);
    }
    #[test]
    fn max_iteration2() {
        let a = 0.0;
        let b = 1000000.0;
        let epsrel = 0.0;
        let epsabs = 1.0e-2;
        let limit = 30;
        let key = 6;

        let qag = Qag {
            key,
            limit,
            points: vec![0.0; 0],
            number_of_thread: 8,
            more_info: true,
        };

        let f = FnVec {
            components: Arc::new(|x: f64| vec![x.sin(), x.cos()]),
        };
        let res = qag.integrate(&f, a, b, epsabs, epsrel);
        let error = res.unwrap_err();

        assert_eq!(error, QagError::MaxIteration);
    }

    #[test]
    fn invalid() {
        let a = 0.0;
        let b = 1000000.0;
        let epsrel = 1.0e-30;
        let epsabs = 0.0;
        let limit = 30;
        let key = 6;

        let qag = Qag {
            key,
            limit,
            points: vec![0.0; 0],
            number_of_thread: 8,
            more_info: true,
        };

        let f = FnVec {
            components: Arc::new(|x: f64| vec![x.sin(), x.cos()]),
        };
        let res = qag.integrate(&f, a, b, epsabs, epsrel);
        let error = res.unwrap_err();

        assert_eq!(error, QagError::Invalid);
    }

    #[test]
    fn key() {
        let a = 0.0;
        let b = 10000.0;
        let epsrel = 0.0;
        let epsabs = 1.0e-3;
        let limit = 10000;
        let correct_result = [1.0 - 10000.0_f64.cos(), 10000.0_f64.sin()];

        for key in 1..7 {
            let qag = Qag {
                key,
                limit,
                points: vec![0.0; 0],
                number_of_thread: 8,
                more_info: true,
            };

            let f = FnVec {
                components: Arc::new(|x: f64| vec![x.sin(), x.cos()]),
            };
            let res = qag.integrate(&f, a, b, epsabs, epsrel).unwrap();

            assert!(
                res.result[0] - correct_result[0] < epsabs
                    && res.result[1] - correct_result[1] < epsabs
            );
        }
    }
    #[test]
    fn semi_infinite() {
        let a = 0.0;
        let b = f64::INFINITY;
        let c = f64::NEG_INFINITY;
        let epsrel = 0.0;
        let epsabs = 1.0e-12;
        let limit = 10000;
        let key = 6;
        let correct_result = [0.4, 0.6];

        let qag = Qag {
            key,
            limit,
            points: vec![0.0; 0],
            number_of_thread: 8,
            more_info: true,
        };

        let f = FnVec {
            components: Arc::new(|x: f64| {
                vec![
                    x.sin().powi(2) / x.abs().exp(),
                    x.cos().powi(2) / x.abs().exp(),
                ]
            }),
        };

        let res1 = qag.integrate(&f, a, b, epsabs, epsrel).unwrap();
        let res2 = qag.integrate(&f, c, a, epsabs, epsrel).unwrap();

        assert!(
            res1.result[0] - correct_result[0] < epsabs
                && res1.result[1] - correct_result[1] < epsabs
        );
        assert!(
            res2.result[0] - correct_result[0] < epsabs
                && res2.result[1] - correct_result[1] < epsabs
        );
    }
    #[test]
    fn double_infinite() {
        let a = f64::NEG_INFINITY;
        let b = f64::INFINITY;
        let epsrel = 0.0;
        let epsabs = 1.0e-10;
        let limit = 10000;
        let key = 6;
        let correct_result = [1.2879903316984565533522585284072106913, 1.5974];

        let qag = Qag {
            key,
            limit,
            points: vec![0.0; 0],
            number_of_thread: 8,
            more_info: true,
        };

        let f = FnVec {
            components: Arc::new(|x: f64| {
                vec![
                    x.sin().powi(2) / x.abs().exp2(),
                    x.cos().powi(2) / x.abs().exp2(),
                ]
            }),
        };

        let res = qag.integrate(&f, a, b, epsabs, epsrel).unwrap();
        assert!(
            res.result[0] - correct_result[0] < epsabs
                && res.result[1] - correct_result[1] < epsabs
        );
    }
    #[test]
    fn additional_points() {
        let a = 0.0;
        let b = 1.0;
        let epsrel = 0.0;
        let epsabs = 1.0;
        let limit = 10000;
        let key = 6;
        let points = vec![0.0, 0.2, 0.4, 0.6, 0.8, 1.0];

        let qag = Qag {
            key,
            limit,
            points: points.clone(),
            number_of_thread: 8,
            more_info: true,
        };
        let f = FnVec {
            components: Arc::new(|x: f64| vec![x.cos(), x.sin()]),
        };
        let res = qag.integrate(&f, a, b, epsabs, epsrel).unwrap();
        let mut res_hash = res.more_info.unwrap().hash.clone();
        assert_eq!(res_hash.len(), qag.points.len() - 1);
        for k in 0..points.len() - 1 {
            res_hash.remove(&((Myf64 { x: points[k] }, Myf64 { x: points[k + 1] })));
        }
        assert_eq!(res_hash.len(), 0);
    }
}