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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//! Factor Analysis
//!
//! Factor analysis is a dimensionality reduction technique that identifies latent factors
//! that explain the correlations among observed variables.

use crate::error::{StatsError, StatsResult as Result};
use scirs2_core::ndarray::{Array1, Array2, ArrayView2, Axis};
use scirs2_core::random::{rngs::StdRng, SeedableRng};
use scirs2_core::validation::*;

/// Factor Analysis model
#[derive(Debug, Clone)]
pub struct FactorAnalysis {
    /// Number of factors to extract
    pub n_factors: usize,
    /// Maximum number of iterations for EM algorithm
    pub max_iter: usize,
    /// Convergence tolerance
    pub tol: f64,
    /// Whether to perform varimax rotation
    pub rotation: RotationType,
    /// Random state for reproducibility
    pub random_state: Option<u64>,
}

/// Type of factor rotation
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RotationType {
    /// No rotation
    None,
    /// Varimax rotation (orthogonal)
    Varimax,
    /// Promax rotation (oblique)
    Promax,
}

/// Result of factor analysis
#[derive(Debug, Clone)]
pub struct FactorAnalysisResult {
    /// Factor loadings matrix (p x k)
    pub loadings: Array2<f64>,
    /// Specific variances (unique factors)
    pub noise_variance: Array1<f64>,
    /// Factors scores for training data (n x k)
    pub scores: Array2<f64>,
    /// Mean of training data
    pub mean: Array1<f64>,
    /// Log-likelihood of the model
    pub log_likelihood: f64,
    /// Number of iterations until convergence
    pub n_iter: usize,
    /// Proportion of variance explained by each factor
    pub explained_variance_ratio: Array1<f64>,
    /// Communalities (proportion of variance in each variable explained by factors)
    pub communalities: Array1<f64>,
}

impl Default for FactorAnalysis {
    fn default() -> Self {
        Self {
            n_factors: 2,
            max_iter: 1000,
            tol: 1e-6,
            rotation: RotationType::Varimax,
            random_state: None,
        }
    }
}

impl FactorAnalysis {
    /// Create a new factor analysis instance
    pub fn new(n_factors: usize) -> Result<Self> {
        check_positive(n_factors, "n_factors")?;
        Ok(Self {
            n_factors,
            ..Default::default()
        })
    }

    /// Set maximum iterations
    pub fn with_max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    /// Set convergence tolerance
    pub fn with_tolerance(mut self, tol: f64) -> Self {
        self.tol = tol;
        self
    }

    /// Set rotation type
    pub fn with_rotation(mut self, rotation: RotationType) -> Self {
        self.rotation = rotation;
        self
    }

    /// Set random state
    pub fn with_random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    /// Fit the factor analysis model
    pub fn fit(&self, data: ArrayView2<f64>) -> Result<FactorAnalysisResult> {
        checkarray_finite(&data, "data")?;
        let (n_samples, n_features) = data.dim();

        if n_samples < 2 {
            return Err(StatsError::InvalidArgument(
                "n_samples must be at least 2".to_string(),
            ));
        }

        if self.n_factors >= n_features {
            return Err(StatsError::InvalidArgument(format!(
                "n_factors ({}) must be less than n_features ({})",
                self.n_factors, n_features
            )));
        }

        // Center the data
        let mean = data.mean_axis(Axis(0)).expect("Operation failed");
        let mut centereddata = data.to_owned();
        for mut row in centereddata.rows_mut() {
            row -= &mean;
        }

        // Initialize parameters
        let (mut loadings, mut psi) = self.initialize_parameters(&centereddata)?;

        let mut prev_log_likelihood = f64::NEG_INFINITY;
        let mut n_iter = 0;

        // EM algorithm
        for iteration in 0..self.max_iter {
            // E-step: compute expected sufficient statistics
            let (e_h, e_hht) = self.e_step(&centereddata, &loadings, &psi)?;

            // M-step: update parameters
            let (new_loadings, new_psi) = self.m_step(&centereddata, &e_h, &e_hht)?;

            // Compute log-likelihood
            let log_likelihood =
                self.compute_log_likelihood(&centereddata, &new_loadings, &new_psi)?;

            // Check convergence
            if (log_likelihood - prev_log_likelihood).abs() < self.tol {
                loadings = new_loadings;
                psi = new_psi;
                n_iter = iteration + 1;
                break;
            }

            loadings = new_loadings;
            psi = new_psi;
            prev_log_likelihood = log_likelihood;
            n_iter = iteration + 1;
        }

        if n_iter == self.max_iter {
            return Err(StatsError::ConvergenceError(format!(
                "EM algorithm failed to converge after {} iterations",
                self.max_iter
            )));
        }

        // Apply rotation if specified
        let rotated_loadings = match self.rotation {
            RotationType::None => loadings,
            RotationType::Varimax => self.varimax_rotation(&loadings)?,
            RotationType::Promax => self.promax_rotation(&loadings)?,
        };

        // Compute factor scores
        let scores = self.compute_factor_scores(&centereddata, &rotated_loadings, &psi)?;

        // Compute explained variance and communalities
        let explained_variance_ratio = self.compute_explained_variance(&rotated_loadings);
        let communalities = self.compute_communalities(&rotated_loadings);

        // Final log-likelihood
        let final_log_likelihood =
            self.compute_log_likelihood(&centereddata, &rotated_loadings, &psi)?;

        Ok(FactorAnalysisResult {
            loadings: rotated_loadings,
            noise_variance: psi,
            scores,
            mean,
            log_likelihood: final_log_likelihood,
            n_iter,
            explained_variance_ratio,
            communalities,
        })
    }

    /// Initialize factor loadings and specific variances
    fn initialize_parameters(&self, data: &Array2<f64>) -> Result<(Array2<f64>, Array1<f64>)> {
        let (n_samples, n_features) = data.dim();

        // Initialize using SVD of data (using scirs2_linalg)
        let (_u, s, vt) = scirs2_linalg::svd(&data.view(), false, None).map_err(|e| {
            StatsError::ComputationError(format!("SVD initialization failed: {}", e))
        })?;

        let v = vt.t().to_owned();

        // Initial loadings from first k components
        let mut loadings = Array2::zeros((n_features, self.n_factors));
        for i in 0..self.n_factors {
            let scale = (s[i] / (n_samples as f64).sqrt()).max(1e-6);
            for j in 0..n_features {
                loadings[[j, i]] = v[[j, i]] * scale;
            }
        }

        // Initialize specific variances
        let mut psi = Array1::ones(n_features);
        for i in 0..n_features {
            let communality = loadings.row(i).dot(&loadings.row(i));
            psi[i] = (1.0 - communality).max(0.01); // Ensure positive
        }

        Ok((loadings, psi))
    }

    /// E-step of EM algorithm
    fn e_step(
        &self,
        data: &Array2<f64>,
        loadings: &Array2<f64>,
        psi: &Array1<f64>,
    ) -> Result<(Array2<f64>, Array2<f64>)> {
        let (n_samples, n_features) = data.dim();

        // Construct precision matrix: Psi^{-1}
        let mut psi_inv = Array2::zeros((n_features, n_features));
        for i in 0..n_features {
            if psi[i] <= 0.0 {
                return Err(StatsError::ComputationError(
                    "Specific variances must be positive".to_string(),
                ));
            }
            psi_inv[[i, i]] = 1.0 / psi[i];
        }

        // Compute M = I + L^T Psi^{-1} L
        let lt_psi_inv = loadings.t().dot(&psi_inv);
        let m = Array2::eye(self.n_factors) + lt_psi_inv.dot(loadings);

        // Invert M
        let m_inv = scirs2_linalg::inv(&m.view(), None).map_err(|e| {
            StatsError::ComputationError(format!("Failed to invert M matrix: {}", e))
        })?;

        // Compute conditional expectations
        let mut e_h = Array2::zeros((n_samples, self.n_factors));
        let e_hht = m_inv.clone(); // This is E[h h^T | x]

        for i in 0..n_samples {
            let x = data.row(i);
            let e_h_i = m_inv.dot(&lt_psi_inv.dot(&x.to_owned()));
            e_h.row_mut(i).assign(&e_h_i);
        }

        Ok((e_h, e_hht))
    }

    /// M-step of EM algorithm
    fn m_step(
        &self,
        data: &Array2<f64>,
        e_h: &Array2<f64>,
        e_hht: &Array2<f64>,
    ) -> Result<(Array2<f64>, Array1<f64>)> {
        let (n_samples, n_features) = data.dim();

        // Update loadings: L = (X^T E[H]) (E[H^T H])^{-1}
        let xte_h = data.t().dot(e_h);
        let sum_e_hht = e_hht * n_samples as f64; // Sum over samples

        let sum_e_hht_inv = scirs2_linalg::inv(&sum_e_hht.view(), None).map_err(|e| {
            StatsError::ComputationError(format!("Failed to invert sum E[HH^T]: {}", e))
        })?;

        let new_loadings = xte_h.dot(&sum_e_hht_inv);

        // Update specific variances
        let mut new_psi = Array1::zeros(n_features);

        for j in 0..n_features {
            let x_j = data.column(j);
            let l_j = new_loadings.row(j);

            let mut sum_var = 0.0;
            for i in 0..n_samples {
                let x_ij = x_j[i];
                let e_h_i = e_h.row(i);
                let residual = x_ij - l_j.dot(&e_h_i.to_owned());
                sum_var += residual * residual;

                // Add E[h h^T] term
                let quad_form = l_j.dot(&e_hht.dot(&l_j.to_owned()));
                sum_var += quad_form;
            }

            new_psi[j] = (sum_var / n_samples as f64).max(1e-6); // Ensure positive
        }

        Ok((new_loadings, new_psi))
    }

    /// Compute log-likelihood
    fn compute_log_likelihood(
        &self,
        data: &Array2<f64>,
        loadings: &Array2<f64>,
        psi: &Array1<f64>,
    ) -> Result<f64> {
        let (n_samples, n_features) = data.dim();

        // Construct covariance matrix: Sigma = L L^T + Psi
        let ll_t = loadings.dot(&loadings.t());
        let mut sigma = ll_t;
        for i in 0..n_features {
            sigma[[i, i]] += psi[i];
        }

        // Compute determinant and inverse
        let det_sigma = scirs2_linalg::det(&sigma.view(), None).map_err(|e| {
            StatsError::ComputationError(format!("Failed to compute determinant: {}", e))
        })?;

        if det_sigma <= 0.0 {
            return Err(StatsError::ComputationError(
                "Covariance matrix must be positive definite".to_string(),
            ));
        }

        let sigma_inv = scirs2_linalg::inv(&sigma.view(), None).map_err(|e| {
            StatsError::ComputationError(format!("Failed to invert covariance: {}", e))
        })?;

        // Compute log-likelihood
        let mut log_likelihood = 0.0;
        let log_det_term =
            -0.5 * n_features as f64 * (2.0 * std::f64::consts::PI).ln() - 0.5 * det_sigma.ln();

        for i in 0..n_samples {
            let x = data.row(i);
            let quad_form = x.dot(&sigma_inv.dot(&x.to_owned()));
            log_likelihood += log_det_term - 0.5 * quad_form;
        }

        Ok(log_likelihood)
    }

    /// Varimax rotation
    fn varimax_rotation(&self, loadings: &Array2<f64>) -> Result<Array2<f64>> {
        let (n_features, n_factors) = loadings.dim();
        let mut rotated = loadings.clone();

        let max_iter = 30;
        let tol = 1e-6;

        for _ in 0..max_iter {
            let rotation_matrix = Array2::<f64>::eye(n_factors);
            let mut converged = true;

            // Rotate each pair of factors
            for i in 0..n_factors {
                for j in (i + 1)..n_factors {
                    let col_i = rotated.column(i).to_owned();
                    let col_j = rotated.column(j).to_owned();

                    // Compute rotation angle
                    let u = &col_i * &col_i - &col_j * &col_j;
                    let v = 2.0 * &col_i * &col_j;

                    let a = u.sum();
                    let b = v.sum();
                    let c = (&u * &u - &v * &v).sum();
                    let d = 2.0 * (&u * &v).sum();

                    let num = d - 2.0 * a * b / n_features as f64;
                    let den = c - (a * a - b * b) / n_features as f64;

                    if den.abs() < 1e-10 {
                        continue;
                    }

                    let phi = 0.25 * (num / den).atan();

                    if phi.abs() > tol {
                        converged = false;

                        // Apply rotation
                        let cos_phi = phi.cos();
                        let sin_phi = phi.sin();

                        let new_col_i = cos_phi * &col_i - sin_phi * &col_j;
                        let new_col_j = sin_phi * &col_i + cos_phi * &col_j;

                        rotated.column_mut(i).assign(&new_col_i);
                        rotated.column_mut(j).assign(&new_col_j);
                    }
                }
            }

            if converged {
                break;
            }
        }

        Ok(rotated)
    }

    /// Promax rotation (oblique)
    fn promax_rotation(&self, loadings: &Array2<f64>) -> Result<Array2<f64>> {
        // First apply varimax rotation
        let varimax_rotated = self.varimax_rotation(loadings)?;

        // Then apply promax transformation
        let kappa = 4.0; // Power parameter
        let (n_features, n_factors) = varimax_rotated.dim();

        // Compute target matrix by raising loadings to power kappa
        let mut target = Array2::zeros((n_features, n_factors));
        for i in 0..n_features {
            for j in 0..n_factors {
                let val = varimax_rotated[[i, j]];
                target[[i, j]] = val.abs().powf(kappa) * val.signum();
            }
        }

        // Solve for transformation matrix using least squares
        // T = (L^T L)^{-1} L^T P where P is target
        let ltl = varimax_rotated.t().dot(&varimax_rotated);
        let ltl_inv = scirs2_linalg::inv(&ltl.view(), None)
            .map_err(|e| StatsError::ComputationError(format!("Failed to invert L^T L: {}", e)))?;

        let ltp = varimax_rotated.t().dot(&target);
        let transform = ltl_inv.dot(&ltp);

        // Apply transformation
        let rotated = varimax_rotated.dot(&transform);

        Ok(rotated)
    }

    /// Compute factor scores using regression method
    fn compute_factor_scores(
        &self,
        data: &Array2<f64>,
        loadings: &Array2<f64>,
        psi: &Array1<f64>,
    ) -> Result<Array2<f64>> {
        let n_features = loadings.nrows();

        // Construct precision matrix
        let mut psi_inv = Array2::zeros((n_features, n_features));
        for i in 0..n_features {
            psi_inv[[i, i]] = 1.0 / psi[i];
        }

        // Compute factor score coefficient matrix: (L^T Psi^{-1} L)^{-1} L^T Psi^{-1}
        let lt_psi_inv = loadings.t().dot(&psi_inv);
        let lt_psi_inv_l = lt_psi_inv.dot(loadings);

        let lt_psi_inv_l_inv = scirs2_linalg::inv(&lt_psi_inv_l.view(), None).map_err(|e| {
            StatsError::ComputationError(format!("Failed to compute factor score weights: {}", e))
        })?;

        let score_weights = lt_psi_inv_l_inv.dot(&lt_psi_inv);

        // Compute scores
        let scores = data.dot(&score_weights.t());

        Ok(scores)
    }

    /// Compute explained variance ratio for each factor
    fn compute_explained_variance(&self, loadings: &Array2<f64>) -> Array1<f64> {
        let factor_variances = loadings
            .axis_iter(Axis(1))
            .map(|col| col.dot(&col))
            .collect::<Vec<_>>();

        let total_variance: f64 = factor_variances.iter().sum();

        Array1::from_vec(factor_variances).mapv(|v| v / total_variance)
    }

    /// Compute communalities (proportion of variance explained for each variable)
    fn compute_communalities(&self, loadings: &Array2<f64>) -> Array1<f64> {
        let mut communalities = Array1::zeros(loadings.nrows());

        for i in 0..loadings.nrows() {
            communalities[i] = loadings.row(i).dot(&loadings.row(i));
        }

        communalities
    }

    /// Transform new data to factor space
    pub fn transform(
        &self,
        data: ArrayView2<f64>,
        result: &FactorAnalysisResult,
    ) -> Result<Array2<f64>> {
        checkarray_finite(&data, "data")?;

        if data.ncols() != result.mean.len() {
            return Err(StatsError::DimensionMismatch(format!(
                "data has {} features, expected {}",
                data.ncols(),
                result.mean.len()
            )));
        }

        // Center the data
        let mut centered = data.to_owned();
        for mut row in centered.rows_mut() {
            row -= &result.mean;
        }

        // Compute factor scores
        self.compute_factor_scores(&centered, &result.loadings, &result.noise_variance)
    }
}

/// Exploratory Factor Analysis (EFA) utilities
pub mod efa {
    use super::*;

    /// Determine optimal number of factors using parallel analysis
    pub fn parallel_analysis(
        data: ArrayView2<f64>,
        n_simulations: usize,
        percentile: f64,
        seed: Option<u64>,
    ) -> Result<usize> {
        checkarray_finite(&data, "data")?;
        check_positive(n_simulations, "n_simulations")?;

        if percentile <= 0.0 || percentile >= 100.0 {
            return Err(StatsError::InvalidArgument(
                "percentile must be between 0 and 100".to_string(),
            ));
        }

        let (n_samples, n_features) = data.dim();

        // Compute eigenvalues of real data correlation matrix
        let real_eigenvalues = compute_correlation_eigenvalues(data)?;

        // Initialize RNG
        let mut rng = match seed {
            Some(s) => StdRng::seed_from_u64(s),
            None => {
                use std::time::{SystemTime, UNIX_EPOCH};
                let s = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs();
                StdRng::seed_from_u64(s)
            }
        };

        // Generate random data and compute eigenvalues
        let mut simulated_eigenvalues = Vec::with_capacity(n_simulations);

        for _ in 0..n_simulations {
            // Generate random normal data with same dimensions
            let mut randomdata = Array2::zeros((n_samples, n_features));
            use scirs2_core::random::{Distribution, Normal};
            let normal = Normal::new(0.0, 1.0).map_err(|e| {
                StatsError::ComputationError(format!("Failed to create normal distribution: {}", e))
            })?;

            for i in 0..n_samples {
                for j in 0..n_features {
                    randomdata[[i, j]] = normal.sample(&mut rng);
                }
            }

            let eigenvalues = compute_correlation_eigenvalues(randomdata.view())?;
            simulated_eigenvalues.push(eigenvalues);
        }

        // Compute percentile thresholds
        let mut thresholds = Array1::zeros(n_features);
        for i in 0..n_features {
            let mut values: Vec<f64> = simulated_eigenvalues.iter().map(|ev| ev[i]).collect();
            values.sort_by(|a, b| a.partial_cmp(b).expect("Operation failed"));

            let index = ((percentile / 100.0) * (n_simulations - 1) as f64).round() as usize;
            thresholds[i] = values[index.min(n_simulations - 1)];
        }

        // Count factors where real eigenvalue > threshold
        let mut n_factors = 0;
        for i in 0..n_features {
            if real_eigenvalues[i] > thresholds[i] {
                n_factors += 1;
            } else {
                break;
            }
        }

        Ok(n_factors.max(1)) // At least 1 factor
    }

    /// Compute eigenvalues of correlation matrix
    fn compute_correlation_eigenvalues(data: ArrayView2<f64>) -> Result<Array1<f64>> {
        // Center data
        let mean = data.mean_axis(Axis(0)).expect("Operation failed");
        let mut centered = data.to_owned();
        for mut row in centered.rows_mut() {
            row -= &mean;
        }

        // Compute correlation matrix
        let cov = centered.t().dot(&centered) / (data.nrows() - 1) as f64;

        // Standardize to correlation
        let mut corr = cov.clone();
        for i in 0..corr.nrows() {
            for j in 0..corr.ncols() {
                let std_i = cov[[i, i]].sqrt();
                let std_j = cov[[j, j]].sqrt();
                if std_i > 1e-10 && std_j > 1e-10 {
                    corr[[i, j]] = cov[[i, j]] / (std_i * std_j);
                }
            }
        }

        // Compute eigenvalues using scirs2_linalg
        let (eigenvalues, _eigenvectors) =
            scirs2_linalg::eigh_f64_lapack(&corr.view()).map_err(|e| {
                StatsError::ComputationError(format!("Eigenvalue decomposition failed: {}", e))
            })?;

        // Sort in descending order
        let mut sorted_eigenvalues: Vec<f64> = eigenvalues.to_vec();
        sorted_eigenvalues.sort_by(|a: &f64, b: &f64| b.partial_cmp(a).expect("Operation failed"));

        Ok(Array1::from_vec(sorted_eigenvalues))
    }

    /// Kaiser-Meyer-Olkin (KMO) measure of sampling adequacy
    pub fn kmo_test(data: ArrayView2<f64>) -> Result<f64> {
        checkarray_finite(&data, "data")?;

        // Compute correlation matrix
        let mean = data.mean_axis(Axis(0)).expect("Operation failed");
        let mut centered = data.to_owned();
        for mut row in centered.rows_mut() {
            row -= &mean;
        }

        let cov = centered.t().dot(&centered) / (data.nrows() - 1) as f64;
        let n = cov.nrows();

        // Standardize to correlation
        let mut corr = Array2::zeros((n, n));
        for i in 0..n {
            for j in 0..n {
                let std_i = cov[[i, i]].sqrt();
                let std_j = cov[[j, j]].sqrt();
                if std_i > 1e-10 && std_j > 1e-10 {
                    corr[[i, j]] = cov[[i, j]] / (std_i * std_j);
                } else if i == j {
                    corr[[i, j]] = 1.0;
                }
            }
        }

        // Compute anti-image correlation matrix
        let corr_inv = scirs2_linalg::inv(&corr.view(), None).map_err(|e| {
            StatsError::ComputationError(format!("Failed to invert correlation matrix: {}", e))
        })?;

        // Compute KMO statistic
        let mut sum_squared_corr = 0.0;
        let mut sum_squared_partial = 0.0;

        for i in 0..n {
            for j in 0..n {
                if i != j {
                    sum_squared_corr += corr[[i, j]] * corr[[i, j]];

                    // Partial correlation
                    let partial = -corr_inv[[i, j]] / (corr_inv[[i, i]] * corr_inv[[j, j]]).sqrt();
                    sum_squared_partial += partial * partial;
                }
            }
        }

        let kmo = sum_squared_corr / (sum_squared_corr + sum_squared_partial);
        Ok(kmo)
    }

    /// Bartlett's test of sphericity
    pub fn bartlett_test(data: ArrayView2<f64>) -> Result<(f64, f64)> {
        checkarray_finite(&data, "data")?;
        let (n, p) = data.dim();

        if n <= p {
            return Err(StatsError::InvalidArgument(
                "Number of samples must exceed number of variables".to_string(),
            ));
        }

        // Compute correlation matrix
        let mean = data.mean_axis(Axis(0)).expect("Operation failed");
        let mut centered = data.to_owned();
        for mut row in centered.rows_mut() {
            row -= &mean;
        }

        let cov = centered.t().dot(&centered) / (n - 1) as f64;

        // Standardize to correlation
        let mut corr = Array2::zeros((p, p));
        for i in 0..p {
            for j in 0..p {
                let std_i = cov[[i, i]].sqrt();
                let std_j = cov[[j, j]].sqrt();
                if std_i > 1e-10 && std_j > 1e-10 {
                    corr[[i, j]] = cov[[i, j]] / (std_i * std_j);
                } else if i == j {
                    corr[[i, j]] = 1.0;
                }
            }
        }

        // Compute test statistic
        let det_corr = scirs2_linalg::det(&corr.view(), None).map_err(|e| {
            StatsError::ComputationError(format!("Failed to compute determinant: {}", e))
        })?;

        if det_corr <= 0.0 {
            return Err(StatsError::ComputationError(
                "Correlation matrix must be positive definite".to_string(),
            ));
        }

        let chi2 = -(n as f64 - 1.0 - (2.0 * p as f64 + 5.0) / 6.0) * det_corr.ln();
        let df = p * (p - 1) / 2;

        // Approximate p-value using chi-square distribution
        let p_value = chi2_survival(chi2, df as f64);

        Ok((chi2, p_value))
    }
}

/// Approximate survival function for chi-square distribution
#[allow(dead_code)]
fn chi2_survival(x: f64, df: f64) -> f64 {
    if x <= 0.0 {
        return 1.0;
    }

    // Very rough approximation - in practice use proper chi-square CDF
    let mean = df;
    let var = 2.0 * df;
    let std = var.sqrt();

    // Normal approximation for large df
    if df > 30.0 {
        let z = (x - mean) / std;
        return 0.5 * (1.0 - erf(z / std::f64::consts::SQRT_2));
    }

    // Simple exponential approximation for small df
    (-x / mean).exp()
}

/// Error function approximation
#[allow(dead_code)]
fn erf(x: f64) -> f64 {
    // Abramowitz and Stegun approximation
    let a1 = 0.254829592;
    let a2 = -0.284496736;
    let a3 = 1.421413741;
    let a4 = -1.453152027;
    let a5 = 1.061405429;
    let p = 0.3275911;

    let sign = if x >= 0.0 { 1.0 } else { -1.0 };
    let x = x.abs();

    let t = 1.0 / (1.0 + p * x);
    let y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * (-x * x).exp();

    sign * y
}