scirs2-stats 0.4.2

Statistical functions module for SciRS2 (scirs2-stats)
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
726
727
728
729
730
731
//! Non-parametric statistical tests
//!
//! This module provides implementations of various non-parametric statistical tests,
//! including the Wilcoxon signed-rank test, Mann-Whitney U test, and the Kruskal-Wallis test.

use crate::error::{StatsError, StatsResult};
use scirs2_core::ndarray::ArrayView1;
use scirs2_core::numeric::{Float, NumCast};
use std::cmp::Ordering;

/// Performs the Wilcoxon signed-rank test for paired samples.
///
/// The Wilcoxon signed-rank test is a non-parametric statistical test that compares
/// two related samples to assess whether their population mean ranks differ. It's an
/// alternative to the paired t-test when the data cannot be assumed to be normally
/// distributed.
///
/// # Arguments
///
/// * `x` - First array of observations
/// * `y` - Second array of observations (paired with `x`)
/// * `zero_method` - How to handle zero differences: "wilcox" (default), "pratt", or "zsplit"
/// * `correction` - Whether to apply continuity correction
///
/// # Returns
///
/// A tuple containing (test statistic, p-value)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_stats::wilcoxon;
///
/// // Create two paired samples
/// let before = array![125.0, 115.0, 130.0, 140.0, 140.0, 115.0, 140.0, 125.0, 140.0, 135.0];
/// let after = array![110.0, 122.0, 125.0, 120.0, 140.0, 124.0, 123.0, 137.0, 135.0, 145.0];
///
/// // Perform the Wilcoxon signed-rank test
/// let (stat, p_value) = wilcoxon(&before.view(), &after.view(), "wilcox", true).expect("Operation failed");
///
/// println!("Wilcoxon signed-rank test: W = {}, p-value = {}", stat, p_value);
/// // For a significance level of 0.05, we would reject the null hypothesis if p < 0.05
/// let significant = p_value < 0.05;
/// ```
#[allow(dead_code)]
pub fn wilcoxon<F>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
    zero_method: &str,
    correction: bool,
) -> StatsResult<(F, F)>
where
    F: Float + std::iter::Sum<F> + std::ops::Div<Output = F> + NumCast + std::fmt::Display,
{
    // Check if the arrays are empty
    if x.is_empty() || y.is_empty() {
        return Err(StatsError::InvalidArgument(
            "Input arrays cannot be empty".to_string(),
        ));
    }

    // Check if the arrays have the same length
    if x.len() != y.len() {
        return Err(StatsError::DimensionMismatch(
            "Input arrays must have the same length for paired test".to_string(),
        ));
    }

    // Calculate the differences between paired observations
    let mut differences = Vec::with_capacity(x.len());
    for i in 0..x.len() {
        differences.push((x[i] - y[i], i));
    }

    // Handle zero differences according to the specified _method
    let differences = match zero_method {
        "wilcox" => {
            // Remove zero differences
            differences
                .into_iter()
                .filter(|(diff_, _)| !diff_.is_zero())
                .collect::<Vec<_>>()
        }
        "pratt" => {
            // Include zeros in ranking
            differences
        }
        "zsplit" => {
            // Split zeros evenly between positive and negative ranks
            // This is more complex and would require special handling
            return Err(StatsError::InvalidArgument(
                "zsplit _method not implemented yet".to_string(),
            ));
        }
        _ => {
            return Err(StatsError::InvalidArgument(format!(
                "Unknown zero_method: {}. Use 'wilcox', 'pratt', or 'zsplit'",
                zero_method
            )))
        }
    };

    // If no non-zero differences, return error
    if differences.is_empty() {
        return Err(StatsError::InvalidArgument(
            "All differences are zero, cannot perform Wilcoxon test".to_string(),
        ));
    }

    // Sort differences by absolute value for ranking
    let mut ranked_diffs = differences;
    ranked_diffs.sort_by(|(a, _), (b, _)| a.abs().partial_cmp(&b.abs()).unwrap_or(Ordering::Equal));

    // Assign ranks, handling ties appropriately
    let mut ranks = vec![F::zero(); ranked_diffs.len()];
    let mut i = 0;
    while i < ranked_diffs.len() {
        let current_abs_diff = ranked_diffs[i].0.abs();
        let mut j = i;

        // Find the end of the tie group
        while j < ranked_diffs.len() - 1 && ranked_diffs[j + 1].0.abs() == current_abs_diff {
            j += 1;
        }

        // Calculate average rank for this tie group
        let avg_rank = F::from(i + j).expect("Failed to convert to float")
            / F::from(2.0).expect("Failed to convert constant to float")
            + F::one();

        // Assign ranks to all tied values
        for (idx, rank) in ranks.iter_mut().enumerate().take(j + 1).skip(i) {
            let _original_idx = ranked_diffs[idx].1;
            *rank = avg_rank;
        }

        i = j + 1;
    }

    // Calculate the sum of positive ranks (W+) and negative ranks (W-)
    let mut w_plus = F::zero();
    let mut w_minus = F::zero();

    for (i, (diff_, _)) in ranked_diffs.iter().enumerate() {
        if diff_.is_sign_positive() {
            w_plus = w_plus + ranks[i];
        } else {
            w_minus = w_minus + ranks[i];
        }
    }

    // The test statistic is the smaller of W+ and W-
    let w = if w_plus < w_minus { w_plus } else { w_minus };

    // Calculate the p-value
    let n = F::from(ranked_diffs.len()).expect("Operation failed");

    // Expected value and standard deviation under the null hypothesis
    let w_mean = n * (n + F::one()) / F::from(4.0).expect("Failed to convert constant to float");
    let w_sd = (n
        * (n + F::one())
        * (F::from(2.0).expect("Failed to convert constant to float") * n + F::one())
        / F::from(24.0).expect("Failed to convert constant to float"))
    .sqrt();

    // Apply continuity correction if requested
    let correction_factor = if correction {
        F::from(0.5).expect("Failed to convert constant to float")
    } else {
        F::zero()
    };

    // Calculate z-statistic
    let z = (w - w_mean + correction_factor) / w_sd;

    // Convert to p-value (two-tailed test)
    let p_value = F::from(2.0).expect("Failed to convert constant to float") * normal_cdf(-z.abs());

    Ok((w, p_value))
}

/// Performs the Mann-Whitney U test for independent samples.
///
/// The Mann-Whitney U test (also known as Wilcoxon rank-sum test) is a non-parametric
/// test for assessing whether two independent samples come from the same distribution.
/// It's an alternative to the independent t-test when the data cannot be assumed to be
/// normally distributed.
///
/// # Arguments
///
/// * `x` - First array of observations
/// * `y` - Second array of observations
/// * `alternative` - Alternative hypothesis: "two-sided" (default), "less", or "greater"
/// * `use_continuity` - Whether to apply continuity correction
///
/// # Returns
///
/// A tuple containing (test statistic, p-value)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_stats::mann_whitney;
///
/// // Create two independent samples
/// let group1 = array![2.9, 3.0, 2.5, 2.6, 3.2, 2.8];
/// let group2 = array![3.8, 3.7, 3.9, 4.0, 4.2];
///
/// // Perform the Mann-Whitney U test
/// let (stat, p_value) = mann_whitney(&group1.view(), &group2.view(), "two-sided", true).expect("Operation failed");
///
/// println!("Mann-Whitney U test: U = {}, p-value = {}", stat, p_value);
/// // For a significance level of 0.05, we would reject the null hypothesis if p < 0.05
/// let significant = p_value < 0.05;
/// ```
#[allow(dead_code)]
pub fn mann_whitney<F>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
    alternative: &str,
    use_continuity: bool,
) -> StatsResult<(F, F)>
where
    F: Float
        + std::iter::Sum<F>
        + std::ops::Div<Output = F>
        + NumCast
        + std::fmt::Debug
        + std::fmt::Display,
{
    // Check if the arrays are empty
    if x.is_empty() || y.is_empty() {
        return Err(StatsError::InvalidArgument(
            "Input arrays cannot be empty".to_string(),
        ));
    }

    // Check alternative parameter
    match alternative {
        "two-sided" | "less" | "greater" => {}
        _ => {
            return Err(StatsError::InvalidArgument(format!(
                "Unknown alternative: {}. Use 'two-sided', 'less', or 'greater'",
                alternative
            )))
        }
    }

    // Get the sizes of the samples
    let n1 = x.len();
    let n2 = y.len();

    // Combine all values into a single vector, keeping track of which sample they're from
    let mut all_values = Vec::with_capacity(n1 + n2);

    // 0 indicates group x, 1 indicates group y
    for &value in x.iter() {
        all_values.push((value, 0));
    }
    for &value in y.iter() {
        all_values.push((value, 1));
    }

    // Sort the values
    all_values.sort_by(|a_, b_| a_.partial_cmp(b_).unwrap_or(Ordering::Equal));

    // Assign ranks, handling ties
    let n = all_values.len();
    let mut ranks = vec![F::zero(); n];

    let mut i = 0;
    while i < n {
        let current_value = all_values[i].0;
        let mut j = i;

        // Find the end of the tie group
        while j < n - 1 && all_values[j + 1].0 == current_value {
            j += 1;
        }

        // Calculate average rank for this tie group
        let avg_rank = F::from(i + j).expect("Failed to convert to float")
            / F::from(2.0).expect("Failed to convert constant to float")
            + F::one();

        // Assign ranks to all tied values
        for rank in ranks.iter_mut().take(j + 1).skip(i) {
            *rank = avg_rank;
        }

        i = j + 1;
    }

    // Calculate the rank sum for group x
    let mut rank_sum_x = F::zero();
    for i in 0..n {
        if all_values[i].1 == 0 {
            rank_sum_x = rank_sum_x + ranks[i];
        }
    }

    // Calculate the U statistics
    let n1_f = F::from(n1).expect("Failed to convert to float");
    let n2_f = F::from(n2).expect("Failed to convert to float");

    let u1 = rank_sum_x
        - (n1_f * (n1_f + F::one())) / F::from(2.0).expect("Failed to convert constant to float");
    let u2 = n1_f * n2_f - u1;

    // The Mann-Whitney U statistic is the minimum of U1 and U2
    let u = u1.min(u2);

    // Calculate the mean and standard deviation of U under the null hypothesis
    let mean_u = n1_f * n2_f / F::from(2.0).expect("Failed to convert constant to float");

    // Calculate tie correction factor
    let mut tie_correction = F::zero();
    if i < n {
        let mut i = 0;
        while i < n {
            let current_value = all_values[i].0;
            let mut j = i;

            // Find the end of the tie group
            while j < n - 1 && all_values[j + 1].0 == current_value {
                j += 1;
            }

            // If there are ties, calculate the correction factor
            if j > i {
                let t = F::from(j - i + 1).expect("Failed to convert to float");
                tie_correction = tie_correction + (t.powi(3) - t);
            }

            i = j + 1;
        }
    }

    let n_f = F::from(n).expect("Failed to convert to float");
    let tie_correction = tie_correction / (n_f.powi(3) - n_f);

    let var_u = (n1_f * n2_f * (n_f + F::one())
        / F::from(12.0).expect("Failed to convert constant to float"))
        * (F::one() - tie_correction);
    let std_dev_u = var_u.sqrt();

    // Apply _continuity correction if requested
    let correction = if use_continuity {
        F::from(0.5).expect("Failed to convert constant to float")
    } else {
        F::zero()
    };

    // Calculate z-score based on the alternative hypothesis
    let z = match alternative {
        "less" => {
            if u == u1 {
                (u + correction - mean_u) / std_dev_u
            } else {
                (u - correction - mean_u) / std_dev_u
            }
        }
        "greater" => {
            if u == u1 {
                (u - correction - mean_u) / std_dev_u
            } else {
                (u + correction - mean_u) / std_dev_u
            }
        }
        _ => {
            // "two-sided"
            (u.abs() - correction - mean_u.abs()) / std_dev_u
        }
    };

    // Calculate p-value based on the alternative hypothesis
    let p_value = match alternative {
        "less" => normal_cdf(z),
        "greater" => F::one() - normal_cdf(z),
        _ => F::from(2.0).expect("Failed to convert constant to float") * normal_cdf(-z.abs()),
    };

    Ok((u, p_value))
}

/// Performs the Kruskal-Wallis H-test for independent samples.
///
/// The Kruskal-Wallis H-test is a non-parametric method for testing whether
/// samples originate from the same distribution. It is used for comparing
/// two or more independent samples of equal or different sizes.
///
/// # Arguments
///
/// * `samples` - A vector of arrays, where each array contains the observations for one group
///
/// # Returns
///
/// A tuple containing (H statistic, p-value)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_stats::kruskal_wallis;
///
/// // Create three independent samples
/// let group1 = array![2.9, 3.0, 2.5, 2.6, 3.2];
/// let group2 = array![3.8, 3.7, 3.9, 4.0, 4.2];
/// let group3 = array![2.8, 3.4, 3.7, 2.2, 2.0];
///
/// // Perform the Kruskal-Wallis test
/// let samples = vec![group1.view(), group2.view(), group3.view()];
/// let (h, p_value) = kruskal_wallis(&samples).expect("Operation failed");
///
/// println!("Kruskal-Wallis H-test: H = {}, p-value = {}", h, p_value);
/// // For a significance level of 0.05, we would reject the null hypothesis if p < 0.05
/// let significant = p_value < 0.05;
/// ```
#[allow(dead_code)]
pub fn kruskal_wallis<F>(samples: &[ArrayView1<F>]) -> StatsResult<(F, F)>
where
    F: Float + std::iter::Sum<F> + std::ops::Div<Output = F> + NumCast + std::fmt::Display,
{
    // Check if there are at least two groups
    if samples.len() < 2 {
        return Err(StatsError::InvalidArgument(
            "At least two samples are required for Kruskal-Wallis test".to_string(),
        ));
    }

    // Check if any group is empty
    for (i, sample) in samples.iter().enumerate() {
        if sample.is_empty() {
            return Err(StatsError::InvalidArgument(format!(
                "Sample {} is empty",
                i
            )));
        }
    }

    // Combine all _samples into a single vector, keeping track of the group
    let mut all_values = Vec::new();
    let mut groupsizes = Vec::with_capacity(samples.len());

    for (group_idx, sample) in samples.iter().enumerate() {
        groupsizes.push(sample.len());
        for &value in sample.iter() {
            all_values.push((value, group_idx));
        }
    }

    // Sort all values
    all_values.sort_by(|a_, b_| a_.partial_cmp(b_).unwrap_or(Ordering::Equal));

    // Assign ranks, handling ties
    let n = all_values.len();
    let mut ranks = vec![F::zero(); n];
    let mut i = 0;
    while i < n {
        let current_value = all_values[i].0;
        let mut j = i;

        // Find the end of the tie group
        while j < n - 1 && all_values[j + 1].0 == current_value {
            j += 1;
        }

        // Calculate average rank for this tie group
        let avg_rank = F::from(i + j).expect("Failed to convert to float")
            / F::from(2.0).expect("Failed to convert constant to float")
            + F::one();

        // Assign ranks to all tied values
        for rank in ranks.iter_mut().take(j + 1).skip(i) {
            *rank = avg_rank;
        }

        i = j + 1;
    }

    // Calculate rank sums for each group
    let mut rank_sums = vec![F::zero(); samples.len()];
    for i in 0..n {
        let group = all_values[i].1;
        rank_sums[group] = rank_sums[group] + ranks[i];
    }

    // Calculate the H statistic
    let n_f = F::from(n).expect("Failed to convert to float");
    let mut h = F::zero();

    for (i, &rank_sum) in rank_sums.iter().enumerate() {
        let n_i = F::from(groupsizes[i]).expect("Failed to convert to float");
        h = h + (rank_sum * rank_sum) / n_i;
    }

    h = (F::from(12.0).expect("Failed to convert constant to float") / (n_f * (n_f + F::one())))
        * h
        - F::from(3.0).expect("Failed to convert constant to float") * (n_f + F::one());

    // Check for ties
    let mut tie_correction = F::one();
    let mut i = 0;
    while i < n {
        let current_value = all_values[i].0;
        let mut j = i;

        // Find the end of the tie group
        while j < n - 1 && all_values[j + 1].0 == current_value {
            j += 1;
        }

        // If there are ties, calculate the correction factor
        if j > i {
            let t = F::from(j - i + 1).expect("Failed to convert to float");
            tie_correction = tie_correction - (t.powi(3) - t) / (n_f.powi(3) - n_f);
        }

        i = j + 1;
    }

    // Apply tie correction if necessary
    if tie_correction < F::one() {
        h = h / tie_correction;
    }

    // Calculate p-value (chi-square distribution with k-1 degrees of freedom)
    let df = F::from(samples.len() - 1).expect("Operation failed");
    let p_value = chi_square_sf(h, df);

    Ok((h, p_value))
}

/// Performs the Friedman test for repeated measures.
///
/// The Friedman test is a non-parametric statistical test used to detect differences
/// in treatments across multiple test attempts. It is similar to the Kruskal-Wallis test,
/// but used for dependent samples (repeated measures design).
///
/// # Arguments
///
/// * `data` - A matrix where rows represent subjects and columns represent treatments/conditions
///
/// # Returns
///
/// A tuple containing (chi-square statistic, p-value)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array2};
/// use scirs2_stats::friedman;
///
/// // Create a 2D array where each row is a subject and each column is a treatment
/// let data = array![
///     [7.0, 9.0, 8.0],
///     [6.0, 5.0, 7.0],
///     [9.0, 7.0, 6.0],
///     [8.0, 5.0, 6.0]
/// ];
///
/// // Perform the Friedman test
/// let (chi2, p_value) = friedman(&data.view()).expect("Operation failed");
///
/// println!("Friedman test: Chi² = {}, p-value = {}", chi2, p_value);
/// // For a significance level of 0.05, we would reject the null hypothesis if p < 0.05
/// let significant = p_value < 0.05;
/// ```
#[allow(dead_code)]
pub fn friedman<F>(data: &scirs2_core::ndarray::ArrayView2<F>) -> StatsResult<(F, F)>
where
    F: Float
        + std::iter::Sum<F>
        + std::ops::Div<Output = F>
        + NumCast
        + std::ops::AddAssign
        + std::fmt::Display,
{
    // Get the number of subjects (n) and treatments (k)
    let n = data.nrows();
    let k = data.ncols();

    // Check if there are at least 2 subjects and 2 treatments
    if n < 2 || k < 2 {
        return Err(StatsError::InvalidArgument(
            "At least 2 subjects and 2 treatments are required for Friedman test".to_string(),
        ));
    }

    // Rank data within each subject (row)
    let mut ranks = scirs2_core::ndarray::Array2::<F>::zeros((n, k));

    for i in 0..n {
        // Extract the row
        let row = data.row(i);

        // Create a vector of (value, column_index) pairs
        let mut rowdata = Vec::with_capacity(k);
        for j in 0..k {
            rowdata.push((row[j], j));
        }

        // Sort by value
        rowdata.sort_by(|a_, b_| a_.partial_cmp(b_).unwrap_or(Ordering::Equal));

        // Assign ranks, handling ties
        let mut rank_idx = 0;
        while rank_idx < k {
            let current_value = rowdata[rank_idx].0;
            let mut tied_idx = rank_idx;

            // Find the end of the tie group
            while tied_idx < k - 1 && rowdata[tied_idx + 1].0 == current_value {
                tied_idx += 1;
            }

            // Calculate average rank for this tie group
            let _tie_count = tied_idx - rank_idx + 1;
            let avg_rank = F::from(rank_idx + tied_idx).expect("Failed to convert to float")
                / F::from(2.0).expect("Failed to convert constant to float")
                + F::one();

            // Assign average rank to all tied values
            for data_item in rowdata.iter().take(tied_idx + 1).skip(rank_idx) {
                let col_idx = data_item.1;
                ranks[[i, col_idx]] = avg_rank;
            }

            // Move to the next group
            rank_idx = tied_idx + 1;
        }
    }

    // Calculate rank sums for each treatment (column)
    let mut rank_sums = vec![F::zero(); k];
    for j in 0..k {
        let mut col_sum = F::zero();
        for i in 0..n {
            col_sum += ranks[[i, j]];
        }
        rank_sums[j] = col_sum;
    }

    // Calculate the test statistic
    let n_f = F::from(n).expect("Failed to convert to float");
    let k_f = F::from(k).expect("Failed to convert to float");

    let mut sum_ranks_squared = F::zero();
    for &rank_sum in &rank_sums {
        sum_ranks_squared += rank_sum.powi(2);
    }

    let chi2 = (F::from(12.0).expect("Failed to convert constant to float")
        / (n_f * k_f * (k_f + F::one())))
        * sum_ranks_squared
        - F::from(3.0).expect("Failed to convert constant to float") * n_f * (k_f + F::one());

    // Calculate p-value (chi-square distribution with k-1 degrees of freedom)
    let df = k_f - F::one();
    let p_value = chi_square_sf(chi2, df);

    Ok((chi2, p_value))
}

// Helper function: Standard normal CDF approximation
#[allow(dead_code)]
fn normal_cdf<F: Float + NumCast>(x: F) -> F {
    let x_f64 = <f64 as NumCast>::from(x).expect("Operation failed");

    // Approximation of the standard normal CDF
    let cdf = if x_f64 < -8.0 {
        0.0
    } else if x_f64 > 8.0 {
        1.0
    } else {
        // Abramowitz and Stegun approximation
        let abs_x = x_f64.abs();
        let t = 1.0 / (1.0 + 0.2316419 * abs_x);
        let d = 0.3989423 * (-0.5 * x_f64 * x_f64).exp();
        let p = t
            * (0.319381530
                + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));

        if x_f64 >= 0.0 {
            1.0 - d * p
        } else {
            d * p
        }
    };

    F::from(cdf).expect("Failed to convert to float")
}

// Helper function: Chi-square survival function (1 - CDF)
#[allow(dead_code)]
fn chi_square_sf<F: Float + NumCast>(x: F, df: F) -> F {
    let x_f64 = <f64 as NumCast>::from(x).expect("Operation failed");
    let df_f64 = <f64 as NumCast>::from(df).expect("Operation failed");

    if x_f64 <= 0.0 {
        return F::one();
    }

    // Degree of freedom must be positive
    if df_f64 <= 0.0 {
        return F::zero();
    }

    // Approximation for the chi-square upper tail probability
    // Wilson-Hilferty transformation
    let z;

    if df_f64 > 100.0 {
        // For large df, use normal approximation with Wilson-Hilferty transformation
        z = (x_f64 / df_f64).powf(1.0 / 3.0)
            - (1.0 - 2.0 / (9.0 * df_f64)) / (1.0 / (3.0 * df_f64).sqrt());
    } else if df_f64 > 1.0 {
        // For moderate df
        z = (x_f64 / df_f64 - 1.0) * (0.5 * df_f64).sqrt();
    } else {
        // For df = 1 (special case)
        z = (x_f64 * 0.5).sqrt();
    }

    // Convert to p-value using standard normal survival function
    let p = 1.0 - normal_cdf::<f64>(z);

    F::from(p).expect("Failed to convert to float")
}