scirs2-integrate 0.4.1

Numerical integration module for SciRS2 (scirs2-integrate)
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Vector-valued integration
//!
//! This module provides integration methods for vector-valued functions.
//! These methods are useful when you need to integrate a function that
//! returns arrays rather than scalar values.

use scirs2_core::ndarray::Array1;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::f64::consts::PI;
use std::fmt;

use crate::error::{IntegrateError, IntegrateResult};

/// Result type for vector-valued integration
#[derive(Clone, Debug)]
pub struct QuadVecResult<T> {
    /// The integral estimate
    pub integral: Array1<T>,
    /// The error estimate
    pub error: Array1<T>,
    /// Number of function evaluations
    pub nfev: usize,
    /// Number of integration subintervals used
    pub nintervals: usize,
    /// Whether the integration converged successfully
    pub success: bool,
}

impl<T: fmt::Display> fmt::Display for QuadVecResult<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "QuadVecResult(\n  integral=[{:}],\n  error=[{:}],\n  nfev={},\n  nintervals={},\n  success={}\n)",
            self.integral
                .iter()
                .map(|v| format!("{v}"))
                .collect::<Vec<_>>()
                .join(", "),
            self.error
                .iter()
                .map(|v| format!("{v}"))
                .collect::<Vec<_>>()
                .join(", "),
            self.nfev,
            self.nintervals,
            self.success
        )
    }
}

/// Options for quad_vec integration
#[derive(Clone, Debug)]
pub struct QuadVecOptions {
    /// Absolute tolerance
    pub epsabs: f64,
    /// Relative tolerance
    pub epsrel: f64,
    /// Norm to use for error estimation
    pub norm: NormType,
    /// Maximum number of subintervals
    pub limit: usize,
    /// Quadrature rule to use
    pub rule: QuadRule,
    /// Additional points where the integrand should be sampled
    pub points: Option<Vec<f64>>,
}

impl Default for QuadVecOptions {
    fn default() -> Self {
        Self {
            epsabs: 1e-10,
            epsrel: 1e-8,
            norm: NormType::L2,
            limit: 50,
            rule: QuadRule::GK21,
            points: None,
        }
    }
}

/// Type of norm to use for error estimation
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum NormType {
    /// Maximum absolute value
    Max,
    /// Euclidean (L2) norm
    L2,
}

/// Quadrature rule to use
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum QuadRule {
    /// 15-point Gauss-Kronrod rule
    GK15,
    /// 21-point Gauss-Kronrod rule
    GK21,
    /// Composite trapezoidal rule
    Trapezoid,
}

/// Subinterval for adaptive quadrature
#[derive(Clone, Debug)]
struct Subinterval {
    /// Left endpoint
    a: f64,
    /// Right endpoint
    b: f64,
    /// Integral estimate on this subinterval
    integral: Array1<f64>,
    /// Error estimate on this subinterval
    error: Array1<f64>,
    /// Norm of the error estimate (priority for subdivision)
    error_norm: f64,
}

impl PartialEq for Subinterval {
    fn eq(&self, other: &Self) -> bool {
        self.error_norm == other.error_norm
    }
}

impl Eq for Subinterval {}

impl PartialOrd for Subinterval {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Subinterval {
    fn cmp(&self, other: &Self) -> Ordering {
        // We want a max heap, so reverse the ordering
        other
            .error_norm
            .partial_cmp(&self.error_norm)
            .unwrap_or(Ordering::Equal)
    }
}

/// Compute a norm for error estimation
#[allow(dead_code)]
fn compute_norm(array: &Array1<f64>, normtype: NormType) -> f64 {
    match normtype {
        NormType::Max => {
            let mut max_abs = 0.0;
            for &val in array.iter() {
                let abs_val = val.abs();
                if abs_val > max_abs {
                    max_abs = abs_val;
                }
            }
            max_abs
        }
        NormType::L2 => {
            let mut sum_squares: f64 = 0.0;
            for &val in array.iter() {
                sum_squares += val * val;
            }
            sum_squares.sqrt()
        }
    }
}

/// Integration of a vector-valued function.
///
/// This function is similar to `quad`, but for functions that return
/// arrays (vectors) rather than scalars.
///
/// # Parameters
///
/// * `f` - Function to integrate. Should take a float and return an array.
/// * `a` - Lower bound of integration.
/// * `b` - Upper bound of integration.
/// * `options` - Integration options (optional).
///
/// # Returns
///
/// A result containing the integral estimate, error, and other information.
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{Array1, arr1};
/// use scirs2_integrate::quad_vec::{quad_vec, QuadVecOptions};
///
/// // Integrate a function that returns a 2D vector
/// let f = |x: f64| arr1(&[x.sin(), x.cos()]);
/// let result = quad_vec(f, 0.0, std::f64::consts::PI, None).expect("Operation failed");
///
/// // Result should be approximately [2.0, 0.0]
/// assert!((result.integral[0] - 2.0).abs() < 1e-10);
/// assert!(result.integral[1].abs() < 1e-10);
/// ```
#[allow(dead_code)]
pub fn quad_vec<F>(
    f: F,
    a: f64,
    b: f64,
    options: Option<QuadVecOptions>,
) -> IntegrateResult<QuadVecResult<f64>>
where
    F: Fn(f64) -> Array1<f64>,
{
    let options = options.unwrap_or_default();

    // Validate inputs
    if !a.is_finite() || !b.is_finite() {
        return Err(IntegrateError::ValueError(
            "Integration limits must be finite".to_string(),
        ));
    }

    // Check if interval is effectively zero
    if (b - a).abs() <= f64::EPSILON * a.abs().max(b.abs()) {
        // Evaluate at midpoint to get vector dimension
        let fval = f((a + b) / 2.0);
        let zeros = Array1::zeros(fval.len());

        return Ok(QuadVecResult {
            integral: zeros.clone(),
            error: zeros,
            nfev: 1,
            nintervals: 0,
            success: true,
        });
    }

    // Determine initial intervals
    let intervals = if let Some(ref points) = options.points {
        // Start with user-supplied breakpoints
        let mut sorted_points: Vec<f64> = points.clone();
        sorted_points.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));

        // Filter out points outside [a, b] and remove duplicates
        let mut filtered_points: Vec<f64> = Vec::new();
        for &point in sorted_points.iter() {
            if point > a
                && point < b
                && (filtered_points.is_empty()
                    || (point - filtered_points.last().expect("Operation failed")).abs()
                        > f64::EPSILON)
            {
                filtered_points.push(point);
            }
        }

        // Create initial intervals
        let mut intervals: Vec<(f64, f64)> = Vec::new();

        if filtered_points.is_empty() {
            intervals.push((a, b));
        } else {
            intervals.push((a, filtered_points[0]));

            for i in 0..filtered_points.len() - 1 {
                intervals.push((filtered_points[i], filtered_points[i + 1]));
            }

            intervals.push((*filtered_points.last().expect("Operation failed"), b));
        }

        intervals
    } else {
        // Just use the whole interval
        vec![(a, b)]
    };

    // Evaluate function once to determine output size
    let fval = f((intervals[0].0 + intervals[0].1) / 2.0);
    let output_size = fval.len();

    // Initialize priority queue for adaptive subdivision
    let mut subintervals = BinaryHeap::new();
    let mut nfev = 1; // We've already evaluated f once

    // Process initial intervals
    for (a_i, b_i) in intervals {
        let (integral, error, evals) = evaluate_interval(&f, a_i, b_i, output_size, options.rule)?;

        nfev += evals;

        let error_norm = compute_norm(&error, options.norm);

        subintervals.push(Subinterval {
            a: a_i,
            b: b_i,
            integral,
            error,
            error_norm,
        });
    }

    // Adaptive subdivision
    while subintervals.len() < options.limit {
        // Get interval with largest error
        let interval = match subintervals.pop() {
            Some(i) => i,
            None => break, // Shouldn't happen, but just in case
        };

        // Check if we've reached desired accuracy
        let total_integral = get_total(&subintervals, &interval, |i| &i.integral);
        let total_error = get_total(&subintervals, &interval, |i| &i.error);

        let error_norm = compute_norm(&total_error, options.norm);
        let abs_tol = options.epsabs;
        let rel_tol = options.epsrel * compute_norm(&total_integral, options.norm);

        if error_norm <= abs_tol || error_norm <= rel_tol {
            // Add the interval back, we'll compute the final result later
            subintervals.push(interval);
            break;
        }

        // Split the interval
        let mid = (interval.a + interval.b) / 2.0;

        // Evaluate on the two halves
        let (left_integral, left_error, left_evals) =
            evaluate_interval(&f, interval.a, mid, output_size, options.rule)?;

        let (right_integral, right_error, right_evals) =
            evaluate_interval(&f, mid, interval.b, output_size, options.rule)?;

        nfev += left_evals + right_evals;

        // Create new intervals
        let left_error_norm = compute_norm(&left_error, options.norm);
        let right_error_norm = compute_norm(&right_error, options.norm);

        subintervals.push(Subinterval {
            a: interval.a,
            b: mid,
            integral: left_integral,
            error: left_error,
            error_norm: left_error_norm,
        });

        subintervals.push(Subinterval {
            a: mid,
            b: interval.b,
            integral: right_integral,
            error: right_error,
            error_norm: right_error_norm,
        });
    }

    // Compute final result
    let interval_vec: Vec<Subinterval> = subintervals.into_vec();
    let mut total_integral = Array1::zeros(output_size);
    let mut total_error = Array1::zeros(output_size);

    for interval in &interval_vec {
        for (i, &val) in interval.integral.iter().enumerate() {
            total_integral[i] += val;
        }

        for (i, &val) in interval.error.iter().enumerate() {
            total_error[i] += val;
        }
    }

    // Check for convergence
    let error_norm = compute_norm(&total_error, options.norm);
    let abs_tol = options.epsabs;
    let rel_tol = options.epsrel * compute_norm(&total_integral, options.norm);

    let success = error_norm <= abs_tol || error_norm <= rel_tol;

    Ok(QuadVecResult {
        integral: total_integral,
        error: total_error,
        nfev,
        nintervals: interval_vec.len(),
        success,
    })
}

/// Compute a property of all intervals combined
#[allow(dead_code)]
fn get_total<F, T>(heap: &BinaryHeap<Subinterval>, extra: &Subinterval, extract: F) -> Array1<T>
where
    F: Fn(&Subinterval) -> &Array1<T>,
    T: Clone + scirs2_core::numeric::Zero,
{
    let mut result = extract(extra).clone();

    for interval in heap.iter() {
        let property = extract(interval);

        for (i, val) in property.iter().enumerate() {
            result[i] = result[i].clone() + val.clone();
        }
    }

    result
}

/// Evaluate the integral on a specific interval
#[allow(dead_code)]
fn evaluate_interval<F>(
    f: &F,
    a: f64,
    b: f64,
    output_size: usize,
    rule: QuadRule,
) -> IntegrateResult<(Array1<f64>, Array1<f64>, usize)>
where
    F: Fn(f64) -> Array1<f64>,
{
    match rule {
        QuadRule::GK15 => {
            // Gauss-Kronrod 15-point rule (7-point Gauss, 15-point Kronrod)
            // Points and weights from SciPy
            let nodes = [
                -0.9914553711208126f64,
                -0.9491079123427585,
                -0.8648644233597691,
                -0.7415311855993944,
                -0.5860872354676911,
                -0.4058451513773972,
                -0.2077849550078985,
                0.0,
                0.2077849550078985,
                0.4058451513773972,
                0.5860872354676911,
                0.7415311855993944,
                0.8648644233597691,
                0.9491079123427585,
                0.9914553711208126,
            ];

            let weights_k = [
                0.022935322010529224f64,
                0.063_092_092_629_978_56,
                0.10479001032225018,
                0.14065325971552592,
                0.169_004_726_639_267_9,
                0.190_350_578_064_785_4,
                0.20443294007529889,
                0.20948214108472782,
                0.20443294007529889,
                0.190_350_578_064_785_4,
                0.169_004_726_639_267_9,
                0.14065325971552592,
                0.10479001032225018,
                0.063_092_092_629_978_56,
                0.022935322010529224,
            ];

            // Abscissae for the 7-point Gauss rule (odd indices of xgk)
            let weights_g = [
                0.129_484_966_168_869_7_f64,
                0.27970539148927664,
                0.381_830_050_505_118_9,
                0.417_959_183_673_469_4,
                0.381_830_050_505_118_9,
                0.27970539148927664,
                0.129_484_966_168_869_7,
            ];

            evaluate_rule(f, a, b, output_size, &nodes, &weights_g, &weights_k)
        }
        QuadRule::GK21 => {
            // Gauss-Kronrod 21-point rule (10-point Gauss, 21-point Kronrod)
            // Points and weights from SciPy
            let nodes = [
                -0.9956571630258081f64,
                -0.9739065285171717,
                -0.9301574913557082,
                -0.8650633666889845,
                -0.7808177265864169,
                -0.6794095682990244,
                -0.5627571346686047,
                -0.4333953941292472,
                -0.2943928627014602,
                -0.1488743389816312,
                0.0,
                0.1488743389816312,
                0.2943928627014602,
                0.4333953941292472,
                0.5627571346686047,
                0.6794095682990244,
                0.7808177265864169,
                0.8650633666889845,
                0.9301574913557082,
                0.9739065285171717,
                0.9956571630258081,
            ];

            let weights_k = [
                0.011694638867371874f64,
                0.032558162307964725,
                0.054755896574351995,
                0.075_039_674_810_919_96,
                0.093_125_454_583_697_6,
                0.109_387_158_802_297_64,
                0.123_491_976_262_065_84,
                0.134_709_217_311_473_34,
                0.142_775_938_577_060_09,
                0.147_739_104_901_338_49,
                0.149_445_554_002_916_9,
                0.147_739_104_901_338_49,
                0.142_775_938_577_060_09,
                0.134_709_217_311_473_34,
                0.123_491_976_262_065_84,
                0.109_387_158_802_297_64,
                0.093_125_454_583_697_6,
                0.075_039_674_810_919_96,
                0.054755896574351995,
                0.032558162307964725,
                0.011694638867371874,
            ];

            // Abscissae for the 10-point Gauss rule (every other point)
            let weights_g = [
                0.066_671_344_308_688_14f64,
                0.149_451_349_150_580_6,
                0.219_086_362_515_982_04,
                0.269_266_719_309_996_36,
                0.295_524_224_714_752_9,
                0.295_524_224_714_752_9,
                0.269_266_719_309_996_36,
                0.219_086_362_515_982_04,
                0.149_451_349_150_580_6,
                0.066_671_344_308_688_14,
            ];

            evaluate_rule(f, a, b, output_size, &nodes, &weights_g, &weights_k)
        }
        QuadRule::Trapezoid => {
            // Simple trapezoid rule with 15 points
            let n = 15;
            let mut integral = Array1::zeros(output_size);
            let mut error = Array1::zeros(output_size);

            let h = (b - a) / (n as f64 - 1.0);
            let fa = f(a);
            let fb = f(b);

            // Add endpoints with half weight
            for (i, (&fa_i, &fb_i)) in fa.iter().zip(fb.iter()).enumerate() {
                integral[i] = 0.5 * (fa_i + fb_i);
            }

            // Add interior points
            for j in 1..n - 1 {
                let x = a + (j as f64) * h;
                let fx = f(x);

                for (i, &fx_i) in fx.iter().enumerate() {
                    integral[i] += fx_i;
                }
            }

            // Scale by h
            for i in 0..output_size {
                integral[i] *= h;

                // Crude error estimate
                error[i] = 1e-2 * integral[i].abs();
            }

            Ok((integral, error, n))
        }
    }
}

/// Evaluate a Gauss-Kronrod rule on an interval
#[allow(dead_code)]
fn evaluate_rule<F>(
    f: &F,
    a: f64,
    b: f64,
    output_size: usize,
    nodes: &[f64],
    weights_g: &[f64],
    weights_k: &[f64],
) -> IntegrateResult<(Array1<f64>, Array1<f64>, usize)>
where
    F: Fn(f64) -> Array1<f64>,
{
    let _n = nodes.len();

    let mut integral_k = Array1::zeros(output_size);
    let mut integral_g = Array1::zeros(output_size);

    // Map nodes to [a, b]
    let mid = (a + b) / 2.0;
    let half_length = (b - a) / 2.0;

    let mut nfev = 0;

    // For GK rules, Gauss points are at odd indices (1, 3, 5, ...)
    let mut gauss_idx = 0;

    // Evaluate at all Kronrod points
    for (i, &node) in nodes.iter().enumerate() {
        let x = mid + half_length * node;
        let fx = f(x);
        nfev += 1;

        // Add to Kronrod integral
        for (j, &fx_j) in fx.iter().enumerate() {
            integral_k[j] += weights_k[i] * fx_j;
        }

        // Check if this is also a Gauss point
        // For GK15: Gauss points are at indices 1, 3, 5, 7, 9, 11, 13
        // For GK21: Gauss points are at indices 1, 3, 5, 7, 9, 11, 13, 15, 17, 19
        if i % 2 == 1 && gauss_idx < weights_g.len() {
            for (j, &fx_j) in fx.iter().enumerate() {
                integral_g[j] += weights_g[gauss_idx] * fx_j;
            }
            gauss_idx += 1;
        }
    }

    // Scale by half-length
    integral_k *= half_length;
    integral_g *= half_length;

    // Compute error estimate
    // Error is estimated as (200 * |I_k - I_g|)^1.5
    let mut error = Array1::zeros(output_size);
    for i in 0..output_size {
        let diff = (integral_k[i] - integral_g[i]).abs();
        error[i] = (200.0 * diff).powf(1.5_f64);
    }

    Ok((integral_k, error, nfev))
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use scirs2_core::ndarray::arr1;

    #[test]
    fn test_simple_integral() {
        // Integrate [x, x^2] from 0 to 1
        let f = |x: f64| arr1(&[x, x * x]);
        let result = quad_vec(f, 0.0, 1.0, None).expect("Operation failed");

        assert_abs_diff_eq!(result.integral[0], 0.5, epsilon = 1e-10);
        assert_abs_diff_eq!(result.integral[1], 1.0 / 3.0, epsilon = 1e-10);
        assert!(result.success);
    }

    #[test]
    fn test_trig_functions() {
        // Integrate [sin(x), cos(x)] from 0 to π
        let f = |x: f64| arr1(&[x.sin(), x.cos()]);
        let result = quad_vec(f, 0.0, PI, None).expect("Operation failed");

        assert_abs_diff_eq!(result.integral[0], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(result.integral[1], 0.0, epsilon = 1e-10);
        assert!(result.success);
    }

    #[test]
    fn test_with_breakpoints() {
        // Integrate [x, x^2] from 0 to 2 with a breakpoint at x=1
        let f = |x: f64| arr1(&[x, x * x]);

        let options = QuadVecOptions {
            points: Some(vec![1.0]),
            ..Default::default()
        };

        let result = quad_vec(f, 0.0, 2.0, Some(options)).expect("Operation failed");

        assert_abs_diff_eq!(result.integral[0], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(result.integral[1], 8.0 / 3.0, epsilon = 1e-10);
        assert!(result.success);
    }

    #[test]
    fn test_different_rules() {
        // Test with different quadrature rules
        let f = |x: f64| arr1(&[x.sin()]);

        let options_gk15 = QuadVecOptions {
            rule: QuadRule::GK15,
            ..Default::default()
        };

        let options_gk21 = QuadVecOptions {
            rule: QuadRule::GK21,
            ..Default::default()
        };

        let options_trapezoid = QuadVecOptions {
            rule: QuadRule::Trapezoid,
            ..Default::default()
        };

        let result_gk15 = quad_vec(f, 0.0, PI, Some(options_gk15)).expect("Operation failed");
        let result_gk21 = quad_vec(f, 0.0, PI, Some(options_gk21)).expect("Operation failed");
        let result_trapezoid =
            quad_vec(f, 0.0, PI, Some(options_trapezoid)).expect("Operation failed");

        assert_abs_diff_eq!(result_gk15.integral[0], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(result_gk21.integral[0], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(result_trapezoid.integral[0], 2.0, epsilon = 2e-3); // Lower precision for trapezoid
    }

    #[test]
    fn test_error_norms() {
        // Test Max norm
        let arr = arr1(&[1.0, -2.0, 0.5]);
        let max_norm = compute_norm(&arr, NormType::Max);
        assert_abs_diff_eq!(max_norm, 2.0, epsilon = 1e-10);

        // Test L2 norm
        let l2_norm = compute_norm(&arr, NormType::L2);
        assert_abs_diff_eq!(
            l2_norm,
            (1.0f64 * 1.0 + 2.0 * 2.0 + 0.5 * 0.5).sqrt(),
            epsilon = 1e-10
        );
    }
}