Skip to main content

data_beans/alg/collapse_data/state_aware_batch_fold/
node_compositions.rs

1//! Node compositions, and scoring counts against them: what the local swaps
2//! move pseudobulks by, and what places a unit the fit never saw (predict,
3//! impute) on a node or a link state.
4//!
5//! ```text
6//! ln p_{k,b} = ln normalize(μ_k ⊙ f_{k,b}),   score(x → k) = Σ_g x_g · ln p_{k,b,g}
7//! ```
8//!
9//! with `μ_k` the node's fold-corrected composition and `f_{k,b}` its fold
10//! in batch `b` (carrying δ). A batch the fit never saw has no fold: its
11//! units are scored against `μ_k` alone, on counts the caller has divided by
12//! that batch's own δ.
13
14use super::pseudobulk_sums::PseudobulkSums;
15use legume_numeric::matrix::traits::MatOps;
16use nalgebra::DMatrix;
17use rayon::prelude::*;
18
19/// Each node's fold-corrected composition, log, genes × nodes:
20/// `ln normalize(μ_k + floor)`, `μ_k` the node's sum with each pseudobulk's
21/// fold (`log_fold`, genes × (nodes · batches)) divided out. The floor makes
22/// a gene the node never showed unlikely, not impossible.
23pub(crate) fn node_log_mean_compositions(
24    sums: &PseudobulkSums,
25    node: &[Option<usize>],
26    n_nodes: usize,
27    log_fold: &DMatrix<f32>,
28) -> DMatrix<f32> {
29    let n_genes = sums.n_genes;
30    let nb = log_fold.ncols() / n_nodes.max(1);
31    let mut mu = DMatrix::<f32>::zeros(n_genes, n_nodes);
32    for (pb, k) in node.iter().enumerate() {
33        if let Some(k) = *k {
34            let col = k * nb + sums.batch[pb];
35            for &(g, x) in &sums.counts[pb] {
36                mu[(g, k)] += x * (-log_fold[(g, col)]).exp();
37            }
38        }
39    }
40    for mut c in mu.column_iter_mut() {
41        let floor = (c.sum() / n_genes.max(1) as f32 * 1e-3).max(1e-12);
42        c.add_scalar_mut(floor);
43    }
44    mu.sum_to_one_columns_inplace();
45    mu.apply(|v| *v = v.ln());
46    mu
47}
48
49/// Each node's composition in each batch, log, genes × (nodes · batches):
50/// `ln normalize(μ_k ⊙ fold_{k,b})`.
51pub(crate) fn node_log_compositions(
52    sums: &PseudobulkSums,
53    node: &[Option<usize>],
54    n_nodes: usize,
55    log_fold: &DMatrix<f32>,
56) -> DMatrix<f32> {
57    let nb = log_fold.ncols() / n_nodes;
58    let log_mean = node_log_mean_compositions(sums, node, n_nodes, log_fold);
59    log_compositions_with_fold(&log_mean, log_fold, (0..n_nodes * nb).map(|col| col / nb))
60}
61
62/// `ln normalize(exp(log_mean[:, k]) ⊙ exp(log_fold[:, col]))` for each
63/// column `col` of `log_fold` taken, `k` its node (`node_of_col`, in the
64/// order taken: column `j` of the result is the `j`-th taken).
65fn log_compositions_with_fold(
66    log_mean: &DMatrix<f32>,
67    log_fold: &DMatrix<f32>,
68    node_of_col: impl Iterator<Item = usize>,
69) -> DMatrix<f32> {
70    let cols: Vec<nalgebra::DVector<f32>> = node_of_col
71        .enumerate()
72        .map(|(col, k)| log_mean.column(k) + log_fold.column(col))
73        .collect();
74    let mut p = DMatrix::from_columns(&cols);
75    p.log_softmax_columns_inplace();
76    p
77}
78
79/// The log likelihood of `counts` (gene, count) under the composition in
80/// column `col` of `log_p` (genes × columns, each a log composition), up
81/// to the multinomial constant: `Σ_g x_g · log_p[g, col]`. Swaps score a
82/// pseudobulk by it; placement scores a unit the fit never saw by it.
83pub(crate) fn composition_score(
84    counts: impl Iterator<Item = (usize, f32)>,
85    log_p: &DMatrix<f32>,
86    col: usize,
87) -> f32 {
88    counts.map(|(g, x)| x * log_p[(g, col)]).sum()
89}
90
91/// The column of `log_p` that explains `counts` best ([`composition_score`]);
92/// `None` when `counts` hold no read.
93pub(crate) fn best_column_by_composition(
94    counts: &[(usize, f32)],
95    log_p: &DMatrix<f32>,
96) -> Option<usize> {
97    if counts.iter().all(|&(_, x)| x <= 0.0) {
98        return None;
99    }
100    (0..log_p.ncols())
101        .map(|k| (k, composition_score(counts.iter().copied(), log_p, k)))
102        .max_by(|a, b| a.1.total_cmp(&b.1))
103        .map(|(k, _)| k)
104}
105
106/// Places units the fit never saw, by composition: each node's composition
107/// in each batch, built once, then any number of count columns scored
108/// against them ([`Self::place`]).
109pub struct CompositionPlacer {
110    /// Per batch the fit saw: each node's composition in it, log, genes × nodes.
111    log_p_of_batch: Vec<DMatrix<f32>>,
112    /// Each node's fold-corrected composition, log, genes × nodes: what a
113    /// batch the fit never saw is scored against.
114    log_mean: DMatrix<f32>,
115}
116
117impl CompositionPlacer {
118    /// From the nodes' fold-corrected compositions `log_mean` (genes ×
119    /// nodes) and their folds `log_fold` (genes × (nodes · `n_batches`)).
120    pub fn new(
121        log_mean: &DMatrix<f32>,
122        log_fold: &DMatrix<f32>,
123        n_batches: usize,
124    ) -> anyhow::Result<Self> {
125        let (n_genes, n_nodes) = log_mean.shape();
126        anyhow::ensure!(
127            log_fold.nrows() == n_genes && log_fold.ncols() == n_nodes * n_batches,
128            "placement: fold {}×{}, compositions {n_genes}×{n_nodes} over {n_batches} batches",
129            log_fold.nrows(),
130            log_fold.ncols(),
131        );
132        let log_p_of_batch = (0..n_batches)
133            .into_par_iter()
134            .map(|b| {
135                let cols: Vec<usize> = (0..n_nodes).map(|k| k * n_batches + b).collect();
136                let fold = log_fold.select_columns(&cols);
137                log_compositions_with_fold(log_mean, &fold, 0..n_nodes)
138            })
139            .collect();
140        Ok(Self {
141            log_p_of_batch,
142            log_mean: log_mean.clone(),
143        })
144    }
145
146    /// Each count column (`(gene, count)` pairs) on the node whose
147    /// composition explains it best ([`composition_score`]). `batch[c]` is
148    /// `Some(b)` for a batch the fit saw (scored against each node's
149    /// composition in `b`, the counts as read) or `None` for one it never
150    /// saw (scored against the fold-corrected compositions alone, the counts
151    /// divided by that batch's own δ). `None` for a column with no read.
152    /// Errors on a length mismatch, a batch or gene outside the fit.
153    pub fn place(
154        &self,
155        counts: &[Vec<(usize, f32)>],
156        batch: &[Option<usize>],
157    ) -> anyhow::Result<Vec<Option<usize>>> {
158        let (n_genes, nb) = (self.log_mean.nrows(), self.log_p_of_batch.len());
159        anyhow::ensure!(
160            counts.len() == batch.len(),
161            "placement: {} count columns, {} batch entries",
162            counts.len(),
163            batch.len()
164        );
165        if let Some(b) = batch.iter().flatten().find(|&&b| b >= nb) {
166            anyhow::bail!("placement: batch {b}, the fit saw {nb}");
167        }
168        if let Some(g) = counts
169            .iter()
170            .flatten()
171            .map(|&(g, _)| g)
172            .find(|&g| g >= n_genes)
173        {
174            anyhow::bail!("placement: gene {g}, the fit has {n_genes}");
175        }
176        Ok(counts
177            .par_iter()
178            .zip(batch)
179            .map(|(x, b)| {
180                let log_p = b.map_or(&self.log_mean, |b| &self.log_p_of_batch[b]);
181                best_column_by_composition(x, log_p)
182            })
183            .collect())
184    }
185}
186
187/// One placement by [`CompositionPlacer`]: built, then used once.
188pub fn place_by_composition(
189    counts: &[Vec<(usize, f32)>],
190    batch: &[Option<usize>],
191    log_mean: &DMatrix<f32>,
192    log_fold: &DMatrix<f32>,
193    n_batches: usize,
194) -> anyhow::Result<Vec<Option<usize>>> {
195    CompositionPlacer::new(log_mean, log_fold, n_batches)?.place(counts, batch)
196}