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
//! # Principal Component Analysis (PCA) for Single-Cell Data
//!
//! This module provides high-performance PCA implementation optimized for single-cell RNA-seq data.
//! PCA is a fundamental dimensionality reduction technique that identifies the directions of maximum
//! variance in high-dimensional data.
//!
//! ## Overview
//!
//! PCA transforms the original gene expression space into a new coordinate system where:
//! - The first principal component captures the most variance
//! - Each subsequent component captures the most remaining variance
//! - Components are orthogonal (uncorrelated) to each other
//!
//! ## Key Features
//!
//! - **Sparse Matrix Support**: Optimized for sparse single-cell expression matrices
//! - **Feature Selection Integration**: Works with highly variable genes or custom gene selections
//! - **Multiple SVD Methods**: Choice of SVD algorithms for different performance characteristics
//! - **Memory Efficient**: Handles large datasets without excessive memory usage
//! - **Configurable Centering**: Option to center data (recommended for most analyses)
//!
//! ## When to Use PCA
//!
//! ✅ **Good for:**
//! - Initial exploration of dataset structure
//! - Noise reduction before clustering
//! - Input for other dimensionality reduction methods (t-SNE, UMAP)
//! - Quality control and batch effect detection
//! - Identifying major sources of variation
//!
//! ⚠️ **Limitations:**
//! - Linear method - may not capture complex non-linear relationships
//! - First components may be dominated by technical effects
//! - Interpretation can be challenging with many genes
//!
//! ## Typical Workflow
//!
//! ```rust,ignore
//! use single_rust::memory::processing::dimred::pca::run_pca_sparse_masked;
//! use single_rust::memory::processing::dimred::FeatureSelectionMethod;
//! use single_algebra::dimred::pca::SVDMethod;
//!
//! // 1. Select highly variable genes
//! let hvg_mask = compute_highly_variable_genes(&adata, None)?;
//! let feature_selection = FeatureSelectionMethod::HighlyVariableSelection(hvg_mask);
//!
//! // 2. Run PCA with 50 components
//! let pca_result = run_pca_sparse_masked::<f64>(
//! &adata.x(),
//! Some(feature_selection),
//! Some(true), // Center the data
//! Some(false), // Verbose output
//! Some(50), // Number of components
//! Some(1.0), // Regularization parameter
//! Some(42), // Random seed for reproducibility
//! Some(SVDMethod::Randomized), // Fast randomized SVD
//! )?;
//!
//! // 3. Access results
//! let embeddings = pca_result.transformed; // Cell embeddings in PC space
//! let variance_explained = pca_result.explained_variance_ratio; // Variance per component
//! let loadings = pca_result.feature_importance; // Gene loadings/weights
//! ```
use crateFeatureSelectionMethod;
use crate;
use DynCsrMatrix;
use ArrayData;
use IMArrayElement;
use anyhow;
use ;
use Uniform;
use Distribution;
use rng;
use ;
use FloatOpsTS;
use Deref;
/// Results from Principal Component Analysis.
///
/// Contains all the essential outputs from PCA analysis including the transformed data,
/// variance explained by each component, and feature importance scores.
///
/// ## Fields
///
/// - `transformed`: Cell embeddings in the principal component space (cells × components)
/// - `explained_variance_ratio`: Fraction of total variance explained by each component
/// - `cumulative_explained_variance_ratio`: Cumulative variance explained up to each component
/// - `feature_importance`: Gene loadings/weights for each component (genes × components)
///
/// ## Usage
///
/// ```rust,ignore
/// let pca_result = run_pca_sparse_masked(&matrix, ...)?;
///
/// // Get embeddings for visualization or clustering
/// let embeddings = pca_result.transformed;
///
/// // Check how much variance is captured
/// let total_variance = pca_result.cumulative_explained_variance_ratio[[49]]; // 50th component
///
/// // Find important genes for first component
/// let pc1_loadings = pca_result.feature_importance.column(0);
/// ```
/// Perform Principal Component Analysis on sparse single-cell expression data.
///
/// This function provides a comprehensive PCA implementation optimized for single-cell data,
/// with support for feature selection, sparse matrices, and various SVD algorithms.
///
/// ## Algorithm Details
///
/// The implementation uses efficient sparse matrix operations and supports multiple SVD methods:
/// - **Randomized SVD**: Fast approximation, good for large datasets
/// - **Full SVD**: Exact computation, slower but more accurate
/// - **Truncated SVD**: Memory efficient for large matrices
///
/// ## Parameters
///
/// * `matrix` - The expression matrix (cells × genes) as IMArrayElement
/// * `feature_selection_method` - Method for selecting genes (HVGs recommended)
/// * `center` - Whether to center the data (recommended: true)
/// * `verbose` - Enable verbose output for debugging
/// * `n_components` - Number of principal components to compute (default: 50)
/// * `alpha` - Regularization parameter for numerical stability (default: 1.0)
/// * `random_seed` - Seed for reproducible results (default: 42)
/// * `svd_method` - SVD algorithm to use (default: Randomized)
///
/// ## Returns
///
/// Returns a `PCAResult` containing:
/// - Transformed cell embeddings
/// - Variance explained by each component
/// - Feature importance/loading scores
///
/// ## Examples
///
/// ### Basic Usage
/// ```rust,ignore
/// // Simple PCA with default parameters
/// let result = run_pca_sparse_masked::<f64>(
/// &adata.x(),
/// None, // Use default random selection
/// Some(true), // Center the data
/// None, // No verbose output
/// Some(50), // 50 components
/// None, // Default alpha
/// None, // Default seed
/// None, // Default SVD method
/// )?;
/// ```
///
/// ### Advanced Usage with HVGs
/// ```rust,ignore
/// // PCA using highly variable genes
/// let hvg_mask = compute_highly_variable_genes(&adata, None)?;
/// let feature_selection = FeatureSelectionMethod::HighlyVariableSelection(hvg_mask);
///
/// let result = run_pca_sparse_masked::<f64>(
/// &adata.x(),
/// Some(feature_selection),
/// Some(true), // Center for better component interpretation
/// Some(false), // Quiet mode
/// Some(30), // Fewer components for speed
/// Some(0.1), // Higher regularization
/// Some(123), // Custom seed
/// Some(SVDMethod::Randomized), // Fast approximation
/// )?;
/// ```
///
/// ## Performance Considerations
///
/// - **Feature Selection**: Using 1000-5000 highly variable genes typically optimal
/// - **Components**: 30-50 components usually capture most biological variation
/// - **SVD Method**: Randomized SVD recommended for >10,000 cells
/// - **Centering**: Essential for proper component interpretation but increases memory usage
///
/// ## Errors
///
/// Returns error if:
/// - Matrix format is not supported (only CSR matrices supported)
/// - Data type is not F32 or F64
/// - Feature selection mask length doesn't match number of genes
/// - SVD computation fails (e.g., insufficient rank)
/// Generate a random boolean mask for gene selection.
///
/// Creates a boolean vector where `num_random_selection` randomly chosen positions
/// are set to `true`, and all others are `false`. This is used for benchmarking
/// and testing purposes when you want to select a random subset of genes.
///
/// ## Parameters
///
/// * `n_genes` - Total number of genes in the dataset
/// * `num_random_selection` - Number of genes to randomly select
///
/// ## Returns
///
/// Boolean vector of length `n_genes` with exactly `num_random_selection` true values
/// at random positions.
///
/// ## Note
///
/// This function uses the default random number generator. For reproducible results,
/// set the global random seed before calling, or consider using the `random_seed`
/// parameter in `run_pca_sparse_masked`.
///
/// ## Example
///
/// ```rust,ignore
/// // Select 2000 random genes from 20000 total genes
/// let mask = generate_random_mask(20000, 2000);
/// assert_eq!(mask.len(), 20000);
/// assert_eq!(mask.iter().filter(|&&x| x).count(), 2000);
/// ```