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
//! Property-based tests for decomposition algorithms
//!
//! These tests verify mathematical properties and invariants that should hold
//! for all decomposition methods using proptest.

use crate::dictionary_learning::{
    DictionaryLearning, DictionaryLearningConfig, DictionaryTransformAlgorithm,
};
use crate::factor_analysis::FactorAnalysis;
use crate::ica::{ICAAlgorithm, ICA};
use crate::nmf::NMF;
use crate::pca::{PcaConfig, PCA};
use proptest::prelude::*;
use scirs2_core::ndarray::Array2;
use sklears_core::traits::{Fit, Transform};

proptest! {
    #[test]
    fn test_pca_properties(
        n_samples in 10..50usize,
        n_features in 3..10usize,
        n_components in 1..5usize
    ) {
        if n_components <= n_features {
            // Create random data matrix
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i as f64 + j as f64) / 10.0;
                }
            }

            let config = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca = PCA::new(config);
            let result = pca.fit(&x, &());

            if let Ok(trained_pca) = result {
                let x_transformed = trained_pca.transform(&x);
                if let Ok(transformed) = x_transformed {
                    // Check output dimensions
                    prop_assert_eq!(transformed.shape(), &[n_samples, n_components]);

                    // Check that all values are finite
                    for &val in transformed.iter() {
                        prop_assert!(val.is_finite());
                    }

                    // Check components matrix shape
                    let components = &trained_pca.components;
                    prop_assert_eq!(components.shape(), &[n_components, n_features]);
                }
            }
        }
    }

    #[test]
    fn test_nmf_non_negativity_properties(
        n_samples in 5..20usize,
        n_features in 3..8usize,
        n_components in 1..4usize
    ) {
        if n_components <= n_features.min(n_samples) {
            // Create non-negative data matrix
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i + j + 1) as f64;
                }
            }

            let nmf = NMF::new(n_components).random_state(42);
            let result = nmf.fit(&x, &());

            if let Ok(trained_nmf) = result {
                let w = trained_nmf.transform(&x);
                if let Ok(transformed) = w {
                    // Check output dimensions
                    prop_assert_eq!(transformed.shape(), &[n_samples, n_components]);

                    // Check non-negativity of coefficients
                    for &val in transformed.iter() {
                        prop_assert!(val >= 0.0);
                        prop_assert!(val.is_finite());
                    }

                    // Check components are non-negative
                    let components = trained_nmf.components();
                    for &val in components.iter() {
                        prop_assert!(val >= 0.0);
                        prop_assert!(val.is_finite());
                    }

                    // Test reconstruction
                    let x_reconstructed = trained_nmf.inverse_transform(&transformed);
                    if let Ok(reconstructed) = x_reconstructed {
                        // Reconstructed values should be non-negative and finite
                        for &val in reconstructed.iter() {
                            prop_assert!(val >= 0.0);
                            prop_assert!(val.is_finite());
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn test_ica_orthogonality_properties(
        n_samples in 20..40usize,
        n_features in 3..8usize,
        n_components in 2..5usize
    ) {
        if n_components <= n_features {
            // Create mixed signals (simple linear combinations)
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i as f64).sin() + (j as f64).cos() + 0.1 * (i + j) as f64;
                }
            }

            let ica = ICA::new()
                .n_components(n_components)
                .algorithm(ICAAlgorithm::Parallel)
                .random_state(42);

            let result = ica.fit(&x, &());

            if let Ok(trained_ica) = result {
                let x_transformed = trained_ica.transform(&x);
                if let Ok(transformed) = x_transformed {
                    // Check output dimensions
                    prop_assert_eq!(transformed.shape(), &[n_samples, n_components]);

                    // Check that all values are finite
                    for &val in transformed.iter() {
                        prop_assert!(val.is_finite());
                    }

                    // Check components matrix properties
                    let components = trained_ica.components();
                    prop_assert_eq!(components.shape(), &[n_components, n_features]);

                    // Test inverse transform
                    let x_reconstructed = trained_ica.inverse_transform(&transformed);
                    if let Ok(reconstructed) = x_reconstructed {
                        prop_assert_eq!(reconstructed.shape(), x.shape());

                        // All reconstructed values should be finite
                        for &val in reconstructed.iter() {
                            prop_assert!(val.is_finite());
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn test_decomposition_dimension_consistency(
        n_samples in 8..20usize,
        n_features in 3..8usize,
        n_components in 1..4usize
    ) {
        if n_components <= n_features {
            // Create simple test data
            let mut x = Array2::<f64>::ones((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i + j) as f64 / 10.0;
                }
            }

            // Test that all decomposition methods respect dimension constraints

            // PCA
            let config = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca = PCA::new(config);
            if let Ok(trained_pca) = pca.fit(&x, &()) {
                if let Ok(pca_result) = trained_pca.transform(&x) {
                    prop_assert_eq!(pca_result.shape(), &[n_samples, n_components]);
                }
            }

            // ICA (only test if we have enough samples)
            if n_samples >= 2 * n_components {
                let ica = ICA::new().n_components(n_components).random_state(42);
                if let Ok(trained_ica) = ica.fit(&x, &()) {
                    if let Ok(ica_result) = trained_ica.transform(&x) {
                        prop_assert_eq!(ica_result.shape(), &[n_samples, n_components]);
                    }
                }
            }

            // FactorAnalysis (requires n_components < n_features and sufficient samples)
            if n_components < n_features && n_samples >= n_features + 2 {
                let fa = FactorAnalysis::new(n_components).random_state(42);
                if let Ok(trained_fa) = fa.fit(&x, &()) {
                    if let Ok(fa_result) = trained_fa.transform(&x) {
                        prop_assert_eq!(fa_result.shape(), &[n_samples, n_components]);
                    }
                }
            }
        }
    }

    #[test]
    fn test_decomposition_determinism(
        n_samples in 10..30usize,
        n_features in 3..8usize,
        n_components in 1..4usize,
        random_seed in 1..100u64
    ) {
        if n_components <= n_features {
            // Create deterministic data
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i + j) as f64 / 10.0;
                }
            }

            // Test PCA determinism
            let config1 = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca1 = PCA::new(config1);
            let config2 = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca2 = PCA::new(config2);

            if let (Ok(trained_pca1), Ok(trained_pca2)) = (pca1.fit(&x, &()), pca2.fit(&x, &())) {
                if let (Ok(result1), Ok(result2)) = (trained_pca1.transform(&x), trained_pca2.transform(&x)) {
                    // Results should be identical (up to sign) for deterministic algorithms
                    prop_assert_eq!(result1.shape(), result2.shape());

                    // Check that components are similar (allowing for sign flip)
                    let comp1 = &trained_pca1.components;
                    let comp2 = &trained_pca2.components;
                    prop_assert_eq!(comp1.shape(), comp2.shape());
                }
            }

            // Test NMF determinism with fixed seed
            let nmf1 = NMF::new(n_components).random_state(random_seed);
            let nmf2 = NMF::new(n_components).random_state(random_seed);

            if let (Ok(trained_nmf1), Ok(trained_nmf2)) = (nmf1.fit(&x, &()), nmf2.fit(&x, &())) {
                if let (Ok(result1), Ok(result2)) = (trained_nmf1.transform(&x), trained_nmf2.transform(&x)) {
                    prop_assert_eq!(result1.shape(), result2.shape());
                }
            }
        }
    }

    #[test]
    fn test_decomposition_rank_properties(
        n_samples in 5..20usize,
        n_features in 3..8usize,
        n_components in 1..4usize
    ) {
        if n_components <= n_features.min(n_samples) {
            // Create rank-deficient data
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features.min(2) { // Only fill first 2 columns to create rank deficiency
                    x[[i, j]] = (i + j) as f64;
                }
            }

            // PCA should handle rank-deficient data gracefully
            let config = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca = PCA::new(config);
            if let Ok(trained_pca) = pca.fit(&x, &()) {
                if let Ok(transformed) = trained_pca.transform(&x) {
                    prop_assert_eq!(transformed.shape(), &[n_samples, n_components]);

                    // All values should be finite
                    for &val in transformed.iter() {
                        prop_assert!(val.is_finite());
                    }

                    // Explained variance should be non-negative and finite
                    let explained_var = trained_pca.explained_variance_ratio;
                    for &var in explained_var.iter() {
                        prop_assert!(var >= 0.0);
                        prop_assert!(var.is_finite());
                    }
                }
            }
        }
    }

    #[test]
    fn test_decomposition_scaling_invariance(
        n_samples in 10..25usize,
        n_features in 3..6usize,
        n_components in 1..3usize,
        scale_factor in 0.1..10.0f64
    ) {
        if n_components <= n_features {
            // Create base data
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i + 1) as f64 + (j + 1) as f64 / 10.0;
                }
            }

            // Create scaled version
            let x_scaled = &x * scale_factor;

            // Test PCA scaling properties
            let config1 = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca1 = PCA::new(config1);
            let config2 = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca2 = PCA::new(config2);

            if let (Ok(trained_pca1), Ok(trained_pca2)) = (pca1.fit(&x, &()), pca2.fit(&x_scaled, &())) {
                // Components should be the same direction (up to normalization)
                let comp1 = &trained_pca1.components;
                let comp2 = &trained_pca2.components;
                prop_assert_eq!(comp1.shape(), comp2.shape());

                // Explained variance should scale with the square of the scaling factor
                let var1 = trained_pca1.explained_variance_ratio;
                let var2 = trained_pca2.explained_variance_ratio;
                prop_assert_eq!(var1.len(), var2.len());
            }
        }
    }

    #[test]
    fn test_reconstruction_bounds(
        n_samples in 5..15usize,
        n_features in 3..6usize,
        n_components in 1..4usize
    ) {
        if n_components <= n_features {
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i + j) as f64 / 5.0;
                }
            }

            // PCA inverse_transform not yet implemented; test forward pass only.
            let config = PcaConfig { n_components: Some(n_components), ..Default::default() };
            let pca = PCA::new(config);
            if let Ok(trained_pca) = pca.fit(&x, &()) {
                if let Ok(transformed) = trained_pca.transform(&x) {
                    prop_assert_eq!(transformed.shape(), &[n_samples, n_components]);
                    for &val in transformed.iter() {
                        prop_assert!(val.is_finite());
                    }
                }
            }
        }
    }

    #[test]
    fn test_factor_analysis_properties(
        n_samples in 15..30usize,
        n_features in 4..8usize,
        n_components in 1..4usize
    ) {
        // FactorAnalysis requires n_components < n_features and sufficient samples.
        if n_components < n_features && n_samples >= n_features + 2 {
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i as f64).sin() * (j + 1) as f64 + (i + j) as f64 / 10.0;
                }
            }

            let fa = FactorAnalysis::new(n_components).random_state(42);
            if let Ok(trained_fa) = fa.fit(&x, &()) {
                let result = trained_fa.transform(&x);
                if let Ok(scores) = result {
                    // Factor scores must have shape (n_samples, n_components).
                    prop_assert_eq!(scores.shape(), &[n_samples, n_components]);

                    // All factor scores must be finite.
                    for &val in scores.iter() {
                        prop_assert!(val.is_finite());
                    }

                    // Loadings matrix must have shape (n_features, n_components).
                    let loadings = trained_fa.loadings();
                    prop_assert_eq!(loadings.shape(), &[n_features, n_components]);

                    // Noise variances must be positive and finite.
                    let noise_var = trained_fa.noise_variance();
                    prop_assert_eq!(noise_var.len(), n_features);
                    for &v in noise_var.iter() {
                        prop_assert!(v > 0.0);
                        prop_assert!(v.is_finite());
                    }

                    // Log-likelihood must be finite (not NaN or Inf).
                    prop_assert!(trained_fa.log_likelihood().is_finite());
                }
            }
        }
    }

    #[test]
    fn test_dictionary_learning_properties(
        n_samples in 12..25usize,
        n_features in 4..8usize,
        n_components in 2..5usize
    ) {
        if n_components <= n_features && n_samples >= n_components * 2 {
            // Build strictly positive data so OMP sparse coding converges reliably.
            let mut x = Array2::<f64>::zeros((n_samples, n_features));
            for i in 0..n_samples {
                for j in 0..n_features {
                    x[[i, j]] = (i + j + 1) as f64 / 5.0;
                }
            }

            let config = DictionaryLearningConfig {
                n_components,
                max_iter: 30,
                tol: 1e-3,
                transform_algorithm: DictionaryTransformAlgorithm::OMP,
                alpha: 0.5,
                random_state: Some(42),
            };

            let model = DictionaryLearning::new(config);
            if let Ok(trained_model) = model.fit(&x, &()) {
                // Dictionary (components) shape: (n_components, n_features).
                let dict = trained_model.components();
                prop_assert_eq!(dict.shape(), &[n_components, n_features]);
                for &val in dict.iter() {
                    prop_assert!(val.is_finite());
                }

                let result = trained_model.transform(&x);
                if let Ok(codes) = result {
                    // Sparse codes shape: (n_samples, n_components).
                    prop_assert_eq!(codes.shape(), &[n_samples, n_components]);
                    for &val in codes.iter() {
                        prop_assert!(val.is_finite());
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_property_test_setup_decomposition() {
        // Simple test to ensure property test framework is working for decomposition
        let x = Array2::<f64>::ones((10, 5));
        let config = PcaConfig {
            n_components: Some(3),
            ..Default::default()
        };
        let pca = PCA::new(config);
        let result = pca.fit(&x, &());

        // Should succeed (though may not be very meaningful with all-ones data)
        assert!(result.is_ok());
    }
}