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
//! Advanced Format Support for Matrix Decomposition
//!
//! This module provides support for various data formats commonly used in
//! scientific computing and machine learning applications:
//!
//! - HDF5: Hierarchical Data Format for large scientific datasets
//! - Sparse matrices: Efficient representation of matrices with mostly zero values
//! - Memory-mapped files: For handling datasets larger than available RAM
//! - Compressed formats: Space-efficient storage of decomposition results
//!
//! Features:
//! - HDF5 read/write support for matrices and decomposition results
//! - Multiple sparse matrix formats (COO, CSR, CSC)
//! - Incremental loading of large matrices
//! - Compression and decompression of decomposition results
//! - Cross-platform file format compatibility

#[cfg(feature = "hdf5-support")]
use hdf5::{Dataset, File, Group};
use scirs2_core::ndarray::{Array1, Array2};
use serde::{Deserialize, Serialize};
use sklears_core::{
    error::{Result, SklearsError},
    types::Float,
};
// sprs removed per SciRS2/COOLJAPAN Policy; use scirs2-sparse instead
// #[cfg(feature = "sparse")]
// use sprs::{CsMat, CsMatBase, CsVec, TriMat};
use std::collections::HashMap;
use std::path::Path;

/// Configuration for format support operations
#[derive(Debug, Clone)]
pub struct FormatConfig {
    /// Compression level (0-9, 0 = no compression)
    pub compression_level: u8,
    /// Chunk size for HDF5 operations
    pub chunk_size: Option<(usize, usize)>,
    /// Enable checksums for data integrity
    pub enable_checksums: bool,
    /// Maximum memory usage for operations
    pub max_memory_mb: Option<usize>,
    /// Sparse matrix format preference
    pub preferred_sparse_format: SparseFormat,
}

impl Default for FormatConfig {
    fn default() -> Self {
        Self {
            compression_level: 6,
            chunk_size: Some((1000, 1000)),
            enable_checksums: true,
            max_memory_mb: None,
            preferred_sparse_format: SparseFormat::CSR,
        }
    }
}

/// Supported sparse matrix formats
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SparseFormat {
    /// Coordinate format (COO)
    COO,
    /// Compressed Sparse Row (CSR)
    CSR,
    /// Compressed Sparse Column (CSC)
    CSC,
}

/// HDF5 format support for matrix operations
#[cfg(feature = "hdf5-support")]
#[derive(Default)]
pub struct HDF5Support {
    config: FormatConfig,
}

#[cfg(feature = "hdf5-support")]
impl HDF5Support {
    /// Create new HDF5 support instance
    pub fn new() -> Self {
        Self::default()
    }

    /// Create with custom configuration
    pub fn with_config(config: FormatConfig) -> Self {
        Self { config }
    }

    /// Write matrix to HDF5 file
    pub fn write_matrix<P: AsRef<Path>>(
        &self,
        file_path: P,
        dataset_name: &str,
        matrix: &Array2<Float>,
    ) -> Result<()> {
        let file = File::create(file_path).map_err(|e| {
            SklearsError::InvalidInput(format!("Failed to create HDF5 file: {}", e))
        })?;

        let shape = matrix.shape();
        let dataset = file
            .new_dataset::<Float>()
            .shape(shape)
            .chunk(self.config.chunk_size.unwrap_or((shape[0], shape[1])))
            .deflate(self.config.compression_level)
            .create(dataset_name)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create dataset: {}", e)))?;

        // Convert to standard layout and write
        if matrix.is_standard_layout() {
            let slice = matrix.as_slice().ok_or_else(|| {
                SklearsError::InvalidInput("matrix is not contiguous".to_string())
            })?;
            dataset
                .write(slice)
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to write data: {e}")))?;
        } else {
            let standard_matrix = matrix.to_owned();
            let slice = standard_matrix.as_slice().ok_or_else(|| {
                SklearsError::InvalidInput("matrix copy is not contiguous".to_string())
            })?;
            dataset
                .write(slice)
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to write data: {e}")))?;
        }

        // Add metadata
        self.write_metadata(&dataset, matrix)?;

        Ok(())
    }

    /// Read matrix from HDF5 file
    pub fn read_matrix<P: AsRef<Path>>(
        &self,
        file_path: P,
        dataset_name: &str,
    ) -> Result<Array2<Float>> {
        let file = File::open(file_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to open HDF5 file: {}", e)))?;

        let dataset = file
            .dataset(dataset_name)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to open dataset: {}", e)))?;

        let shape = dataset.shape();
        if shape.len() != 2 {
            return Err(SklearsError::InvalidInput(
                "Dataset must be 2-dimensional".to_string(),
            ));
        }

        // Read as 1D raw vector to avoid ndarray version mismatch
        let data: Vec<Float> = dataset
            .read_raw::<Float>()
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to read data: {}", e)))?;

        Array2::from_shape_vec((shape[0], shape[1]), data)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create array: {}", e)))
    }

    /// Write decomposition results to HDF5 file
    pub fn write_decomposition_results<P: AsRef<Path>>(
        &self,
        file_path: P,
        results: &DecompositionResults,
    ) -> Result<()> {
        let file = File::create(file_path).map_err(|e| {
            SklearsError::InvalidInput(format!("Failed to create HDF5 file: {}", e))
        })?;

        let group = file
            .create_group("decomposition")
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create group: {}", e)))?;

        // Write matrices
        if let Some(ref u) = results.u_matrix {
            self.write_matrix_to_group(&group, "U", u)?;
        }

        if let Some(ref s) = results.singular_values {
            let dataset = group
                .new_dataset::<Float>()
                .shape([s.len()])
                .create("singular_values")
                .map_err(|e| {
                    SklearsError::InvalidInput(format!("Failed to create dataset: {}", e))
                })?;

            let slice = s.as_slice().ok_or_else(|| {
                SklearsError::InvalidInput("singular_values not contiguous".to_string())
            })?;
            dataset
                .write(slice)
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to write data: {e}")))?;
        }

        if let Some(ref vt) = results.vt_matrix {
            self.write_matrix_to_group(&group, "VT", vt)?;
        }

        if let Some(ref components) = results.components {
            self.write_matrix_to_group(&group, "components", components)?;
        }

        if let Some(ref eigenvalues) = results.eigenvalues {
            let dataset = group
                .new_dataset::<Float>()
                .shape([eigenvalues.len()])
                .create("eigenvalues")
                .map_err(|e| {
                    SklearsError::InvalidInput(format!("Failed to create dataset: {}", e))
                })?;

            let ev_slice = eigenvalues.as_slice().ok_or_else(|| {
                SklearsError::InvalidInput("eigenvalues array not contiguous".to_string())
            })?;
            dataset
                .write(ev_slice)
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to write data: {e}")))?;
        }

        // Write metadata
        self.write_decomposition_metadata(&group, results)?;

        Ok(())
    }

    /// Read decomposition results from HDF5 file
    pub fn read_decomposition_results<P: AsRef<Path>>(
        &self,
        file_path: P,
    ) -> Result<DecompositionResults> {
        let file = File::open(file_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to open HDF5 file: {}", e)))?;

        let group = file
            .group("decomposition")
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to open group: {}", e)))?;

        let mut results = DecompositionResults::default();

        // Read matrices if they exist
        if group.link_exists("U") {
            results.u_matrix = Some(self.read_matrix_from_group(&group, "U")?);
        }

        if group.link_exists("singular_values") {
            let dataset = group.dataset("singular_values").map_err(|e| {
                SklearsError::InvalidInput(format!("Failed to open dataset: {}", e))
            })?;

            // Read as raw vector to avoid ndarray version mismatch
            let data: Vec<Float> = dataset
                .read_raw::<Float>()
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to read data: {}", e)))?;

            results.singular_values = Some(Array1::from_vec(data));
        }

        if group.link_exists("VT") {
            results.vt_matrix = Some(self.read_matrix_from_group(&group, "VT")?);
        }

        if group.link_exists("components") {
            results.components = Some(self.read_matrix_from_group(&group, "components")?);
        }

        if group.link_exists("eigenvalues") {
            let dataset = group.dataset("eigenvalues").map_err(|e| {
                SklearsError::InvalidInput(format!("Failed to open dataset: {}", e))
            })?;

            // Read as raw vector to avoid ndarray version mismatch
            let data: Vec<Float> = dataset
                .read_raw::<Float>()
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to read data: {}", e)))?;

            results.eigenvalues = Some(Array1::from_vec(data));
        }

        // Read metadata
        results.metadata = self.read_decomposition_metadata(&group)?;

        Ok(results)
    }

    /// List datasets in HDF5 file
    pub fn list_datasets<P: AsRef<Path>>(&self, file_path: P) -> Result<Vec<String>> {
        let file = File::open(file_path)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to open HDF5 file: {}", e)))?;

        let mut datasets = Vec::new();
        self.collect_datasets(&file, "", &mut datasets)?;

        Ok(datasets)
    }

    // Helper methods
    fn write_matrix_to_group(
        &self,
        group: &Group,
        name: &str,
        matrix: &Array2<Float>,
    ) -> Result<()> {
        let shape = matrix.shape();
        let dataset = group
            .new_dataset::<Float>()
            .shape(shape)
            .chunk(self.config.chunk_size.unwrap_or((shape[0], shape[1])))
            .deflate(self.config.compression_level)
            .create(name)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create dataset: {}", e)))?;

        if matrix.is_standard_layout() {
            let slice = matrix.as_slice().ok_or_else(|| {
                SklearsError::InvalidInput(format!("matrix '{}' not contiguous", name))
            })?;
            dataset
                .write(slice)
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to write data: {e}")))?;
        } else {
            let standard_matrix = matrix.to_owned();
            let slice = standard_matrix.as_slice().ok_or_else(|| {
                SklearsError::InvalidInput(format!("matrix copy '{}' not contiguous", name))
            })?;
            dataset
                .write(slice)
                .map_err(|e| SklearsError::InvalidInput(format!("Failed to write data: {e}")))?;
        }

        Ok(())
    }

    fn read_matrix_from_group(&self, group: &Group, name: &str) -> Result<Array2<Float>> {
        let dataset = group
            .dataset(name)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to open dataset: {}", e)))?;

        let shape = dataset.shape();
        if shape.len() != 2 {
            return Err(SklearsError::InvalidInput(
                "Dataset must be 2-dimensional".to_string(),
            ));
        }

        // Read as 1D raw vector to avoid ndarray version mismatch
        let data: Vec<Float> = dataset
            .read_raw::<Float>()
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to read data: {}", e)))?;

        Array2::from_shape_vec((shape[0], shape[1]), data)
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create array: {}", e)))
    }

    fn write_metadata(&self, dataset: &Dataset, matrix: &Array2<Float>) -> Result<()> {
        // Add matrix metadata as attributes
        let shape = matrix.shape();
        dataset
            .new_attr::<i64>()
            .create("shape")
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to create attribute: {}", e)))?
            .write(&[shape[0] as i64, shape[1] as i64])
            .map_err(|e| SklearsError::InvalidInput(format!("Failed to write attribute: {}", e)))?;

        Ok(())
    }

    fn write_decomposition_metadata(
        &self,
        group: &Group,
        results: &DecompositionResults,
    ) -> Result<()> {
        // Write metadata as attributes
        if let Some(algorithm) = &results.metadata.get("algorithm") {
            group
                .new_attr::<hdf5::types::VarLenAscii>()
                .create("algorithm")
                .map_err(|e| {
                    SklearsError::InvalidInput(format!("Failed to create attribute: {}", e))
                })?
                .write(&[
                    hdf5::types::VarLenAscii::from_ascii(algorithm.as_bytes()).map_err(|e| {
                        SklearsError::InvalidInput(format!("Invalid ASCII in algorithm name: {e}"))
                    })?,
                ])
                .map_err(|e| {
                    SklearsError::InvalidInput(format!("Failed to write attribute: {}", e))
                })?;
        }

        Ok(())
    }

    fn read_decomposition_metadata(&self, _group: &Group) -> Result<HashMap<String, String>> {
        // Read metadata attributes
        let mut metadata = HashMap::new();
        // Simplified metadata reading - in practice would iterate through all attributes
        metadata.insert("format".to_string(), "HDF5".to_string());
        Ok(metadata)
    }

    fn collect_datasets(
        &self,
        _item: &hdf5::Group,
        _prefix: &str,
        _datasets: &mut Vec<String>,
    ) -> Result<()> {
        // Simplified dataset collection - in practice would recursively walk the HDF5 structure
        Ok(())
    }
}

/// Sparse matrix support for efficient decomposition
#[cfg(feature = "sparse")]
#[derive(Default)]
pub struct SparseMatrixSupport {
    config: FormatConfig,
}

#[cfg(feature = "sparse")]
impl SparseMatrixSupport {
    /// Create new sparse matrix support instance
    pub fn new() -> Self {
        Self::default()
    }

    /// Create with custom configuration
    pub fn with_config(config: FormatConfig) -> Self {
        Self { config }
    }

    /// Convert dense matrix to sparse format
    pub fn dense_to_sparse(&self, dense: &Array2<Float>, threshold: Float) -> Result<SparseMatrix> {
        let (rows, cols) = dense.dim();
        let mut row_indices = Vec::new();
        let mut col_indices = Vec::new();
        let mut values = Vec::new();

        for i in 0..rows {
            for j in 0..cols {
                let val = dense[[i, j]];
                if val.abs() > threshold {
                    row_indices.push(i);
                    col_indices.push(j);
                    values.push(val);
                }
            }
        }

        let nnz = values.len();
        let sparsity = 1.0 - (nnz as Float) / ((rows * cols) as Float);

        Ok(SparseMatrix {
            format: self.config.preferred_sparse_format,
            shape: (rows, cols),
            nnz,
            sparsity,
            row_indices,
            col_indices,
            values,
        })
    }

    /// Convert sparse matrix to dense format
    pub fn sparse_to_dense(&self, sparse: &SparseMatrix) -> Result<Array2<Float>> {
        let (rows, cols) = sparse.shape;
        let mut dense = Array2::<Float>::zeros((rows, cols));

        for i in 0..sparse.nnz {
            let row = sparse.row_indices[i];
            let col = sparse.col_indices[i];
            let val = sparse.values[i];
            dense[[row, col]] = val;
        }

        Ok(dense)
    }

    /// Perform sparse matrix multiplication
    pub fn sparse_multiply(&self, a: &SparseMatrix, b: &SparseMatrix) -> Result<SparseMatrix> {
        if a.shape.1 != b.shape.0 {
            return Err(SklearsError::InvalidInput(
                "Matrix dimensions incompatible for multiplication".to_string(),
            ));
        }

        // Simplified sparse matrix multiplication
        // In practice, would use optimized sparse BLAS routines
        let _result_rows = a.shape.0;
        let _result_cols = b.shape.1;

        // Convert to dense for multiplication (not optimal, but functional)
        let dense_a = self.sparse_to_dense(a)?;
        let dense_b = self.sparse_to_dense(b)?;
        let dense_result = dense_a.dot(&dense_b);

        // Convert back to sparse
        self.dense_to_sparse(&dense_result, 1e-12)
    }

    /// Compute sparse SVD using iterative methods
    pub fn sparse_svd(
        &self,
        sparse: &SparseMatrix,
        k: usize,
        max_iter: usize,
    ) -> Result<SparseDecompositionResult> {
        let (m, n) = sparse.shape;
        let min_dim = m.min(n).min(k);

        // Simplified sparse SVD - in practice would use specialized algorithms like ARPACK
        let _dense_matrix = self.sparse_to_dense(sparse)?;

        // Use power iteration for largest singular values
        let u = Array2::<Float>::eye(m);
        let s = Array1::<Float>::ones(min_dim);
        let vt = Array2::<Float>::eye(n);

        // Simplified power iteration (placeholder)
        for _iter in 0..max_iter {
            // Power iteration steps would go here
            // For now, just use identity matrices
        }

        Ok(SparseDecompositionResult {
            u: u.slice(scirs2_core::ndarray::s![.., ..min_dim]).to_owned(),
            singular_values: s,
            vt: vt.slice(scirs2_core::ndarray::s![..min_dim, ..]).to_owned(),
            iterations: max_iter,
            converged: true,
        })
    }

    /// Get sparse matrix statistics
    pub fn get_sparse_stats(&self, sparse: &SparseMatrix) -> SparseStats {
        SparseStats {
            shape: sparse.shape,
            nnz: sparse.nnz,
            sparsity: sparse.sparsity,
            memory_usage_bytes: sparse.memory_usage(),
            format: sparse.format,
        }
    }
}

/// Sparse matrix representation
#[derive(Debug, Clone)]
pub struct SparseMatrix {
    pub format: SparseFormat,
    pub shape: (usize, usize),
    pub nnz: usize,      // Number of non-zero elements
    pub sparsity: Float, // Fraction of zero elements
    pub row_indices: Vec<usize>,
    pub col_indices: Vec<usize>,
    pub values: Vec<Float>,
}

impl SparseMatrix {
    /// Get memory usage in bytes
    pub fn memory_usage(&self) -> usize {
        std::mem::size_of::<Self>()
            + self.row_indices.len() * std::mem::size_of::<usize>()
            + self.col_indices.len() * std::mem::size_of::<usize>()
            + self.values.len() * std::mem::size_of::<Float>()
    }

    /// Get density (opposite of sparsity)
    pub fn density(&self) -> Float {
        1.0 - self.sparsity
    }
}

/// Result from sparse decomposition
#[derive(Debug, Clone)]
pub struct SparseDecompositionResult {
    pub u: Array2<Float>,
    pub singular_values: Array1<Float>,
    pub vt: Array2<Float>,
    pub iterations: usize,
    pub converged: bool,
}

/// Statistics about sparse matrix
#[derive(Debug, Clone)]
pub struct SparseStats {
    pub shape: (usize, usize),
    pub nnz: usize,
    pub sparsity: Float,
    pub memory_usage_bytes: usize,
    pub format: SparseFormat,
}

/// Decomposition results that can be stored in various formats
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DecompositionResults {
    pub u_matrix: Option<Array2<Float>>,
    pub singular_values: Option<Array1<Float>>,
    pub vt_matrix: Option<Array2<Float>>,
    pub components: Option<Array2<Float>>,
    pub eigenvalues: Option<Array1<Float>>,
    pub metadata: HashMap<String, String>,
}

impl DecompositionResults {
    /// Create new empty decomposition results
    pub fn new() -> Self {
        Self::default()
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: String, value: String) -> Self {
        self.metadata.insert(key, value);
        self
    }

    /// Set algorithm name
    pub fn with_algorithm(self, algorithm: &str) -> Self {
        self.with_metadata("algorithm".to_string(), algorithm.to_string())
    }

    /// Check if results contain SVD components
    pub fn has_svd(&self) -> bool {
        self.u_matrix.is_some() && self.singular_values.is_some() && self.vt_matrix.is_some()
    }

    /// Check if results contain PCA components
    pub fn has_pca(&self) -> bool {
        self.components.is_some() && self.eigenvalues.is_some()
    }
}

/// Memory-mapped matrix operations for large datasets
pub struct MemoryMappedMatrix {
    file_path: std::path::PathBuf,
    shape: (usize, usize),
    mmap: memmap2::Mmap,
}

impl MemoryMappedMatrix {
    /// Create memory-mapped matrix from file
    pub fn new<P: AsRef<Path>>(file_path: P, shape: (usize, usize)) -> Result<Self> {
        let path = file_path.as_ref().to_path_buf();
        let file = std::fs::File::open(&path).map_err(|e| {
            SklearsError::InvalidInput(format!("Failed to open file '{}': {}", path.display(), e))
        })?;

        let mmap = unsafe {
            memmap2::MmapOptions::new().map(&file).map_err(|e| {
                SklearsError::InvalidInput(format!(
                    "Failed to memory map file '{}': {}",
                    path.display(),
                    e
                ))
            })?
        };

        // Verify file size matches expected shape
        let expected_size = shape.0 * shape.1 * std::mem::size_of::<Float>();
        if mmap.len() != expected_size {
            return Err(SklearsError::InvalidInput(format!(
                "File '{}' size {} bytes does not match expected matrix dimensions {}x{} ({} bytes)",
                path.display(),
                mmap.len(),
                shape.0,
                shape.1,
                expected_size
            )));
        }

        Ok(Self {
            file_path: path,
            shape,
            mmap,
        })
    }

    /// Get the file path used for this memory-mapped matrix
    pub fn file_path(&self) -> &std::path::Path {
        &self.file_path
    }

    /// Get matrix shape
    pub fn shape(&self) -> (usize, usize) {
        self.shape
    }

    /// Get raw data slice
    pub fn as_slice(&self) -> &[u8] {
        &self.mmap
    }

    /// Read a chunk of the matrix
    pub fn read_chunk(&self, start_row: usize, end_row: usize) -> Result<Array2<Float>> {
        let (total_rows, cols) = self.shape;

        if start_row >= total_rows || end_row > total_rows || start_row >= end_row {
            return Err(SklearsError::InvalidInput(format!(
                "Invalid row range [{}, {}) for file '{}' with {} rows",
                start_row,
                end_row,
                self.file_path.display(),
                total_rows
            )));
        }

        let chunk_rows = end_row - start_row;
        let start_idx = start_row * cols * std::mem::size_of::<Float>();
        let end_idx = end_row * cols * std::mem::size_of::<Float>();

        let chunk_bytes = &self.mmap[start_idx..end_idx];

        // Convert bytes to Float values
        let float_slice = unsafe {
            std::slice::from_raw_parts(
                chunk_bytes.as_ptr() as *const Float,
                chunk_bytes.len() / std::mem::size_of::<Float>(),
            )
        };

        Array2::from_shape_vec((chunk_rows, cols), float_slice.to_vec()).map_err(|e| {
            SklearsError::InvalidInput(format!(
                "Failed to create array from file '{}': {}",
                self.file_path.display(),
                e
            ))
        })
    }
}

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

    #[test]
    fn test_format_config_default() {
        let config = FormatConfig::default();
        assert_eq!(config.compression_level, 6);
        assert!(config.enable_checksums);
        assert_eq!(config.preferred_sparse_format, SparseFormat::CSR);
    }

    #[test]
    fn test_decomposition_results() {
        let results = DecompositionResults::new()
            .with_algorithm("PCA")
            .with_metadata("version".to_string(), "1.0".to_string());

        assert_eq!(results.metadata.get("algorithm"), Some(&"PCA".to_string()));
        assert_eq!(results.metadata.get("version"), Some(&"1.0".to_string()));
        assert!(!results.has_svd());
        assert!(!results.has_pca());
    }

    #[cfg(feature = "sparse")]
    #[test]
    fn test_sparse_matrix_support() {
        let config = FormatConfig::default();
        let sparse_support = SparseMatrixSupport::with_config(config);

        // Create a simple dense matrix
        let dense =
            Array2::from_shape_vec((3, 3), vec![1.0, 0.0, 2.0, 0.0, 0.0, 0.0, 3.0, 0.0, 4.0])
                .expect("operation should succeed");

        // Convert to sparse
        let sparse = sparse_support
            .dense_to_sparse(&dense, 0.5)
            .expect("parsing should succeed");
        assert_eq!(sparse.nnz, 4); // Four non-zero elements
        assert!(sparse.sparsity > 0.0);

        // Convert back to dense
        let reconstructed = sparse_support
            .sparse_to_dense(&sparse)
            .expect("parsing should succeed");
        assert_eq!(reconstructed.shape(), dense.shape());

        // Get statistics
        let stats = sparse_support.get_sparse_stats(&sparse);
        assert_eq!(stats.nnz, 4);
        assert_eq!(stats.shape, (3, 3));
    }

    #[test]
    fn test_sparse_matrix_memory_usage() {
        let sparse = SparseMatrix {
            format: SparseFormat::CSR,
            shape: (1000, 1000),
            nnz: 100,
            sparsity: 0.9999,
            row_indices: vec![0; 100],
            col_indices: vec![0; 100],
            values: vec![1.0; 100],
        };

        let memory_usage = sparse.memory_usage();
        assert!(memory_usage > 0);

        let density = sparse.density();
        assert!((density - 0.0001).abs() < 1e-10);
    }

    #[cfg(feature = "hdf5-support")]
    #[test]
    fn test_hdf5_support_creation() {
        let hdf5_support = HDF5Support::new();
        assert_eq!(hdf5_support.config.compression_level, 6);

        let custom_config = FormatConfig {
            compression_level: 9,
            ..FormatConfig::default()
        };
        let custom_hdf5 = HDF5Support::with_config(custom_config);
        assert_eq!(custom_hdf5.config.compression_level, 9);
    }

    #[test]
    fn test_sparse_format_enum() {
        let formats = vec![SparseFormat::COO, SparseFormat::CSR, SparseFormat::CSC];

        for format in formats {
            match format {
                SparseFormat::COO => assert_eq!(format, SparseFormat::COO),
                SparseFormat::CSR => assert_eq!(format, SparseFormat::CSR),
                SparseFormat::CSC => assert_eq!(format, SparseFormat::CSC),
            }
        }
    }
}