Skip to main content

data_beans/
qc_lib.rs

1//! Cell-axis quality control (library-only): robust (MAD) outlier detection
2//! plus the near-empty floor. Built on the streaming stat collectors in the
3//! sibling `qc` module and consumed by senna / pinto — NOT by the data-beans
4//! CLI — so it lives in its own module that the binary never compiles (keeps
5//! `qc` fully bin-used and avoids dead-code in the bin target).
6
7use 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///////////////////////////////////////////////////////////////////////////////////
20// Cell-axis quality control: robust (MAD) outlier detection + near-empty floor. //
21///////////////////////////////////////////////////////////////////////////////////
22//
23// This MAY DROP CELLS (columns): callers that enable QC end up with fewer
24// cells in the working set and/or in the per-cell outputs than the input had,
25// so downstream consumers must not assume a 1:1 positional mapping to the
26// input barcodes — join by cell name. (Feature/row QC, off by default, may
27// likewise drop genes/rows.)
28//
29// Shared by senna and pinto. Two-tier policy (see `compute_qc`):
30//   * near-empty cells (`nnz < min_cell_nnz`) are kept in training but
31//     dropped from the *output*;
32//   * non-near-empty MAD outliers are dropped from *training* via
33//     `SparseIoVec::mask_columns` (so they leave the outputs too).
34
35/// Configuration for cell QC. Plain struct (no clap) so non-clap crates
36/// can construct it directly; the clap surface is [`QcArgs`].
37#[derive(Clone, Debug)]
38pub struct QcConfig {
39    /// MAD multiplier for the robust band (larger = more permissive).
40    pub n_mads: f32,
41    /// Near-empty floor: cells with fewer than this many detected features
42    /// (nnz across all rows) are masked at output, not dropped from
43    /// training. 0 disables the floor.
44    pub min_cell_nnz: usize,
45    /// Hard floor on total counts per cell, in addition to MAD. 0 disables.
46    pub min_counts_per_cell: f32,
47    /// Regex over row (feature) names selecting mitochondrial genes; enables
48    /// the per-cell mito-fraction metric. `None` disables it.
49    pub mito_pattern: Option<String>,
50    /// Optional hard max mitochondrial fraction (0..1).
51    pub mito_max_frac: Option<f32>,
52    /// Regex selecting ribosomal genes (enables ribo-fraction metric).
53    pub ribo_pattern: Option<String>,
54    /// Optional hard max ribosomal fraction (0..1).
55    pub ribo_max_frac: Option<f32>,
56    /// Per-cell metrics that drive MAD outlier flagging.
57    pub mad_on_n_genes: bool,
58    pub mad_on_counts: bool,
59    pub mad_on_mito: bool,
60    /// Feature-axis QC (off by default): drop genes expressed in fewer than
61    /// this many cells. 0 disables.
62    pub feature_min_cells: usize,
63    /// Master switch for the MAD train-drop tier. When `false`, only the
64    /// near-empty floor (output mask) is computed — used by inference
65    /// (predict/impute) so query cells are never silently dropped.
66    pub drop_outliers: bool,
67    /// Automatic cell calling: pick the per-cell nnz cutoff at the trough
68    /// between the ambient and the cell peak ([`crate::qc::suggest_nnz_cutoff`])
69    /// and **train-drop** every cell below it. So called-out ambient is removed
70    /// up front (via the caller's `mask_columns`), not just output-masked — it
71    /// never shapes the model. The cutoff is authoritative; `min_cell_nnz` does
72    /// NOT floor it (it only drives the separate near-empty output mask). No-op
73    /// when there is no trough (unimodal) or when `drop_outliers` is false
74    /// (inference). Unlike the loader's per-file empty-barcode gate, this runs
75    /// on the pooled cell axis.
76    pub auto_cell_cutoff: bool,
77    /// Print the per-cell nnz histogram + the suggested/applied cutoff (the
78    /// same ASCII summary as `data-beans squeeze --show-histogram`).
79    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
103/// Resolve a regex over row (feature) names into matching row indices, in
104/// the same compact-row order as `SparseIoVec::row_names()`. Feeds
105/// `collect_column_stat_across_vec(.., Some(&rows), ..)` for subset sums.
106pub 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
116/// Per-cell / per-feature QC outcome.
117pub struct QcReport {
118    /// Cells to retain in training (len = num_columns). `false` only for
119    /// non-near-empty MAD outliers — drives `SparseIoVec::mask_columns`.
120    pub train_keep: Vec<bool>,
121    /// Near-empty cells (len = num_columns): kept in training, masked at
122    /// output via [`QcReport::output_keep_idx`].
123    pub near_empty: Vec<bool>,
124    /// Features to retain (len = num_rows). All `true` unless
125    /// `feature_min_cells > 0`.
126    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    /// Indices, in *post-`mask_columns`* column order, of the cells to emit
137    /// at output: surviving (training-kept) cells that are not near-empty.
138    /// Apply with `Mat::select_rows` on per-cell output matrices and filter
139    /// the barcode slice by the same indices.
140    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; // dropped from training entirely
146            }
147            if !self.near_empty[c] {
148                idx.push(new_pos); // c survives at compact index new_pos
149            }
150            new_pos += 1;
151        }
152        idx
153    }
154
155    /// Emit-keep indices in the **original** (unmasked) column order: cells
156    /// that are neither MAD-dropped nor near-empty. For paths that keep every
157    /// cell in training and instead `select_rows` the per-cell outputs
158    /// directly (e.g. bge's `BipartiteEmbeddingCells`, which has no `mask_columns`).
159    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
166/// Compute the two-tier cell-QC report. `block_size` controls the
167/// streaming stat passes (`None` = default chunking).
168pub 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
176/// [`compute_qc`] with columns that are **not cells** exempted — a prior
177/// run's carried pseudobulks. `exempt[c] = true` keeps column `c` out of all
178/// band statistics and out of every verdict. See `qc_from_metrics`.
179pub 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
189/// The per-cell (and, with `feature_cells`, per-feature) metrics QC
190/// decides on, measured once: detected features and total counts per
191/// cell, the mito and ribo fractions where `cfg` names their patterns, and
192/// how many cells detect each feature. [`cell_verdicts`] decides on them
193/// under any config with those patterns, without reading the data again.
194pub 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    // Optional mito / ribo row subsets via row-name regex.
203    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    // Every metric from one pass over the data: per-cell totals across all
225    // rows (nnz = n_genes, tot = total_counts), the subset totals, and the
226    // feature axis stat (only when asked). Use the running-stat accessors
227    // directly to skip the unused mean/std.
228    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    // Fractions of the subsets measured, in the order they were asked for.
233    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
260/// What [`collect_qc_stat`] collects in its one pass.
261struct QcStat {
262    /// Column statistics over all rows.
263    columns: SparseColumnRunningStatistics<f32>,
264    /// Column statistics over each row subset asked for, in that order.
265    subsets: Vec<SparseColumnRunningStatistics<f32>>,
266    /// Row statistics, when asked for.
267    rows: Option<SparseRunningStatistics<f32>>,
268}
269
270/// Collect, reading every block once, the column statistics over all rows
271/// (`collect_column_stat_across_vec` with no selection), those over each
272/// of `row_subsets` (the same with each as its selection) and, with
273/// `with_rows`, the row statistics (`collect_row_stat_across_vec`).
274fn 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
315/// Modality-agnostic cell QC for a [`SparseIoStack`]: per-cell `n_genes` /
316/// `total_counts` are **summed across all member modalities** (a cell rich
317/// in any one modality is kept). Mito/ribo and
318/// feature-axis QC are skipped on stacks (row names are per-modality).
319pub 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, // feature axis not masked on stacks
347        },
348        cfg,
349        None,
350    ))
351}
352
353/// Pre-computed per-cell / per-feature metrics fed to [`cell_verdicts`].
354/// Lets the single-modality and stacked QC paths share one decision rule.
355#[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    /// Cells detecting each feature; `None` when not measured.
362    pub feature_n_cells: Option<Vec<f32>>,
363    pub n_rows: usize,
364}
365
366/// What [`cell_verdicts`] decides: the cells kept in training, the
367/// near-empty ones, and the features kept.
368#[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    /// The rules would have dropped every cell, or every feature, and the
376    /// guardrail kept them all.
377    pub guarded: bool,
378}
379
380impl Verdicts {
381    /// Whether cell `c` reaches the output: kept in training and not
382    /// near-empty.
383    pub fn emitted(&self, c: usize) -> bool {
384        self.train_keep[c] && !self.near_empty[c]
385    }
386}
387
388/// Apply the two-tier QC decision (near-empty floor + MAD outliers) to
389/// pre-computed metrics. Shared by [`compute_qc`] and [`compute_qc_stack`].
390///
391/// `exempt`, when given, marks columns that are **not cells** — a prior run's
392/// carried pseudobulks. They are excluded from every band statistic (a few
393/// hundred smooth averages otherwise drag the MAD center and can guillotine
394/// the real cells wholesale — measured: 400 of 400 real cells dropped as
395/// "outliers" of the carried columns' band) and they receive no verdict:
396/// never near-empty, never dropped. Their exclusion from OUTPUT is a separate
397/// concern handled by the caller.
398fn qc_from_metrics(m: QcMetrics, cfg: &QcConfig, exempt: Option<&[bool]>) -> QcReport {
399    // The histogram + cutoff, optionally printed.
400    if cfg.drop_outliers && (cfg.auto_cell_cutoff || cfg.qc_histogram) {
401        // Of the cells alone, as the cutoff is found among them.
402        let cells = cell_values(&m.n_genes, exempt);
403        let suggested = crate::qc::suggest_nnz_cutoff(&cells);
404        // Display cutoff: the trough suggestion if found, else the
405        // near-empty floor (what the non-auto tier would use).
406        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
430/// `values` of the columns that are cells: all of them, or those `exempt`
431/// does not mark.
432fn 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
444/// The [`QcReport`] of metrics measured once ([`compute_qc_metrics`]),
445/// as [`compute_qc`] makes it: the histogram printed when `cfg` asks.
446pub fn qc_report(m: QcMetrics, cfg: &QcConfig) -> QcReport {
447    qc_from_metrics(m, cfg, None)
448}
449
450/// The two-tier QC decision (near-empty floor + MAD outliers) on `m`
451/// under `cfg`, printing nothing: what [`compute_qc`] decides, for a view
452/// that decides again as its settings change. `exempt` as in
453/// [`compute_qc_exempting`].
454pub fn cell_verdicts(m: &QcMetrics, cfg: &QcConfig, exempt: Option<&[bool]>) -> Verdicts {
455    verdicts(m, cfg, exempt, true)
456}
457
458/// [`cell_verdicts`] without the guardrails' warnings, for a view that
459/// decides again at every key and shows [`Verdicts::guarded`] itself.
460pub(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    // Tier 1: near-empty floor. Exempt columns are never near-empty.
479    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    // Tier 2: MAD outliers among non-near-empty cells. The band statistics
486    // are fit over the non-near-empty, non-exempt cells only, so neither
487    // near-empty cells nor carried pseudobulks contaminate the robust center.
488    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; // floor takes precedence; exempt columns get no verdict
529            }
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        // Automatic cell calling: the trough of n_genes picks the ambient↔real
547        // boundary and train-drops every cell below it, so the caller's
548        // `mask_columns(train_keep)` removes ambient up front. The cutoff
549        // is authoritative — there is NO redundant `min_cell_nnz` floor on it.
550        // When the data is unimodal the trough search returns `None`, so no auto
551        // cutoff is applied and the near-empty floor / MAD tiers stand alone.
552        // The trough is sought among the cells: exempt columns neither
553        // shape it nor fall to it.
554        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    // Guardrail: never produce a matrix with no cell. Exempt columns are
569    // never dropped, so the drops are held against the cells alone.
570    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    // Cells kept in training reach the output only above the near-empty
584    // floor; where none does, the verdicts stand and the output is empty.
585    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    // Feature axis (only when feature_n_cells was computed).
595    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
625/// Filter a per-cell `Vec<T>` in lockstep with a cell keep-mask. Used to
626/// keep batch labels / coordinates aligned after `mask_columns`.
627pub 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
636/// Write a per-cell QC table (TSV): name, n_genes, total_counts,
637/// [mito_frac], [ribo_frac], near_empty (0/1), train_keep (0/1).
638pub 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/// Clap surface for cell QC, shared by senna and pinto subcommands.
687///
688/// **Cell QC is ON by default and CAN DROP CELLS (columns).** Low-quality
689/// cells are removed: near-empty cells are omitted from the per-cell outputs,
690/// and robust (MAD) outlier cells are excluded from training entirely. As a
691/// result, the per-cell output files (`*.latent.parquet`, `*.cell_proj.parquet`,
692/// `*.cell_to_pb.parquet`, `*.cell_embedding.parquet`, pinto propensity, etc.)
693/// **may contain fewer rows (cells) than the input** — do not assume a 1:1,
694/// positional correspondence with the input barcodes; always join by the cell
695/// name/barcode column. Pass `--no-qc` to disable and keep every cell, or
696/// `--qc-report <path>` to dump the per-cell keep/drop flags. (Feature/row QC
697/// is OFF unless `--qc-feature-min-cells` is set.)
698#[derive(clap::Args, Debug, Clone, serde::Serialize, serde::Deserialize)]
699#[serde(default = "legume_numeric::matrix::clap_defaults::clap_defaults")]
700pub struct QcArgs {
701    /// Disable cell QC entirely (keep every input cell).
702    #[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    /// MAD multiplier for the robust outlier band; smaller = drops more cells.
725    #[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    /// Hard max mitochondrial fraction (0..1).
758    #[arg(long = "qc-mito-max-frac", hide = true)]
759    pub qc_mito_max_frac: Option<f32>,
760
761    /// Regex over feature names selecting ribosomal genes.
762    #[arg(long = "qc-ribo-pattern", hide = true)]
763    pub qc_ribo_pattern: Option<String>,
764
765    /// Hard max ribosomal fraction (0..1).
766    #[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        // `--qc-mad-on-genes=false` turns it off; a bare flag leaves it on.
812        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        // `--qc-mad-on-counts=false` turns it off; a bare flag leaves it on.
833        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        // `--qc-mad-on-mito=false` turns it off; a bare flag leaves it on.
848        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    /// QC config, or `None` under `--no-qc`.
878    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            // An empty pattern names no genes: the metric is off, not a
884            // regex that finds every gene.
885            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 gates are ON by default and settable. They were hardcoded
890            // `false` here with no CLI path, which also made `--qc-mads` a dead
891            // flag unless `--qc-mito-pattern` was set (nothing else reads
892            // `n_mads`). Mito stays implicit: it can only run when a pattern
893            // selects the rows to measure.
894            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            // Off by default: the near-empty floor plus the model's own
904            // empty-call (bge's embedding-norm two-step; topic/masked-topic's
905            // flag-don't-drop) is the intended gate. `--qc-auto-cutoff` opts in.
906            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        // Bimodal nnz: 30 ambient (~2) + 30 real (~100). With auto cell calling on
919        // (MAD tiers off so the auto floor is the only decider), the trough
920        // cutoff lands between the modes and the ambient cells are train-dropped.
921        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        // cells: 0 keep, 1 near-empty (kept in training), 2 MAD-drop, 3 keep
954        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        // post-mask order: cell0->0, cell1->1, cell3->2 (cell2 dropped)
966        // emit non-near-empty survivors: 0 and 2
967        assert_eq!(report.output_keep_idx(), vec![0, 2]);
968    }
969}
970
971#[cfg(test)]
972#[path = "qc_lib_tests.rs"]
973mod tests;