use super::BipartiteEmbeddingCells;
use crate::alg::collapse_data::{
collapse_columns_multilevel_with_hierarchy, collapse_columns_multilevel_with_partition,
CollapsedOut, MultilevelCollapseOut, MultilevelParams,
};
use crate::alg::random_projection::{RandColProjOut, RandProjOps};
use crate::alg::refine_multilevel::RefineParams;
use crate::sparse_io_vector::SparseIoVec;
use legume_numeric::param::traits::Inference;
use log::info;
use nalgebra::DMatrix;
use std::borrow::Cow;
#[derive(Clone, Debug)]
pub struct BipartiteEmbeddingPseudobulkArgs {
pub proj_dim: usize,
pub block_size: Option<usize>,
pub hvg_weights: Option<Vec<f32>>,
pub projection_rows: Option<Vec<bool>>,
pub seed: u64,
pub num_levels: usize,
pub sort_dim: usize,
pub knn_pb_samples: usize,
pub num_opt_iter: usize,
pub refine: RefineParams,
pub anchor_batches: Option<Vec<Box<str>>>,
pub bulk_batches: Option<Vec<Box<str>>>,
pub strata: Option<Vec<usize>>,
pub partition: Option<Vec<Vec<usize>>>,
}
pub struct BipartiteEmbeddingPseudobulks {
pub collapsed_levels: Vec<CollapsedOut>,
pub cell_to_pb_per_level: Vec<Vec<usize>>,
feature_to_backend: Option<Vec<usize>>,
delta_col_of_batch: Option<Vec<usize>>,
}
impl BipartiteEmbeddingPseudobulks {
#[must_use]
pub fn finest_collapse(&self) -> (&CollapsedOut, &[usize]) {
(
self.collapsed_levels.last().expect("at least one level"),
self.cell_to_pb_per_level
.last()
.expect("membership per level"),
)
}
#[must_use]
pub fn n_levels(&self) -> usize {
self.collapsed_levels.len()
}
#[must_use]
pub fn rates(&self, level: usize) -> Cow<'_, DMatrix<f32>> {
let collapsed = &self.collapsed_levels[level];
let full = match &collapsed.mu_adjusted {
Some(adj) => adj.posterior_mean(),
None => collapsed.mu_observed.posterior_mean(),
};
select(full, self.feature_to_backend.as_deref(), None)
}
#[must_use]
pub fn cell_to_pb(&self, level: usize) -> &[usize] {
&self.cell_to_pb_per_level[level]
}
pub fn finest_counts(&self) -> anyhow::Result<(DMatrix<f32>, Vec<f32>)> {
let (finest, cell_to_pb) = self.finest_collapse();
let (counts, sizes) = finest.observed_counts(cell_to_pb)?;
let counts = match &self.feature_to_backend {
Some(rows) => counts.select_rows(rows.iter()),
None => counts,
};
Ok((counts, sizes))
}
#[must_use]
pub fn finest_delta(&self) -> Option<Cow<'_, DMatrix<f32>>> {
let (finest, _) = self.finest_collapse();
finest.delta.as_ref().map(|d| {
select(
d.posterior_mean(),
self.feature_to_backend.as_deref(),
self.delta_col_of_batch.as_deref(),
)
})
}
}
fn select<'a>(
m: &'a DMatrix<f32>,
rows: Option<&[usize]>,
cols: Option<&[usize]>,
) -> Cow<'a, DMatrix<f32>> {
match (rows, cols) {
(None, None) => Cow::Borrowed(m),
(Some(r), None) => Cow::Owned(m.select_rows(r.iter())),
(None, Some(c)) => Cow::Owned(m.select_columns(c.iter())),
(Some(r), Some(c)) => Cow::Owned(m.select_rows(r.iter()).select_columns(c.iter())),
}
}
fn delta_columns_by_batch(
collapse_batch_names: &[Box<str>],
batch_names: &[Box<str>],
) -> anyhow::Result<Option<Vec<usize>>> {
if collapse_batch_names == batch_names {
return Ok(None);
}
let col_of: rustc_hash::FxHashMap<&str, usize> = collapse_batch_names
.iter()
.enumerate()
.map(|(c, name)| (name.as_ref(), c))
.collect();
batch_names
.iter()
.map(|name| {
col_of.get(name.as_ref()).copied().ok_or_else(|| {
anyhow::anyhow!(
"batch {name:?} has no δ column in the collapse (collapse batches: {})",
collapse_batch_names.join(", ")
)
})
})
.collect::<anyhow::Result<Vec<usize>>>()
.map(Some)
}
fn compact_rows(unified: &BipartiteEmbeddingCells) -> Option<Vec<usize>> {
let f2b = &unified.feature_to_backend_row;
let identity = f2b.len() == unified.count_backend().num_rows()
&& f2b.iter().enumerate().all(|(i, &r)| i == r);
(!identity).then(|| f2b.clone())
}
pub fn build_bipartite_embedding_pseudobulks(
unified: &mut BipartiteEmbeddingCells,
args: &BipartiteEmbeddingPseudobulkArgs,
) -> anyhow::Result<BipartiteEmbeddingPseudobulks> {
let batch_labels: Vec<Box<str>> = unified.batch_labels();
let proj_out = project(unified, args, &batch_labels)?;
let params = MultilevelParams {
knn_pb_samples: args.knn_pb_samples,
num_levels: args
.partition
.as_ref()
.map_or(args.num_levels, Vec::len)
.max(1),
sort_dim: args.sort_dim,
num_opt_iter: args.num_opt_iter,
refine: args.refine.clone(),
output_calibration: legume_numeric::param::traits::CalibrateTarget::MeanOnly,
anchor_batches: args.anchor_batches.clone(),
bulk_batches: args.bulk_batches.clone(),
observe_panels: true,
keep_finest_stats: true,
pb_tree: None,
strata: args.strata.clone(),
};
let collapse_out = collapse(
unified.count_backend_mut(),
&proj_out.proj,
&batch_labels,
¶ms,
args.partition.as_deref(),
)?;
let mut collapsed_levels = collapse_out.levels;
let mut cell_to_pb_per_level = collapse_out.cell_to_pb_per_level;
collapsed_levels.reverse();
cell_to_pb_per_level.reverse();
let has_delta = collapsed_levels.last().is_some_and(|c| c.delta.is_some());
let delta_col_of_batch = if has_delta {
let collapse_batch_names = unified.count_backend().batch_names().ok_or_else(|| {
anyhow::anyhow!("the collapse fit a δ but the backend has no batch names")
})?;
delta_columns_by_batch(&collapse_batch_names, &unified.batch_names)?
} else {
None
};
Ok(BipartiteEmbeddingPseudobulks {
collapsed_levels,
cell_to_pb_per_level,
feature_to_backend: compact_rows(unified),
delta_col_of_batch,
})
}
fn collapse(
backend: &mut SparseIoVec,
proj: &DMatrix<f32>,
batch_labels: &[Box<str>],
params: &MultilevelParams,
partition: Option<&[Vec<usize>]>,
) -> anyhow::Result<MultilevelCollapseOut> {
let Some(partition) = partition else {
info!(
"Multilevel collapse (sort_dim={}, {} levels requested)...",
params.sort_dim, params.num_levels
);
return collapse_columns_multilevel_with_hierarchy(backend, proj, batch_labels, params);
};
check_partition(partition, backend.num_columns())?;
info!(
"Multilevel collapse on a given partition ({} levels, {} cells; refinement skipped)...",
partition.len(),
backend.num_columns()
);
collapse_columns_multilevel_with_partition(backend, proj, batch_labels, params, partition)
.map_err(|e| e.context("collapsing on the given partition"))
}
fn check_partition(partition: &[Vec<usize>], n_cells: usize) -> anyhow::Result<()> {
anyhow::ensure!(
!partition.is_empty(),
"the given partition has no levels (it needs at least the finest)"
);
for (level, cell_to_pb) in partition.iter().enumerate() {
anyhow::ensure!(
cell_to_pb.len() == n_cells,
"the given partition's level {level} (finest first) maps {} cells, but the count \
backend has {n_cells} columns",
cell_to_pb.len()
);
}
Ok(())
}
fn project(
unified: &BipartiteEmbeddingCells,
args: &BipartiteEmbeddingPseudobulkArgs,
batch_labels: &[Box<str>],
) -> anyhow::Result<RandColProjOut> {
info!(
"Batch-corrected projection (proj_dim={}, {} batches)...",
args.proj_dim,
unified.n_batches()
);
let batch_arg = (unified.n_batches() > 1).then_some(batch_labels);
let backend = unified.count_backend();
let backend_w: Option<Vec<f32>> = match args.hvg_weights.as_deref() {
None => None,
Some(w) => {
anyhow::ensure!(
w.len() == unified.n_features(),
"hvg_weights length {} != n_features {} (the HVG mask must be aligned to the \
unified feature axis BEFORE any subset/coarsening — pass full-axis weights from \
the wrapper)",
w.len(),
unified.n_features()
);
info!(
"HVG-weighted projection: {} weighted features (>= 1.0)",
w.iter().filter(|&&x| x > 0.0).count()
);
let mut backend_w = vec![0.0f32; backend.num_rows()];
for (compact_i, &brow) in unified.feature_to_backend_row.iter().enumerate() {
backend_w[brow] = w[compact_i];
}
Some(backend_w)
}
};
let Some(rows) = args.projection_rows.as_deref() else {
return project_backend(
backend,
args.proj_dim,
args.block_size,
batch_arg,
backend_w.as_deref(),
args.seed,
);
};
let keep = projection_row_mask(rows, &unified.feature_to_backend_row, backend.num_rows())?;
info!(
"Sketching on {} of {} backend rows",
keep.iter().filter(|&&k| k).count(),
keep.len()
);
let mut view = backend.clone_for_collapse();
view.mask_rows(&keep)?;
let view_w = backend_w.map(|w| subset_kept(&w, &keep));
project_backend(
&view,
args.proj_dim,
args.block_size,
batch_arg,
view_w.as_deref(),
args.seed,
)
}
fn projection_row_mask(
rows: &[bool],
feature_to_backend: &[usize],
backend_rows: usize,
) -> anyhow::Result<Vec<bool>> {
anyhow::ensure!(
rows.len() == feature_to_backend.len(),
"projection_rows has {} entries for {} features",
rows.len(),
feature_to_backend.len()
);
let mut keep = vec![false; backend_rows];
for (&on, &brow) in rows.iter().zip(feature_to_backend) {
if on {
keep[brow] = true;
}
}
Ok(keep)
}
fn subset_kept(values: &[f32], keep: &[bool]) -> Vec<f32> {
values
.iter()
.zip(keep)
.filter(|&(_, &k)| k)
.map(|(&v, _)| v)
.collect()
}
fn project_backend<T>(
backend: &SparseIoVec,
proj_dim: usize,
block_size: Option<usize>,
batch_arg: Option<&[T]>,
row_weights: Option<&[f32]>,
seed: u64,
) -> anyhow::Result<RandColProjOut>
where
T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
{
match row_weights {
None => backend
.project_columns_with_batch_correction_seeded(proj_dim, block_size, batch_arg, seed),
Some(w) => {
backend.project_columns_weighted_seeded(proj_dim, block_size, batch_arg, w, seed)
}
}
}
#[cfg(test)]
#[path = "pseudobulks_tests.rs"]
mod tests;