Skip to main content

data_beans/alg/collapse_data/state_aware_batch_fold/
sample_units.rs

1//! Samples kind: the state-aware batch fold over columns as they are (cells,
2//! or carried pseudobulks), from the sample collapse's groups and δ. senna,
3//! bge and pinto's baselines read this kind; the cell-pair kind
4//! ([`super::cell_pair_units`]) builds its pair nodes on this kind's tree.
5//!
6//! 1. The data read once, into pb samples (finest group × batch) sums.
7//! 2. Coarsen: Ward over the coarsest groups' δ-adjusted profiles, cut where
8//!    both children span batches in coarsest pseudobulks.
9//! 3. Uncoarsen: local swaps of pb samples between neighbouring nodes.
10//! 4. The fold top down along the tree, pb sample to pb sample.
11
12use super::coarse_group_ward_tree::{row_scores, CoarseGroupWardTree};
13use super::cross_batch_matched_fold::{
14    delta_as_base_of_every_node, estimate_fold_on_pseudobulks, MatchingCoordinates,
15    StateAwareBatchFold,
16};
17use super::local_swap_refinement::refine_nodes_by_local_swaps;
18use super::node_compositions::{node_log_mean_compositions, place_by_composition};
19use super::pseudobulk_sums::{sum_by_pseudobulk, PseudobulkKeys, PseudobulkSums};
20use super::top_down_fold::estimate_fold_top_down;
21use super::{
22    compact_present, BatchSpanningRule, CollapsePseudobulks, StateAwareBatchFoldParams, PROFILE_DIM,
23};
24use crate::sparse_io_vector::SparseIoVec;
25use log::{info, warn};
26use nalgebra::DMatrix;
27
28/// The samples kind's result: the fold, plus what places an unseen unit.
29#[derive(Clone, Debug)]
30pub struct SampleBatchFold {
31    pub fold: StateAwareBatchFold,
32    pub tree: CoarseGroupWardTree,
33    /// Each unit's node in `tree`, `None` when it keeps δ. The cell-pair kind
34    /// reads this for its endpoints.
35    pub tree_node_of_unit: Vec<Option<usize>>,
36    /// Each unit's matching coordinates (components × units).
37    pub coords: DMatrix<f32>,
38    /// genes × n_nodes: each node's fold-corrected composition, log; an
39    /// unseen unit takes the node that explains its counts best
40    /// ([`Self::place_unseen_samples`]).
41    pub node_log_mean_composition: DMatrix<f32>,
42    /// Each node's (dense id's) node in `tree`.
43    pub tree_node_of_node: Vec<usize>,
44}
45
46/// Where an unseen unit lands: its node (the fold's column, with its batch)
47/// and that node's place in the tree (what an unseen pair climbs from).
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub struct UnseenPlacement {
50    pub node: usize,
51    pub tree_node: usize,
52}
53
54impl SampleBatchFold {
55    /// Where unseen units land, by composition
56    /// ([`super::node_compositions`]): each count column (`(gene, count)`
57    /// pairs; a caller may add a unit's spatial neighbours' counts to steady
58    /// it) on the node that explains it best. `batch[c]`: `Some(b)` for a
59    /// batch the fit saw (the counts as read; its fold is then the node's
60    /// column in `b`), `None` for one it never saw (the counts divided by
61    /// that batch's own δ, which is also all it is divided by). `None` for
62    /// a unit with no read. Errors on a length mismatch, a batch or gene
63    /// outside the fit.
64    pub fn place_unseen_samples(
65        &self,
66        counts: &[Vec<(usize, f32)>],
67        batch: &[Option<usize>],
68    ) -> anyhow::Result<Vec<Option<UnseenPlacement>>> {
69        Ok(place_by_composition(
70            counts,
71            batch,
72            &self.node_log_mean_composition,
73            &self.fold.log_fold,
74            self.fold.n_batches,
75        )?
76        .into_iter()
77        .map(|k| {
78            k.map(|k| UnseenPlacement {
79                node: k,
80                tree_node: self.tree_node_of_node[k],
81            })
82        })
83        .collect())
84    }
85}
86
87/// Each coarse group's δ-adjusted pooled profile (groups × genes), log1p of
88/// counts per 10⁴, from the pb sample sums.
89fn delta_adjusted_group_profiles(
90    sums: &PseudobulkSums,
91    n_groups: usize,
92    log_delta: &DMatrix<f32>,
93) -> DMatrix<f32> {
94    let mut prof = DMatrix::<f32>::zeros(n_groups, sums.n_genes);
95    for pb in 0..sums.len() {
96        let (k, b) = (sums.coarsest[pb], sums.batch[pb]);
97        for &(g, x) in &sums.counts[pb] {
98            prof[(k, g)] += x * (-log_delta[(g, b)]).exp();
99        }
100    }
101    for mut row in prof.row_iter_mut() {
102        let tot: f32 = row.sum();
103        if tot > 0.0 {
104            row.apply(|v| *v = (*v / tot * 1e4).ln_1p());
105        }
106    }
107    prof
108}
109
110/// The nodes a Ward tree over the coarsest groups is cut into.
111pub(crate) struct NodesCutFromWardTree {
112    pub(crate) tree: CoarseGroupWardTree,
113    /// Each pseudobulk's node (dense id), `None` when its group is in no
114    /// spanning node.
115    pub(crate) node_of_pb: Vec<Option<usize>>,
116    /// Each node's (dense id's) node in `tree`.
117    pub(crate) tree_node_of_node: Vec<usize>,
118}
119
120/// Coarsening, shared by the samples kind and the cell pairs' link states:
121/// Ward over the `n_groups` coarsest groups of `sums` (`sums.coarsest`, ids
122/// `0..n_groups`), on their pooled profiles divided by `log_delta`, cut
123/// where both children span `rule` (counted in each pseudobulk's
124/// `(coarsest group, span label)`).
125pub(crate) fn cut_nodes_from_ward_tree_over_coarsest_groups(
126    sums: &PseudobulkSums,
127    n_groups: usize,
128    log_delta: &DMatrix<f32>,
129    rule: &BatchSpanningRule,
130) -> anyhow::Result<NodesCutFromWardTree> {
131    let prof = delta_adjusted_group_profiles(sums, n_groups, log_delta);
132    let tree = CoarseGroupWardTree::build(&row_scores(
133        &prof,
134        PROFILE_DIM.min(n_groups.saturating_sub(1)).max(1),
135    )?)?;
136    let mut members = vec![Vec::new(); n_groups];
137    for pb in 0..sums.len() {
138        members[sums.coarsest[pb]].push((sums.coarsest[pb], sums.span_label[pb]));
139    }
140    let group_count: Vec<Vec<usize>> = members.into_iter().map(|m| rule.count(m)).collect();
141    let node_of_group = tree.cut_where_both_children_span_batches(&group_count, rule);
142    let tree_node_of_pb: Vec<Option<usize>> =
143        sums.coarsest.iter().map(|&g| node_of_group[g]).collect();
144    let (node_of_pb, tree_node_of_node) = compact_present(&tree_node_of_pb);
145    Ok(NodesCutFromWardTree {
146        tree,
147        node_of_pb,
148        tree_node_of_node,
149    })
150}
151
152/// The samples kind: a fold per (gene × node × batch) over columns as they are.
153///
154/// * `pseudobulks`: each column's finest and coarsest collapse group
155///   (shared across batches): its pb sample (finest × batch, what the fold
156///   matches) and the tree's leaves (coarsest).
157/// * `log_delta`: the collapse's δ, log, genes × batches.
158/// * `proj`: the batch-corrected projection the collapse ran on (dims × columns).
159pub fn estimate_state_aware_batch_fold_over_samples(
160    data: &SparseIoVec,
161    batch: &[usize],
162    pseudobulks: &CollapsePseudobulks<'_>,
163    log_delta: &DMatrix<f32>,
164    proj: &DMatrix<f32>,
165    params: &StateAwareBatchFoldParams,
166) -> anyhow::Result<SampleBatchFold> {
167    let n = data.num_columns();
168    let nb = log_delta.ncols();
169    anyhow::ensure!(
170        batch.len() == n
171            && pseudobulks.finest.len() == n
172            && pseudobulks.coarsest.len() == n
173            && proj.ncols() == n,
174        "batch fold: one batch, group and projection column per column"
175    );
176    let (span_label, n_labels) = params.span_labels_of_samples(batch, nb)?;
177    let rule = BatchSpanningRule::new(params, n_labels);
178
179    let coord_map = MatchingCoordinates::fit(proj)?;
180    let coords = coord_map.apply(proj);
181    // the data read once: pb samples (finest group in one batch)
182    let key: Vec<Option<(usize, usize, usize)>> = (0..n)
183        .map(|u| Some((pseudobulks.finest[u], batch[u], 0)))
184        .collect();
185    let sums = sum_by_pseudobulk(
186        data,
187        &PseudobulkKeys {
188            key: &key,
189            batch,
190            span_label: &span_label,
191            coarsest: pseudobulks.coarsest,
192            coords: &coords,
193        },
194    )?;
195
196    // coarsen: Ward over the coarsest groups, cut where both children span
197    let n_groups = pseudobulks.coarsest.iter().max().map_or(0, |&m| m + 1);
198    let NodesCutFromWardTree {
199        tree,
200        node_of_pb: node,
201        tree_node_of_node,
202    } = cut_nodes_from_ward_tree_over_coarsest_groups(&sums, n_groups, log_delta, &rule)?;
203    let n_nodes = tree_node_of_node.len();
204    if n_nodes == 0 {
205        warn!(
206            "batch fold: no node spans {} of {} labels with {} coarsest pseudobulks each; keeping δ",
207            rule.min_spans, rule.n_labels, rule.min_pseudobulks
208        );
209    } else {
210        info!("batch fold: {n_groups} coarse groups cut into {n_nodes} nodes");
211    }
212
213    // uncoarsen: a first fold, then local swaps of pb samples under it
214    let first_fold = estimate_fold_on_pseudobulks(
215        &sums,
216        &node,
217        n_nodes,
218        &delta_as_base_of_every_node(log_delta, n_nodes),
219        params,
220    )?;
221    let node = refine_nodes_by_local_swaps(&sums, &rule, node, n_nodes, &first_fold);
222
223    // the fold top down along the tree, from the root to each refined node
224    let final_tree_node: Vec<Option<usize>> = node
225        .iter()
226        .map(|k| k.map(|k| tree_node_of_node[k]))
227        .collect();
228    let fold_of = estimate_fold_top_down(&sums, &tree, &final_tree_node, log_delta, params)?;
229    let mut log_fold = DMatrix::<f32>::zeros(log_delta.nrows(), n_nodes * nb);
230    for (k, t) in tree_node_of_node.iter().enumerate() {
231        log_fold
232            .columns_mut(k * nb, nb)
233            .copy_from(fold_of.get(t).unwrap_or(log_delta));
234    }
235
236    // each unit takes its pb sample's node
237    let node_of_unit: Vec<Option<usize>> = sums
238        .of_unit
239        .iter()
240        .map(|pb| pb.and_then(|pb| node[pb]))
241        .collect();
242    let tree_node_of_unit: Vec<Option<usize>> = node_of_unit
243        .iter()
244        .map(|k| k.map(|k| tree_node_of_node[k]))
245        .collect();
246    let node_log_mean_composition = node_log_mean_compositions(&sums, &node, n_nodes, &log_fold);
247
248    Ok(SampleBatchFold {
249        fold: StateAwareBatchFold {
250            n_batches: nb,
251            n_nodes,
252            log_fold,
253            log_delta: log_delta.clone(),
254            node_of_unit,
255        },
256        tree,
257        tree_node_of_unit,
258        coords,
259        node_log_mean_composition,
260        tree_node_of_node,
261    })
262}