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::pseudobulk_sums::{sum_by_pseudobulk, PseudobulkKeys, PseudobulkSums};
19use super::top_down_fold::estimate_fold_top_down;
20use super::{
21    compact_present, BatchSpanningRule, CollapsePseudobulks, StateAwareBatchFoldParams, PROFILE_DIM,
22};
23use crate::sparse_io_vector::SparseIoVec;
24use log::{info, warn};
25use nalgebra::DMatrix;
26use std::ops::AddAssign;
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    pub coord_map: MatchingCoordinates,
37    /// Each unit's matching coordinates (components × units).
38    pub coords: DMatrix<f32>,
39    /// components × n_nodes: the mean coordinates of each node's units; an
40    /// unseen unit takes its nearest node.
41    pub node_centroids: 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, from their projections `proj` (dims ×
56    /// units): each takes the nearest node centroid.
57    pub fn place_unseen_samples(&self, proj: &DMatrix<f32>) -> Vec<Option<UnseenPlacement>> {
58        let z = self.coord_map.apply(proj);
59        (0..z.ncols())
60            .map(|c| {
61                (0..self.node_centroids.ncols())
62                    .map(|k| {
63                        (
64                            k,
65                            (z.column(c) - self.node_centroids.column(k)).norm_squared(),
66                        )
67                    })
68                    .min_by(|a, b| a.1.total_cmp(&b.1))
69                    .map(|(k, _)| UnseenPlacement {
70                        node: k,
71                        tree_node: self.tree_node_of_node[k],
72                    })
73            })
74            .collect()
75    }
76}
77
78/// Each coarse group's δ-adjusted pooled profile (groups × genes), log1p of
79/// counts per 10⁴, from the pb sample sums.
80fn delta_adjusted_group_profiles(
81    sums: &PseudobulkSums,
82    n_groups: usize,
83    log_delta: &DMatrix<f32>,
84) -> DMatrix<f32> {
85    let mut prof = DMatrix::<f32>::zeros(n_groups, sums.n_genes);
86    for pb in 0..sums.len() {
87        let (k, b) = (sums.coarsest[pb], sums.batch[pb]);
88        for &(g, x) in &sums.counts[pb] {
89            prof[(k, g)] += x * (-log_delta[(g, b)]).exp();
90        }
91    }
92    for mut row in prof.row_iter_mut() {
93        let tot: f32 = row.sum();
94        if tot > 0.0 {
95            row.apply(|v| *v = (*v / tot * 1e4).ln_1p());
96        }
97    }
98    prof
99}
100
101/// The samples kind: a fold per (gene × node × batch) over columns as they are.
102///
103/// * `pseudobulks`: each column's finest and coarsest collapse group
104///   (shared across batches): its pb sample (finest × batch, what the fold
105///   matches) and the tree's leaves (coarsest).
106/// * `log_delta`: the collapse's δ, log, genes × batches.
107/// * `proj`: the batch-corrected projection the collapse ran on (dims × columns).
108pub fn estimate_state_aware_batch_fold_over_samples(
109    data: &SparseIoVec,
110    batch: &[usize],
111    pseudobulks: &CollapsePseudobulks<'_>,
112    log_delta: &DMatrix<f32>,
113    proj: &DMatrix<f32>,
114    params: &StateAwareBatchFoldParams,
115) -> anyhow::Result<SampleBatchFold> {
116    let n = data.num_columns();
117    let nb = log_delta.ncols();
118    anyhow::ensure!(
119        batch.len() == n
120            && pseudobulks.finest.len() == n
121            && pseudobulks.coarsest.len() == n
122            && proj.ncols() == n,
123        "batch fold: one batch, group and projection column per column"
124    );
125    let (span_label, n_labels) = params.span_labels_of_samples(batch, nb)?;
126    let rule = BatchSpanningRule::new(params, n_labels);
127
128    let coord_map = MatchingCoordinates::fit(proj)?;
129    let coords = coord_map.apply(proj);
130    // the data read once: pb samples (finest group in one batch)
131    let key: Vec<Option<(usize, usize, usize)>> = (0..n)
132        .map(|u| Some((pseudobulks.finest[u], batch[u], 0)))
133        .collect();
134    let sums = sum_by_pseudobulk(
135        data,
136        &PseudobulkKeys {
137            key: &key,
138            batch,
139            span_label: &span_label,
140            coarsest: pseudobulks.coarsest,
141            coords: &coords,
142        },
143    )?;
144
145    // coarsen: Ward over the coarsest groups, cut where both children span
146    let n_groups = pseudobulks.coarsest.iter().max().map_or(0, |&m| m + 1);
147    let prof = delta_adjusted_group_profiles(&sums, n_groups, log_delta);
148    let tree = CoarseGroupWardTree::build(&row_scores(
149        &prof,
150        PROFILE_DIM.min(n_groups.saturating_sub(1)).max(1),
151    )?)?;
152    let mut members = vec![Vec::new(); n_groups];
153    for pb in 0..sums.len() {
154        members[sums.coarsest[pb]].push((sums.coarsest[pb], sums.span_label[pb]));
155    }
156    let group_count: Vec<Vec<usize>> = members.into_iter().map(|m| rule.count(m)).collect();
157    let node_of_group = tree.cut_where_both_children_span_batches(&group_count, &rule);
158    let tree_node_of_pb: Vec<Option<usize>> =
159        sums.coarsest.iter().map(|&g| node_of_group[g]).collect();
160    let (node, tree_node_of_node) = compact_present(&tree_node_of_pb);
161    let n_nodes = tree_node_of_node.len();
162    if n_nodes == 0 {
163        warn!(
164            "batch fold: no node spans {} of {} labels with {} coarsest pseudobulks each; keeping δ",
165            rule.min_spans, rule.n_labels, rule.min_pseudobulks
166        );
167    } else {
168        info!("batch fold: {n_groups} coarse groups cut into {n_nodes} nodes");
169    }
170
171    // uncoarsen: a first fold, then local swaps of pb samples under it
172    let first_fold = estimate_fold_on_pseudobulks(
173        &sums,
174        &node,
175        n_nodes,
176        &delta_as_base_of_every_node(log_delta, n_nodes),
177        params,
178    )?;
179    let node = refine_nodes_by_local_swaps(&sums, &rule, node, n_nodes, &first_fold);
180
181    // the fold top down along the tree, from the root to each refined node
182    let final_tree_node: Vec<Option<usize>> = node
183        .iter()
184        .map(|k| k.map(|k| tree_node_of_node[k]))
185        .collect();
186    let fold_of = estimate_fold_top_down(&sums, &tree, &final_tree_node, log_delta, params)?;
187    let mut log_fold = DMatrix::<f32>::zeros(log_delta.nrows(), n_nodes * nb);
188    for (k, t) in tree_node_of_node.iter().enumerate() {
189        log_fold
190            .columns_mut(k * nb, nb)
191            .copy_from(fold_of.get(t).unwrap_or(log_delta));
192    }
193
194    // each unit takes its pb sample's node
195    let node_of_unit: Vec<Option<usize>> = sums
196        .of_unit
197        .iter()
198        .map(|pb| pb.and_then(|pb| node[pb]))
199        .collect();
200    let tree_node_of_unit: Vec<Option<usize>> = node_of_unit
201        .iter()
202        .map(|k| k.map(|k| tree_node_of_node[k]))
203        .collect();
204    let mut node_centroids = DMatrix::<f32>::zeros(coords.nrows(), n_nodes);
205    let mut cnt = vec![0f32; n_nodes];
206    for (c, k) in node_of_unit.iter().enumerate() {
207        if let Some(k) = *k {
208            node_centroids.column_mut(k).add_assign(coords.column(c));
209            cnt[k] += 1.0;
210        }
211    }
212    for (k, &c) in cnt.iter().enumerate() {
213        node_centroids.column_mut(k).scale_mut(1.0 / c.max(1.0));
214    }
215
216    Ok(SampleBatchFold {
217        fold: StateAwareBatchFold {
218            n_batches: nb,
219            n_nodes,
220            log_fold,
221            log_delta: log_delta.clone(),
222            node_of_unit,
223        },
224        tree,
225        tree_node_of_unit,
226        coord_map,
227        coords,
228        node_centroids,
229        tree_node_of_node,
230    })
231}