From 9f2d191669f2ba76b45a8203ad642cf879942ab3 Mon Sep 17 00:00:00 2001 From: Josh Garton Date: Wed, 2 Sep 2026 12:12:13 -0500 Subject: [PATCH] Clamp n_pcs to rank so default pipeline does not panic after tight QC. pbmc_1k_v3 at --max-pct-mt 5 kept 21 cells; PCA asked for 50 PCs and indexed OOB. --- src/main.rs | 14 ++++++++++++++ src/pca.rs | 12 +++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 5a66e51..6c83a92 100644 --- a/src/main.rs +++ b/src/main.rs @@ -616,6 +616,16 @@ fn run_pipeline( let kept_var: Vec = kept_genes.iter().map(|&i| var_names[i].clone()).collect(); timings.push(("qc_filter", t0.elapsed().as_secs_f64())); eprintln!("[pipeline] QC: {} cells, {} genes", n_kept, kept_var.len()); + if n_kept < 2 { + anyhow::bail!( + "too few cells after QC ({n_kept}); lower --min-genes or raise --max-pct-mt (default 5.0)" + ); + } + if n_kept < 100 { + eprintln!( + "[pipeline] WARN: only {n_kept} cells after QC; default --max-pct-mt 5.0 is tight on some 10x H5s" + ); + } // Step 3: Normalize (skip if input is already normalized) let normed = if skip_normalize { @@ -667,6 +677,10 @@ fn run_pipeline( ); // Step 6: PCA (on scaled dense matrix) + let n_pcs = n_pcs + .min(n_kept.saturating_sub(1)) + .min(scaled.ncols().saturating_sub(1)) + .max(1); let t0 = Instant::now(); let pca_result = pca::run_pca_scaled( &scaled, diff --git a/src/pca.rs b/src/pca.rs index 2b5ae79..91fe62d 100644 --- a/src/pca.rs +++ b/src/pca.rs @@ -582,7 +582,11 @@ pub fn run_pca_sparse( let total_t0 = Instant::now(); let n_cells = mat.rows(); let n_genes = mat.cols(); - let k = n_components + oversampling; + let n_components = n_components + .min(n_cells.saturating_sub(1)) + .min(n_genes.saturating_sub(1)) + .max(1); + let k = (n_components + oversampling).min(n_genes).min(n_cells); eprintln!( "[pca-sparse] {}x{} matrix, {} components, {} power iterations", @@ -626,6 +630,7 @@ pub fn run_pca_sparse( // Convert to f64 flat for small_svd (reuse existing dense SVD) let k_actual = k.min(n_genes).min(n_cells); + let n_components = n_components.min(k_actual).max(1); let mut b_flat = vec![0.0f64; k_actual * n_genes]; for i in 0..k_actual { for j in 0..n_genes { @@ -735,6 +740,10 @@ pub fn run_pca_scaled( let total_t0 = Instant::now(); let n_cells = scaled.nrows(); let n_genes = scaled.ncols(); + let n_components = n_components + .min(n_cells.saturating_sub(1)) + .min(n_genes.saturating_sub(1)) + .max(1); let k = (n_components + oversampling).min(n_genes).min(n_cells); eprintln!( @@ -778,6 +787,7 @@ pub fn run_pca_scaled( // Convert to f64 flat for small_svd let k_actual = k.min(n_genes).min(n_cells); + let n_components = n_components.min(k_actual).max(1); let mut b_flat = vec![0.0f64; k_actual * n_genes]; for i in 0..k_actual { for j in 0..n_genes {