data-beans 0.14.1

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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Barcode-keyed loader for arbitrary multi-modal panels, and the pseudobulks
//! a graph embedding trains on. Each input file contributes its rows to a
//! unified feature axis; cells (barcodes) are unioned across files. Per-cell
//! batch labels (from `batch_files`, `@batch` tags, or file names) are
//! deduped into a global namespace so downstream samplers can restrict
//! negatives to within-batch.
//!
//! Moved here from legume-graph-embedding, which now trains on what this
//! module hands it ([`BipartiteEmbeddingCells::for_each_count`] and [`BipartiteEmbeddingPseudobulks`]; each app
//! adapts them to its trainer) and no longer depends on data-beans.

mod count_stream;
mod pseudobulks;

pub use pseudobulks::{
    build_bipartite_embedding_pseudobulks, BipartiteEmbeddingPseudobulkArgs,
    BipartiteEmbeddingPseudobulks,
};

use crate::aux::data_loading::{read_data_on_shared_rows, ReadSharedRowsArgs};
use crate::aux::feature_names::FeatureNameKind;
use crate::sparse_io_vector::{ColumnAlignment, SparseIoVec};
use log::info;
use rustc_hash::FxHashMap;

pub struct BipartiteEmbeddingCells {
    //////////////////
    // cell indices //
    //////////////////
    pub barcodes: Vec<Box<str>>,

    /// Global cell id → global batch id.
    pub batch_membership: Vec<u32>,

    /// Global batch labels in id order.
    pub batch_names: Vec<Box<str>>,

    /// Global cell id → global condition id, from optional per-cell
    /// condition labels. Defaults to a copy of `batch_membership` when no
    /// separate condition input is given. Retained loader state: no model
    /// currently reads it.
    pub condition_membership: Vec<u32>,

    /// Global condition labels in id order. Defaults to `batch_names`.
    pub condition_names: Vec<Box<str>>,

    /// Per unified cell, a bitmask of which input files (modalities) the
    /// cell appears in: bit `b` set ⇔ the cell's barcode is present in
    /// backend `b`. Single-file / non-multiome loads set bit 0 for every
    /// cell. `count_ones() >= 2` marks a **matched** (multi-modal bridge)
    /// cell. Drives `--multiome` auto modality-batching and matched-cell
    /// up-weighting.
    pub cell_modality: Vec<u32>,

    ///////////////////
    // feature index //
    ///////////////////
    pub feature_names: Vec<Box<str>>,
    /// For each compact feature id `i ∈ 0..n_features()`, the row index into
    /// `backend`. Identity (`0..n_features()`) when no HVG was applied; the
    /// HVG selection indices after `subset_features`.
    pub feature_to_backend_row: Vec<usize>,

    /// Modality id per feature, when the load namespaced rows as
    /// `{name}/{modality}` (a multiome load). `None` for a single panel.
    ///
    /// Taken from the suffix list the loader was GIVEN, never re-parsed out of
    /// the row names: other producers use the same separator for a different
    /// grammar — faba/gem rows are `{gene}/{modality}/{channel}`, whose last
    /// field is the splice channel — and a trailing-field rule reads those as
    /// two modalities and silently re-scopes their negative pools.
    pub feature_modality: Option<std::sync::Arc<[u32]>>,

    /// The underlying sparse count matrix.
    pub backend: SparseIoVec,
}

impl BipartiteEmbeddingCells {
    /// Borrow the sparse count backend.
    #[must_use]
    pub fn count_backend(&self) -> &SparseIoVec {
        &self.backend
    }

    /// Mutably borrow the sparse count backend.
    pub fn count_backend_mut(&mut self) -> &mut SparseIoVec {
        &mut self.backend
    }

    #[must_use]
    pub fn n_cells(&self) -> usize {
        self.barcodes.len()
    }

    #[must_use]
    pub fn n_features(&self) -> usize {
        self.feature_names.len()
    }

    #[must_use]
    pub fn n_batches(&self) -> usize {
        self.batch_names.len()
    }

    /// Per-cell batch labels (`batch_names[batch_membership[c]]`), in cell-id
    /// order. Length == `n_cells()`. The string form the projection /
    /// multilevel collapse consume for within-batch negatives.
    #[must_use]
    pub fn batch_labels(&self) -> Vec<Box<str>> {
        self.batch_membership
            .iter()
            .map(|&b| self.batch_names[b as usize].clone())
            .collect()
    }

    /// Restrict to a subset of features (by current feature id): remaps them
    /// to compact `0..k` ids, updates `feature_names` and composes
    /// `feature_to_backend_row` so the new compact id `i` still maps to the
    /// right row in `backend`. The backend itself is not touched.
    ///
    /// Used to apply HVG selection (`crate::alg::hvg::select_hvg_streaming`).
    pub fn subset_features(&mut self, selected_indices: &[usize]) {
        if selected_indices.len() == self.n_features() {
            return; // no-op
        }
        let n_old = self.n_features();
        let new_feature_names: Vec<Box<str>> = selected_indices
            .iter()
            .map(|&i| {
                debug_assert!(i < n_old, "selected index {i} out of range");
                self.feature_names[i].clone()
            })
            .collect();
        let new_feature_to_backend_row: Vec<usize> = selected_indices
            .iter()
            .map(|&i| self.feature_to_backend_row[i])
            .collect();
        let new_feature_modality: Option<std::sync::Arc<[u32]>> =
            self.feature_modality.as_ref().map(|m| {
                selected_indices
                    .iter()
                    .map(|&i| m[i])
                    .collect::<Vec<u32>>()
                    .into()
            });
        info!(
            "Feature subset: {} → {} features",
            n_old,
            new_feature_names.len()
        );
        self.feature_names = new_feature_names;
        self.feature_to_backend_row = new_feature_to_backend_row;
        self.feature_modality = new_feature_modality;
    }

    /// Build a `BipartiteEmbeddingCells` from a single in-memory `SparseIoVec` plus
    /// per-cell batch labels. Internal helper for [`load_bipartite_embedding_cells`].
    fn from_sparse_io(
        data: SparseIoVec,
        batch_labels: &[Box<str>],
        condition_labels: Option<&[Box<str>]>,
        auto_modality_batch: bool,
        feature_suffix: Option<&[Box<str>]>,
    ) -> anyhow::Result<Self> {
        let feature_names = data.row_names()?;
        let feature_modality = feature_modality_from_suffix(&feature_names, feature_suffix);
        let barcodes = data.column_names()?;

        // Per-cell modality bitmask: which input backend(s) each unified
        // barcode appears in. Single-backend loads → bit 0 for all cells.
        let n_back = data.len();
        let cell_modality = if n_back > 1 {
            let bc_to_idx: FxHashMap<&str, usize> = barcodes
                .iter()
                .enumerate()
                .map(|(i, b)| (b.as_ref(), i))
                .collect();
            let mut mask = vec![0u32; barcodes.len()];
            for b in 0..n_back.min(32) {
                for name in data[b].column_names()? {
                    if let Some(&i) = bc_to_idx.get(name.as_ref()) {
                        mask[i] |= 1u32 << b;
                    }
                }
            }
            mask
        } else {
            vec![1u32; barcodes.len()]
        };

        // `--multiome` auto-batch: when no explicit batch labels were
        // resolved, group cells by their modality-presence pattern so the
        // δ-correction integrates matched + unimodal cohorts onto shared
        // axes. Otherwise honor the labels the loader resolved.
        let derived: Vec<Box<str>>;
        let batch_labels: &[Box<str>] = if auto_modality_batch && n_back > 1 {
            derived = cell_modality
                .iter()
                .map(|&m| modality_presence_label(m, n_back))
                .collect();
            &derived
        } else {
            batch_labels
        };
        anyhow::ensure!(
            batch_labels.len() == barcodes.len(),
            "batch labels {} != cells {}",
            batch_labels.len(),
            barcodes.len()
        );

        // Dedupe batch labels into a global namespace (in first-seen order).
        let (batch_membership, batch_names) = dedup_labels(batch_labels);

        info!(
            "Unified barcodes: {} total (single in-memory data set)",
            barcodes.len()
        );
        info!(
            "Unified batches: {} ({})",
            batch_names.len(),
            truncate_names(&batch_names, 6)
        );

        // Condition axis: defaults to a copy of the batch axis when no
        // separate per-cell condition labels are supplied. When given,
        // dedupe into a global namespace the same first-seen way.
        let (condition_membership, condition_names): (Vec<u32>, Vec<Box<str>>) =
            match condition_labels {
                None => (batch_membership.clone(), batch_names.clone()),
                Some(labels) => {
                    anyhow::ensure!(
                        labels.len() == barcodes.len(),
                        "condition labels {} != cells {}",
                        labels.len(),
                        barcodes.len()
                    );
                    dedup_labels(labels)
                }
            };
        // Only log conditions when they differ from the batch axis.
        if condition_names != batch_names {
            info!(
                "Unified conditions: {} ({})",
                condition_names.len(),
                truncate_names(&condition_names, 6)
            );
        }

        let n_features = feature_names.len();
        Ok(BipartiteEmbeddingCells {
            barcodes,
            batch_membership,
            batch_names,
            condition_membership,
            condition_names,
            cell_modality,
            feature_names,
            feature_to_backend_row: (0..n_features).collect(),
            feature_modality,
            backend: data,
        })
    }
}

/// Per-feature modality id from the suffix list the loader applied, matching
/// each row against the `/{suffix}` it was namespaced with.
///
/// Deliberately NOT a trailing-field parse of the row name: `/` is also the
/// separator of the `{gene}/{modality}/{channel}` grammar faba writes and gem
/// reads, whose last field is a splice channel. Matching the suffixes the load
/// actually used cannot confuse the two. Returns `None` unless every row
/// carries one of them and at least two are present.
fn feature_modality_from_suffix(
    feature_names: &[Box<str>],
    feature_suffix: Option<&[Box<str>]>,
) -> Option<std::sync::Arc<[u32]>> {
    let suffixes = feature_suffix?;
    let mut ids: FxHashMap<&str, u32> = FxHashMap::default();
    for s in suffixes {
        let next = ids.len() as u32;
        ids.entry(s.as_ref()).or_insert(next);
    }
    if ids.len() < 2 {
        return None;
    }
    let mut out: Vec<u32> = Vec::with_capacity(feature_names.len());
    for name in feature_names {
        let (_, tag) = name.rsplit_once('/')?;
        out.push(*ids.get(tag)?);
    }
    Some(out.into())
}

/// Format the first `max_show` names from a slice, appending "… and N more" when
/// the slice is longer, so INFO log lines stay readable regardless of set size.
fn truncate_names(names: &[Box<str>], max_show: usize) -> String {
    if names.len() <= max_show {
        names
            .iter()
            .map(std::convert::AsRef::as_ref)
            .collect::<Vec<_>>()
            .join(", ")
    } else {
        let shown: Vec<&str> = names[..max_show]
            .iter()
            .map(std::convert::AsRef::as_ref)
            .collect();
        format!("{} … and {} more", shown.join(", "), names.len() - max_show)
    }
}

/// Map per-cell string labels to compact `u32` ids in first-seen order,
/// returning `(membership, names)` where `names[membership[i]] == labels[i]`.
/// Shared by the batch and condition axes.
fn dedup_labels(labels: &[Box<str>]) -> (Vec<u32>, Vec<Box<str>>) {
    let mut to_global: FxHashMap<Box<str>, u32> = FxHashMap::default();
    let mut names: Vec<Box<str>> = Vec::new();
    let membership: Vec<u32> = labels
        .iter()
        .map(|label| {
            *to_global.entry(label.clone()).or_insert_with(|| {
                let g = names.len() as u32;
                names.push(label.clone());
                g
            })
        })
        .collect();
    (membership, names)
}

/// Human-readable batch label for a modality-presence bitmask, e.g.
/// `m0`, `m1`, or `m0+m2`. Stable across cells with the same pattern, so
/// the dedupe in `from_sparse_io` collapses them into one batch each.
fn modality_presence_label(mask: u32, n_back: usize) -> Box<str> {
    let present: Vec<String> = (0..n_back.min(32))
        .filter(|&b| mask & (1u32 << b) != 0)
        .map(|b| format!("m{b}"))
        .collect();
    if present.is_empty() {
        "none".to_string().into_boxed_str()
    } else {
        present.join("+").into_boxed_str()
    }
}

/// Inputs for [`load_bipartite_embedding_cells`]. Build with `..Default::default()` and
/// set only the fields a given flow needs — most callers leave the suffix /
/// condition axes at their `None` defaults.
#[derive(Default)]
pub struct LoadBipartiteEmbeddingCellsArgs {
    /// Sparse data files (prefixes) to load, in order.
    pub data_files: Vec<Box<str>>,
    /// Optional per-cell batch labels. Under [`ColumnAlignment::Union`]
    /// exactly one file (one label per unified cell); under `Disjoint` one
    /// file per data file. `None` → infer from `@batch` tags / file names.
    pub batch_files: Option<Vec<Box<str>>>,
    /// Optional per-cell condition labels (same shape rules as `batch_files`).
    /// `None` → condition = batch.
    pub condition_files: Option<Vec<Box<str>>>,
    /// Cross-file row-name canonicalization. `None` = auto-detect.
    pub feature_kind: Option<FeatureNameKind>,
    /// Preload every sparse column into memory before any pass over cells.
    pub preload: bool,
    /// How to align cells (barcodes) across files.
    pub column_alignment: ColumnAlignment,
    /// Per-file row (feature) modality suffix — see
    /// [`ReadSharedRowsArgs::per_file_feature_suffix`].
    pub per_file_feature_suffix: Option<Vec<Box<str>>>,
    /// Per-file barcode (sample) suffix — see
    /// [`ReadSharedRowsArgs::per_file_barcode_suffix`].
    pub per_file_barcode_suffix: Option<Vec<Option<Box<str>>>>,
}

/// Load one or more sparse files into a single [`BipartiteEmbeddingCells`] by
/// delegating to `read_data_on_shared_rows` (the same loader senna's
/// run-manifest-driven flows use). This guarantees the barcodes stored
/// in `unified.barcodes` — and therefore the row names in
/// `latent.parquet` — line up byte-for-byte with what `senna plot
/// --from`, `senna clustering --from`, etc. observe when they re-load
/// the data. With multiple files, both paths see the
/// `<barcode>@<basename>` disambiguator from `SparseIoVec::push`.
///
/// Cells with the same raw barcode in two files are therefore treated
/// as **distinct** cells (matching the rest of senna). True multimodal
/// stacking — different feature schemas per file with shared cells —
/// is out of scope for this loader.
pub fn load_bipartite_embedding_cells(
    args: LoadBipartiteEmbeddingCellsArgs,
) -> anyhow::Result<BipartiteEmbeddingCells> {
    use legume_numeric::matrix::common_io::read_lines;
    let LoadBipartiteEmbeddingCellsArgs {
        data_files,
        batch_files,
        condition_files,
        feature_kind,
        preload,
        column_alignment,
        per_file_feature_suffix,
        per_file_barcode_suffix,
    } = args;
    if let Some(bf) = batch_files.as_deref() {
        // Under `ColumnAlignment::Union` a single barcode can be in
        // multiple files, so per-file batch lists no longer compose;
        // the loader requires exactly one batch file in that mode.
        // Mirror the same expectation here.
        match column_alignment {
            ColumnAlignment::Disjoint => anyhow::ensure!(
                bf.len() == data_files.len(),
                "batch_files length {} != data_files length {}",
                bf.len(),
                data_files.len()
            ),
            ColumnAlignment::Union => anyhow::ensure!(
                bf.len() == 1,
                "ColumnAlignment::Union requires exactly one --batch-files file \
                 (one label per unified cell); got {}",
                bf.len()
            ),
        }
    }

    let batch_files_present = batch_files.is_some();
    let loaded = read_data_on_shared_rows(ReadSharedRowsArgs {
        data_files,
        batch_files,
        preload,
        feature_kind,
        column_alignment,
        per_file_feature_suffix: per_file_feature_suffix.clone(),
        per_file_barcode_suffix,
        // Condition labels are read one per input column, in file order.
        keep_empty_barcodes: condition_files.is_some(),
        ..Default::default()
    })?;

    // Optional per-cell condition labels. Read line-per-cell, concatenated
    // in file order (matches the unified column order: Disjoint stacks
    // files in order; Union takes one file with one label per unified
    // cell). Validated against the unified cell count below.
    let condition_labels: Option<Vec<Box<str>>> = match condition_files {
        None => None,
        Some(cf) => {
            let n_cells = loaded.data.num_columns();
            if matches!(column_alignment, ColumnAlignment::Union) {
                anyhow::ensure!(
                    cf.len() == 1,
                    "ColumnAlignment::Union requires exactly one --condition-files file \
                     (one label per unified cell); got {}",
                    cf.len()
                );
            }
            let mut labels: Vec<Box<str>> = Vec::with_capacity(n_cells);
            for f in &cf {
                info!("Reading condition file: {f}");
                labels.extend(read_lines(f)?);
            }
            anyhow::ensure!(
                labels.len() == n_cells,
                "condition files have {} lines but data has {} unified cells",
                labels.len(),
                n_cells
            );
            Some(labels)
        }
    };

    // Under Union with no explicit batch file AND no embedded @batch tags,
    // auto-batch by modality-presence so true multiome cohorts (matched +
    // unimodal cells) get corrected for modality drop-out.
    //
    // Do NOT use modality-presence when the loader resolved real per-cell
    // @batch sample IDs: that would discard sample structure and collapse
    // all cells in the same input file into one batch (e.g. every cell in
    // rep1_wt_genes.zarr.zip → "m0", every cell in rep1_wt_m6a.zarr.zip
    // → "m6"), even though they share the same biological samples.
    let batch_tags_are_trivial = loaded.batch.iter().all(|b| b.as_ref() == "all");
    let auto_modality_batch = matches!(column_alignment, ColumnAlignment::Union)
        && !batch_files_present
        && batch_tags_are_trivial;
    BipartiteEmbeddingCells::from_sparse_io(
        loaded.data,
        &loaded.batch,
        condition_labels.as_deref(),
        auto_modality_batch,
        per_file_feature_suffix.as_deref(),
    )
}

/// Validate multiome group structure against the post-load unified barcodes
/// and `cell_modality` bitmasks (bit `b` set ⇔ barcode present in file `b` of
/// the flattened file list).
///
/// Only **cross-group disjointness** is enforced: a barcode must not appear in
/// more than one group. Under `ColumnAlignment::Union` two groups sharing a raw
/// barcode would silently fold into one cell (summing counts from different
/// donors), so this guards against that mistake — fail fast with the offending
/// barcode. Partial overlap *within* a group (patchy multiome — RNA-only /
/// ATAC-only cells) is allowed: bge unions all cells regardless, and the
/// modality-presence auto-batch already labels each group.
///
/// No-op for a single group (nothing to be disjoint from).
///
/// `group_sizes` is the file count per group, in flattened file order (so
/// group 0 owns backend bits `0..group_sizes[0]`, group 1 the next block, …).
pub fn validate_multiome_groups(
    group_sizes: &[usize],
    barcodes: &[Box<str>],
    cell_modality: &[u32],
) -> anyhow::Result<()> {
    if group_sizes.len() <= 1 {
        return Ok(());
    }

    // Per-group bitmask covering that group's flattened file indices.
    let mut offset = 0usize;
    let group_masks: Vec<u32> = group_sizes
        .iter()
        .map(|&n| {
            let mask = (offset..offset + n).fold(0u32, |acc, i| acc | (1u32 << i));
            offset += n;
            mask
        })
        .collect();

    // Cross-group: no barcode's modality bits may span more than one group.
    for (cell_idx, &bits) in cell_modality.iter().enumerate() {
        let n_groups_hit = group_masks.iter().filter(|&&m| bits & m != 0).count();
        if n_groups_hit > 1 {
            anyhow::bail!(
                "multiome: barcode {:?} appears in multiple groups (modality bits \
                 {:#b}). Barcodes must be unique across groups — under Union loading \
                 a shared barcode merges cells from different samples into one.",
                barcodes[cell_idx],
                bits,
            );
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests;