1use crate::qc::{collect_column_stat_across_vec, masked_column_stat};
8use crate::sparse_data_visitors::VisitColumnsOps;
9use crate::sparse_io_stack::SparseIoStack;
10use crate::sparse_io_vector::SparseIoVec;
11use legume_numeric::matrix::common_io::write_lines;
12pub use legume_numeric::matrix::robust_band::{robust_band, robust_outlier_keep, RobustBand, Tail};
13use legume_numeric::matrix::sparse_stat::{SparseColumnRunningStatistics, SparseRunningStatistics};
14use legume_numeric::matrix::traits::RunningStatOps;
15use log::warn;
16use regex::Regex;
17use std::sync::{Arc, Mutex};
18
19#[derive(Clone, Debug)]
38pub struct QcConfig {
39 pub n_mads: f32,
41 pub min_cell_nnz: usize,
45 pub min_counts_per_cell: f32,
47 pub mito_pattern: Option<String>,
50 pub mito_max_frac: Option<f32>,
52 pub ribo_pattern: Option<String>,
54 pub ribo_max_frac: Option<f32>,
56 pub mad_on_n_genes: bool,
58 pub mad_on_counts: bool,
59 pub mad_on_mito: bool,
60 pub feature_min_cells: usize,
63 pub drop_outliers: bool,
67 pub auto_cell_cutoff: bool,
77 pub qc_histogram: bool,
80}
81
82impl Default for QcConfig {
83 fn default() -> Self {
84 Self {
85 n_mads: 5.0,
86 min_cell_nnz: 2,
87 min_counts_per_cell: 0.0,
88 mito_pattern: None,
89 mito_max_frac: None,
90 ribo_pattern: None,
91 ribo_max_frac: None,
92 mad_on_n_genes: true,
93 mad_on_counts: true,
94 mad_on_mito: false,
95 feature_min_cells: 0,
96 drop_outliers: true,
97 auto_cell_cutoff: false,
98 qc_histogram: false,
99 }
100 }
101}
102
103pub fn resolve_rows_by_regex(row_names: &[Box<str>], pattern: &str) -> anyhow::Result<Vec<usize>> {
107 let re = Regex::new(pattern)?;
108 Ok(row_names
109 .iter()
110 .enumerate()
111 .filter(|(_, name)| re.is_match(name))
112 .map(|(i, _)| i)
113 .collect())
114}
115
116pub struct QcReport {
118 pub train_keep: Vec<bool>,
121 pub near_empty: Vec<bool>,
124 pub feature_keep: Vec<bool>,
127 pub n_genes: Vec<f32>,
128 pub total_counts: Vec<f32>,
129 pub mito_frac: Option<Vec<f32>>,
130 pub ribo_frac: Option<Vec<f32>>,
131 pub n_cells_dropped: usize,
132 pub n_features_dropped: usize,
133}
134
135impl QcReport {
136 pub fn output_keep_idx(&self) -> Vec<usize> {
141 let mut idx = Vec::new();
142 let mut new_pos = 0usize;
143 for c in 0..self.train_keep.len() {
144 if !self.train_keep[c] {
145 continue; }
147 if !self.near_empty[c] {
148 idx.push(new_pos); }
150 new_pos += 1;
151 }
152 idx
153 }
154
155 pub fn emit_idx_unmasked(&self) -> Vec<usize> {
160 (0..self.train_keep.len())
161 .filter(|&c| self.train_keep[c] && !self.near_empty[c])
162 .collect()
163 }
164}
165
166pub fn compute_qc(
169 data: &SparseIoVec,
170 cfg: &QcConfig,
171 block_size: Option<usize>,
172) -> anyhow::Result<QcReport> {
173 compute_qc_exempting(data, cfg, block_size, None)
174}
175
176pub fn compute_qc_exempting(
180 data: &SparseIoVec,
181 cfg: &QcConfig,
182 block_size: Option<usize>,
183 exempt: Option<&[bool]>,
184) -> anyhow::Result<QcReport> {
185 let m = compute_qc_metrics(data, cfg, block_size, cfg.feature_min_cells > 0)?;
186 Ok(qc_from_metrics(m, cfg, exempt))
187}
188
189pub fn compute_qc_metrics(
195 data: &SparseIoVec,
196 cfg: &QcConfig,
197 block_size: Option<usize>,
198 feature_cells: bool,
199) -> anyhow::Result<QcMetrics> {
200 let row_names = data.row_names()?;
201
202 let rows_for = |pattern: &Option<String>| -> anyhow::Result<Option<Vec<usize>>> {
204 let Some(pat) = pattern else {
205 return Ok(None);
206 };
207 let rows = resolve_rows_by_regex(&row_names, pat)?;
208 if rows.is_empty() {
209 warn!(
210 "QC: pattern `{}` matched no features — metric disabled",
211 pat
212 );
213 return Ok(None);
214 }
215 Ok(Some(rows))
216 };
217 let mito_rows = rows_for(&cfg.mito_pattern)?;
218 let ribo_rows = rows_for(&cfg.ribo_pattern)?;
219 let subsets: Vec<&[usize]> = [&mito_rows, &ribo_rows]
220 .into_iter()
221 .filter_map(|rows| rows.as_deref())
222 .collect();
223
224 let stat = collect_qc_stat(data, &subsets, feature_cells, block_size)?;
229 let n_genes = stat.columns.count_positives();
230 let total_counts = stat.columns.sum();
231
232 let mut subset_totals = stat.subsets.iter().map(|s| s.sum());
234 let mut frac_for = |rows: &Option<Vec<usize>>| -> Option<Vec<f32>> {
235 rows.as_ref()?;
236 let sub_tot = subset_totals.next()?;
237 Some(
238 sub_tot
239 .iter()
240 .zip(total_counts.iter())
241 .map(|(&s, &t)| if t > 0.0 { s / t } else { 0.0 })
242 .collect(),
243 )
244 };
245 let mito_frac = frac_for(&mito_rows);
246 let ribo_frac = frac_for(&ribo_rows);
247
248 let feature_n_cells = stat.rows.map(|rows| rows.count_positives());
249
250 Ok(QcMetrics {
251 n_genes,
252 total_counts,
253 mito_frac,
254 ribo_frac,
255 feature_n_cells,
256 n_rows: data.num_rows(),
257 })
258}
259
260struct QcStat {
262 columns: SparseColumnRunningStatistics<f32>,
264 subsets: Vec<SparseColumnRunningStatistics<f32>>,
266 rows: Option<SparseRunningStatistics<f32>>,
268}
269
270fn collect_qc_stat(
275 data: &SparseIoVec,
276 row_subsets: &[&[usize]],
277 with_rows: bool,
278 block_size: Option<usize>,
279) -> anyhow::Result<QcStat> {
280 let ncols = data.num_columns();
281 let nrows = data.num_rows();
282
283 let (masks, subsets): (Vec<Vec<bool>>, Vec<_>) = row_subsets
284 .iter()
285 .map(|sel| masked_column_stat(ncols, nrows, sel))
286 .unzip();
287 let mut stat = QcStat {
288 columns: SparseColumnRunningStatistics::new(ncols, nrows),
289 subsets,
290 rows: with_rows.then(|| SparseRunningStatistics::new(nrows)),
291 };
292 data.visit_columns_by_block(&qc_stat_visitor, &masks, &mut stat, block_size)?;
293 Ok(stat)
294}
295
296fn qc_stat_visitor(
297 job: (usize, usize),
298 data: &SparseIoVec,
299 masks: &Vec<Vec<bool>>,
300 arc_stat: Arc<Mutex<&mut QcStat>>,
301) -> anyhow::Result<()> {
302 let (lb, ub) = job;
303 let csc = data.read_columns_csc(lb..ub)?;
304 let mut stat = arc_stat.lock().expect("failed to lock qc stat");
305 stat.columns.add_csc(&csc, lb);
306 for (sub, mask) in stat.subsets.iter_mut().zip(masks) {
307 sub.add_csc_masked(&csc, lb, mask);
308 }
309 if let Some(rows) = stat.rows.as_mut() {
310 rows.add_csc(&csc);
311 }
312 Ok(())
313}
314
315pub fn compute_qc_stack(
320 stack: &SparseIoStack,
321 cfg: &QcConfig,
322 block_size: Option<usize>,
323) -> anyhow::Result<QcReport> {
324 let n_cols = stack.num_columns()?;
325 let mut n_genes = vec![0f32; n_cols];
326 let mut total_counts = vec![0f32; n_cols];
327 for member in stack.stack.iter() {
328 let cs = collect_column_stat_across_vec(member, None, block_size)?;
329 let ng = cs.count_positives();
330 let ct = cs.sum();
331 for c in 0..n_cols {
332 n_genes[c] += ng[c];
333 total_counts[c] += ct[c];
334 }
335 }
336 if cfg.mito_pattern.is_some() || cfg.ribo_pattern.is_some() || cfg.feature_min_cells > 0 {
337 warn!("QC: mito/ribo/feature thresholds are ignored for stacked (multi-modal) data");
338 }
339 Ok(qc_from_metrics(
340 QcMetrics {
341 n_genes,
342 total_counts,
343 mito_frac: None,
344 ribo_frac: None,
345 feature_n_cells: None,
346 n_rows: 0, },
348 cfg,
349 None,
350 ))
351}
352
353#[derive(Clone, Debug)]
356pub struct QcMetrics {
357 pub n_genes: Vec<f32>,
358 pub total_counts: Vec<f32>,
359 pub mito_frac: Option<Vec<f32>>,
360 pub ribo_frac: Option<Vec<f32>>,
361 pub feature_n_cells: Option<Vec<f32>>,
363 pub n_rows: usize,
364}
365
366#[derive(Clone, Debug, PartialEq, Eq)]
369pub struct Verdicts {
370 pub train_keep: Vec<bool>,
371 pub near_empty: Vec<bool>,
372 pub feature_keep: Vec<bool>,
373 pub n_cells_dropped: usize,
374 pub n_features_dropped: usize,
375 pub guarded: bool,
378}
379
380impl Verdicts {
381 pub fn emitted(&self, c: usize) -> bool {
384 self.train_keep[c] && !self.near_empty[c]
385 }
386}
387
388fn qc_from_metrics(m: QcMetrics, cfg: &QcConfig, exempt: Option<&[bool]>) -> QcReport {
399 if cfg.drop_outliers && (cfg.auto_cell_cutoff || cfg.qc_histogram) {
401 let cells = cell_values(&m.n_genes, exempt);
403 let suggested = crate::qc::suggest_nnz_cutoff(&cells);
404 let shown = suggested.unwrap_or(cfg.min_cell_nnz);
407 crate::qc::eprint_nnz_summary("Cell", "nnz", &cells, shown, suggested);
408 }
409 let v = cell_verdicts(&m, cfg, exempt);
410 let QcMetrics {
411 n_genes,
412 total_counts,
413 mito_frac,
414 ribo_frac,
415 ..
416 } = m;
417 QcReport {
418 train_keep: v.train_keep,
419 near_empty: v.near_empty,
420 feature_keep: v.feature_keep,
421 n_genes,
422 total_counts,
423 mito_frac,
424 ribo_frac,
425 n_cells_dropped: v.n_cells_dropped,
426 n_features_dropped: v.n_features_dropped,
427 }
428}
429
430fn cell_values<'a>(values: &'a [f32], exempt: Option<&[bool]>) -> std::borrow::Cow<'a, [f32]> {
433 match exempt {
434 Some(e) => values
435 .iter()
436 .zip(e)
437 .filter(|&(_, &x)| !x)
438 .map(|(&v, _)| v)
439 .collect(),
440 None => values.into(),
441 }
442}
443
444pub fn qc_report(m: QcMetrics, cfg: &QcConfig) -> QcReport {
447 qc_from_metrics(m, cfg, None)
448}
449
450pub fn cell_verdicts(m: &QcMetrics, cfg: &QcConfig, exempt: Option<&[bool]>) -> Verdicts {
455 verdicts(m, cfg, exempt, true)
456}
457
458pub(crate) fn cell_verdicts_quiet(m: &QcMetrics, cfg: &QcConfig) -> Verdicts {
461 verdicts(m, cfg, None, false)
462}
463
464fn verdicts(m: &QcMetrics, cfg: &QcConfig, exempt: Option<&[bool]>, warn: bool) -> Verdicts {
465 let QcMetrics {
466 n_genes,
467 total_counts,
468 mito_frac,
469 ribo_frac,
470 feature_n_cells,
471 n_rows,
472 } = m;
473 let n_rows = *n_rows;
474 let n_cols = n_genes.len();
475
476 let is_exempt = |c: usize| exempt.is_some_and(|e| e[c]);
477
478 let near_empty: Vec<bool> = n_genes
480 .iter()
481 .enumerate()
482 .map(|(c, &g)| !is_exempt(c) && (g as usize) < cfg.min_cell_nnz)
483 .collect();
484
485 let not_near_empty: Vec<bool> = near_empty
489 .iter()
490 .enumerate()
491 .map(|(c, &e)| !e && !is_exempt(c))
492 .collect();
493 let consider = Some(not_near_empty.as_slice());
494 let mut outlier = vec![false; n_cols];
495 if cfg.drop_outliers {
496 let mut bands: Vec<Vec<bool>> = Vec::new();
497 if cfg.mad_on_n_genes {
498 bands.push(robust_outlier_keep(
499 n_genes,
500 cfg.n_mads,
501 Tail::Lower,
502 true,
503 consider,
504 ));
505 }
506 if cfg.mad_on_counts {
507 bands.push(robust_outlier_keep(
508 total_counts,
509 cfg.n_mads,
510 Tail::Lower,
511 true,
512 consider,
513 ));
514 }
515 if cfg.mad_on_mito {
516 if let Some(mf) = mito_frac.as_ref() {
517 bands.push(robust_outlier_keep(
518 mf,
519 cfg.n_mads,
520 Tail::Upper,
521 false,
522 consider,
523 ));
524 }
525 }
526 for c in 0..n_cols {
527 if near_empty[c] || is_exempt(c) {
528 continue; }
530 let mut fail = total_counts[c] < cfg.min_counts_per_cell;
531 if let (Some(mf), Some(cap)) = (mito_frac.as_ref(), cfg.mito_max_frac) {
532 fail |= mf[c] > cap;
533 }
534 if let (Some(rf), Some(cap)) = (ribo_frac.as_ref(), cfg.ribo_max_frac) {
535 fail |= rf[c] > cap;
536 }
537 for band in bands.iter() {
538 if !band[c] {
539 fail = true;
540 break;
541 }
542 }
543 outlier[c] = fail;
544 }
545
546 if cfg.auto_cell_cutoff {
555 if let Some(cut) = crate::qc::suggest_nnz_cutoff(&cell_values(n_genes, exempt)) {
556 for (c, &g) in n_genes.iter().enumerate() {
557 if !is_exempt(c) && (g as usize) < cut {
558 outlier[c] = true;
559 }
560 }
561 }
562 }
563 }
564
565 let mut train_keep: Vec<bool> = outlier.iter().map(|&o| !o).collect();
566 let mut n_cells_dropped = outlier.iter().filter(|&&o| o).count();
567
568 let n_cells = (0..n_cols).filter(|&c| !is_exempt(c)).count();
571 let mut guarded = false;
572 if n_cells > 0 && n_cells_dropped >= n_cells {
573 if warn {
574 warn!(
575 "QC would drop all {} cells — keeping all (check thresholds)",
576 n_cells
577 );
578 }
579 train_keep = vec![true; n_cols];
580 n_cells_dropped = 0;
581 guarded = true;
582 }
583 let emits = |c: usize| !is_exempt(c) && train_keep[c] && !near_empty[c];
586 if warn && n_cells > 0 && !(0..n_cols).any(emits) {
587 warn!(
588 "QC leaves none of the {} cells in the output: each is near-empty \
589 (fewer than {} detected features) or dropped (check thresholds)",
590 n_cells, cfg.min_cell_nnz
591 );
592 }
593
594 let (feature_keep, n_features_dropped) = match feature_n_cells {
596 Some(n_cells_expr) => {
597 let keep: Vec<bool> = n_cells_expr
598 .iter()
599 .map(|&c| (c as usize) >= cfg.feature_min_cells)
600 .collect();
601 let dropped = keep.iter().filter(|&&k| !k).count();
602 if !keep.is_empty() && dropped >= keep.len() {
603 if warn {
604 warn!("QC would drop all features — keeping all");
605 }
606 guarded = true;
607 (vec![true; keep.len()], 0)
608 } else {
609 (keep, dropped)
610 }
611 }
612 None => (vec![true; n_rows], 0),
613 };
614
615 Verdicts {
616 train_keep,
617 near_empty,
618 feature_keep,
619 n_cells_dropped,
620 n_features_dropped,
621 guarded,
622 }
623}
624
625pub fn filter_by_keep<T: Clone>(items: &[T], keep: &[bool]) -> Vec<T> {
628 items
629 .iter()
630 .zip(keep.iter())
631 .filter(|&(_, &k)| k)
632 .map(|(x, _)| x.clone())
633 .collect()
634}
635
636pub fn write_qc_report(
639 path: &str,
640 cell_names: &[Box<str>],
641 report: &QcReport,
642) -> anyhow::Result<()> {
643 use std::fmt::Write as _;
644 let n = report.train_keep.len();
645 anyhow::ensure!(
646 cell_names.len() == n,
647 "write_qc_report: {} names != {} cells",
648 cell_names.len(),
649 n
650 );
651
652 let mut header = String::from("#cell\tn_genes\ttotal_counts");
653 if report.mito_frac.is_some() {
654 header.push_str("\tmito_frac");
655 }
656 if report.ribo_frac.is_some() {
657 header.push_str("\tribo_frac");
658 }
659 header.push_str("\tnear_empty\ttrain_keep");
660
661 let mut lines: Vec<Box<str>> = Vec::with_capacity(n + 1);
662 lines.push(header.into_boxed_str());
663 for c in 0..n {
664 let mut line = String::new();
665 let _ = write!(
666 line,
667 "{}\t{}\t{}",
668 cell_names[c], report.n_genes[c], report.total_counts[c]
669 );
670 if let Some(mf) = report.mito_frac.as_ref() {
671 let _ = write!(line, "\t{}", mf[c]);
672 }
673 if let Some(rf) = report.ribo_frac.as_ref() {
674 let _ = write!(line, "\t{}", rf[c]);
675 }
676 let _ = write!(
677 line,
678 "\t{}\t{}",
679 report.near_empty[c] as u8, report.train_keep[c] as u8
680 );
681 lines.push(line.into_boxed_str());
682 }
683 write_lines(&lines, path)
684}
685
686#[derive(clap::Args, Debug, Clone, serde::Serialize, serde::Deserialize)]
699#[serde(default = "legume_numeric::matrix::clap_defaults::clap_defaults")]
700pub struct QcArgs {
701 #[arg(
703 long = "no-qc",
704 default_value_t = false,
705 long_help = "Disable cell quality control entirely and keep every input cell.\n\
706 \n\
707 By DEFAULT (without this flag) cell QC is:\n \
708 - a near-empty nnz floor (--qc-min-cell-nnz), and\n \
709 - MAD-outlier drops on detected features and total counts\n \
710 (--qc-mad-on-genes / --qc-mad-on-counts, band --qc-mads).\n\
711 \n\
712 Empty barcodes are dropped earlier, per input file, by the loader.\n\
713 A pooled trough cut on top of that stays OFF unless --qc-auto-cutoff.\n\
714 \n\
715 Outputs may therefore have FEWER ROWS than the input.\n\
716 Join by the cell/barcode name column, never by position.\n\
717 \n\
718 Use --qc-report to see exactly what was dropped.\n\
719 For the older near-empty-floor-only gate,\n\
720 pass `--qc-mad-on-genes=false --qc-mad-on-counts=false`."
721 )]
722 pub no_qc: bool,
723
724 #[arg(long = "qc-mads", default_value_t = 5.0)]
726 pub qc_mads: f32,
727
728 #[arg(
729 long = "qc-min-cell-nnz",
730 default_value_t = 2,
731 help = "Near-empty floor on a cell's detected-feature count",
732 long_help = "Near-empty floor on the detected-feature count.\n\
733 Cells below it are dropped from the per-cell outputs.\n\
734 They are still kept in training."
735 )]
736 pub qc_min_cell_nnz: usize,
737
738 #[arg(
739 long = "qc-min-counts",
740 hide = true,
741 default_value_t = 0.0,
742 help = "Hard floor on total counts per cell",
743 long_help = "Hard floor on total counts per cell.\n\
744 Cells below it are dropped from training. 0 disables the floor."
745 )]
746 pub qc_min_counts: f32,
747
748 #[arg(
749 long = "qc-mito-pattern",
750 hide = true,
751 help = "Regex over feature names selecting mitochondrial genes",
752 long_help = "Regex over feature names selecting mitochondrial genes.\n\
753 It enables the mito-fraction outlier metric. An example is `(?i)^MT-`."
754 )]
755 pub qc_mito_pattern: Option<String>,
756
757 #[arg(long = "qc-mito-max-frac", hide = true)]
759 pub qc_mito_max_frac: Option<f32>,
760
761 #[arg(long = "qc-ribo-pattern", hide = true)]
763 pub qc_ribo_pattern: Option<String>,
764
765 #[arg(long = "qc-ribo-max-frac", hide = true)]
767 pub qc_ribo_max_frac: Option<f32>,
768
769 #[arg(
770 long = "qc-feature-min-cells",
771 hide = true,
772 default_value_t = 0,
773 help = "Feature/row QC: drop genes expressed in too few cells",
774 long_help = "Feature/row QC; off by default.\n\
775 It DROPS gene rows expressed in fewer than this many cells.\n\
776 \n\
777 Not every consumer applies it.\n\
778 `bge` does not, since QC there is cell-only.\n\
779 `pinto` does not either: it reads only the cell verdict,\n\
780 so setting this costs a stats pass and changes nothing."
781 )]
782 pub qc_feature_min_cells: usize,
783
784 #[arg(
785 long = "qc-report",
786 help = "Write a per-cell QC table (.tsv)",
787 long_help = "Write a per-cell QC table, as .tsv.\n\
788 It carries the metrics plus near_empty and train_keep flags.\n\
789 You can then see exactly which cells were dropped."
790 )]
791 pub qc_report: Option<Box<str>>,
792
793 #[arg(
794 long = "qc-histogram",
795 hide = true,
796 default_value_t = false,
797 help = "Print the per-cell nnz histogram + the (diagnostic) suggested trough cutoff",
798 long_help = "Print an ASCII histogram of the per-cell nnz distribution.\n\
799 The suggested trough cutoff is marked.\n\
800 It is the same summary as `data-beans squeeze --show-histogram`.\n\
801 \n\
802 This is purely diagnostic. The cutoff is shown, not applied.\n\
803 The upfront gate is the conservative --qc-min-cell-nnz floor.\n\
804 Use the histogram to pick --qc-min-cell-nnz by hand."
805 )]
806 pub qc_histogram: bool,
807
808 #[arg(
809 long = "qc-mad-on-genes",
810 hide = true,
811 action = clap::ArgAction::Set,
813 num_args = 0..=1,
814 require_equals = true,
815 default_missing_value = "true",
816 default_value_t = true,
817 help = "MAD-outlier drop on the per-cell detected-feature count",
818 long_help = "Drop cells whose detected-feature count falls outside `median +/- --qc-mads * MAD * 1.4826`.\n\
819 \n\
820 ON by default. This and --qc-mad-on-counts were previously hardcoded OFF,\n\
821 with no way to enable them. That also made --qc-mads inert.\n\
822 Only a set --qc-mito-pattern revived it.\n\
823 \n\
824 Pass `--qc-mad-on-genes=false` for the old behaviour.\n\
825 That is the conservative near-empty nnz gate alone."
826 )]
827 pub qc_mad_on_genes: bool,
828
829 #[arg(
830 long = "qc-mad-on-counts",
831 hide = true,
832 action = clap::ArgAction::Set,
834 num_args = 0..=1,
835 require_equals = true,
836 default_missing_value = "true",
837 default_value_t = true,
838 help = "MAD-outlier drop on per-cell total counts",
839 long_help = "Drop cells whose total count falls outside `median +/- --qc-mads * MAD * 1.4826`.\n\
840 ON by default; see --qc-mad-on-genes."
841 )]
842 pub qc_mad_on_counts: bool,
843
844 #[arg(
845 long = "qc-mad-on-mito",
846 hide = true,
847 action = clap::ArgAction::Set,
849 num_args = 0..=1,
850 require_equals = true,
851 default_missing_value = "true",
852 default_value_t = true,
853 help = "MAD-outlier drop on the mito fraction, given --qc-mito-pattern",
854 long_help = "Drop cells whose mito fraction is above `median + --qc-mads * MAD * 1.4826`.\n\
855 On whenever --qc-mito-pattern is given. `--qc-mad-on-mito=false` leaves\n\
856 only the hard cap, --qc-mito-max-frac, when one is given."
857 )]
858 pub qc_mad_on_mito: bool,
859
860 #[arg(
861 long = "qc-auto-cutoff",
862 hide = true,
863 default_value_t = false,
864 help = "Apply the nnz trough cell-calling cutoff on the pooled cell axis",
865 long_help = "Apply the ambient/cell trough cutoff as a hard cell call.\n\
866 It runs on the pooled per-cell nnz distribution, after the loader's per-file gate.\n\
867 Without this flag it is only reported, via --qc-histogram.\n\
868 \n\
869 OFF by default. The intended gate is the conservative near-empty floor,\n\
870 plus the model's own empty-call.\n\
871 This flag was referenced in the docs before it existed."
872 )]
873 pub qc_auto_cutoff: bool,
874}
875
876impl QcArgs {
877 pub fn to_config(&self) -> Option<QcConfig> {
879 (!self.no_qc).then(|| QcConfig {
880 n_mads: self.qc_mads,
881 min_cell_nnz: self.qc_min_cell_nnz,
882 min_counts_per_cell: self.qc_min_counts,
883 mito_pattern: self.qc_mito_pattern.clone().filter(|p| !p.is_empty()),
886 mito_max_frac: self.qc_mito_max_frac,
887 ribo_pattern: self.qc_ribo_pattern.clone().filter(|p| !p.is_empty()),
888 ribo_max_frac: self.qc_ribo_max_frac,
889 mad_on_n_genes: self.qc_mad_on_genes,
895 mad_on_counts: self.qc_mad_on_counts,
896 mad_on_mito: self
897 .qc_mito_pattern
898 .as_deref()
899 .is_some_and(|p| !p.is_empty())
900 && self.qc_mad_on_mito,
901 feature_min_cells: self.qc_feature_min_cells,
902 drop_outliers: true,
903 auto_cell_cutoff: self.qc_auto_cutoff,
907 qc_histogram: self.qc_histogram,
908 })
909 }
910}
911
912#[cfg(test)]
913mod qc_tests {
914 use super::*;
915
916 #[test]
917 fn auto_cutoff_train_drops_ambient() {
918 let n_genes: Vec<f32> = [vec![2.0; 30], vec![100.0; 30]].concat();
922 let cfg = QcConfig {
923 auto_cell_cutoff: true,
924 qc_histogram: false,
925 drop_outliers: true,
926 mad_on_n_genes: false,
927 mad_on_counts: false,
928 mad_on_mito: false,
929 min_cell_nnz: 0,
930 ..QcConfig::default()
931 };
932 let report = qc_from_metrics(
933 QcMetrics {
934 n_genes: n_genes.clone(),
935 total_counts: n_genes,
936 mito_frac: None,
937 ribo_frac: None,
938 feature_n_cells: None,
939 n_rows: 0,
940 },
941 &cfg,
942 None,
943 );
944 assert_eq!(
945 report.train_keep,
946 [vec![false; 30], vec![true; 30]].concat()
947 );
948 assert_eq!(report.n_cells_dropped, 30);
949 }
950
951 #[test]
952 fn output_keep_idx_skips_dropped_and_near_empty() {
953 let report = QcReport {
955 train_keep: vec![true, true, false, true],
956 near_empty: vec![false, true, false, false],
957 feature_keep: vec![],
958 n_genes: vec![],
959 total_counts: vec![],
960 mito_frac: None,
961 ribo_frac: None,
962 n_cells_dropped: 1,
963 n_features_dropped: 0,
964 };
965 assert_eq!(report.output_keep_idx(), vec![0, 2]);
968 }
969}
970
971#[cfg(test)]
972#[path = "qc_lib_tests.rs"]
973mod tests;