use super::pseudobulk_sums::PseudobulkSums;
use legume_numeric::matrix::traits::MatOps;
use nalgebra::DMatrix;
use rayon::prelude::*;
pub(crate) fn node_log_mean_compositions(
sums: &PseudobulkSums,
node: &[Option<usize>],
n_nodes: usize,
log_fold: &DMatrix<f32>,
) -> DMatrix<f32> {
let n_genes = sums.n_genes;
let nb = log_fold.ncols() / n_nodes.max(1);
let mut mu = DMatrix::<f32>::zeros(n_genes, n_nodes);
for (pb, k) in node.iter().enumerate() {
if let Some(k) = *k {
let col = k * nb + sums.batch[pb];
for &(g, x) in &sums.counts[pb] {
mu[(g, k)] += x * (-log_fold[(g, col)]).exp();
}
}
}
for mut c in mu.column_iter_mut() {
let floor = (c.sum() / n_genes.max(1) as f32 * 1e-3).max(1e-12);
c.add_scalar_mut(floor);
}
mu.sum_to_one_columns_inplace();
mu.apply(|v| *v = v.ln());
mu
}
pub(crate) fn node_log_compositions(
sums: &PseudobulkSums,
node: &[Option<usize>],
n_nodes: usize,
log_fold: &DMatrix<f32>,
) -> DMatrix<f32> {
let nb = log_fold.ncols() / n_nodes;
let log_mean = node_log_mean_compositions(sums, node, n_nodes, log_fold);
log_compositions_with_fold(&log_mean, log_fold, (0..n_nodes * nb).map(|col| col / nb))
}
fn log_compositions_with_fold(
log_mean: &DMatrix<f32>,
log_fold: &DMatrix<f32>,
node_of_col: impl Iterator<Item = usize>,
) -> DMatrix<f32> {
let cols: Vec<nalgebra::DVector<f32>> = node_of_col
.enumerate()
.map(|(col, k)| log_mean.column(k) + log_fold.column(col))
.collect();
let mut p = DMatrix::from_columns(&cols);
p.log_softmax_columns_inplace();
p
}
pub(crate) fn composition_score(
counts: impl Iterator<Item = (usize, f32)>,
log_p: &DMatrix<f32>,
col: usize,
) -> f32 {
counts.map(|(g, x)| x * log_p[(g, col)]).sum()
}
pub(crate) fn best_column_by_composition(
counts: &[(usize, f32)],
log_p: &DMatrix<f32>,
) -> Option<usize> {
if counts.iter().all(|&(_, x)| x <= 0.0) {
return None;
}
(0..log_p.ncols())
.map(|k| (k, composition_score(counts.iter().copied(), log_p, k)))
.max_by(|a, b| a.1.total_cmp(&b.1))
.map(|(k, _)| k)
}
pub struct CompositionPlacer {
log_p_of_batch: Vec<DMatrix<f32>>,
log_mean: DMatrix<f32>,
}
impl CompositionPlacer {
pub fn new(
log_mean: &DMatrix<f32>,
log_fold: &DMatrix<f32>,
n_batches: usize,
) -> anyhow::Result<Self> {
let (n_genes, n_nodes) = log_mean.shape();
anyhow::ensure!(
log_fold.nrows() == n_genes && log_fold.ncols() == n_nodes * n_batches,
"placement: fold {}×{}, compositions {n_genes}×{n_nodes} over {n_batches} batches",
log_fold.nrows(),
log_fold.ncols(),
);
let log_p_of_batch = (0..n_batches)
.into_par_iter()
.map(|b| {
let cols: Vec<usize> = (0..n_nodes).map(|k| k * n_batches + b).collect();
let fold = log_fold.select_columns(&cols);
log_compositions_with_fold(log_mean, &fold, 0..n_nodes)
})
.collect();
Ok(Self {
log_p_of_batch,
log_mean: log_mean.clone(),
})
}
pub fn place(
&self,
counts: &[Vec<(usize, f32)>],
batch: &[Option<usize>],
) -> anyhow::Result<Vec<Option<usize>>> {
let (n_genes, nb) = (self.log_mean.nrows(), self.log_p_of_batch.len());
anyhow::ensure!(
counts.len() == batch.len(),
"placement: {} count columns, {} batch entries",
counts.len(),
batch.len()
);
if let Some(b) = batch.iter().flatten().find(|&&b| b >= nb) {
anyhow::bail!("placement: batch {b}, the fit saw {nb}");
}
if let Some(g) = counts
.iter()
.flatten()
.map(|&(g, _)| g)
.find(|&g| g >= n_genes)
{
anyhow::bail!("placement: gene {g}, the fit has {n_genes}");
}
Ok(counts
.par_iter()
.zip(batch)
.map(|(x, b)| {
let log_p = b.map_or(&self.log_mean, |b| &self.log_p_of_batch[b]);
best_column_by_composition(x, log_p)
})
.collect())
}
}
pub fn place_by_composition(
counts: &[Vec<(usize, f32)>],
batch: &[Option<usize>],
log_mean: &DMatrix<f32>,
log_fold: &DMatrix<f32>,
n_batches: usize,
) -> anyhow::Result<Vec<Option<usize>>> {
CompositionPlacer::new(log_mean, log_fold, n_batches)?.place(counts, batch)
}