Skip to main content

data_beans/alg/collapse_data/state_aware_batch_fold/
mod.rs

1//! State-aware batch fold: one fold per (gene × node × batch), on top of δ.
2//!
3//! δ (gene × batch) cannot hold the part of a batch effect that depends on the
4//! cell state (donor × state), and that part alone keeps batches apart in every
5//! local neighbourhood. This module estimates it on coarse nodes that are
6//! state-pure **and** span batches, at pseudobulk sample sizes.
7//!
8//! Two kinds of unit, by meaning; keep them apart:
9//!
10//! * **samples** ([`sample_units`]): columns as they are, cells or carried
11//!   pseudobulks, with the existing sample collapse's groups. For senna, bge
12//!   and pinto's baselines. Entry: [`estimate_state_aware_batch_fold_over_samples`].
13//! * **cell pairs** ([`cell_pair_units`]): pair units built once
14//!   ([`build_cell_pair_units`]: every cell's reads split once over its pairs
15//!   and a self-loop), collapsed on their own for the pair δ. A pair's state
16//!   ([`PairStates`]) is its **link state** by default (learned from the
17//!   pair after its cells' fold is divided out, [`link_state_pair_fold`]),
18//!   or its **endpoint states** (placed on the samples kind's tree by its
19//!   endpoints). For link-based methods, where the pair is the unit. Entry:
20//!   [`collapse_cell_pairs_and_estimate_state_aware_batch_fold`]; it needs the
21//!   samples kind's result first.
22//!
23//! Both read the data once, into per-pseudobulk sums
24//! ([`pseudobulk_sums`]); everything after runs on those sums: the tree over
25//! the coarsest sample groups and its batch-spanning cut
26//! ([`coarse_group_ward_tree`], coarsening, bottom up), local swaps of whole
27//! pseudobulks between nodes ([`local_swap_refinement`], uncoarsening, top
28//! down), and the fold matched pseudobulk to pseudobulk across batches within
29//! each node ([`cross_batch_matched_fold`]). The samples kind estimates the
30//! fold top down along the tree, each node a residual over its parent's
31//! ([`top_down_fold`]); the cell-pair kind matches once per pair node (top
32//! down over pair keys did worse on the sims, 2026-11-21).
33//!
34//! If not even the root spans enough batches, every unit keeps δ, with a
35//! warning; the estimate never fails for that reason.
36
37pub mod cell_pair_units;
38pub mod coarse_group_ward_tree;
39pub mod cross_batch_matched_fold;
40pub mod link_state_pair_fold;
41pub(crate) mod local_swap_refinement;
42pub mod node_compositions;
43pub(crate) mod pseudobulk_sums;
44pub mod sample_units;
45pub(crate) mod top_down_fold;
46
47pub use cell_pair_units::{
48    build_cell_pair_units, collapse_cell_pairs_and_estimate_state_aware_batch_fold,
49    split_cell_reads_over_pair_units_without_double_counting, CellPairBatchFold,
50    CellPairFoldParams, CellPairUnits, PairNodeOfEndpointNodes, PairStateModel, PairStates,
51};
52pub use coarse_group_ward_tree::{CoarseGroupWardTree, EXACT_WARD_MAX_GROUPS};
53pub use cross_batch_matched_fold::{MatchingCoordinates, StateAwareBatchFold};
54pub use link_state_pair_fold::{cell_predicted_pair_log_fold, LinkStateDecomposition};
55pub use node_compositions::{place_by_composition, CompositionPlacer};
56pub use sample_units::{
57    estimate_state_aware_batch_fold_over_samples, SampleBatchFold, UnseenPlacement,
58};
59
60/// Nearest pseudobulks drawn from each other batch for a counterfactual.
61pub const DEFAULT_FOLD_KNN: usize = 10;
62/// Pseudo-count on both sides of a node's fold ratio (shrinks thin genes to 1).
63pub const DEFAULT_FOLD_PSEUDO_COUNT: f32 = 10.0;
64/// Principal components of the projection the matching runs in.
65pub(crate) const COORD_DIM: usize = 30;
66/// Principal components of the group profiles Ward links.
67pub(crate) const PROFILE_DIM: usize = 20;
68
69#[derive(Clone, Debug)]
70pub struct StateAwareBatchFoldParams {
71    pub knn: usize,
72    pub pseudo_count: f32,
73    /// Coarsest pseudobulks (a collapse's coarsest group in one batch: pb
74    /// samples for samples, pb pairs for pairs) a batch (or donor) needs
75    /// inside a node to count as spanned: the matching's `knn` by default, so
76    /// a node keeps pseudobulk sample sizes. With few coarsest groups (say
77    /// 16) the cut makes few, large nodes; with fewer than this many, nothing
78    /// spans and every unit keeps δ, with a warning.
79    pub min_pseudobulks: usize,
80    /// Label a node must span, per column of the samples (cells): a donor,
81    /// say. `None` spans batches.
82    pub span_labels: Option<Vec<usize>>,
83    /// Distinct labels a node must span, each with `min_pseudobulks`
84    /// pseudobulks. `None`: half the batches (rounded up), or 2 donors when
85    /// `span_labels` is set.
86    pub min_spans: Option<usize>,
87    pub block_size: Option<usize>,
88}
89
90impl Default for StateAwareBatchFoldParams {
91    fn default() -> Self {
92        Self {
93            knn: DEFAULT_FOLD_KNN,
94            pseudo_count: DEFAULT_FOLD_PSEUDO_COUNT,
95            min_pseudobulks: DEFAULT_FOLD_KNN,
96            span_labels: None,
97            min_spans: None,
98            block_size: None,
99        }
100    }
101}
102
103impl StateAwareBatchFoldParams {
104    /// Each sample's span label (its donor, or its batch) and how many there are.
105    pub(crate) fn span_labels_of_samples(
106        &self,
107        batch: &[usize],
108        n_batches: usize,
109    ) -> anyhow::Result<(Vec<usize>, usize)> {
110        match &self.span_labels {
111            Some(l) => {
112                anyhow::ensure!(l.len() == batch.len(), "span labels: one per column");
113                Ok((l.clone(), l.iter().max().map_or(0, |&m| m + 1)))
114            }
115            None => Ok((batch.to_vec(), n_batches)),
116        }
117    }
118}
119
120/// A collapse's groups, per unit: the finest (each in one batch, the
121/// pseudobulks the fold matches) and the coarsest (each in one batch, the
122/// pseudobulks a node's size is counted in; the tree's leaves for samples).
123#[derive(Clone, Copy, Debug)]
124pub struct CollapsePseudobulks<'a> {
125    pub finest: &'a [usize],
126    pub coarsest: &'a [usize],
127}
128
129/// When a node spans: how many labels there are, how many it must span, and
130/// how many coarsest pseudobulks a label needs in it.
131pub(crate) struct BatchSpanningRule {
132    pub(crate) n_labels: usize,
133    pub(crate) min_spans: usize,
134    pub(crate) min_pseudobulks: usize,
135}
136
137impl BatchSpanningRule {
138    pub(crate) fn new(params: &StateAwareBatchFoldParams, n_labels: usize) -> Self {
139        let default_min = if params.span_labels.is_some() {
140            2
141        } else {
142            n_labels.div_ceil(2)
143        };
144        Self {
145            n_labels,
146            min_spans: params.min_spans.unwrap_or(default_min).max(2),
147            min_pseudobulks: params.min_pseudobulks,
148        }
149    }
150
151    /// Does a node holding `count[label]` coarsest pseudobulks span enough labels?
152    pub(crate) fn spans(&self, count: &[usize]) -> bool {
153        count.iter().filter(|&&c| c >= self.min_pseudobulks).count() >= self.min_spans
154    }
155
156    /// The distinct `(coarsest pseudobulk, label)` keys among `members`, per
157    /// label: what [`Self::spans`] reads.
158    pub(crate) fn count(&self, members: impl IntoIterator<Item = (usize, usize)>) -> Vec<usize> {
159        let seen: rustc_hash::FxHashSet<(usize, usize)> = members.into_iter().collect();
160        let mut count = vec![0usize; self.n_labels];
161        for (_, l) in seen {
162            count[l] += 1;
163        }
164        count
165    }
166}
167
168/// Dense ids `0..` for the `Some` values of `labels`, in order of first
169/// appearance (data-beans' `compact_labels`), and the distinct values in
170/// that order.
171pub(crate) fn compact_present<K: Copy + Eq + std::hash::Hash>(
172    labels: &[Option<K>],
173) -> (Vec<Option<usize>>, Vec<K>) {
174    let present: Vec<K> = labels.iter().flatten().copied().collect();
175    let (dense, n) = crate::alg::dc_poisson::compact_labels(&present);
176    let mut distinct = Vec::with_capacity(n);
177    let mut it = dense.into_iter();
178    let out = labels
179        .iter()
180        .map(|l| {
181            l.map(|k| {
182                let d = it.next().expect("one dense id per present label");
183                if d == distinct.len() {
184                    distinct.push(k);
185                }
186                d
187            })
188        })
189        .collect();
190    (out, distinct)
191}
192
193#[cfg(test)]
194mod tests;