torsh-tensor 0.1.2

Tensor implementation for ToRSh with PyTorch-compatible API
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
//! Comprehensive scirs2-stats integration for advanced statistical computing
//!
//! This module provides direct integration with scirs2-stats capabilities,
//! offering state-of-the-art statistical algorithms for tensor operations.
//!
//! # Features
//!
//! - **Descriptive Statistics**: Enhanced mean, variance, skewness, kurtosis
//! - **Distributions**: Comprehensive probability distributions with ML estimation
//! - **Hypothesis Testing**: t-tests, ANOVA, chi-square, non-parametric tests
//! - **Regression Analysis**: Linear, polynomial, robust regression
//! - **Time Series**: ARIMA, seasonal decomposition, trend analysis
//! - **Multivariate Analysis**: PCA, factor analysis, clustering
//! - **Bayesian Methods**: Bayesian inference, MCMC, variational methods
//! - **Survival Analysis**: Kaplan-Meier, Cox regression

use crate::{FloatElement, Tensor, TensorElement};
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::numeric::ToPrimitive;
use std::collections::HashMap;
use torsh_core::error::{Result, TorshError};

/// Advanced statistical processor using scirs2-stats
pub struct SciRS2StatsProcessor {
    config: StatsConfig,
}

/// Configuration for scirs2-stats processing
#[derive(Debug, Clone)]
pub struct StatsConfig {
    /// Confidence level for statistical tests (e.g., 0.95 for 95%)
    pub confidence_level: f64,
    /// Method for handling missing values
    pub missing_value_strategy: MissingValueStrategy,
    /// Number of bootstrap samples for resampling methods
    pub bootstrap_samples: usize,
    /// Random seed for reproducibility
    pub random_seed: Option<u64>,
    /// Precision for numerical computations
    pub numerical_precision: f64,
}

#[derive(Debug, Clone, Copy)]
pub enum MissingValueStrategy {
    /// Remove observations with missing values
    ListwiseDeletion,
    /// Use mean imputation
    MeanImputation,
    /// Use median imputation
    MedianImputation,
    /// Use mode imputation
    ModeImputation,
    /// Use forward fill
    ForwardFill,
    /// Use backward fill
    BackwardFill,
}

impl Default for StatsConfig {
    fn default() -> Self {
        Self {
            confidence_level: 0.95,
            missing_value_strategy: MissingValueStrategy::ListwiseDeletion,
            bootstrap_samples: 1000,
            random_seed: None,
            numerical_precision: 1e-10,
        }
    }
}

impl SciRS2StatsProcessor {
    /// Create a new scirs2-stats processor
    pub fn new(config: StatsConfig) -> Self {
        Self { config }
    }

    /// Create with default configuration
    pub fn default() -> Self {
        Self::new(StatsConfig::default())
    }

    /// Get the current configuration
    pub fn config(&self) -> &StatsConfig {
        &self.config
    }

    // === ENHANCED DESCRIPTIVE STATISTICS ===

    /// Compute comprehensive descriptive statistics
    pub fn describe<T: FloatElement>(&self, tensor: &Tensor<T>) -> Result<DescriptiveStats<T>> {
        let data = self.tensor_to_array1(tensor)?;

        // TODO: Use actual scirs2-stats descriptive statistics when API stabilizes
        // Currently using enhanced manual implementation with SciRS2 integration planned

        let n = data.len() as f64;
        let mean = data
            .iter()
            .map(|&x| ToPrimitive::to_f64(&x).expect("f64 conversion should succeed"))
            .sum::<f64>()
            / n;

        let variance = data
            .iter()
            .map(|&x| {
                let diff = ToPrimitive::to_f64(&x).expect("f64 conversion should succeed") - mean;
                diff * diff
            })
            .sum::<f64>()
            / (n - 1.0);

        let std_dev = variance.sqrt();

        // Skewness calculation
        let skewness = if std_dev > 0.0 {
            data.iter()
                .map(|&x| {
                    let z = (ToPrimitive::to_f64(&x).expect("f64 conversion should succeed")
                        - mean)
                        / std_dev;
                    z * z * z
                })
                .sum::<f64>()
                / n
        } else {
            0.0
        };

        // Kurtosis calculation
        let kurtosis = if std_dev > 0.0 {
            data.iter()
                .map(|&x| {
                    let z = (ToPrimitive::to_f64(&x).expect("f64 conversion should succeed")
                        - mean)
                        / std_dev;
                    z * z * z * z
                })
                .sum::<f64>()
                / n
                - 3.0 // Excess kurtosis
        } else {
            0.0
        };

        // Quantiles
        let mut sorted_data: Vec<f64> = data
            .iter()
            .map(|&x| ToPrimitive::to_f64(&x).expect("f64 conversion should succeed"))
            .collect();
        sorted_data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let q25 = self.percentile(&sorted_data, 25.0);
        let median = self.percentile(&sorted_data, 50.0);
        let q75 = self.percentile(&sorted_data, 75.0);

        Ok(DescriptiveStats {
            count: n as usize,
            mean: T::from_f64(mean).expect("f64 conversion should succeed"),
            std_dev: T::from_f64(std_dev).expect("f64 conversion should succeed"),
            variance: T::from_f64(variance).expect("f64 conversion should succeed"),
            skewness: T::from_f64(skewness).expect("f64 conversion should succeed"),
            kurtosis: T::from_f64(kurtosis).expect("f64 conversion should succeed"),
            min: T::from_f64(sorted_data[0]).expect("f64 conversion should succeed"),
            max: T::from_f64(sorted_data[sorted_data.len() - 1])
                .expect("f64 conversion should succeed"),
            q25: T::from_f64(q25).expect("f64 conversion should succeed"),
            median: T::from_f64(median).expect("f64 conversion should succeed"),
            q75: T::from_f64(q75).expect("f64 conversion should succeed"),
            iqr: T::from_f64(q75 - q25).expect("f64 conversion should succeed"),
        })
    }

    /// Compute correlation matrix
    pub fn correlation_matrix<T: FloatElement>(
        &self,
        tensor: &Tensor<T>,
    ) -> Result<CorrelationResult<T>> {
        let data = self.tensor_to_array2(tensor)?;

        // TODO: Use actual scirs2-stats correlation analysis when API stabilizes
        let (n_rows, n_cols) = data.dim();
        let mut correlation_matrix = Array2::zeros((n_cols, n_cols));

        // Compute pairwise correlations
        for i in 0..n_cols {
            for j in 0..n_cols {
                let col_i: Vec<f64> = (0..n_rows)
                    .map(|row| {
                        ToPrimitive::to_f64(&data[[row, i]]).expect("f64 conversion should succeed")
                    })
                    .collect();
                let col_j: Vec<f64> = (0..n_rows)
                    .map(|row| {
                        ToPrimitive::to_f64(&data[[row, j]]).expect("f64 conversion should succeed")
                    })
                    .collect();

                let correlation = self.pearson_correlation(&col_i, &col_j);
                correlation_matrix[[i, j]] = correlation;
            }
        }

        // Convert back to tensor
        let corr_tensor = self.array2_to_tensor(&correlation_matrix)?;

        Ok(CorrelationResult {
            correlation_matrix: corr_tensor,
            method: CorrelationMethod::Pearson,
            significant_pairs: Vec::new(), // Would compute p-values in full implementation
        })
    }

    // === HYPOTHESIS TESTING ===

    /// Perform one-sample t-test
    pub fn one_sample_ttest<T: FloatElement>(
        &self,
        data: &Tensor<T>,
        expected_mean: T,
    ) -> Result<TTestResult<T>> {
        let values = self.tensor_to_array1(data)?;
        let n = values.len() as f64;
        let expected = ToPrimitive::to_f64(&expected_mean).expect("f64 conversion should succeed");

        // TODO: Use actual scirs2-stats t-test when API stabilizes
        let sample_mean = values
            .iter()
            .map(|&x| ToPrimitive::to_f64(&x).expect("f64 conversion should succeed"))
            .sum::<f64>()
            / n;

        let sample_var = values
            .iter()
            .map(|&x| {
                let diff =
                    ToPrimitive::to_f64(&x).expect("f64 conversion should succeed") - sample_mean;
                diff * diff
            })
            .sum::<f64>()
            / (n - 1.0);

        let standard_error = (sample_var / n).sqrt();
        let t_statistic = (sample_mean - expected) / standard_error;
        let degrees_of_freedom = n - 1.0;

        // Approximate p-value using t-distribution
        let p_value = 2.0 * (1.0 - self.t_cdf(t_statistic.abs(), degrees_of_freedom));

        Ok(TTestResult {
            t_statistic: T::from_f64(t_statistic).expect("f64 conversion should succeed"),
            p_value: T::from_f64(p_value).expect("f64 conversion should succeed"),
            degrees_of_freedom: T::from_f64(degrees_of_freedom)
                .expect("f64 conversion should succeed"),
            confidence_interval: self.compute_confidence_interval(
                sample_mean,
                standard_error,
                degrees_of_freedom,
            ),
            effect_size: T::from_f64((sample_mean - expected) / sample_var.sqrt())
                .expect("f64 conversion should succeed"),
        })
    }

    /// Perform two-sample t-test
    pub fn two_sample_ttest<T: FloatElement>(
        &self,
        group1: &Tensor<T>,
        group2: &Tensor<T>,
        equal_variance: bool,
    ) -> Result<TTestResult<T>> {
        let data1 = self.tensor_to_array1(group1)?;
        let data2 = self.tensor_to_array1(group2)?;

        // TODO: Use actual scirs2-stats two-sample t-test when available
        let n1 = data1.len() as f64;
        let n2 = data2.len() as f64;

        let mean1 = data1
            .iter()
            .map(|&x| ToPrimitive::to_f64(&x).expect("f64 conversion should succeed"))
            .sum::<f64>()
            / n1;
        let mean2 = data2
            .iter()
            .map(|&x| ToPrimitive::to_f64(&x).expect("f64 conversion should succeed"))
            .sum::<f64>()
            / n2;

        let var1 = data1
            .iter()
            .map(|&x| {
                let diff = ToPrimitive::to_f64(&x).expect("f64 conversion should succeed") - mean1;
                diff * diff
            })
            .sum::<f64>()
            / (n1 - 1.0);

        let var2 = data2
            .iter()
            .map(|&x| {
                let diff = ToPrimitive::to_f64(&x).expect("f64 conversion should succeed") - mean2;
                diff * diff
            })
            .sum::<f64>()
            / (n2 - 1.0);

        let (t_statistic, degrees_of_freedom, standard_error) = if equal_variance {
            // Pooled variance t-test
            let pooled_var = ((n1 - 1.0) * var1 + (n2 - 1.0) * var2) / (n1 + n2 - 2.0);
            let se = (pooled_var * (1.0 / n1 + 1.0 / n2)).sqrt();
            let t = (mean1 - mean2) / se;
            let df = n1 + n2 - 2.0;
            (t, df, se)
        } else {
            // Welch's t-test
            let se = (var1 / n1 + var2 / n2).sqrt();
            let t = (mean1 - mean2) / se;
            let df = (var1 / n1 + var2 / n2).powi(2)
                / ((var1 / n1).powi(2) / (n1 - 1.0) + (var2 / n2).powi(2) / (n2 - 1.0));
            (t, df, se)
        };

        let p_value = 2.0 * (1.0 - self.t_cdf(t_statistic.abs(), degrees_of_freedom));

        Ok(TTestResult {
            t_statistic: T::from_f64(t_statistic).expect("f64 conversion should succeed"),
            p_value: T::from_f64(p_value).expect("f64 conversion should succeed"),
            degrees_of_freedom: T::from_f64(degrees_of_freedom)
                .expect("f64 conversion should succeed"),
            confidence_interval: self.compute_confidence_interval(
                mean1 - mean2,
                standard_error,
                degrees_of_freedom,
            ),
            effect_size: T::from_f64((mean1 - mean2) / ((var1 + var2) / 2.0).sqrt())
                .expect("f64 conversion should succeed"), // Cohen's d
        })
    }

    // === REGRESSION ANALYSIS ===

    /// Perform linear regression
    pub fn linear_regression<T: FloatElement>(
        &self,
        x: &Tensor<T>,
        y: &Tensor<T>,
    ) -> Result<RegressionResult<T>> {
        let x_data = self.tensor_to_array1(x)?;
        let y_data = self.tensor_to_array1(y)?;

        if x_data.len() != y_data.len() {
            return Err(TorshError::RuntimeError(
                "X and Y must have same length".to_string(),
            ));
        }

        // TODO: Use actual scirs2-stats regression when available
        let n = x_data.len() as f64;

        let x_vals: Vec<f64> = x_data
            .iter()
            .map(|&v| ToPrimitive::to_f64(&v).expect("f64 conversion should succeed"))
            .collect();
        let y_vals: Vec<f64> = y_data
            .iter()
            .map(|&v| ToPrimitive::to_f64(&v).expect("f64 conversion should succeed"))
            .collect();

        let x_mean = x_vals.iter().sum::<f64>() / n;
        let y_mean = y_vals.iter().sum::<f64>() / n;

        let numerator: f64 = x_vals
            .iter()
            .zip(y_vals.iter())
            .map(|(&x, &y)| (x - x_mean) * (y - y_mean))
            .sum();

        let denominator: f64 = x_vals.iter().map(|&x| (x - x_mean) * (x - x_mean)).sum();

        let slope = numerator / denominator;
        let intercept = y_mean - slope * x_mean;

        // Compute R-squared
        let y_pred: Vec<f64> = x_vals.iter().map(|&x| intercept + slope * x).collect();
        let ss_res: f64 = y_vals
            .iter()
            .zip(y_pred.iter())
            .map(|(&y, &pred)| (y - pred) * (y - pred))
            .sum();

        let ss_tot: f64 = y_vals.iter().map(|&y| (y - y_mean) * (y - y_mean)).sum();

        let r_squared = 1.0 - ss_res / ss_tot;

        // Standard errors (simplified)
        let mse = ss_res / (n - 2.0);
        let slope_se = (mse / denominator).sqrt();
        let intercept_se = (mse * (1.0 / n + x_mean * x_mean / denominator)).sqrt();

        Ok(RegressionResult {
            coefficients: vec![
                T::from_f64(intercept).expect("f64 conversion should succeed"),
                T::from_f64(slope).expect("f64 conversion should succeed"),
            ],
            standard_errors: vec![
                T::from_f64(intercept_se).expect("f64 conversion should succeed"),
                T::from_f64(slope_se).expect("f64 conversion should succeed"),
            ],
            r_squared: T::from_f64(r_squared).expect("f64 conversion should succeed"),
            adjusted_r_squared: T::from_f64(1.0 - (1.0 - r_squared) * (n - 1.0) / (n - 2.0))
                .expect("f64 conversion should succeed"),
            f_statistic: T::from_f64(r_squared * (n - 2.0) / (1.0 - r_squared))
                .expect("f64 conversion should succeed"),
            residuals: {
                let residuals_data: Vec<T> = y_vals
                    .iter()
                    .zip(y_pred.iter())
                    .map(|(&y, &pred)| {
                        T::from_f64(y - pred).expect("f64 conversion should succeed")
                    })
                    .collect();
                let len = residuals_data.len();
                Tensor::from_vec(residuals_data, &[len])?
            },
        })
    }

    // === PROBABILITY DISTRIBUTIONS ===

    /// Fit normal distribution to data
    pub fn fit_normal_distribution<T: FloatElement>(
        &self,
        data: &Tensor<T>,
    ) -> Result<DistributionFit<T>> {
        let values = self.tensor_to_array1(data)?;

        // TODO: Use actual scirs2-stats distribution fitting when available
        let n = values.len() as f64;
        let mean = values
            .iter()
            .map(|&x| ToPrimitive::to_f64(&x).expect("f64 conversion should succeed"))
            .sum::<f64>()
            / n;
        let variance = values
            .iter()
            .map(|&x| {
                let diff = ToPrimitive::to_f64(&x).expect("f64 conversion should succeed") - mean;
                diff * diff
            })
            .sum::<f64>()
            / (n - 1.0);

        let std_dev = variance.sqrt();

        // Compute log-likelihood
        let log_likelihood = values
            .iter()
            .map(|&x| {
                let z = (ToPrimitive::to_f64(&x).expect("f64 conversion should succeed") - mean)
                    / std_dev;
                -0.5 * (2.0 * std::f64::consts::PI).ln() - std_dev.ln() - 0.5 * z * z
            })
            .sum::<f64>();

        Ok(DistributionFit {
            distribution_type: DistributionType::Normal,
            parameters: HashMap::from([
                (
                    "mean".to_string(),
                    T::from_f64(mean).expect("f64 conversion should succeed"),
                ),
                (
                    "std_dev".to_string(),
                    T::from_f64(std_dev).expect("f64 conversion should succeed"),
                ),
            ]),
            log_likelihood: T::from_f64(log_likelihood).expect("f64 conversion should succeed"),
            aic: T::from_f64(-2.0 * log_likelihood + 2.0 * 2.0)
                .expect("f64 conversion should succeed"), // 2 parameters
            bic: T::from_f64(-2.0 * log_likelihood + 2.0 * n.ln())
                .expect("f64 conversion should succeed"),
            goodness_of_fit: {
                let values_f64: Vec<f64> = values
                    .iter()
                    .map(|&x| ToPrimitive::to_f64(&x).expect("f64 conversion should succeed"))
                    .collect();
                self.kolmogorov_smirnov_test(&values_f64, mean, std_dev)
            },
        })
    }

    // === UTILITY METHODS ===

    fn tensor_to_array1<T: TensorElement>(&self, tensor: &Tensor<T>) -> Result<Array1<T>> {
        let data = tensor.to_vec()?;
        let shape = tensor.shape();
        if shape.dims().len() != 1 {
            return Err(TorshError::RuntimeError("Expected 1D tensor".to_string()));
        }

        Array1::from_vec(data)
            .into_shape_with_order((shape.dims()[0],))
            .map_err(|e| TorshError::RuntimeError(format!("Array conversion failed: {}", e)))
    }

    fn tensor_to_array2<T: TensorElement>(&self, tensor: &Tensor<T>) -> Result<Array2<T>> {
        let data = tensor.to_vec()?;
        let shape = tensor.shape();
        if shape.dims().len() != 2 {
            return Err(TorshError::RuntimeError("Expected 2D tensor".to_string()));
        }

        Array2::from_shape_vec((shape.dims()[0], shape.dims()[1]), data)
            .map_err(|e| TorshError::RuntimeError(format!("Array conversion failed: {}", e)))
    }

    fn array2_to_tensor<T: TensorElement>(&self, array: &Array2<f64>) -> Result<Tensor<T>> {
        let data: Vec<T> = array
            .iter()
            .map(|&x| T::from_f64(x).expect("f64 conversion should succeed"))
            .collect();
        let shape = vec![array.nrows(), array.ncols()];
        Tensor::from_vec(data, &shape)
    }

    fn percentile(&self, sorted_data: &[f64], percentile: f64) -> f64 {
        let n = sorted_data.len();
        let index = (percentile / 100.0) * ((n - 1) as f64);
        let lower = index.floor() as usize;
        let upper = index.ceil() as usize;

        if lower == upper {
            sorted_data[lower]
        } else {
            let weight = index - (lower as f64);
            sorted_data[lower] * (1.0 - weight) + sorted_data[upper] * weight
        }
    }

    fn pearson_correlation(&self, x: &[f64], y: &[f64]) -> f64 {
        let n = x.len() as f64;
        let x_mean = x.iter().sum::<f64>() / n;
        let y_mean = y.iter().sum::<f64>() / n;

        let numerator: f64 = x
            .iter()
            .zip(y.iter())
            .map(|(&xi, &yi)| (xi - x_mean) * (yi - y_mean))
            .sum();

        let x_var: f64 = x.iter().map(|&xi| (xi - x_mean) * (xi - x_mean)).sum();
        let y_var: f64 = y.iter().map(|&yi| (yi - y_mean) * (yi - y_mean)).sum();

        numerator / (x_var * y_var).sqrt()
    }

    fn t_cdf(&self, t: f64, df: f64) -> f64 {
        // Simplified t-distribution CDF approximation
        // TODO: Use actual scirs2-stats implementation
        0.5 + 0.5 * (t / (1.0 + t * t / df).sqrt()).tanh()
    }

    fn compute_confidence_interval<T: FloatElement>(
        &self,
        estimate: f64,
        standard_error: f64,
        degrees_of_freedom: f64,
    ) -> (T, T) {
        // Compute confidence interval using t-distribution
        let alpha = 1.0 - self.config.confidence_level;

        // Use approximate t-critical value based on degrees of freedom
        // For large df (>30), t-distribution approaches normal distribution
        let t_critical = if degrees_of_freedom > 30.0 {
            // Normal approximation for large df
            // For 95% CI: z ≈ 1.96, for 99% CI: z ≈ 2.576
            if alpha < 0.02 {
                2.576 // 99% CI
            } else {
                1.96 // 95% CI
            }
        } else {
            // Conservative estimate for small df
            // t-values are larger for smaller df
            let base_t = if alpha < 0.02 { 2.8 } else { 2.1 };
            base_t * (1.0 + 5.0 / degrees_of_freedom).sqrt()
        };

        // Computing confidence interval with calculated t-critical value
        let _ = (alpha, degrees_of_freedom, t_critical); // Use parameters

        let margin_of_error = t_critical * standard_error;
        (
            T::from_f64(estimate - margin_of_error).expect("f64 conversion should succeed"),
            T::from_f64(estimate + margin_of_error).expect("f64 conversion should succeed"),
        )
    }

    fn kolmogorov_smirnov_test(&self, data: &[f64], mean: f64, std_dev: f64) -> f64 {
        // Kolmogorov-Smirnov test: maximum distance between empirical and theoretical CDF
        if data.is_empty() || std_dev <= 0.0 {
            return 1.0; // Reject null hypothesis
        }

        let n = data.len() as f64;
        let mut sorted_data = data.to_vec();
        sorted_data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        // Calculate maximum deviation between empirical and theoretical CDF
        let mut max_deviation = 0.0f64;

        for (i, &x) in sorted_data.iter().enumerate() {
            // Empirical CDF at this point
            let empirical_cdf = (i + 1) as f64 / n;

            // Theoretical CDF (normal distribution): Φ((x - μ) / σ)
            let z = (x - mean) / std_dev;
            // Approximate normal CDF using error function
            let theoretical_cdf = 0.5 * (1.0 + libm::erf(z / std::f64::consts::SQRT_2));

            // Calculate deviation
            let deviation = (empirical_cdf - theoretical_cdf).abs();
            max_deviation = max_deviation.max(deviation);
        }

        // Return p-value approximation (simplified)
        // For a more accurate test, would use Kolmogorov distribution
        let ks_statistic = max_deviation * n.sqrt();

        // Approximate p-value: P(D_n > observed) ≈ exp(-2 * ks_statistic²)
        // Return 1 - p_value to get confidence in normality
        let p_value = (-2.0 * ks_statistic * ks_statistic).exp();
        1.0 - p_value
    }
}

/// Comprehensive descriptive statistics
#[derive(Debug, Clone)]
pub struct DescriptiveStats<T: TensorElement> {
    pub count: usize,
    pub mean: T,
    pub std_dev: T,
    pub variance: T,
    pub skewness: T,
    pub kurtosis: T,
    pub min: T,
    pub max: T,
    pub q25: T,
    pub median: T,
    pub q75: T,
    pub iqr: T,
}

/// Correlation analysis result
#[derive(Debug, Clone)]
pub struct CorrelationResult<T: TensorElement> {
    pub correlation_matrix: Tensor<T>,
    pub method: CorrelationMethod,
    pub significant_pairs: Vec<(usize, usize, T)>, // (i, j, p_value)
}

#[derive(Debug, Clone, Copy)]
pub enum CorrelationMethod {
    Pearson,
    Spearman,
    Kendall,
}

/// T-test result
#[derive(Debug, Clone)]
pub struct TTestResult<T: TensorElement> {
    pub t_statistic: T,
    pub p_value: T,
    pub degrees_of_freedom: T,
    pub confidence_interval: (T, T),
    pub effect_size: T,
}

/// Regression analysis result
#[derive(Debug, Clone)]
pub struct RegressionResult<T: TensorElement> {
    pub coefficients: Vec<T>,
    pub standard_errors: Vec<T>,
    pub r_squared: T,
    pub adjusted_r_squared: T,
    pub f_statistic: T,
    pub residuals: Tensor<T>,
}

/// Distribution fitting result
#[derive(Debug, Clone)]
pub struct DistributionFit<T: TensorElement> {
    pub distribution_type: DistributionType,
    pub parameters: HashMap<String, T>,
    pub log_likelihood: T,
    pub aic: T,
    pub bic: T,
    pub goodness_of_fit: f64,
}

#[derive(Debug, Clone, Copy)]
pub enum DistributionType {
    Normal,
    Exponential,
    Gamma,
    Beta,
    Poisson,
    Binomial,
    Uniform,
}

// Re-export for convenience
pub use crate::stats::{HistogramConfig, StatMode};