Skip to main content

data_beans/alg/
pseudobulk.rs

1use rustc_hash::FxHashMap as HashMap;
2use std::ops::AddAssign;
3use std::sync::{Arc, Mutex};
4
5use anyhow::{bail, Result};
6use log::info;
7use nalgebra::{DMatrix, DVector};
8
9use crate::aux::cell_annotations::{CellAnnotations, CellTypeMembership};
10use crate::sparse_data_visitors::VisitColumnsOps;
11use crate::sparse_io_vector::SparseIoVec;
12use legume_numeric::param::dmatrix_gamma::GammaMatrix;
13use legume_numeric::param::traits::TwoStatParam;
14
15/// Accumulates gene-level count sums per (individual × cell_type).
16///
17/// Layout: genes × (n_individuals * n_cell_types)
18/// Column index for (individual i, cell_type k) = k * n_individuals + i
19struct CollapseStat {
20    /// Weighted sum of counts: genes × (n_indv * n_ct)
21    count_sum: DMatrix<f32>,
22    /// Effective cell count per (individual, cell_type): n_indv * n_ct
23    cell_weight: DVector<f32>,
24    /// Number of cell types
25    n_cell_types: usize,
26}
27
28/// Input to the visitor: cell-level membership matrix.
29struct VisitorInput {
30    /// Cell membership: cells × cell_types.
31    membership: DMatrix<f32>,
32}
33
34/// Poisson-Gamma pseudobulk output.
35#[derive(Debug)]
36pub struct CollapsedPseudobulk {
37    /// Per cell type: GammaMatrix (genes × individuals)
38    pub gamma_params: Vec<GammaMatrix>,
39    /// Ordered cell type names
40    pub cell_type_names: Vec<Box<str>>,
41    /// Ordered individual IDs
42    pub individual_ids: Vec<Box<str>>,
43    /// Gene names
44    pub gene_names: Vec<Box<str>>,
45    /// Effective cell count per (cell_type_idx, individual_idx) — fractional for soft membership
46    pub cell_weights: Vec<Vec<f32>>,
47}
48
49/// Collapse single-cell counts into Poisson-Gamma pseudobulk parameters.
50///
51/// Groups cells by individual, then weights each cell's expression by its
52/// cell type membership (hard one-hot or soft probabilities).
53///
54/// # Arguments
55/// * `data_vec` - Sparse single-cell count matrix (SparseIoVec over one or more backends)
56/// * `annotations` - Cell-to-individual mapping
57/// * `membership` - Membership matrix (cells × cell_types) and cell type names
58/// * `a0` - Gamma prior shape parameter (default: 1.0)
59/// * `b0` - Gamma prior rate parameter (default: 1.0)
60pub fn collapse_pseudobulk(
61    data_vec: SparseIoVec,
62    annotations: &CellAnnotations,
63    membership: &CellTypeMembership,
64    a0: f32,
65    b0: f32,
66) -> Result<CollapsedPseudobulk> {
67    collapse_pseudobulk_weighted(data_vec, annotations, membership, a0, b0, None)
68}
69
70/// Same as [`collapse_pseudobulk`], but row-scales the per-(individual,
71/// cell_type) count sums by `gene_weights[g]` before the Gamma update. This
72/// is the NB-Fisher housekeeping adjustment used by pinto (see
73/// `gene_weighting::compute_nb_fisher_weights`); housekeeping genes get
74/// attenuated in the posterior mean while informative genes stay at w≈1.
75pub fn collapse_pseudobulk_weighted(
76    mut data_vec: SparseIoVec,
77    annotations: &CellAnnotations,
78    membership: &CellTypeMembership,
79    a0: f32,
80    b0: f32,
81    gene_weights: Option<&[f32]>,
82) -> Result<CollapsedPseudobulk> {
83    let num_genes = data_vec.num_rows();
84    let num_cells = data_vec.num_columns();
85    let n_cell_types = membership.cell_type_names.len();
86
87    if num_genes == 0 || num_cells == 0 {
88        bail!(
89            "SC backend has no data (rows={}, cols={})",
90            num_genes,
91            num_cells
92        );
93    }
94
95    if membership.matrix.nrows() != num_cells || membership.matrix.ncols() != n_cell_types {
96        bail!(
97            "Membership matrix shape ({}, {}) doesn't match (cells={}, cell_types={})",
98            membership.matrix.nrows(),
99            membership.matrix.ncols(),
100            num_cells,
101            n_cell_types
102        );
103    }
104
105    let column_names = data_vec.column_names()?;
106    let gene_names = data_vec.row_names()?;
107
108    info!("SC backend: {} genes × {} cells", num_genes, num_cells);
109
110    let individual_labels = annotations.to_column_aligned_vec(&column_names, "");
111    let matched = individual_labels.iter().filter(|s| !s.is_empty()).count();
112
113    info!("Matched {}/{} cells to annotations", matched, num_cells);
114
115    if matched == 0 {
116        bail!("No cells matched between SC backend and annotations");
117    }
118
119    // Assign groups by individual
120    data_vec.assign_groups(&individual_labels, None);
121
122    let group_keys = data_vec
123        .group_keys()
124        .ok_or_else(|| anyhow::anyhow!("groups not assigned"))?
125        .clone();
126
127    // Map group_key -> individual_idx, skipping unmatched cells (empty key)
128    let ind_lookup: HashMap<&str, usize> = annotations
129        .individual_ids
130        .iter()
131        .enumerate()
132        .map(|(i, id)| (id.as_ref(), i))
133        .collect();
134
135    let n_groups = group_keys.len();
136    let n_individuals = annotations.individual_ids.len();
137
138    info!(
139        "Created {} individual groups, {} cell types",
140        n_groups, n_cell_types
141    );
142
143    // Initialize accumulator: genes × (n_groups * n_cell_types)
144    let stat_cols = n_groups * n_cell_types;
145    let mut stat = CollapseStat {
146        count_sum: DMatrix::zeros(num_genes, stat_cols),
147        cell_weight: DVector::zeros(stat_cols),
148        n_cell_types,
149    };
150
151    let visitor_input = VisitorInput {
152        membership: membership.matrix.clone(),
153    };
154
155    // Visit groups in parallel
156    data_vec.visit_columns_by_group(&collect_stat_visitor, &visitor_input, &mut stat)?;
157
158    // Build GammaMatrix per cell type
159    let mut gamma_params: Vec<GammaMatrix> = Vec::with_capacity(n_cell_types);
160    let mut cell_weights: Vec<Vec<f32>> = Vec::with_capacity(n_cell_types);
161
162    // Map group_keys back to individual indices, skipping unmatched group
163    let group_to_ind: Vec<Option<usize>> = group_keys
164        .iter()
165        .map(|key| ind_lookup.get(key.as_ref()).copied())
166        .collect();
167
168    if let Some(w) = gene_weights {
169        if w.len() != num_genes {
170            bail!("gene_weights length {} != num_genes {}", w.len(), num_genes);
171        }
172    }
173
174    for ct_idx in 0..n_cell_types {
175        let mut count_sum_ct = DMatrix::<f32>::zeros(num_genes, n_individuals);
176        let mut weight_ct = DVector::<f32>::zeros(n_individuals);
177
178        for (group_idx, ind_opt) in group_to_ind.iter().enumerate() {
179            let Some(&ind_idx) = ind_opt.as_ref() else {
180                continue;
181            };
182            let src_col = ct_idx * n_groups + group_idx;
183            count_sum_ct
184                .column_mut(ind_idx)
185                .add_assign(&stat.count_sum.column(src_col));
186            weight_ct[ind_idx] += stat.cell_weight[src_col];
187        }
188
189        if let Some(w) = gene_weights {
190            for (g, &wg) in w.iter().enumerate() {
191                count_sum_ct.row_mut(g).scale_mut(wg);
192            }
193        }
194
195        let denom = DMatrix::from_fn(num_genes, n_individuals, |_g, i| weight_ct[i]);
196
197        let mut gamma = GammaMatrix::new((num_genes, n_individuals), a0, b0);
198        gamma.update_stat(&count_sum_ct, &denom);
199        gamma.calibrate();
200
201        let cw: Vec<f32> = weight_ct.iter().copied().collect();
202        let n_with_cells = cw.iter().filter(|&&c| c > 0.0).count();
203        let total_weight: f32 = cw.iter().sum();
204
205        info!(
206            "Cell type {}: {} individuals with cells, total weight {:.1}",
207            membership.cell_type_names[ct_idx], n_with_cells, total_weight
208        );
209
210        gamma_params.push(gamma);
211        cell_weights.push(cw);
212    }
213
214    Ok(CollapsedPseudobulk {
215        gamma_params,
216        cell_type_names: membership.cell_type_names.clone(),
217        individual_ids: annotations.individual_ids.clone(),
218        gene_names,
219        cell_weights,
220    })
221}
222
223/// Visitor: for each individual group, multiply sparse counts by membership
224/// weights and accumulate.
225///
226/// Computes: `y_gk = Y_gn * Z_nk` (genes × cell_types) per individual
227fn collect_stat_visitor(
228    group_id: usize,
229    cells: &[usize],
230    data: &SparseIoVec,
231    input: &VisitorInput,
232    arc_stat: Arc<Mutex<&mut CollapseStat>>,
233) -> Result<()> {
234    if cells.is_empty() {
235        return Ok(());
236    }
237
238    let y_gn = data.read_columns_csc(cells.iter().cloned())?;
239    let n_cells = cells.len();
240    let n_ct = input.membership.ncols();
241
242    let mut z_nk = DMatrix::<f32>::zeros(n_cells, n_ct);
243    for (local_idx, &global_idx) in cells.iter().enumerate() {
244        z_nk.row_mut(local_idx)
245            .copy_from(&input.membership.row(global_idx));
246    }
247
248    let y_gk: DMatrix<f32> = &y_gn * &z_nk;
249    let z_k = DVector::from_fn(n_ct, |k, _| z_nk.column(k).sum());
250
251    let mut stat = arc_stat.lock().expect("lock");
252    let n_groups = stat.cell_weight.len() / stat.n_cell_types;
253
254    for k in 0..n_ct {
255        let col = k * n_groups + group_id;
256        stat.count_sum.column_mut(col).add_assign(&y_gk.column(k));
257        stat.cell_weight[col] += z_k[k];
258    }
259
260    Ok(())
261}
262
263#[cfg(test)]
264#[path = "pseudobulk_tests.rs"]
265mod tests;