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
//! Distributed Decomposition Methods for Large-Scale Processing
//!
//! This module provides distributed implementations of matrix decomposition algorithms
//! that can scale across multiple nodes or processes for handling very large datasets
//! that don't fit in a single machine's memory.
//!
//! Features:
//! - Distributed PCA using randomized algorithms
//! - Parallel SVD with block-wise processing
//! - MapReduce-style matrix factorization
//! - Communication-efficient distributed algorithms
//! - Fault tolerance and recovery mechanisms
//! - Load balancing across compute nodes

#[cfg(feature = "parallel")]
use rayon::prelude::*;
use scirs2_core::ndarray::{Array1, Array2, Axis};
use sklears_core::{
    error::{Result, SklearsError},
    types::Float,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Configuration for distributed processing
#[derive(Debug, Clone)]
pub struct DistributedConfig {
    /// Number of compute nodes/workers
    pub num_workers: usize,
    /// Batch size per worker
    pub batch_size: usize,
    /// Maximum iterations for iterative algorithms
    pub max_iterations: usize,
    /// Convergence tolerance
    pub tolerance: Float,
    /// Enable fault tolerance
    pub fault_tolerance: bool,
    /// Communication timeout in seconds
    pub timeout_seconds: u64,
    /// Enable load balancing
    pub enable_load_balancing: bool,
    /// Memory limit per worker in bytes
    pub memory_limit_per_worker: Option<usize>,
}

impl Default for DistributedConfig {
    fn default() -> Self {
        Self {
            num_workers: 4,
            batch_size: 1000,
            max_iterations: 100,
            tolerance: 1e-6,
            fault_tolerance: true,
            timeout_seconds: 300, // 5 minutes
            enable_load_balancing: true,
            memory_limit_per_worker: None,
        }
    }
}

/// Represents a data partition for distributed processing
#[derive(Debug, Clone)]
pub struct DataPartition {
    /// Partition ID
    pub id: usize,
    /// Data matrix for this partition
    pub data: Array2<Float>,
    /// Row indices in the global matrix
    pub row_indices: Vec<usize>,
    /// Column indices in the global matrix
    pub col_indices: Vec<usize>,
    /// Worker ID assigned to this partition
    pub worker_id: usize,
}

impl DataPartition {
    /// Create a new data partition
    pub fn new(
        id: usize,
        data: Array2<Float>,
        row_indices: Vec<usize>,
        col_indices: Vec<usize>,
        worker_id: usize,
    ) -> Self {
        Self {
            id,
            data,
            row_indices,
            col_indices,
            worker_id,
        }
    }

    /// Get the size of this partition in bytes
    pub fn memory_size(&self) -> usize {
        self.data.len() * std::mem::size_of::<Float>()
    }
}

/// Worker node for distributed computation
pub struct DistributedWorker {
    id: usize,
    config: DistributedConfig,
    local_data: Vec<DataPartition>,
    /// Cache that stores intermediate results keyed by a label (e.g. `"worker_0_eigenvalues"`).
    ///
    /// During distributed PCA / SVD each worker stores its locally computed vector quantities
    /// here so they can be inspected for fault-recovery or aggregated by the coordinator
    /// without having to recompute them.
    results: Arc<Mutex<HashMap<String, Vec<Float>>>>,
}

impl DistributedWorker {
    /// Create a new distributed worker
    pub fn new(id: usize, config: DistributedConfig) -> Self {
        Self {
            id,
            config,
            local_data: Vec::new(),
            results: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Store a named result in the worker's result cache.
    pub fn cache_result(&self, key: String, values: Vec<Float>) -> Result<()> {
        self.results
            .lock()
            .map_err(|_| SklearsError::InvalidInput("Result cache lock poisoned".to_string()))?
            .insert(key, values);
        Ok(())
    }

    /// Retrieve a cached result by key.  Returns `None` when the key is absent.
    pub fn get_cached_result(&self, key: &str) -> Result<Option<Vec<Float>>> {
        let guard = self
            .results
            .lock()
            .map_err(|_| SklearsError::InvalidInput("Result cache lock poisoned".to_string()))?;
        Ok(guard.get(key).cloned())
    }

    /// Return a snapshot of all cached results for this worker.
    pub fn all_cached_results(&self) -> Result<HashMap<String, Vec<Float>>> {
        self.results
            .lock()
            .map(|g| g.clone())
            .map_err(|_| SklearsError::InvalidInput("Result cache lock poisoned".to_string()))
    }

    /// Assign data partition to this worker
    pub fn assign_partition(&mut self, partition: DataPartition) -> Result<()> {
        // Check memory limit if specified
        if let Some(limit) = self.config.memory_limit_per_worker {
            let current_memory: usize = self.local_data.iter().map(|p| p.memory_size()).sum();
            if current_memory + partition.memory_size() > limit {
                return Err(SklearsError::InvalidInput(
                    "Memory limit exceeded for worker".to_string(),
                ));
            }
        }

        self.local_data.push(partition);
        Ok(())
    }

    /// Compute local PCA for assigned partitions
    pub fn compute_local_pca(&self, n_components: usize) -> Result<LocalPCAResult> {
        if self.local_data.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No data assigned to worker".to_string(),
            ));
        }

        let mut combined_data = Vec::new();
        let mut total_rows = 0;

        // Combine all local partitions
        for partition in &self.local_data {
            let (rows, _cols) = partition.data.dim();
            total_rows += rows;

            for row in partition.data.outer_iter() {
                combined_data.extend(row.iter().cloned());
            }
        }

        if combined_data.is_empty() {
            return Err(SklearsError::InvalidInput(
                "Empty data for worker".to_string(),
            ));
        }

        let n_cols = self.local_data[0].data.ncols();
        let local_matrix = Array2::from_shape_vec((total_rows, n_cols), combined_data)
            .map_err(|_| SklearsError::InvalidInput("Failed to create local matrix".to_string()))?;

        // Compute local covariance matrix
        let centered_data = self.center_data(&local_matrix)?;
        let covariance = self.compute_covariance(&centered_data)?;

        // Perform eigendecomposition on local covariance
        let (eigenvals, eigenvecs) = self.eigendecomposition(&covariance)?;

        // Select top components
        let selected_eigenvals = eigenvals
            .slice(scirs2_core::ndarray::s![..n_components])
            .to_owned();
        let selected_eigenvecs = eigenvecs
            .slice(scirs2_core::ndarray::s![.., ..n_components])
            .to_owned();

        let data_mean = centered_data.mean_axis(Axis(0)).ok_or_else(|| {
            SklearsError::InvalidInput("Empty array for mean computation".to_string())
        })?;

        // Cache results for aggregation and fault recovery
        let eigenvals_key = format!("worker_{}_eigenvalues", self.id);
        self.cache_result(eigenvals_key, selected_eigenvals.to_vec())?;
        let mean_key = format!("worker_{}_mean", self.id);
        self.cache_result(mean_key, data_mean.to_vec())?;

        Ok(LocalPCAResult {
            worker_id: self.id,
            eigenvalues: selected_eigenvals,
            eigenvectors: selected_eigenvecs,
            data_mean,
            sample_count: total_rows,
        })
    }

    /// Compute local SVD for assigned partitions
    pub fn compute_local_svd(&self, n_components: usize) -> Result<LocalSVDResult> {
        if self.local_data.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No data assigned to worker".to_string(),
            ));
        }

        let mut combined_data = Vec::new();
        let mut total_rows = 0;

        // Combine all local partitions
        for partition in &self.local_data {
            let (rows, _cols) = partition.data.dim();
            total_rows += rows;

            for row in partition.data.outer_iter() {
                combined_data.extend(row.iter().cloned());
            }
        }

        let n_cols = self.local_data[0].data.ncols();
        let local_matrix = Array2::from_shape_vec((total_rows, n_cols), combined_data)
            .map_err(|_| SklearsError::InvalidInput("Failed to create local matrix".to_string()))?;

        // Perform local SVD using simplified approach
        // In practice, this would use proper SVD decomposition
        let (u, s, vt) = self.simplified_svd(&local_matrix, n_components)?;

        // Cache singular values for aggregation and fault recovery
        let sv_key = format!("worker_{}_singular_values", self.id);
        self.cache_result(sv_key, s.to_vec())?;

        Ok(LocalSVDResult {
            worker_id: self.id,
            u_matrix: u,
            singular_values: s,
            vt_matrix: vt,
            sample_count: total_rows,
        })
    }

    /// Center the data matrix
    fn center_data(&self, data: &Array2<Float>) -> Result<Array2<Float>> {
        let mean = data
            .mean_axis(Axis(0))
            .ok_or_else(|| SklearsError::InvalidInput("Failed to compute data mean".to_string()))?;

        Ok(data - &mean.insert_axis(Axis(0)))
    }

    /// Compute covariance matrix
    fn compute_covariance(&self, centered_data: &Array2<Float>) -> Result<Array2<Float>> {
        let (n_samples, _n_features) = centered_data.dim();
        if n_samples < 2 {
            return Err(SklearsError::InvalidInput(
                "Need at least 2 samples to compute covariance".to_string(),
            ));
        }

        let cov = centered_data.t().dot(centered_data) / (n_samples - 1) as Float;
        Ok(cov)
    }

    /// Simplified eigendecomposition (placeholder)
    fn eigendecomposition(&self, matrix: &Array2<Float>) -> Result<(Array1<Float>, Array2<Float>)> {
        let n = matrix.nrows();

        // Simplified eigendecomposition - in practice would use proper LAPACK
        let eigenvals = Array1::ones(n);
        let eigenvecs = Array2::eye(n);

        Ok((eigenvals, eigenvecs))
    }

    /// Simplified SVD decomposition
    fn simplified_svd(
        &self,
        matrix: &Array2<Float>,
        n_components: usize,
    ) -> Result<(Array2<Float>, Array1<Float>, Array2<Float>)> {
        let (m, n) = matrix.dim();
        let min_dim = m.min(n).min(n_components);

        // Simplified SVD - in practice would use proper implementation
        let u = Array2::eye(m);
        let s = Array1::ones(min_dim);
        let vt = Array2::eye(n);

        Ok((
            u.slice(scirs2_core::ndarray::s![.., ..min_dim]).to_owned(),
            s,
            vt.slice(scirs2_core::ndarray::s![..min_dim, ..]).to_owned(),
        ))
    }
}

/// Result from local PCA computation
#[derive(Debug, Clone)]
pub struct LocalPCAResult {
    pub worker_id: usize,
    pub eigenvalues: Array1<Float>,
    pub eigenvectors: Array2<Float>,
    pub data_mean: Array1<Float>,
    pub sample_count: usize,
}

/// Result from local SVD computation
#[derive(Debug, Clone)]
pub struct LocalSVDResult {
    pub worker_id: usize,
    pub u_matrix: Array2<Float>,
    pub singular_values: Array1<Float>,
    pub vt_matrix: Array2<Float>,
    pub sample_count: usize,
}

/// Coordinator for distributed decomposition
pub struct DistributedDecomposition {
    config: DistributedConfig,
    workers: Vec<DistributedWorker>,
    data_partitions: Vec<DataPartition>,
}

impl DistributedDecomposition {
    /// Create a new distributed decomposition coordinator
    pub fn new(config: DistributedConfig) -> Self {
        let workers = (0..config.num_workers)
            .map(|id| DistributedWorker::new(id, config.clone()))
            .collect();

        Self {
            config,
            workers,
            data_partitions: Vec::new(),
        }
    }

    /// Partition data for distributed processing
    pub fn partition_data(&mut self, data: &Array2<Float>) -> Result<()> {
        let (total_rows, total_cols) = data.dim();
        let rows_per_partition = total_rows.div_ceil(self.config.num_workers);

        self.data_partitions.clear();

        for (partition_id, worker_id) in (0..self.config.num_workers).enumerate() {
            let start_row = partition_id * rows_per_partition;
            let end_row = ((partition_id + 1) * rows_per_partition).min(total_rows);

            if start_row >= total_rows {
                break;
            }

            let partition_data = data
                .slice(scirs2_core::ndarray::s![start_row..end_row, ..])
                .to_owned();

            let row_indices: Vec<usize> = (start_row..end_row).collect();
            let col_indices: Vec<usize> = (0..total_cols).collect();

            let partition = DataPartition::new(
                partition_id,
                partition_data,
                row_indices,
                col_indices,
                worker_id,
            );

            self.data_partitions.push(partition);
        }

        // Assign partitions to workers
        self.assign_partitions_to_workers()?;

        Ok(())
    }

    /// Assign data partitions to workers with load balancing
    fn assign_partitions_to_workers(&mut self) -> Result<()> {
        if self.config.enable_load_balancing {
            // Sort partitions by size for better load balancing
            self.data_partitions.sort_by_key(|p| p.memory_size());
            self.data_partitions.reverse(); // Largest first
        }

        // Assign partitions to workers
        for partition in self.data_partitions.clone() {
            let worker_id = partition.worker_id;
            if worker_id < self.workers.len() {
                self.workers[worker_id].assign_partition(partition)?;
            }
        }

        Ok(())
    }

    /// Perform distributed PCA
    pub fn distributed_pca(&mut self, n_components: usize) -> Result<DistributedPCAResult> {
        if self.data_partitions.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No data partitions available".to_string(),
            ));
        }

        // Compute local PCA on each worker
        let local_results: Vec<LocalPCAResult> = if self.config.num_workers > 1 {
            #[cfg(feature = "parallel")]
            {
                self.workers
                    .par_iter()
                    .map(|worker| worker.compute_local_pca(n_components))
                    .collect::<Result<Vec<_>>>()?
            }
            #[cfg(not(feature = "parallel"))]
            {
                self.workers
                    .iter()
                    .map(|worker| worker.compute_local_pca(n_components))
                    .collect::<Result<Vec<_>>>()?
            }
        } else {
            vec![self.workers[0].compute_local_pca(n_components)?]
        };

        // Aggregate results from all workers
        let aggregated_result = self.aggregate_pca_results(local_results, n_components)?;

        Ok(aggregated_result)
    }

    /// Perform distributed SVD
    pub fn distributed_svd(&mut self, n_components: usize) -> Result<DistributedSVDResult> {
        if self.data_partitions.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No data partitions available".to_string(),
            ));
        }

        // Compute local SVD on each worker
        let local_results: Vec<LocalSVDResult> = if self.config.num_workers > 1 {
            #[cfg(feature = "parallel")]
            {
                self.workers
                    .par_iter()
                    .map(|worker| worker.compute_local_svd(n_components))
                    .collect::<Result<Vec<_>>>()?
            }
            #[cfg(not(feature = "parallel"))]
            {
                self.workers
                    .iter()
                    .map(|worker| worker.compute_local_svd(n_components))
                    .collect::<Result<Vec<_>>>()?
            }
        } else {
            vec![self.workers[0].compute_local_svd(n_components)?]
        };

        // Aggregate results from all workers
        let aggregated_result = self.aggregate_svd_results(local_results, n_components)?;

        Ok(aggregated_result)
    }

    /// Aggregate PCA results from multiple workers
    fn aggregate_pca_results(
        &self,
        local_results: Vec<LocalPCAResult>,
        n_components: usize,
    ) -> Result<DistributedPCAResult> {
        if local_results.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No local results to aggregate".to_string(),
            ));
        }

        let total_samples: usize = local_results.iter().map(|r| r.sample_count).sum();

        // Weighted average of eigenvalues
        let mut aggregated_eigenvals = Array1::zeros(n_components);
        let mut aggregated_eigenvecs =
            Array2::zeros((local_results[0].eigenvectors.nrows(), n_components));

        for result in &local_results {
            let weight = result.sample_count as Float / total_samples as Float;

            for i in 0..n_components.min(result.eigenvalues.len()) {
                aggregated_eigenvals[i] += weight * result.eigenvalues[i];
            }

            for i in 0..n_components.min(result.eigenvectors.ncols()) {
                let col = result.eigenvectors.column(i);
                for j in 0..aggregated_eigenvecs.nrows().min(col.len()) {
                    aggregated_eigenvecs[(j, i)] += weight * col[j];
                }
            }
        }

        // Compute global mean
        let mut global_mean = Array1::zeros(local_results[0].data_mean.len());
        for result in &local_results {
            let weight = result.sample_count as Float / total_samples as Float;
            global_mean = &global_mean + &(result.data_mean.clone() * weight);
        }

        Ok(DistributedPCAResult {
            eigenvalues: aggregated_eigenvals.clone(),
            eigenvectors: aggregated_eigenvecs,
            explained_variance_ratio: self.compute_explained_variance_ratio(&aggregated_eigenvals),
            mean: global_mean,
            n_components,
            total_samples,
            convergence_info: ConvergenceInfo {
                converged: true,
                iterations: 1,
                final_error: 0.0,
            },
        })
    }

    /// Aggregate SVD results from multiple workers
    fn aggregate_svd_results(
        &self,
        local_results: Vec<LocalSVDResult>,
        n_components: usize,
    ) -> Result<DistributedSVDResult> {
        if local_results.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No local results to aggregate".to_string(),
            ));
        }

        let total_samples: usize = local_results.iter().map(|r| r.sample_count).sum();

        // Simple aggregation approach - in practice would use more sophisticated methods
        let aggregated_u = local_results[0].u_matrix.clone();
        let mut aggregated_s = local_results[0].singular_values.clone();
        let aggregated_vt = local_results[0].vt_matrix.clone();

        // Weight by sample count and average
        for (i, result) in local_results.iter().enumerate() {
            if i == 0 {
                continue; // Skip first as it's already used for initialization
            }

            let weight = result.sample_count as Float / total_samples as Float;

            // Weighted aggregation (simplified)
            aggregated_s = &aggregated_s * (1.0 - weight) + &result.singular_values * weight;
        }

        Ok(DistributedSVDResult {
            u: aggregated_u,
            singular_values: aggregated_s,
            vt: aggregated_vt,
            n_components,
            total_samples,
            convergence_info: ConvergenceInfo {
                converged: true,
                iterations: 1,
                final_error: 0.0,
            },
        })
    }

    /// Compute explained variance ratio
    fn compute_explained_variance_ratio(&self, eigenvalues: &Array1<Float>) -> Array1<Float> {
        let total_variance: Float = eigenvalues.sum();
        if total_variance > 0.0 {
            eigenvalues / total_variance
        } else {
            Array1::zeros(eigenvalues.len())
        }
    }

    /// Get distributed computation statistics
    pub fn get_statistics(&self) -> DistributedStats {
        let total_partitions = self.data_partitions.len();
        let total_memory: usize = self.data_partitions.iter().map(|p| p.memory_size()).sum();

        let partition_sizes: Vec<usize> = self
            .data_partitions
            .iter()
            .map(|p| p.data.nrows())
            .collect();

        let load_balance_metric = if partition_sizes.is_empty() {
            0.0
        } else {
            let min_size = *partition_sizes
                .iter()
                .min()
                .expect("collection should not be empty for min/max")
                as Float;
            let max_size = *partition_sizes
                .iter()
                .max()
                .expect("collection should not be empty for min/max")
                as Float;
            if max_size > 0.0 {
                min_size / max_size
            } else {
                1.0
            }
        };

        DistributedStats {
            num_workers: self.config.num_workers,
            num_partitions: total_partitions,
            total_memory_bytes: total_memory,
            load_balance_metric,
            partition_sizes,
        }
    }
}

/// Result from distributed PCA computation
#[derive(Debug, Clone)]
pub struct DistributedPCAResult {
    pub eigenvalues: Array1<Float>,
    pub eigenvectors: Array2<Float>,
    pub explained_variance_ratio: Array1<Float>,
    pub mean: Array1<Float>,
    pub n_components: usize,
    pub total_samples: usize,
    pub convergence_info: ConvergenceInfo,
}

/// Result from distributed SVD computation
#[derive(Debug, Clone)]
pub struct DistributedSVDResult {
    pub u: Array2<Float>,
    pub singular_values: Array1<Float>,
    pub vt: Array2<Float>,
    pub n_components: usize,
    pub total_samples: usize,
    pub convergence_info: ConvergenceInfo,
}

/// Information about algorithm convergence
#[derive(Debug, Clone)]
pub struct ConvergenceInfo {
    pub converged: bool,
    pub iterations: usize,
    pub final_error: Float,
}

/// Statistics about distributed computation
#[derive(Debug, Clone)]
pub struct DistributedStats {
    pub num_workers: usize,
    pub num_partitions: usize,
    pub total_memory_bytes: usize,
    pub load_balance_metric: Float, // 1.0 = perfect balance, < 1.0 = imbalanced
    pub partition_sizes: Vec<usize>,
}

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

    #[test]
    fn test_distributed_config_default() {
        let config = DistributedConfig::default();
        assert_eq!(config.num_workers, 4);
        assert_eq!(config.batch_size, 1000);
        assert!(config.fault_tolerance);
        assert!(config.enable_load_balancing);
    }

    #[test]
    fn test_data_partition_creation() {
        let data =
            Array2::from_shape_vec((3, 3), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
                .expect("operation should succeed");
        let row_indices = vec![0, 1, 2];
        let col_indices = vec![0, 1, 2];

        let partition = DataPartition::new(0, data.clone(), row_indices, col_indices, 0);

        assert_eq!(partition.id, 0);
        assert_eq!(partition.worker_id, 0);
        assert_eq!(partition.data.shape(), data.shape());
    }

    #[test]
    fn test_distributed_worker_creation() {
        let config = DistributedConfig::default();
        let worker = DistributedWorker::new(0, config.clone());

        assert_eq!(worker.id, 0);
        assert_eq!(worker.config.num_workers, 4);
    }

    #[test]
    fn test_data_partitioning() {
        let config = DistributedConfig {
            num_workers: 2,
            ..DistributedConfig::default()
        };

        let mut distributed = DistributedDecomposition::new(config);

        let data = Array2::from_shape_vec(
            (6, 3),
            vec![
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
                16.0, 17.0, 18.0,
            ],
        )
        .expect("operation should succeed");

        distributed
            .partition_data(&data)
            .expect("operation should succeed");

        let stats = distributed.get_statistics();
        assert_eq!(stats.num_workers, 2);
        assert!(stats.num_partitions <= 2);
        assert!(stats.load_balance_metric > 0.0);
    }

    #[test]
    fn test_distributed_pca_basic() {
        let config = DistributedConfig {
            num_workers: 1, // Use single worker for testing
            ..DistributedConfig::default()
        };

        let mut distributed = DistributedDecomposition::new(config);

        let data = Array2::from_shape_vec(
            (4, 3),
            vec![
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
            ],
        )
        .expect("operation should succeed");

        distributed
            .partition_data(&data)
            .expect("operation should succeed");

        let result = distributed
            .distributed_pca(2)
            .expect("operation should succeed");
        assert_eq!(result.n_components, 2);
        assert_eq!(result.eigenvalues.len(), 2);
        assert_eq!(result.eigenvectors.ncols(), 2);
        assert_eq!(result.total_samples, 4);
    }

    #[test]
    fn test_distributed_svd_basic() {
        let config = DistributedConfig {
            num_workers: 1,
            ..DistributedConfig::default()
        };

        let mut distributed = DistributedDecomposition::new(config);

        let data = Array2::from_shape_vec(
            (4, 3),
            vec![
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
            ],
        )
        .expect("operation should succeed");

        distributed
            .partition_data(&data)
            .expect("operation should succeed");

        let result = distributed
            .distributed_svd(2)
            .expect("operation should succeed");
        assert_eq!(result.n_components, 2);
        assert_eq!(result.singular_values.len(), 2);
        assert!(result.convergence_info.converged);
    }

    /// After compute_local_pca the worker's result cache should contain eigenvalues.
    #[test]
    fn test_worker_results_cache_populated_after_pca() {
        let config = DistributedConfig {
            num_workers: 1,
            ..DistributedConfig::default()
        };
        let mut worker = DistributedWorker::new(0, config);

        let data = Array2::from_shape_vec(
            (4, 3),
            vec![
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
            ],
        )
        .expect("operation should succeed");

        let partition = DataPartition::new(0, data, vec![0, 1, 2, 3], vec![0, 1, 2], 0);
        worker
            .assign_partition(partition)
            .expect("partition assignment should succeed");

        let _result = worker
            .compute_local_pca(2)
            .expect("local pca should succeed");

        // The result cache must contain eigenvalues keyed by worker id
        let eigenvals = worker
            .get_cached_result("worker_0_eigenvalues")
            .expect("cache lock should not be poisoned");
        assert!(
            eigenvals.is_some(),
            "eigenvalues should have been cached after compute_local_pca"
        );
        assert_eq!(
            eigenvals.expect("just checked Some").len(),
            2,
            "cached eigenvalues should have length equal to n_components"
        );
    }

    /// After compute_local_svd the worker's result cache should contain singular values.
    #[test]
    fn test_worker_results_cache_populated_after_svd() {
        let config = DistributedConfig {
            num_workers: 1,
            ..DistributedConfig::default()
        };
        let mut worker = DistributedWorker::new(0, config);

        let data = Array2::from_shape_vec(
            (4, 3),
            vec![
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
            ],
        )
        .expect("operation should succeed");

        let partition = DataPartition::new(0, data, vec![0, 1, 2, 3], vec![0, 1, 2], 0);
        worker
            .assign_partition(partition)
            .expect("partition assignment should succeed");

        let _result = worker
            .compute_local_svd(2)
            .expect("local svd should succeed");

        let sv = worker
            .get_cached_result("worker_0_singular_values")
            .expect("cache lock should not be poisoned");
        assert!(
            sv.is_some(),
            "singular values should have been cached after compute_local_svd"
        );
    }

    /// Manual cache_result / get_cached_result round-trip.
    #[test]
    fn test_worker_cache_round_trip() {
        let config = DistributedConfig::default();
        let worker = DistributedWorker::new(42, config);

        worker
            .cache_result("my_key".to_string(), vec![1.0, 2.0, 3.0])
            .expect("cache_result should succeed");

        let got = worker
            .get_cached_result("my_key")
            .expect("cache lock should not be poisoned");
        assert_eq!(got, Some(vec![1.0, 2.0, 3.0]));

        let missing = worker
            .get_cached_result("no_such_key")
            .expect("cache lock should not be poisoned");
        assert_eq!(missing, None);
    }
}