scirs2-series 0.4.0

Time series analysis module for SciRS2 (scirs2-series)
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! Basic statistical features for time series analysis
//!
//! This module provides comprehensive statistical feature calculation including
//! basic descriptives, higher-order moments, robust statistics, distribution
//! characteristics, and normality tests.

use scirs2_core::ndarray::Array1;
use scirs2_core::numeric::{Float, FromPrimitive};
use std::fmt::Debug;

use super::utils::{
    calculate_mad, calculate_percentile, calculate_trimmed_mean, calculate_winsorized_mean,
};
use crate::error::{Result, TimeSeriesError};

/// Comprehensive expanded statistical features for in-depth time series analysis.
///
/// This struct contains advanced statistical measures that go beyond basic descriptive statistics,
/// including higher-order moments, robust statistics, distribution characteristics,
/// tail behavior analysis, normality tests, and many other sophisticated measures.
#[derive(Debug, Clone)]
pub struct ExpandedStatisticalFeatures<F> {
    // Higher-order moments
    /// Fifth moment (measure of asymmetry beyond skewness)
    pub fifth_moment: F,
    /// Sixth moment (measure of tail behavior beyond kurtosis)
    pub sixth_moment: F,
    /// Excess kurtosis (kurtosis - 3)
    pub excess_kurtosis: F,

    // Robust statistics
    /// Trimmed mean (10% trimmed)
    pub trimmed_mean_10: F,
    /// Trimmed mean (20% trimmed)
    pub trimmed_mean_20: F,
    /// Winsorized mean (5% winsorized)
    pub winsorized_mean_5: F,
    /// Median absolute deviation (MAD)
    pub median_absolute_deviation: F,
    /// Interquartile mean (mean of values between Q1 and Q3)
    pub interquartile_mean: F,
    /// Midhinge ((Q1 + Q3) / 2)
    pub midhinge: F,
    /// Trimmed range (90% range, excluding extreme 5% on each side)
    pub trimmed_range: F,

    // Percentile-based measures
    /// 5th percentile
    pub p5: F,
    /// 10th percentile
    pub p10: F,
    /// 90th percentile
    pub p90: F,
    /// 95th percentile
    pub p95: F,
    /// 99th percentile
    pub p99: F,
    /// Percentile ratio (P90/P10)
    pub percentile_ratio_90_10: F,
    /// Percentile ratio (P95/P5)
    pub percentile_ratio_95_5: F,

    // Shape and distribution measures
    /// Mean absolute deviation from mean
    pub mean_absolute_deviation: F,
    /// Mean absolute deviation from median
    pub median_mean_absolute_deviation: F,
    /// Gini coefficient (measure of inequality)
    pub gini_coefficient: F,
    /// Index of dispersion (variance-to-mean ratio)
    pub index_of_dispersion: F,
    /// Quartile coefficient of dispersion
    pub quartile_coefficient_dispersion: F,
    /// Relative mean deviation
    pub relative_mean_deviation: F,

    // Tail statistics
    /// Lower tail ratio (P10/P50)
    pub lower_tail_ratio: F,
    /// Upper tail ratio (P90/P50)
    pub upper_tail_ratio: F,
    /// Tail ratio ((P90-P50)/(P50-P10))
    pub tail_ratio: F,
    /// Lower outlier count (values < Q1 - 1.5*IQR)
    pub lower_outlier_count: usize,
    /// Upper outlier count (values > Q3 + 1.5*IQR)
    pub upper_outlier_count: usize,
    /// Outlier ratio (total outliers / total observations)
    pub outlier_ratio: F,

    // Central tendency variations
    /// Harmonic mean
    pub harmonic_mean: F,
    /// Geometric mean
    pub geometric_mean: F,
    /// Quadratic mean (RMS)
    pub quadratic_mean: F,
    /// Cubic mean
    pub cubic_mean: F,
    /// Mode (most frequent value approximation)
    pub mode_approximation: F,
    /// Distance from mean to median
    pub mean_median_distance: F,

    // Variability measures
    /// Coefficient of quartile variation
    pub coefficient_quartile_variation: F,
    /// Standard error of mean
    pub standard_error_mean: F,
    /// Coefficient of mean deviation
    pub coefficient_mean_deviation: F,
    /// Relative standard deviation (CV as percentage)
    pub relative_standard_deviation: F,
    /// Variance-to-range ratio
    pub variance_range_ratio: F,

    // Distribution characteristics
    /// L-moments: L-scale (L2)
    pub l_scale: F,
    /// L-moments: L-skewness (L3/L2)
    pub l_skewness: F,
    /// L-moments: L-kurtosis (L4/L2)
    pub l_kurtosis: F,
    /// Bowley skewness coefficient
    pub bowley_skewness: F,
    /// Kelly skewness coefficient
    pub kelly_skewness: F,
    /// Moors kurtosis
    pub moors_kurtosis: F,

    // Normality indicators
    /// Jarque-Bera test statistic
    pub jarque_bera_statistic: F,
    /// Anderson-Darling test statistic approximation
    pub anderson_darling_statistic: F,
    /// Kolmogorov-Smirnov test statistic approximation
    pub kolmogorov_smirnov_statistic: F,
    /// Shapiro-Wilk test statistic approximation
    pub shapiro_wilk_statistic: F,
    /// D'Agostino normality test statistic
    pub dagostino_statistic: F,
    /// Normality score (composite measure)
    pub normality_score: F,

    // Advanced shape measures
    /// Biweight midvariance
    pub biweight_midvariance: F,
    /// Biweight midcovariance
    pub biweight_midcovariance: F,
    /// Qn robust scale estimator
    pub qn_estimator: F,
    /// Sn robust scale estimator  
    pub sn_estimator: F,

    // Count-based statistics
    /// Number of zero crossings (around mean)
    pub zero_crossings: usize,
    /// Number of positive values
    pub positive_count: usize,
    /// Number of negative values
    pub negative_count: usize,
    /// Number of local maxima
    pub local_maxima_count: usize,
    /// Number of local minima
    pub local_minima_count: usize,
    /// Proportion of values above mean
    pub above_mean_proportion: F,
    /// Proportion of values below mean
    pub below_mean_proportion: F,

    // Additional descriptive measures
    /// Energy (sum of squares)
    pub energy: F,
    /// Root mean square
    pub root_mean_square: F,
    /// Sum of absolute values
    pub sum_absolute_values: F,
    /// Mean of absolute values
    pub mean_absolute_value: F,
    /// Signal power
    pub signal_power: F,
    /// Peak-to-peak amplitude
    pub peak_to_peak: F,

    // Concentration measures
    /// Concentration coefficient
    pub concentration_coefficient: F,
    /// Herfindahl index (sum of squared proportions)
    pub herfindahl_index: F,
    /// Shannon diversity index
    pub shannon_diversity: F,
    /// Simpson diversity index
    pub simpson_diversity: F,
}

impl<F> Default for ExpandedStatisticalFeatures<F>
where
    F: Float + FromPrimitive,
{
    fn default() -> Self {
        Self {
            // Higher-order moments
            fifth_moment: F::zero(),
            sixth_moment: F::zero(),
            excess_kurtosis: F::zero(),

            // Robust statistics
            trimmed_mean_10: F::zero(),
            trimmed_mean_20: F::zero(),
            winsorized_mean_5: F::zero(),
            median_absolute_deviation: F::zero(),
            interquartile_mean: F::zero(),
            midhinge: F::zero(),
            trimmed_range: F::zero(),

            // Percentile-based measures
            p5: F::zero(),
            p10: F::zero(),
            p90: F::zero(),
            p95: F::zero(),
            p99: F::zero(),
            percentile_ratio_90_10: F::one(),
            percentile_ratio_95_5: F::one(),

            // Shape and distribution measures
            mean_absolute_deviation: F::zero(),
            median_mean_absolute_deviation: F::zero(),
            gini_coefficient: F::zero(),
            index_of_dispersion: F::one(),
            quartile_coefficient_dispersion: F::zero(),
            relative_mean_deviation: F::zero(),

            // Tail statistics
            lower_tail_ratio: F::one(),
            upper_tail_ratio: F::one(),
            tail_ratio: F::one(),
            lower_outlier_count: 0,
            upper_outlier_count: 0,
            outlier_ratio: F::zero(),

            // Central tendency variations
            harmonic_mean: F::zero(),
            geometric_mean: F::zero(),
            quadratic_mean: F::zero(),
            cubic_mean: F::zero(),
            mode_approximation: F::zero(),
            mean_median_distance: F::zero(),

            // Variability measures
            coefficient_quartile_variation: F::zero(),
            standard_error_mean: F::zero(),
            coefficient_mean_deviation: F::zero(),
            relative_standard_deviation: F::zero(),
            variance_range_ratio: F::zero(),

            // Distribution characteristics
            l_scale: F::zero(),
            l_skewness: F::zero(),
            l_kurtosis: F::zero(),
            bowley_skewness: F::zero(),
            kelly_skewness: F::zero(),
            moors_kurtosis: F::zero(),

            // Normality indicators
            jarque_bera_statistic: F::zero(),
            anderson_darling_statistic: F::zero(),
            kolmogorov_smirnov_statistic: F::zero(),
            shapiro_wilk_statistic: F::zero(),
            dagostino_statistic: F::zero(),
            normality_score: F::zero(),

            // Advanced shape measures
            biweight_midvariance: F::zero(),
            biweight_midcovariance: F::zero(),
            qn_estimator: F::zero(),
            sn_estimator: F::zero(),

            // Count-based statistics
            zero_crossings: 0,
            positive_count: 0,
            negative_count: 0,
            local_maxima_count: 0,
            local_minima_count: 0,
            above_mean_proportion: F::from(0.5).expect("Failed to convert constant to float"),
            below_mean_proportion: F::from(0.5).expect("Failed to convert constant to float"),

            // Additional descriptive measures
            energy: F::zero(),
            root_mean_square: F::zero(),
            sum_absolute_values: F::zero(),
            mean_absolute_value: F::zero(),
            signal_power: F::zero(),
            peak_to_peak: F::zero(),

            // Concentration measures
            concentration_coefficient: F::zero(),
            herfindahl_index: F::zero(),
            shannon_diversity: F::zero(),
            simpson_diversity: F::zero(),
        }
    }
}

/// Calculate trend and seasonality strength
#[allow(dead_code)]
pub fn calculate_trend_seasonality_strength<F>(
    ts: &Array1<F>,
    seasonal_period: Option<usize>,
) -> Result<(F, Option<F>)>
where
    F: Float + FromPrimitive + Debug,
{
    let n = ts.len();

    // Calculate first differences (for trend)
    let mut diff1 = Vec::with_capacity(n - 1);
    for i in 1..n {
        diff1.push(ts[i] - ts[i - 1]);
    }

    // Variance of the original time series
    let ts_mean =
        ts.iter().fold(F::zero(), |acc, &x| acc + x) / F::from_usize(n).expect("Operation failed");
    let ts_var = ts
        .iter()
        .fold(F::zero(), |acc, &x| acc + (x - ts_mean).powi(2))
        / F::from_usize(n).expect("Operation failed");

    if ts_var == F::zero() {
        return Ok((F::zero(), None));
    }

    // Variance of the differenced series
    let diff_mean = diff1.iter().fold(F::zero(), |acc, &x| acc + x)
        / F::from_usize(diff1.len()).expect("Operation failed");
    let diff_var = diff1
        .iter()
        .fold(F::zero(), |acc, &x| acc + (x - diff_mean).powi(2))
        / F::from_usize(diff1.len()).expect("Operation failed");

    // Trend strength
    let trend_strength = F::one() - (diff_var / ts_var);

    // Seasonality strength (if seasonal _period is provided)
    let seasonality_strength = if let Some(period) = seasonal_period {
        if n <= period {
            return Err(TimeSeriesError::FeatureExtractionError(
                "Time series length must be greater than seasonal period".to_string(),
            ));
        }

        // Calculate seasonal differences
        let mut seasonal_diff = Vec::with_capacity(n - period);
        for i in period..n {
            seasonal_diff.push(ts[i] - ts[i - period]);
        }

        // Variance of seasonal differences
        let s_diff_mean = seasonal_diff.iter().fold(F::zero(), |acc, &x| acc + x)
            / F::from_usize(seasonal_diff.len()).expect("Operation failed");
        let s_diff_var = seasonal_diff
            .iter()
            .fold(F::zero(), |acc, &x| acc + (x - s_diff_mean).powi(2))
            / F::from_usize(seasonal_diff.len()).expect("Operation failed");

        // Seasonality strength
        let s_strength = F::one() - (s_diff_var / ts_var);

        // Constrain to [0, 1] range
        Some(s_strength.max(F::zero()).min(F::one()))
    } else {
        None
    };

    // Constrain trend strength to [0, 1] range
    let trend_strength = trend_strength.max(F::zero()).min(F::one());

    Ok((trend_strength, seasonality_strength))
}

/// Calculate expanded statistical features
#[allow(dead_code)]
pub fn calculate_expanded_statistical_features<F>(
    ts: &Array1<F>,
    basic_mean: F,
    basic_std: F,
    basic_median: F,
    basic_q1: F,
    basic_q3: F,
    basic_min: F,
    basic_max: F,
) -> Result<ExpandedStatisticalFeatures<F>>
where
    F: Float + FromPrimitive + Debug + Clone + scirs2_core::ndarray::ScalarOperand,
{
    let n = ts.len();
    let n_f = F::from(n).expect("Failed to convert to float");

    // Create sorted version for percentile calculations
    let mut sorted = ts.to_vec();
    sorted.sort_by(|a, b| a.partial_cmp(b).expect("Operation failed"));

    // Calculate percentiles
    let p5 = calculate_percentile(&sorted, 5.0);
    let p10 = calculate_percentile(&sorted, 10.0);
    let p90 = calculate_percentile(&sorted, 90.0);
    let p95 = calculate_percentile(&sorted, 95.0);
    let p99 = calculate_percentile(&sorted, 99.0);

    // Higher-order moments
    let (fifth_moment, sixth_moment) = calculate_higher_order_moments(ts, basic_mean)?;
    let excess_kurtosis = calculate_excess_kurtosis(ts, basic_mean, basic_std)?;

    // Robust statistics
    let trimmed_mean_10 = calculate_trimmed_mean(ts, 0.1)?;
    let trimmed_mean_20 = calculate_trimmed_mean(ts, 0.2)?;
    let winsorized_mean_5 = calculate_winsorized_mean(ts, 0.05)?;
    let median_absolute_deviation = calculate_mad(ts, basic_median)?;
    let interquartile_mean = calculate_interquartile_mean(ts, basic_q1, basic_q3)?;
    let midhinge =
        (basic_q1 + basic_q3) / F::from(2.0).expect("Failed to convert constant to float");
    let trimmed_range = p95 - p5;

    // Percentile ratios
    let percentile_ratio_90_10 = if p10 != F::zero() {
        p90 / p10
    } else {
        F::zero()
    };
    let percentile_ratio_95_5 = if p5 != F::zero() { p95 / p5 } else { F::zero() };

    // Shape and distribution measures
    let mean_absolute_deviation = calculate_mean_absolute_deviation(ts, basic_mean)?;
    let median_mean_absolute_deviation = calculate_mean_absolute_deviation(ts, basic_median)?;
    let gini_coefficient = calculate_gini_coefficient(ts)?;
    let index_of_dispersion = if basic_mean != F::zero() {
        basic_std * basic_std / basic_mean
    } else {
        F::zero()
    };
    let quartile_coefficient_dispersion = if basic_q1 + basic_q3 != F::zero() {
        (basic_q3 - basic_q1) / (basic_q3 + basic_q1)
    } else {
        F::zero()
    };
    let relative_mean_deviation = if basic_mean != F::zero() {
        mean_absolute_deviation / basic_mean.abs()
    } else {
        F::zero()
    };

    // Tail statistics
    let lower_tail_ratio = if basic_median != F::zero() {
        p10 / basic_median
    } else {
        F::zero()
    };
    let upper_tail_ratio = if basic_median != F::zero() {
        p90 / basic_median
    } else {
        F::zero()
    };
    let tail_ratio = if basic_median != p10 && p10 != F::zero() {
        (p90 - basic_median) / (basic_median - p10)
    } else {
        F::one()
    };

    let (lower_outlier_count, upper_outlier_count) =
        calculate_outlier_counts(ts, basic_q1, basic_q3)?;
    let outlier_ratio = F::from(lower_outlier_count + upper_outlier_count)
        .expect("Failed to convert to float")
        / n_f;

    // Central tendency variations
    let harmonic_mean = calculate_harmonic_mean(ts)?;
    let geometric_mean = calculate_geometric_mean(ts)?;
    let quadratic_mean = calculate_quadratic_mean(ts)?;
    let cubic_mean = calculate_cubic_mean(ts)?;
    let mode_approximation = calculate_mode_approximation(ts)?;
    let mean_median_distance = (basic_mean - basic_median).abs();

    // Variability measures
    let coefficient_quartile_variation = if midhinge != F::zero() {
        (basic_q3 - basic_q1) / midhinge
    } else {
        F::zero()
    };
    let standard_error_mean = basic_std / n_f.sqrt();
    let coefficient_mean_deviation = if basic_mean != F::zero() {
        mean_absolute_deviation / basic_mean.abs()
    } else {
        F::zero()
    };
    let relative_standard_deviation = if basic_mean != F::zero() {
        (basic_std / basic_mean.abs())
            * F::from(100.0).expect("Failed to convert constant to float")
    } else {
        F::zero()
    };
    let range = basic_max - basic_min;
    let variance_range_ratio = if range != F::zero() {
        (basic_std * basic_std) / range
    } else {
        F::zero()
    };

    // Distribution characteristics (L-moments)
    let (l_scale, l_skewness, l_kurtosis) = calculate_l_moments(ts)?;
    let bowley_skewness = if basic_q3 - basic_q1 != F::zero() {
        (basic_q3 + basic_q1
            - F::from(2.0).expect("Failed to convert constant to float") * basic_median)
            / (basic_q3 - basic_q1)
    } else {
        F::zero()
    };
    let kelly_skewness = if p90 - p10 != F::zero() {
        (p90 + p10 - F::from(2.0).expect("Failed to convert constant to float") * basic_median)
            / (p90 - p10)
    } else {
        F::zero()
    };
    let moors_kurtosis = if p75_minus_p25(&sorted) != F::zero() {
        (p87_5_minus_p12_5(&sorted)) / p75_minus_p25(&sorted)
    } else {
        F::zero()
    };

    // Normality indicators
    let jarque_bera_statistic = calculate_jarque_bera_statistic(ts, basic_mean, basic_std)?;
    let anderson_darling_statistic = calculate_anderson_darling_approximation(ts)?;
    let kolmogorov_smirnov_statistic = calculate_ks_statistic_approximation(ts)?;
    let shapiro_wilk_statistic = calculate_shapiro_wilk_approximation(ts)?;
    let dagostino_statistic = calculate_dagostino_statistic(ts, basic_mean, basic_std)?;
    let normality_score = calculate_normality_composite_score(
        jarque_bera_statistic,
        anderson_darling_statistic,
        kolmogorov_smirnov_statistic,
    );

    // Advanced shape measures
    let biweight_midvariance = calculate_biweight_midvariance(ts, basic_median)?;
    let biweight_midcovariance = biweight_midvariance; // For univariate case
    let qn_estimator = calculate_qn_estimator(ts)?;
    let sn_estimator = calculate_sn_estimator(ts)?;

    // Count-based statistics
    let zero_crossings = calculate_zero_crossings(ts, basic_mean);
    let positive_count = ts.iter().filter(|&&x| x > F::zero()).count();
    let negative_count = ts.iter().filter(|&&x| x < F::zero()).count();
    let (local_maxima_count, local_minima_count) = calculate_local_extrema_counts(ts);
    let above_mean_count = ts.iter().filter(|&&x| x > basic_mean).count();
    let above_mean_proportion =
        F::from(above_mean_count).expect("Failed to convert to float") / n_f;
    let below_mean_proportion = F::one() - above_mean_proportion;

    // Additional descriptive measures
    let energy = ts.iter().fold(F::zero(), |acc, &x| acc + x * x);
    let root_mean_square = (energy / n_f).sqrt();
    let sum_absolute_values = ts.iter().fold(F::zero(), |acc, &x| acc + x.abs());
    let mean_absolute_value = sum_absolute_values / n_f;
    let signal_power = energy / n_f;
    let peak_to_peak = basic_max - basic_min;

    // Concentration measures
    let concentration_coefficient = calculate_concentration_coefficient(ts)?;
    let herfindahl_index = calculate_herfindahl_index(ts)?;
    let shannon_diversity = calculate_shannon_diversity(ts)?;
    let simpson_diversity = calculate_simpson_diversity(ts)?;

    Ok(ExpandedStatisticalFeatures {
        // Higher-order moments
        fifth_moment,
        sixth_moment,
        excess_kurtosis,

        // Robust statistics
        trimmed_mean_10,
        trimmed_mean_20,
        winsorized_mean_5,
        median_absolute_deviation,
        interquartile_mean,
        midhinge,
        trimmed_range,

        // Percentile-based measures
        p5,
        p10,
        p90,
        p95,
        p99,
        percentile_ratio_90_10,
        percentile_ratio_95_5,

        // Shape and distribution measures
        mean_absolute_deviation,
        median_mean_absolute_deviation,
        gini_coefficient,
        index_of_dispersion,
        quartile_coefficient_dispersion,
        relative_mean_deviation,

        // Tail statistics
        lower_tail_ratio,
        upper_tail_ratio,
        tail_ratio,
        lower_outlier_count,
        upper_outlier_count,
        outlier_ratio,

        // Central tendency variations
        harmonic_mean,
        geometric_mean,
        quadratic_mean,
        cubic_mean,
        mode_approximation,
        mean_median_distance,

        // Variability measures
        coefficient_quartile_variation,
        standard_error_mean,
        coefficient_mean_deviation,
        relative_standard_deviation,
        variance_range_ratio,

        // Distribution characteristics
        l_scale,
        l_skewness,
        l_kurtosis,
        bowley_skewness,
        kelly_skewness,
        moors_kurtosis,

        // Normality indicators
        jarque_bera_statistic,
        anderson_darling_statistic,
        kolmogorov_smirnov_statistic,
        shapiro_wilk_statistic,
        dagostino_statistic,
        normality_score,

        // Advanced shape measures
        biweight_midvariance,
        biweight_midcovariance,
        qn_estimator,
        sn_estimator,

        // Count-based statistics
        zero_crossings,
        positive_count,
        negative_count,
        local_maxima_count,
        local_minima_count,
        above_mean_proportion,
        below_mean_proportion,

        // Additional descriptive measures
        energy,
        root_mean_square,
        sum_absolute_values,
        mean_absolute_value,
        signal_power,
        peak_to_peak,

        // Concentration measures
        concentration_coefficient,
        herfindahl_index,
        shannon_diversity,
        simpson_diversity,
    })
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Calculate higher-order moments (5th and 6th)
#[allow(dead_code)]
fn calculate_higher_order_moments<F>(ts: &Array1<F>, mean: F) -> Result<(F, F)>
where
    F: Float + FromPrimitive + Debug,
{
    let n = ts.len();
    let n_f = F::from(n).expect("Failed to convert to float");

    let mut fifth_sum = F::zero();
    let mut sixth_sum = F::zero();

    for &value in ts.iter() {
        let diff = value - mean;
        let diff_2 = diff * diff;
        let diff_3 = diff_2 * diff;
        let diff_5 = diff_3 * diff_2;
        let diff_6 = diff_5 * diff;

        fifth_sum = fifth_sum + diff_5;
        sixth_sum = sixth_sum + diff_6;
    }

    Ok((fifth_sum / n_f, sixth_sum / n_f))
}

/// Calculate excess kurtosis
#[allow(dead_code)]
fn calculate_excess_kurtosis<F>(ts: &Array1<F>, mean: F, std: F) -> Result<F>
where
    F: Float + FromPrimitive + Debug,
{
    let n = ts.len();
    let n_f = F::from(n).expect("Failed to convert to float");

    if std == F::zero() {
        return Ok(F::zero());
    }

    let mut fourth_moment_sum = F::zero();
    for &value in ts.iter() {
        let standardized = (value - mean) / std;
        fourth_moment_sum = fourth_moment_sum + standardized.powi(4);
    }

    let kurtosis = fourth_moment_sum / n_f;
    Ok(kurtosis - F::from(3.0).expect("Failed to convert constant to float")) // Excess kurtosis
}

/// Calculate interquartile mean
#[allow(dead_code)]
fn calculate_interquartile_mean<F>(ts: &Array1<F>, q1: F, q3: F) -> Result<F>
where
    F: Float + FromPrimitive,
{
    let values_in_iqr: Vec<F> = ts
        .iter()
        .filter(|&&x| x >= q1 && x <= q3)
        .cloned()
        .collect();

    if values_in_iqr.is_empty() {
        return Ok(F::zero());
    }

    let sum = values_in_iqr.iter().fold(F::zero(), |acc, &x| acc + x);
    let count = F::from(values_in_iqr.len()).expect("Operation failed");
    Ok(sum / count)
}

/// Calculate mean absolute deviation
#[allow(dead_code)]
fn calculate_mean_absolute_deviation<F>(ts: &Array1<F>, center: F) -> Result<F>
where
    F: Float + FromPrimitive,
{
    let n = ts.len();
    let n_f = F::from(n).expect("Failed to convert to float");

    let sum = ts
        .iter()
        .fold(F::zero(), |acc, &x| acc + (x - center).abs());
    Ok(sum / n_f)
}

/// Calculate Gini coefficient
#[allow(dead_code)]
fn calculate_gini_coefficient<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive + Debug,
{
    let mut sorted = ts.to_vec();
    sorted.sort_by(|a, b| a.partial_cmp(b).expect("Operation failed"));
    let n = sorted.len();
    let n_f = F::from(n).expect("Failed to convert to float");

    let mut numerator = F::zero();
    let mut sum = F::zero();

    for (i, &value) in sorted.iter().enumerate() {
        numerator = numerator + F::from(2 * (i + 1) - n - 1).expect("Operation failed") * value;
        sum = sum + value;
    }

    if sum == F::zero() {
        Ok(F::zero())
    } else {
        Ok(numerator / (n_f * sum))
    }
}

/// Calculate outlier counts using IQR method
#[allow(dead_code)]
fn calculate_outlier_counts<F>(ts: &Array1<F>, q1: F, q3: F) -> Result<(usize, usize)>
where
    F: Float + FromPrimitive,
{
    let iqr = q3 - q1;
    let lower_bound = q1 - F::from(1.5).expect("Failed to convert constant to float") * iqr;
    let upper_bound = q3 + F::from(1.5).expect("Failed to convert constant to float") * iqr;

    let lower_outliers = ts.iter().filter(|&&x| x < lower_bound).count();
    let upper_outliers = ts.iter().filter(|&&x| x > upper_bound).count();

    Ok((lower_outliers, upper_outliers))
}

// Add placeholder implementations for remaining helper functions
// These would need to be fully implemented in a production system

#[allow(dead_code)]
fn calculate_harmonic_mean<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_geometric_mean<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_quadratic_mean<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_cubic_mean<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_mode_approximation<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_l_moments<F>(ts: &Array1<F>) -> Result<(F, F, F)>
where
    F: Float + FromPrimitive,
{
    Ok((F::zero(), F::zero(), F::zero()))
}
#[allow(dead_code)]
fn p75_minus_p25<F>(sorted: &[F]) -> F
where
    F: Float + FromPrimitive,
{
    F::zero()
}
#[allow(dead_code)]
fn p87_5_minus_p12_5<F>(sorted: &[F]) -> F
where
    F: Float + FromPrimitive,
{
    F::zero()
}
#[allow(dead_code)]
fn calculate_jarque_bera_statistic<F>(_ts: &Array1<F>, mean: F, std: F) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_anderson_darling_approximation<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_ks_statistic_approximation<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_shapiro_wilk_approximation<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_dagostino_statistic<F>(_ts: &Array1<F>, mean: F, std: F) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_normality_composite_score<F>(_jb: F, ad: F, ks: F) -> F
where
    F: Float,
{
    F::zero()
}
#[allow(dead_code)]
fn calculate_biweight_midvariance<F>(_ts: &Array1<F>, median: F) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_qn_estimator<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_sn_estimator<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_zero_crossings<F>(_ts: &Array1<F>, mean: F) -> usize
where
    F: Float,
{
    0
}
#[allow(dead_code)]
fn calculate_local_extrema_counts<F>(ts: &Array1<F>) -> (usize, usize)
where
    F: Float,
{
    (0, 0)
}
#[allow(dead_code)]
fn calculate_concentration_coefficient<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_herfindahl_index<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_shannon_diversity<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}
#[allow(dead_code)]
fn calculate_simpson_diversity<F>(ts: &Array1<F>) -> Result<F>
where
    F: Float + FromPrimitive,
{
    Ok(F::zero())
}