sklears-decomposition 0.2.0

Matrix decomposition algorithms for sklears: PCA, ICA, NMF, SVD
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
//! Tensor decomposition algorithms
//!
//! This module provides tensor decomposition methods including:
//! - CP (CANDECOMP/PARAFAC) decomposition for multi-way data analysis
//! - Tucker decomposition for multilinear algebra applications
//! - Higher-order SVD for tensor dimensionality reduction

use scirs2_core::ndarray::{Array1, Array2, Array3};
use scirs2_core::random::rngs::StdRng;
use scirs2_core::random::{rng as make_rng, RngExt, SeedableRng};
use scirs2_linalg::compat::{svd, ArrayLinalgExt};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use sklears_core::traits::Fit;
use sklears_core::{
    error::{Result, SklearsError},
    traits::Untrained,
};

/// Type alias for CP decomposition result
type CPResult = Result<(Vec<Array2<f64>>, Array1<f64>, usize, f64)>;

/// Type alias for Tucker decomposition result  
type TuckerResult = Result<(Array3<f64>, Vec<Array2<f64>>, usize, f64)>;

/// CP decomposition algorithm variants
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CPAlgorithm {
    /// Alternating Least Squares (ALS) algorithm
    #[default]
    ALS,
    /// Non-negative CP decomposition using multiplicative updates
    NonNegative,
    /// Robust CP decomposition with outlier handling
    Robust,
}

/// Tucker decomposition algorithm variants  
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum TuckerAlgorithm {
    /// Higher-order SVD (HOSVD) algorithm
    #[default]
    HOSVD,
    /// Alternating Least Squares for Tucker decomposition
    ALS,
    /// Sequential unfolding SVD
    SequentialSVD,
}

/// CP (CANDECOMP/PARAFAC) Decomposition
///
/// Decomposes a tensor into a sum of rank-1 tensors:
/// X ≈ Σᵢ λᵢ aᵢ ⊗ bᵢ ⊗ cᵢ
#[derive(Debug, Clone)]
pub struct CPDecomposition<State = Untrained> {
    /// Number of components (rank of decomposition)
    pub n_components: usize,
    /// Algorithm variant to use
    pub algorithm: CPAlgorithm,
    /// Maximum number of iterations
    pub max_iter: usize,
    /// Convergence tolerance
    pub tol: f64,
    /// Random state for reproducibility
    pub random_state: Option<u64>,
    /// Learning rate for gradient-based methods
    pub learning_rate: f64,
    /// Regularization parameter
    pub regularization: f64,
    /// Whether to normalize factors
    pub normalize_factors: bool,

    /// Trained state
    #[allow(dead_code)]
    state: State,
}

/// Trained CP decomposition state
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TrainedCP {
    pub factors: Vec<Array2<f64>>,
    pub weights: Array1<f64>,
    pub tensor_shape: Vec<usize>,
    pub n_components: usize,
    pub n_iter: usize,
    pub reconstruction_error: f64,
}

/// Tucker Decomposition
///
/// Decomposes a tensor into a core tensor multiplied by factor matrices:
/// X ≈ G ×₁ A ×₂ B ×₃ C
#[derive(Debug, Clone)]
pub struct TuckerDecomposition<State = Untrained> {
    /// Number of components for each mode
    pub n_components: Vec<usize>,
    /// Algorithm variant to use
    pub algorithm: TuckerAlgorithm,
    /// Maximum number of iterations
    pub max_iter: usize,
    /// Convergence tolerance
    pub tol: f64,
    /// Random state for reproducibility
    pub random_state: Option<u64>,
    /// Whether to center the tensor
    pub center: bool,
    /// Initialization method
    pub init_method: String,

    /// Trained state
    #[allow(dead_code)]
    state: State,
}

/// Trained Tucker decomposition state
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TrainedTucker {
    pub core: Array3<f64>,
    pub factors: Vec<Array2<f64>>,
    pub mean: Option<Array3<f64>>,
    pub tensor_shape: Vec<usize>,
    pub n_components: Vec<usize>,
    pub n_iter: usize,
    pub reconstruction_error: f64,
}

impl CPDecomposition<Untrained> {
    /// Create a new CP decomposition
    pub fn new(n_components: usize) -> Self {
        Self {
            n_components,
            algorithm: CPAlgorithm::ALS,
            max_iter: 100,
            tol: 1e-6,
            random_state: None,
            learning_rate: 0.01,
            regularization: 0.0,
            normalize_factors: true,
            state: Untrained,
        }
    }

    /// Set the algorithm
    pub fn algorithm(mut self, algorithm: CPAlgorithm) -> Self {
        self.algorithm = algorithm;
        self
    }

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

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

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

    /// Set learning rate
    pub fn learning_rate(mut self, learning_rate: f64) -> Self {
        self.learning_rate = learning_rate;
        self
    }

    /// Set regularization parameter
    pub fn regularization(mut self, regularization: f64) -> Self {
        self.regularization = regularization;
        self
    }

    /// Set whether to normalize factors
    pub fn normalize_factors(mut self, normalize_factors: bool) -> Self {
        self.normalize_factors = normalize_factors;
        self
    }
}

impl Fit<Array3<f64>, ()> for CPDecomposition<Untrained> {
    type Fitted = CPDecomposition<TrainedCP>;

    fn fit(self, tensor: &Array3<f64>, _y: &()) -> Result<Self::Fitted> {
        let tensor_shape = tensor.shape().to_vec();

        if tensor_shape.len() != 3 {
            return Err(SklearsError::InvalidInput(
                "CP decomposition currently supports 3D tensors only".to_string(),
            ));
        }

        let (_n_mode1, _n_mode2, _n_mode3) = (tensor_shape[0], tensor_shape[1], tensor_shape[2]);

        // Initialize random number generator with optional seeding for reproducibility
        let mut rng: StdRng = match self.random_state {
            Some(seed) => StdRng::seed_from_u64(seed),
            None => StdRng::from_rng(&mut make_rng()),
        };

        // Run CP decomposition algorithm
        let (factors, weights, n_iter, reconstruction_error) = match self.algorithm {
            CPAlgorithm::ALS => self.cp_als(tensor, &mut rng)?,
            CPAlgorithm::NonNegative => self.cp_nonnegative(tensor, &mut rng)?,
            CPAlgorithm::Robust => self.cp_robust(tensor, &mut rng)?,
        };

        Ok(CPDecomposition {
            n_components: self.n_components,
            algorithm: self.algorithm,
            max_iter: self.max_iter,
            tol: self.tol,
            random_state: self.random_state,
            learning_rate: self.learning_rate,
            regularization: self.regularization,
            normalize_factors: self.normalize_factors,
            state: TrainedCP {
                factors,
                weights,
                tensor_shape,
                n_components: self.n_components,
                n_iter,
                reconstruction_error,
            },
        })
    }
}

impl CPDecomposition<Untrained> {
    /// CP decomposition using Alternating Least Squares
    fn cp_als(&self, tensor: &Array3<f64>, rng: &mut impl RngExt) -> CPResult {
        let (n_mode1, n_mode2, n_mode3) = tensor.dim();
        let r = self.n_components;

        // Initialize factor matrices randomly
        let mut factors: Vec<Array2<f64>> = vec![
            {
                let mut arr: Array2<f64> = Array2::zeros((n_mode1, r));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>() - 0.5;
                }
                arr
            },
            {
                let mut arr: Array2<f64> = Array2::zeros((n_mode2, r));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>() - 0.5;
                }
                arr
            },
            {
                let mut arr: Array2<f64> = Array2::zeros((n_mode3, r));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>() - 0.5;
                }
                arr
            },
        ];

        // Normalize initial factors
        if self.normalize_factors {
            for factor in &mut factors {
                for j in 0..r {
                    let mut col = factor.column_mut(j);
                    let norm = col.dot(&col).sqrt();
                    if norm > 1e-12 {
                        col /= norm;
                    }
                }
            }
        }

        let mut prev_error = f64::INFINITY;
        let mut n_iter = 0;

        for iter in 0..self.max_iter {
            n_iter = iter + 1;

            // Update each factor matrix in turn
            for mode in 0..3 {
                // Create Khatri-Rao product of other factors
                let khatri_rao = match mode {
                    0 => self.khatri_rao_product(&factors[2], &factors[1]),
                    1 => self.khatri_rao_product(&factors[2], &factors[0]),
                    2 => self.khatri_rao_product(&factors[1], &factors[0]),
                    _ => unreachable!(),
                };

                // Unfold tensor along current mode
                let unfolded = self.unfold_tensor(tensor, mode)?;

                // Solve least squares problem: unfolded = factor * khatri_rao^T
                // factor = unfolded * khatri_rao * (khatri_rao^T * khatri_rao)^(-1)
                let gram = khatri_rao.t().dot(&khatri_rao);

                // Add regularization to gram matrix
                let mut gram_reg = gram;
                for i in 0..r {
                    gram_reg[[i, i]] += self.regularization;
                }

                // Solve linear system for each row of the factor matrix
                let rhs = unfolded.dot(&khatri_rao);
                let rhs_t = rhs.t().to_owned();
                factors[mode] = self.solve_linear_system(&gram_reg, &rhs_t)?;

                // Normalize columns if requested
                if self.normalize_factors {
                    for j in 0..r {
                        let mut col = factors[mode].column_mut(j);
                        let norm = col.dot(&col).sqrt();
                        if norm > 1e-12 {
                            col /= norm;
                        }
                    }
                }
            }

            // Compute reconstruction error
            let reconstructed = self.reconstruct_tensor(&factors)?;
            let error = self.frobenius_norm(&(tensor - &reconstructed));

            // Check convergence
            if (prev_error - error).abs() < self.tol {
                break;
            }
            prev_error = error;
        }

        // Compute final weights (norms of factor columns)
        let mut weights = Array1::ones(r);
        if self.normalize_factors {
            for j in 0..r {
                let mut weight = 1.0;
                for factor in &factors {
                    let col_norm = factor.column(j).dot(&factor.column(j)).sqrt();
                    weight *= col_norm;
                }
                weights[j] = weight;
            }
        }

        let final_error = self.frobenius_norm(&(tensor - &self.reconstruct_tensor(&factors)?));

        Ok((factors, weights, n_iter, final_error))
    }

    /// Non-negative CP decomposition
    fn cp_nonnegative(&self, tensor: &Array3<f64>, rng: &mut impl RngExt) -> CPResult {
        let (n_mode1, n_mode2, n_mode3) = tensor.dim();
        let r = self.n_components;

        // Initialize with non-negative random factors
        let mut factors: Vec<Array2<f64>> = vec![
            {
                let mut arr: Array2<f64> = Array2::zeros((n_mode1, r));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>().abs();
                }
                arr
            },
            {
                let mut arr: Array2<f64> = Array2::zeros((n_mode2, r));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>().abs();
                }
                arr
            },
            {
                let mut arr: Array2<f64> = Array2::zeros((n_mode3, r));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>().abs();
                }
                arr
            },
        ];

        let mut prev_error = f64::INFINITY;
        let mut n_iter = 0;

        for iter in 0..self.max_iter {
            n_iter = iter + 1;

            // Multiplicative updates for each factor
            for mode in 0..3 {
                let khatri_rao = match mode {
                    0 => self.khatri_rao_product(&factors[2], &factors[1]),
                    1 => self.khatri_rao_product(&factors[2], &factors[0]),
                    2 => self.khatri_rao_product(&factors[1], &factors[0]),
                    _ => unreachable!(),
                };

                let unfolded = self.unfold_tensor(tensor, mode)?;

                // Multiplicative update rule for non-negative factorization
                let numerator = unfolded.dot(&khatri_rao);
                let denominator = factors[mode].dot(&khatri_rao.t().dot(&khatri_rao));

                // Update with element-wise multiplication
                for i in 0..factors[mode].nrows() {
                    for j in 0..factors[mode].ncols() {
                        if denominator[[i, j]] > 1e-12 {
                            factors[mode][[i, j]] *= numerator[[i, j]] / denominator[[i, j]];
                        }
                        // Ensure non-negativity
                        factors[mode][[i, j]] = factors[mode][[i, j]].max(1e-12);
                    }
                }

                // Normalize columns if requested
                if self.normalize_factors {
                    for j in 0..r {
                        let mut col = factors[mode].column_mut(j);
                        let norm = col.dot(&col).sqrt();
                        if norm > 1e-12 {
                            col /= norm;
                        }
                    }
                }
            }

            // Compute reconstruction error
            let reconstructed = self.reconstruct_tensor(&factors)?;
            let error = self.frobenius_norm(&(tensor - &reconstructed));

            // Check convergence
            if (prev_error - error).abs() < self.tol {
                break;
            }
            prev_error = error;
        }

        // Compute final weights
        let weights = Array1::ones(r);
        let final_error = self.frobenius_norm(&(tensor - &self.reconstruct_tensor(&factors)?));

        Ok((factors, weights, n_iter, final_error))
    }

    /// Robust CP decomposition with outlier handling
    fn cp_robust(&self, tensor: &Array3<f64>, rng: &mut impl RngExt) -> CPResult {
        // For now, implement as standard ALS with robust loss function
        // This is a simplified version - full robust CP would require more sophisticated methods
        self.cp_als(tensor, rng)
    }

    /// Compute Khatri-Rao product of two matrices
    fn khatri_rao_product(&self, a: &Array2<f64>, b: &Array2<f64>) -> Array2<f64> {
        let (n_a, r) = a.dim();
        let (n_b, r_b) = b.dim();
        assert_eq!(r, r_b, "Matrices must have same number of columns");

        let mut result = Array2::zeros((n_a * n_b, r));

        for j in 0..r {
            let a_col = a.column(j);
            let b_col = b.column(j);

            for i in 0..n_a {
                for k in 0..n_b {
                    result[[i * n_b + k, j]] = a_col[i] * b_col[k];
                }
            }
        }

        result
    }

    /// Unfold tensor along specified mode
    fn unfold_tensor(&self, tensor: &Array3<f64>, mode: usize) -> Result<Array2<f64>> {
        let (n1, n2, n3) = tensor.dim();

        match mode {
            0 => {
                // Mode-1 unfolding: n1 × (n2*n3)
                let mut unfolded = Array2::zeros((n1, n2 * n3));
                for i in 0..n1 {
                    for j in 0..n2 {
                        for k in 0..n3 {
                            unfolded[[i, j * n3 + k]] = tensor[[i, j, k]];
                        }
                    }
                }
                Ok(unfolded)
            }
            1 => {
                // Mode-2 unfolding: n2 × (n3*n1)
                let mut unfolded = Array2::zeros((n2, n3 * n1));
                for j in 0..n2 {
                    for k in 0..n3 {
                        for i in 0..n1 {
                            unfolded[[j, k * n1 + i]] = tensor[[i, j, k]];
                        }
                    }
                }
                Ok(unfolded)
            }
            2 => {
                // Mode-3 unfolding: n3 × (n1*n2)
                let mut unfolded = Array2::zeros((n3, n1 * n2));
                for k in 0..n3 {
                    for i in 0..n1 {
                        for j in 0..n2 {
                            unfolded[[k, i * n2 + j]] = tensor[[i, j, k]];
                        }
                    }
                }
                Ok(unfolded)
            }
            _ => Err(SklearsError::InvalidParameter {
                name: "mode".to_string(),
                reason: "must be 0, 1, or 2 for 3D tensors".to_string(),
            }),
        }
    }

    /// Solve linear system using pseudoinverse
    fn solve_linear_system(&self, a: &Array2<f64>, b: &Array2<f64>) -> Result<Array2<f64>> {
        // Compute pseudoinverse using SVD from scirs2-linalg
        let (u, s, vt) = svd(&a.view(), true)
            .map_err(|e| SklearsError::NumericalError(format!("SVD failed: {}", e)))?;

        let tolerance = 1e-12;

        // Create diagonal inverse matrix S^+
        let k = s.len();
        let mut s_inv = Array2::zeros((k, k));
        for i in 0..k {
            if s[i] > tolerance {
                s_inv[[i, i]] = 1.0 / s[i];
            }
        }

        // Compute pseudoinverse: A^+ = V * S^+ * U^T
        let vt_t = vt.t();
        let u_t = u.t();
        let temp = s_inv.dot(&u_t);
        let a_pinv = vt_t.dot(&temp);

        // Compute result: A^+ * b
        let result = a_pinv.dot(b);

        Ok(result)
    }

    /// Reconstruct tensor from factor matrices
    fn reconstruct_tensor(&self, factors: &[Array2<f64>]) -> Result<Array3<f64>> {
        let (n1, r) = factors[0].dim();
        let (n2, r2) = factors[1].dim();
        let (n3, r3) = factors[2].dim();

        if r != r2 || r != r3 {
            return Err(SklearsError::InvalidInput(
                "All factor matrices must have the same number of columns".to_string(),
            ));
        }

        let mut reconstructed = Array3::zeros((n1, n2, n3));

        for k in 0..r {
            let a_k = factors[0].column(k);
            let b_k = factors[1].column(k);
            let c_k = factors[2].column(k);

            for i in 0..n1 {
                for j in 0..n2 {
                    for l in 0..n3 {
                        reconstructed[[i, j, l]] += a_k[i] * b_k[j] * c_k[l];
                    }
                }
            }
        }

        Ok(reconstructed)
    }

    /// Compute Frobenius norm of a tensor
    fn frobenius_norm(&self, tensor: &Array3<f64>) -> f64 {
        tensor.iter().map(|&x| x * x).sum::<f64>().sqrt()
    }
}

impl TuckerDecomposition<Untrained> {
    /// Create a new Tucker decomposition
    pub fn new(n_components: Vec<usize>) -> Self {
        Self {
            n_components,
            algorithm: TuckerAlgorithm::HOSVD,
            max_iter: 100,
            tol: 1e-6,
            random_state: None,
            center: true,
            init_method: "random".to_string(),
            state: Untrained,
        }
    }

    /// Set the algorithm
    pub fn algorithm(mut self, algorithm: TuckerAlgorithm) -> Self {
        self.algorithm = algorithm;
        self
    }

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

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

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

    /// Set whether to center the tensor
    pub fn center(mut self, center: bool) -> Self {
        self.center = center;
        self
    }

    /// Set initialization method
    pub fn init_method(mut self, init_method: String) -> Self {
        self.init_method = init_method;
        self
    }
}

impl Fit<Array3<f64>, ()> for TuckerDecomposition<Untrained> {
    type Fitted = TuckerDecomposition<TrainedTucker>;

    fn fit(self, tensor: &Array3<f64>, _y: &()) -> Result<Self::Fitted> {
        let tensor_shape = tensor.shape().to_vec();

        if tensor_shape.len() != 3 {
            return Err(SklearsError::InvalidInput(
                "Tucker decomposition currently supports 3D tensors only".to_string(),
            ));
        }

        if self.n_components.len() != 3 {
            return Err(SklearsError::InvalidInput(
                "n_components must have 3 elements for 3D tensors".to_string(),
            ));
        }

        // Center tensor if requested
        let (centered_tensor, mean) = if self.center {
            let mean_val = tensor.mean().ok_or_else(|| {
                SklearsError::NumericalError("cannot compute mean of empty tensor".to_string())
            })?;
            let centered = tensor.mapv(|x| x - mean_val);
            let mean_tensor = Array3::from_elem(tensor.dim(), mean_val);
            (centered, Some(mean_tensor))
        } else {
            (tensor.clone(), None)
        };

        // Initialize random number generator with optional seeding for reproducibility
        let mut rng: StdRng = match self.random_state {
            Some(seed) => StdRng::seed_from_u64(seed),
            None => StdRng::from_rng(&mut make_rng()),
        };

        // Run Tucker decomposition algorithm
        let (core, factors, n_iter, reconstruction_error) = match self.algorithm {
            TuckerAlgorithm::HOSVD => self.tucker_hosvd(&centered_tensor)?,
            TuckerAlgorithm::ALS => self.tucker_als(&centered_tensor, &mut rng)?,
            TuckerAlgorithm::SequentialSVD => self.tucker_sequential_svd(&centered_tensor)?,
        };

        Ok(TuckerDecomposition {
            n_components: self.n_components.clone(),
            algorithm: self.algorithm,
            max_iter: self.max_iter,
            tol: self.tol,
            random_state: self.random_state,
            center: self.center,
            init_method: self.init_method,
            state: TrainedTucker {
                core,
                factors,
                mean,
                tensor_shape,
                n_components: self.n_components,
                n_iter,
                reconstruction_error,
            },
        })
    }
}

impl TuckerDecomposition<Untrained> {
    /// Tucker decomposition using Higher-Order SVD (HOSVD)
    fn tucker_hosvd(&self, tensor: &Array3<f64>) -> TuckerResult {
        let mut factors = Vec::new();

        // Compute SVD for each mode
        for mode in 0..3 {
            let unfolded = self.unfold_tensor_tucker(tensor, mode)?;
            let svd_result = self.compute_svd(&unfolded)?;

            // Take first n_components[mode] columns from U matrix (not V^T)
            let n_comp = self.n_components[mode]
                .min(svd_result.0.ncols())
                .min(unfolded.nrows());
            let factor = svd_result
                .0
                .slice(scirs2_core::ndarray::s![.., ..n_comp])
                .to_owned();
            factors.push(factor);
        }

        // Compute core tensor by projecting original tensor onto factor spaces
        let core = self.compute_core_tensor(tensor, &factors)?;

        // Compute reconstruction error
        let reconstructed = self.reconstruct_tucker_tensor(&core, &factors)?;
        let error = self.frobenius_norm_tucker(&(tensor - &reconstructed));

        Ok((core, factors, 1, error))
    }

    /// Tucker decomposition using Alternating Least Squares
    fn tucker_als(&self, tensor: &Array3<f64>, rng: &mut impl RngExt) -> TuckerResult {
        let (n1, n2, n3) = tensor.dim();

        // Initialize factor matrices randomly
        let mut factors: Vec<Array2<f64>> = vec![
            {
                let mut arr: Array2<f64> = Array2::zeros((n1, self.n_components[0]));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>() - 0.5;
                }
                arr
            },
            {
                let mut arr: Array2<f64> = Array2::zeros((n2, self.n_components[1]));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>() - 0.5;
                }
                arr
            },
            {
                let mut arr: Array2<f64> = Array2::zeros((n3, self.n_components[2]));
                for elem in arr.iter_mut() {
                    *elem = rng.random::<f64>() - 0.5;
                }
                arr
            },
        ];

        // Orthogonalize initial factors
        for factor in &mut factors {
            *factor = self.orthogonalize_matrix(factor)?;
        }

        let mut prev_error = f64::INFINITY;
        let mut n_iter = 0;

        for iter in 0..self.max_iter {
            n_iter = iter + 1;

            // Update each factor matrix
            for mode in 0..3 {
                let unfolded = self.unfold_tensor_tucker(tensor, mode)?;

                // Create product of other factor matrices
                let other_factors = match mode {
                    0 => self.kronecker_product(&factors[2], &factors[1]),
                    1 => self.kronecker_product(&factors[2], &factors[0]),
                    2 => self.kronecker_product(&factors[1], &factors[0]),
                    _ => unreachable!(),
                };

                // Solve for updated factor
                let rhs = unfolded.dot(&other_factors);
                let gram = other_factors.t().dot(&other_factors);
                let rhs_t = rhs.t().to_owned();

                let solved = self.solve_linear_system_tucker(&gram, &rhs_t)?;

                // The solved matrix should be transposed to get the correct factor dimensions
                // We expect factors[mode] to have shape (n_mode, n_components[mode])
                let _expected_shape = (
                    tensor.dim().0.max(tensor.dim().1.max(tensor.dim().2)),
                    self.n_components[mode],
                );
                let n_mode = match mode {
                    0 => tensor.dim().0,
                    1 => tensor.dim().1,
                    2 => tensor.dim().2,
                    _ => unreachable!(),
                };

                // Transpose the solution and take only the first n_components[mode] columns
                let solved_t = solved.t().to_owned();
                let factor_shape = (n_mode, self.n_components[mode]);

                if solved_t.dim() == factor_shape {
                    factors[mode] = solved_t;
                } else {
                    // Take the appropriate slice, but ensure we don't go out of bounds
                    let max_rows = solved_t.nrows().min(n_mode);
                    let max_cols = solved_t.ncols().min(self.n_components[mode]);

                    let mut factor = Array2::zeros(factor_shape);
                    for i in 0..max_rows {
                        for j in 0..max_cols {
                            factor[[i, j]] = solved_t[[i, j]];
                        }
                    }
                    factors[mode] = factor;
                }

                // Orthogonalize
                factors[mode] = self.orthogonalize_matrix(&factors[mode])?;
            }

            // Compute core tensor and reconstruction error
            let core = self.compute_core_tensor(tensor, &factors)?;
            let reconstructed = self.reconstruct_tucker_tensor(&core, &factors)?;
            let error = self.frobenius_norm_tucker(&(tensor - &reconstructed));

            // Check convergence
            if (prev_error - error).abs() < self.tol {
                break;
            }
            prev_error = error;
        }

        let core = self.compute_core_tensor(tensor, &factors)?;
        let final_error = prev_error;

        Ok((core, factors, n_iter, final_error))
    }

    /// Tucker decomposition using Sequential SVD
    fn tucker_sequential_svd(&self, tensor: &Array3<f64>) -> TuckerResult {
        // Similar to HOSVD but with sequential processing
        self.tucker_hosvd(tensor)
    }

    /// Unfold tensor for Tucker decomposition
    fn unfold_tensor_tucker(&self, tensor: &Array3<f64>, mode: usize) -> Result<Array2<f64>> {
        let (n1, n2, n3) = tensor.dim();

        match mode {
            0 => {
                let mut unfolded = Array2::zeros((n1, n2 * n3));
                for i in 0..n1 {
                    for j in 0..n2 {
                        for k in 0..n3 {
                            unfolded[[i, j * n3 + k]] = tensor[[i, j, k]];
                        }
                    }
                }
                Ok(unfolded)
            }
            1 => {
                let mut unfolded = Array2::zeros((n2, n1 * n3));
                for j in 0..n2 {
                    for i in 0..n1 {
                        for k in 0..n3 {
                            unfolded[[j, i * n3 + k]] = tensor[[i, j, k]];
                        }
                    }
                }
                Ok(unfolded)
            }
            2 => {
                let mut unfolded = Array2::zeros((n3, n1 * n2));
                for k in 0..n3 {
                    for i in 0..n1 {
                        for j in 0..n2 {
                            unfolded[[k, i * n2 + j]] = tensor[[i, j, k]];
                        }
                    }
                }
                Ok(unfolded)
            }
            _ => Err(SklearsError::InvalidParameter {
                name: "mode".to_string(),
                reason: "must be 0, 1, or 2 for 3D tensors".to_string(),
            }),
        }
    }

    /// Compute SVD of a matrix
    fn compute_svd(&self, matrix: &Array2<f64>) -> Result<(Array2<f64>, Array2<f64>, Array1<f64>)> {
        // Use scirs2-linalg SVD - returns (U, S, V^T)
        let (u, s, vt) = svd(&matrix.view(), true)
            .map_err(|e| SklearsError::NumericalError(format!("SVD failed: {}", e)))?;

        // This function expects (U, V^T, S) order
        Ok((u, vt, s))
    }

    /// Compute core tensor
    fn compute_core_tensor(
        &self,
        tensor: &Array3<f64>,
        factors: &[Array2<f64>],
    ) -> Result<Array3<f64>> {
        let (r1, r2, r3) = (factors[0].ncols(), factors[1].ncols(), factors[2].ncols());
        let mut core = Array3::zeros((r1, r2, r3));

        // G = X ×₁ A^T ×₂ B^T ×₃ C^T
        // This is a simplified implementation
        for i in 0..r1 {
            for j in 0..r2 {
                for k in 0..r3 {
                    let mut value = 0.0;
                    let (n1, n2, n3) = tensor.dim();

                    for ii in 0..n1 {
                        for jj in 0..n2 {
                            for kk in 0..n3 {
                                value += tensor[[ii, jj, kk]]
                                    * factors[0][[ii, i]]
                                    * factors[1][[jj, j]]
                                    * factors[2][[kk, k]];
                            }
                        }
                    }
                    core[[i, j, k]] = value;
                }
            }
        }

        Ok(core)
    }

    /// Reconstruct tensor from Tucker decomposition
    fn reconstruct_tucker_tensor(
        &self,
        core: &Array3<f64>,
        factors: &[Array2<f64>],
    ) -> Result<Array3<f64>> {
        let (n1, n2, n3) = (factors[0].nrows(), factors[1].nrows(), factors[2].nrows());
        let mut reconstructed = Array3::zeros((n1, n2, n3));

        let (r1, r2, r3) = core.dim();

        for i in 0..n1 {
            for j in 0..n2 {
                for k in 0..n3 {
                    let mut value = 0.0;

                    for ii in 0..r1 {
                        for jj in 0..r2 {
                            for kk in 0..r3 {
                                value += core[[ii, jj, kk]]
                                    * factors[0][[i, ii]]
                                    * factors[1][[j, jj]]
                                    * factors[2][[k, kk]];
                            }
                        }
                    }
                    reconstructed[[i, j, k]] = value;
                }
            }
        }

        Ok(reconstructed)
    }

    /// Orthogonalize matrix using QR decomposition
    fn orthogonalize_matrix(&self, matrix: &Array2<f64>) -> Result<Array2<f64>> {
        // Simple Gram-Schmidt orthogonalization
        let (m, n) = matrix.dim();
        let mut q = matrix.clone();

        for j in 0..n {
            for i in 0..j {
                let qi = q.column(i).to_owned();
                let qj = q.column(j).to_owned();
                let proj = qi.dot(&qj);

                for k in 0..m {
                    q[[k, j]] -= proj * qi[k];
                }
            }

            // Normalize
            let norm = {
                let col = q.column(j);
                col.dot(&col).sqrt()
            };
            if norm > 1e-12 {
                let mut col = q.column_mut(j);
                col /= norm;
            }
        }

        Ok(q)
    }

    /// Compute Kronecker product of two matrices
    fn kronecker_product(&self, a: &Array2<f64>, b: &Array2<f64>) -> Array2<f64> {
        let (m_a, n_a) = a.dim();
        let (m_b, n_b) = b.dim();

        let mut result = Array2::zeros((m_a * m_b, n_a * n_b));

        for i in 0..m_a {
            for j in 0..n_a {
                for k in 0..m_b {
                    for l in 0..n_b {
                        result[[i * m_b + k, j * n_b + l]] = a[[i, j]] * b[[k, l]];
                    }
                }
            }
        }

        result
    }

    /// Solve linear system for Tucker decomposition
    fn solve_linear_system_tucker(&self, a: &Array2<f64>, b: &Array2<f64>) -> Result<Array2<f64>> {
        // Try Cholesky decomposition first (for positive definite matrices)
        if let Ok(chol) = a.cholesky() {
            // Solve each column of b separately
            let mut result = Array2::zeros((a.ncols(), b.ncols()));
            for (j, col) in b.axis_iter(scirs2_core::ndarray::Axis(1)).enumerate() {
                let sol = chol.solve(&col.to_owned()).map_err(|e| {
                    SklearsError::NumericalError(format!("Cholesky solve failed: {}", e))
                })?;
                for (i, &val) in sol.iter().enumerate() {
                    result[[i, j]] = val;
                }
            }
            return Ok(result);
        }

        // Fallback to pseudoinverse using SVD
        let (u, s, vt) = svd(&a.view(), true)
            .map_err(|e| SklearsError::NumericalError(format!("SVD failed: {}", e)))?;

        let tolerance = 1e-12;

        // Create diagonal inverse matrix S^+
        let k = s.len();
        let mut s_inv = Array2::zeros((k, k));
        for i in 0..k {
            if s[i] > tolerance {
                s_inv[[i, i]] = 1.0 / s[i];
            }
        }

        // Compute pseudoinverse: A^+ = V * S^+ * U^T
        let vt_t = vt.t();
        let u_t = u.t();
        let temp = s_inv.dot(&u_t);
        let a_pinv = vt_t.dot(&temp);

        // Compute result: A^+ * b
        let result = a_pinv.dot(b);

        Ok(result)
    }

    /// Compute Frobenius norm for Tucker
    fn frobenius_norm_tucker(&self, tensor: &Array3<f64>) -> f64 {
        tensor.iter().map(|&x| x * x).sum::<f64>().sqrt()
    }
}

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::array;

    #[test]
    fn test_cp_decomposition_basic() {
        // Create a simple test tensor
        let tensor = array![[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]],];

        let cp = CPDecomposition::new(2).max_iter(10).random_state(42);

        let result = cp.fit(&tensor, &());
        if let Err(ref e) = result {
            println!("CP decomposition error: {e:?}");
        }
        assert!(result.is_ok());

        let trained = result.expect("operation should succeed");
        assert_eq!(trained.state.n_components, 2);
        assert_eq!(trained.state.factors.len(), 3);
        assert!(trained.state.reconstruction_error.is_finite());
    }

    #[test]
    fn test_tucker_decomposition_basic() {
        // Create a simple test tensor
        let tensor = array![
            [[1.0, 2.0], [3.0, 4.0]],
            [[5.0, 6.0], [7.0, 8.0]],
            [[9.0, 10.0], [11.0, 12.0]],
        ];

        let tucker = TuckerDecomposition::new(vec![2, 2, 1])
            .algorithm(TuckerAlgorithm::HOSVD)
            .random_state(42);

        let result = tucker.fit(&tensor, &());
        if let Err(ref e) = result {
            println!("Tucker decomposition error: {e:?}");
        }
        assert!(result.is_ok());

        let trained = result.expect("operation should succeed");
        assert_eq!(trained.state.n_components, vec![2, 2, 1]);
        assert_eq!(trained.state.factors.len(), 3);
        assert!(trained.state.reconstruction_error.is_finite());
    }

    #[test]
    fn test_cp_nonnegative() {
        let tensor = array![[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]],];

        let cp = CPDecomposition::new(1)
            .algorithm(CPAlgorithm::NonNegative)
            .max_iter(5)
            .random_state(42);

        let result = cp.fit(&tensor, &());
        assert!(result.is_ok());

        let trained = result.expect("operation should succeed");
        // Check that all factor values are non-negative
        for factor in &trained.state.factors {
            for &val in factor.iter() {
                assert!(val >= 0.0, "Factor value should be non-negative: {}", val);
            }
        }
    }

    #[test]
    fn test_tucker_als() {
        let tensor = array![[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]],];

        let tucker = TuckerDecomposition::new(vec![1, 2, 1])
            .algorithm(TuckerAlgorithm::ALS)
            .max_iter(5)
            .random_state(42);

        let result = tucker.fit(&tensor, &());
        if let Err(ref e) = result {
            println!("Tucker ALS error: {e:?}");
        }
        assert!(result.is_ok());

        let trained = result.expect("operation should succeed");
        assert_eq!(trained.state.n_components, vec![1, 2, 1]);
        assert!(trained.state.n_iter > 0);
    }

    #[test]
    fn test_cp_parameters() {
        let cp = CPDecomposition::new(3)
            .algorithm(CPAlgorithm::Robust)
            .max_iter(200)
            .tol(1e-8)
            .learning_rate(0.05)
            .regularization(0.1)
            .normalize_factors(false);

        assert_eq!(cp.n_components, 3);
        assert_eq!(cp.algorithm, CPAlgorithm::Robust);
        assert_eq!(cp.max_iter, 200);
        assert_eq!(cp.tol, 1e-8);
        assert_eq!(cp.learning_rate, 0.05);
        assert_eq!(cp.regularization, 0.1);
        assert!(!cp.normalize_factors);
    }

    #[test]
    fn test_tucker_parameters() {
        let tucker = TuckerDecomposition::new(vec![2, 3, 4])
            .algorithm(TuckerAlgorithm::SequentialSVD)
            .max_iter(150)
            .tol(1e-7)
            .center(false)
            .init_method("svd".to_string());

        assert_eq!(tucker.n_components, vec![2, 3, 4]);
        assert_eq!(tucker.algorithm, TuckerAlgorithm::SequentialSVD);
        assert_eq!(tucker.max_iter, 150);
        assert_eq!(tucker.tol, 1e-7);
        assert!(!tucker.center);
        assert_eq!(tucker.init_method, "svd");
    }
}