data-beans 0.14.2

Sparse genomics data backends, QC, algorithms, and simulation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Everything upstream of a graph embedding's training: the batch-corrected
//! projection, the multilevel collapse it feeds, and the per-level
//! pseudobulk rates the embedding's phase 1 is built from.
//!
//! One module because it is one dependency chain — the projection exists only
//! to hash cells into the collapse, and the collapse exists only to produce
//! these levels. None of it touches a model.

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;

/// How the pseudobulks are built: the projection, then the collapse.
#[derive(Clone, Debug)]
pub struct BipartiteEmbeddingPseudobulkArgs {
    /// Target rank of the random-projection sketch that seeds batch
    /// correction and the multilevel collapse.
    pub proj_dim: usize,
    /// Columns read per block by the projection (`None`: the backend's own).
    pub block_size: Option<usize>,
    /// Per-feature projection weights on the compact feature axis (HVG
    /// weighting); `None`: every feature weighs 1.
    pub hvg_weights: Option<Vec<f32>>,
    /// The features the sketch reads, on the compact feature axis: on a
    /// multi-track axis the base track's rows, since the other tracks are
    /// offsets from the base model, not independent measurements. `None`:
    /// every feature. The collapse itself always runs on every row.
    pub projection_rows: Option<Vec<bool>>,
    pub seed: u64,
    /// Multilevel-collapse levels (coarse → fine).
    pub num_levels: usize,
    /// Binary-tree partition depth at the finest level: at most
    /// `2^sort_dim + 1` pseudobulk leaves.
    pub sort_dim: usize,
    /// In-batch k-NN used when merging cells into pseudobulk samples.
    pub knn_pb_samples: usize,
    /// Coordinate-descent iterations of the per-batch δ inside the collapse.
    pub num_opt_iter: usize,
    pub refine: RefineParams,
    /// See [`MultilevelParams::anchor_batches`].
    pub anchor_batches: Option<Vec<Box<str>>>,
    /// See [`MultilevelParams::bulk_batches`].
    pub bulk_batches: Option<Vec<Box<str>>>,
    /// Per-cell CNV stratum (`0` = mixable); see [`MultilevelParams::strata`].
    pub strata: Option<Vec<usize>>,
    /// A given partition, finest first, one cell → pseudobulk map per level,
    /// each indexing the backend's columns: collapsed on as is, refinement
    /// skipped. `None`: the hash partition, refined.
    pub partition: Option<Vec<Vec<usize>>>,
}

/// The collapse, ordered **coarsest → finest**, with each cell's pseudobulk
/// per level. Read on the unified (compact) feature axis, with δ's columns in
/// the cells' batch-id order.
pub struct BipartiteEmbeddingPseudobulks {
    pub collapsed_levels: Vec<CollapsedOut>,
    /// `cell_to_pb_per_level[l][c]` is cell `c`'s pseudobulk at level `l`.
    pub cell_to_pb_per_level: Vec<Vec<usize>>,
    /// Each compact feature's backend row; `None` when they are the same axis.
    feature_to_backend: Option<Vec<usize>>,
    /// Each of the cells' batches' column in the collapse's δ, in batch-id
    /// order; `None` when that is already δ's own order.
    delta_col_of_batch: Option<Vec<usize>>,
}

impl BipartiteEmbeddingPseudobulks {
    /// The finest collapse and each cell's pseudobulk in it.
    #[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()
    }

    /// Batch-adjusted when the collapse fit a δ, observed otherwise.
    #[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]
    }

    /// The finest level's observed counts and each pseudobulk's cell count.
    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))
    }

    /// The finest level's batch δ, columns in the cells' batch-id order.
    #[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(),
            )
        })
    }
}

/// `m` restricted to `rows` and `cols` in that order; borrowed when neither
/// is given.
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())),
    }
}

/// Each of `batch_names` (the cells' batch-id order) as a column of a δ whose
/// columns are `collapse_batch_names`: `None` when the two orders already
/// agree, an error when a batch has no column.
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)
}

/// Each compact feature's backend row, or `None` when the compact axis is the
/// backend's own.
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())
}

/// Project, collapse, and keep the levels coarsest → finest.
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,
        // A given partition carries its own level count.
        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(),
        // Only `posterior_mean()` is ever read off this, so skip the sd / log_mean /
        // log_sd planes — that is the bulk of the coarsen-stage memory at high
        // pb-sample counts.
        output_calibration: legume_numeric::param::traits::CalibrateTarget::MeanOnly,
        anchor_batches: args.anchor_batches.clone(),
        bulk_batches: args.bulk_batches.clone(),
        observe_panels: true,
        // The feature partition reads the finest level's counts
        // (`CollapsedOut::observed_counts`), and the pseudobulk
        // reference serializes them; both need the sufficient statistics.
        keep_finest_stats: true,
        pb_tree: None,
        strata: args.strata.clone(),
    };
    let collapse_out = collapse(
        unified.count_backend_mut(),
        &proj_out.proj,
        &batch_labels,
        &params,
        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;
    // The collapse emits finest-first. Reverse both so levels run coarsest..finest —
    // `senna topic` uses the same order, so its curriculum trains coarse first.
    collapsed_levels.reverse();
    cell_to_pb_per_level.reverse();
    // δ's columns follow the backend's batch order; the cells' batch ids
    // follow first appearance. Matched by name once, here.
    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,
    })
}

/// The multilevel collapse of `backend`'s columns: built from the hash partition and
/// refined, or — given `partition` (finest first, one cell → pseudobulk map per level,
/// each indexing `backend`'s columns) — collapsed on that partition as is, the
/// refinement skipped. `proj` still seeds the cross-batch matching either way.
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"))
}

/// A given partition must hold at least the finest level, and every level must map each
/// of the backend's `n_cells` columns.
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(())
}

/// The batch-corrected random projection the collapse hashes on, HVG-weighted when the
/// caller supplied weights, on `args.projection_rows` alone when given. The collapse
/// itself still runs on the FULL backend with this sketch, so refinement, `mu_adjusted`
/// and `δ` cover every row.
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();
    // The projection runs on the full backend row axis, which may be wider than the
    // compact feature axis when a prior pass dropped features. Scatter the compact
    // weights to backend rows; rows not in the current feature axis get 0 so they sit
    // out the projection basis.
    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)?;
    // `mask_rows` RENUMBERS the kept rows compactly, so the weight vector has to be
    // subset the same way — a full-axis vector would misalign every row.
    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,
    )
}

/// The backend rows the sketch reads: those of the compact features `rows` marks.
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)
}

/// `values` restricted to the `keep`ed positions, in the same order — the order
/// [`SparseIoVec::mask_rows`] renumbers them into.
fn subset_kept(values: &[f32], keep: &[bool]) -> Vec<f32> {
    values
        .iter()
        .zip(keep)
        .filter(|&(_, &k)| k)
        .map(|(&v, _)| v)
        .collect()
}

/// One random projection over `backend`, weighted when `row_weights` is given (length =
/// `backend.num_rows()`).
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;