data_beans/alg/collapse_data/state_aware_batch_fold/
node_compositions.rs1use super::pseudobulk_sums::PseudobulkSums;
15use legume_numeric::matrix::traits::MatOps;
16use nalgebra::DMatrix;
17use rayon::prelude::*;
18
19pub(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
49pub(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
62fn 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
79pub(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
91pub(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
106pub struct CompositionPlacer {
110 log_p_of_batch: Vec<DMatrix<f32>>,
112 log_mean: DMatrix<f32>,
115}
116
117impl CompositionPlacer {
118 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 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
187pub 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}