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