Skip to main content

data_beans/alg/collapse_data/
mod.rs

1#![allow(dead_code)]
2
3use crate::sparse_data_visitors::*;
4use crate::sparse_io_stack::SparseIoStack;
5use crate::sparse_io_vector::SparseIoVec;
6use legume_numeric::matrix::knn_match::ColumnDict;
7use legume_numeric::matrix::traits::*;
8use legume_numeric::param::dmatrix_gamma::*;
9use legume_numeric::param::traits::Inference;
10use legume_numeric::param::traits::*;
11use log::{info, warn};
12use nalgebra::DMatrix;
13use rayon::prelude::*;
14use std::ops::AddAssign;
15use std::sync::{Arc, Mutex};
16
17use crate::alg::random_projection::binary_sort_columns;
18
19use rustc_hash::FxHashMap as HashMap;
20type CscMat = nalgebra_sparse::CscMatrix<f32>;
21
22/// Sparse pb-sample gene profile: `rows[pbsamp] = Vec<(gene_idx, sum)>` sorted
23/// by `gene_idx`, as produced by `collect_pb_sample_gene_sums` and
24/// consumed by `collect_matched_stat_coarse` and the refinement pass.
25pub type GeneSums = Vec<Vec<(usize, f32)>>;
26
27pub const DEFAULT_KNN: usize = 10;
28pub const DEFAULT_OPT_ITER: usize = 100;
29
30/// Per-level collapse output plus the partition hierarchy across levels.
31///
32/// Returned by [`collapse_columns_multilevel_with_hierarchy`] for
33/// consumers (e.g. `graph-embedding-util`'s nested chain sampler) that
34/// need parent/child maps between pb-samples at adjacent levels.
35/// `cell_to_pb_per_level` is finest-first, parallel to `levels`:
36/// `cell_to_pb_per_level[k][c] = pb_id at level k for cell c`.
37mod pb_samples;
38use pb_samples::{
39    build_pb_sample_layout, build_pb_sample_to_cells, build_pb_samples, collect_pb_sample_gene_sums,
40};
41pub use pb_samples::{PbSampleCollection, PbSampleLayout};
42// Shared cross-batch pb-sample matching, reused by `refine_multilevel`.
43pub(crate) use pb_samples::per_batch_sc_neighbors;
44mod reassign_cells;
45pub use reassign_cells::ReassignCellsParams;
46mod pb_tree;
47// The simulator's per-group reference fit reads column subsets with it.
48#[cfg(feature = "sim")]
49pub(crate) use pb_tree::select_columns;
50pub use pb_tree::{BelowEdge, ContrastGene, PbTree, PbTreeParams, RootRecord, SplitRecord};
51mod refine;
52pub use refine::StackCollapseOut;
53use refine::{
54    compute_level_sort_dims, fine_to_coarse_from_refined, pad_numeric_labels,
55    refine_and_collect_single_layer, refine_and_collect_stack, split_anchored_finest_groups,
56    RefineCollectCtx,
57};
58mod stats;
59use stats::{
60    collect_basic_stat_visitor, collect_batch_stat_visitor, collect_matched_stat_coarse,
61    collect_matched_stat_visitor, collect_observed_stat_from_pb_samples, merge_stat, optimize,
62    KnnParams, DEFAULT_NUM_LEVELS,
63};
64pub use stats::{resample_and_optimize, CollapsedOut, CollapsedStat};
65mod strata;
66pub use strata::collapse_columns_multilevel_with_strata;
67pub mod state_aware_batch_fold;
68
69pub struct MultilevelCollapseOut {
70    pub levels: Vec<CollapsedOut>,
71    pub cell_to_pb_per_level: Vec<Vec<usize>>,
72    /// The tree behind the finest partition, when it was grown (see
73    /// `MultilevelParams::pb_tree`).
74    pub pb_tree: Option<PbTree>,
75}
76
77/// Configuration for multi-level collapsing.
78#[derive(Clone)]
79pub struct MultilevelParams {
80    pub knn_pb_samples: usize,
81    pub num_levels: usize,
82    pub sort_dim: usize,
83    pub num_opt_iter: usize,
84    /// BBKNN + Poisson DC-SBM refinement on top of the hash partition.
85    /// Zero sweeps (`num_gibbs == 0 && num_greedy == 0`) keep the hash
86    /// partition as is.
87    pub refine: crate::alg::refine_multilevel::RefineParams,
88    /// Which posterior planes the *output* `CollapsedOut` should carry.
89    /// `MeanOnly` skips the sd / log_mean / log_sd allocations entirely —
90    /// a big memory win for consumers that only read `posterior_mean()`
91    /// (e.g. bge). Use `All` when the caller exports log-scale dictionaries.
92    pub output_calibration: legume_numeric::param::traits::CalibrateTarget,
93    /// Batch labels whose columns are ALREADY batch-corrected pseudobulks —
94    /// a prior run's carried reference. `Some` switches the cross-batch
95    /// counterfactual from pooled mutual adjustment to **greedy batch
96    /// correction**: every pb-sample's counterfactual is drawn from the
97    /// anchor batches only, so new batches are corrected *toward* the anchor
98    /// frame while an anchor pb-sample self-matches (its δ settles at the
99    /// prior ≈ 1 and is never re-adjusted). Anchored columns also skip
100    /// pb-sample re-merging — each stays its own matching unit, at the
101    /// resolution the prior run already paid for. `None` = pooled behavior,
102    /// bit-identical to before this field existed.
103    pub anchor_batches: Option<Vec<Box<str>>>,
104    /// Batch labels whose columns are ALREADY summaries but are **not** a
105    /// reference frame — bulk RNA-seq samples. Like anchors, each column
106    /// bypasses the partition entirely (its own singleton pb-sample and its
107    /// own singleton finest group — a bulk sample is never re-averaged), but
108    /// unlike anchors it takes no part in cross-batch matching in EITHER
109    /// direction: a bulk sample is a mixture over cell states, so matching it
110    /// to a single-state pb-sample (as source or receiver) would let δ absorb
111    /// composition rather than platform. Bulk therefore contributes observed
112    /// sums only — the dictionary sees it, δ/γ never do, and δ for a bulk
113    /// batch stays at its prior structurally. `None` = no bulk batches.
114    pub bulk_batches: Option<Vec<Box<str>>>,
115    /// Distinguish "unmeasured" from "measured as zero" when backends carry
116    /// different feature panels (`RowAlignment::Union`): per-gene denominators
117    /// count only the mass whose source measures the gene, and δ falls to its
118    /// prior where a batch has no panel coverage. A no-op (bitwise) when every
119    /// backend covers every row. Off for callers whose union is *intentional*
120    /// structural disjointness — multiome stacks modalities on one axis, and
121    /// re-weighting that is its own decision, not a side effect.
122    pub observe_panels: bool,
123    /// Retain the finest level's Gamma sufficient statistics even under
124    /// `MeanOnly` calibration. `--emit-pb-reference` serializes
125    /// `evidence_mean` — data sum over data denominator — which reads
126    /// `a_stat`/`b_stat`; `MeanOnly` normally drops them per block to bound
127    /// memory. Costs two extra `[D, S]` planes per finest-level parameter.
128    pub keep_finest_stats: bool,
129    /// Grow the finest partition as a tree from the marginal top nodes:
130    /// reassign cells by likelihood, then bisect on residual components to
131    /// one leaf target per level. `None` keeps the marginal hash, bit-identical
132    /// to before this field existed.
133    pub pb_tree: Option<PbTreeParams>,
134    /// Per-cell CNV stratum (`0` = mixable residual). Crossed into finest
135    /// codes so no pb-group mixes strata; BBKNN matches only within stratum;
136    /// unmatched clone mass is excluded from the δ update so private CN
137    /// stays in `mu_adjusted`. `None` is bit-identical to the pre-strata path.
138    pub strata: Option<Vec<usize>>,
139}
140
141impl MultilevelParams {
142    pub fn new(proj_dim: usize) -> Self {
143        Self {
144            knn_pb_samples: DEFAULT_KNN,
145            num_levels: DEFAULT_NUM_LEVELS,
146            sort_dim: proj_dim.min(12),
147            num_opt_iter: DEFAULT_OPT_ITER,
148            refine: crate::alg::refine_multilevel::RefineParams::default(),
149            output_calibration: legume_numeric::param::traits::CalibrateTarget::All,
150            anchor_batches: None,
151            bulk_batches: None,
152            observe_panels: true,
153            keep_finest_stats: false,
154            pb_tree: None,
155            strata: None,
156        }
157    }
158
159    /// Copy with [`Self::strata`] set (used by the thin `with_strata` wrapper).
160    #[must_use]
161    pub fn with_strata(&self, strata: Vec<usize>) -> Self {
162        let mut p = self.clone();
163        p.strata = Some(strata);
164        p
165    }
166}
167
168/// Bits needed to encode stratum labels in the low bits of a hash code.
169/// A single occupied stratum needs no bits (identity with the unstratified
170/// path); otherwise `ceil(log2(max_label + 1))`.
171fn stratum_bits(strata: &[usize]) -> usize {
172    let mut occupied: Vec<usize> = strata.to_vec();
173    occupied.sort_unstable();
174    occupied.dedup();
175    if occupied.len() <= 1 {
176        return 0;
177    }
178    let max = *occupied.last().unwrap_or(&0);
179    let n = max + 1;
180    (usize::BITS as usize - n.saturating_sub(1).leading_zeros() as usize).max(1)
181}
182
183/// Cross finest hash/tree codes with per-cell strata so no group mixes
184/// strata. Stratum occupies the **low** bits. Level widths are **not**
185/// bumped — expression budget (`1 << d` tree targets, refine bounds) stays
186/// unchanged; hash/reproject masks add `s_bits` separately.
187fn apply_strata_to_codes(
188    codes: &[usize],
189    level_dims: &[usize],
190    strata: &[usize],
191) -> anyhow::Result<(Vec<usize>, Vec<usize>, usize)> {
192    anyhow::ensure!(
193        codes.len() == strata.len(),
194        "strata has {} entries, codes have {}",
195        strata.len(),
196        codes.len()
197    );
198    let s_bits = stratum_bits(strata);
199    if s_bits == 0 {
200        return Ok((codes.to_vec(), level_dims.to_vec(), 0));
201    }
202    let stratified: Vec<usize> = codes
203        .iter()
204        .zip(strata.iter())
205        .map(|(&c, &s)| (c << s_bits) | s)
206        .collect();
207    Ok((stratified, level_dims.to_vec(), s_bits))
208}
209
210/// Finest cell codes plus what the per-level grouping needs to read them.
211struct FinestCodes {
212    /// Per-cell finest code (stratum bits in the low `strata_bits`).
213    codes: Vec<usize>,
214    /// Per-level expression widths, finest-first — un-bumped by strata.
215    widths: Vec<usize>,
216    /// The tree behind the finest partition, when one was grown.
217    tree: Option<PbTree>,
218    /// Width of the stratum field crossed into `codes` (`0` = no strata).
219    strata_bits: usize,
220}
221
222/// Finest codes and their level widths (finest-first). Without residual
223/// bits: the marginal sketch signs masked by `level_dims`. With them: the
224/// marginal top nodes (optionally re-sorted by `reassign_cells`) are the
225/// roots of a tree grown to one leaf target per level, `2^dim` for each of
226/// `level_dims`, and the nested levels are packed into prefix codes whose
227/// widths replace `level_dims`. Batch membership must already be
228/// registered on `data_vec`.
229///
230/// When [`MultilevelParams::strata`] is set, stratum bits are crossed into
231/// the codes after the tree/hash is grown (so leaf budgets stay expression-
232/// only). Returned widths are the un-bumped expression dims; `strata_bits`
233/// is carried separately for hash/reproject masks.
234fn finest_codes(
235    data_vec: &SparseIoVec,
236    proj_kn: &DMatrix<f32>,
237    level_dims: &[usize],
238    params: &MultilevelParams,
239) -> anyhow::Result<FinestCodes> {
240    let finest_dim = level_dims[0];
241    let nn = proj_kn.ncols();
242    let kk = proj_kn.nrows().min(finest_dim).min(nn);
243    let codes = binary_sort_columns(proj_kn, kk)?;
244    let (codes, widths, tree) = match params.pb_tree.as_ref() {
245        None => (codes, level_dims.to_vec(), None),
246        Some(rb) => {
247            let coarse_bits = if level_dims.len() >= 2 {
248                *level_dims.last().expect("non-empty level dims")
249            } else {
250                stats::DEFAULT_COARSEST_SORT_DIM.min(kk)
251            };
252            let low_mask = (1usize << coarse_bits) - 1;
253            let n = data_vec.num_columns();
254            // Summary columns (carried reference, bulk) are not tree members; they
255            // become singleton pb-samples downstream regardless of their code.
256            let active: Vec<bool> = if data_vec.has_column_multiplicity() {
257                (0..n)
258                    .map(|c| (data_vec.column_multiplicity(c) - 1.0).abs() <= f32::EPSILON)
259                    .collect()
260            } else {
261                vec![true; n]
262            };
263            let low: Vec<usize> = codes.iter().map(|&c| c & low_mask).collect();
264            let (mut node, _) = crate::alg::dc_poisson::compact_labels(&low);
265            // One pass over the store serves both the reassignment and the
266            // tree; per-node reads would decode every chunk once per node.
267            let csc = data_vec.read_columns_csc(0..n)?;
268            let reassigned_cells = match rb.reassign_cells.as_ref() {
269                Some(cr) => {
270                    let col_to_batch = data_vec.get_batch_membership(0..n);
271                    reassign_cells::reassign_cells_to_nodes(
272                        &csc,
273                        &col_to_batch,
274                        data_vec.num_batches().max(1),
275                        &active,
276                        &mut node,
277                        cr,
278                    )
279                }
280                None => 0,
281            };
282            for (c, nd) in node.iter_mut().enumerate() {
283                if !active[c] {
284                    *nd = usize::MAX;
285                }
286            }
287            // Leaf targets per level, coarse to fine — expression budget only.
288            let targets: Vec<usize> = level_dims.iter().rev().map(|&d| 1usize << d).collect();
289            let (codes, widths, mut tree) =
290                pb_tree::build_tree(data_vec, &csc, &node, &codes, &targets, rb)?;
291            tree.reassigned_cells = reassigned_cells;
292            (codes, widths, Some(tree))
293        }
294    };
295    maybe_stratify_codes(codes, widths, tree, params)
296}
297
298/// Apply [`MultilevelParams::strata`] to finest codes, or pass through.
299fn maybe_stratify_codes(
300    codes: Vec<usize>,
301    widths: Vec<usize>,
302    tree: Option<PbTree>,
303    params: &MultilevelParams,
304) -> anyhow::Result<FinestCodes> {
305    let Some(strata) = params.strata.as_deref() else {
306        return Ok(FinestCodes {
307            codes,
308            widths,
309            tree,
310            strata_bits: 0,
311        });
312    };
313    anyhow::ensure!(
314        strata.len() == codes.len(),
315        "MultilevelParams.strata has {} entries, codes have {}",
316        strata.len(),
317        codes.len()
318    );
319    let (codes, widths, s_bits) = apply_strata_to_codes(&codes, &widths, strata)?;
320    let n_occ = {
321        let mut u = strata.to_vec();
322        u.sort_unstable();
323        u.dedup();
324        u.len()
325    };
326    info!(
327        "CNV strata: crossed finest codes with {} cell strata ({} occupied, {} stratum bits)",
328        strata.len(),
329        n_occ,
330        s_bits
331    );
332    Ok(FinestCodes {
333        codes,
334        widths,
335        tree,
336        strata_bits: s_bits,
337    })
338}
339
340/// Resolve [`MultilevelParams::anchor_batches`] / `bulk_batches` names to
341/// batch indices.
342///
343/// A named batch that does not exist is an error, not a shrug: silently
344/// dropping it would quietly fall back to pooled mutual adjustment — the
345/// exact behavior anchoring (and the bulk exclusion) exists to prevent.
346fn resolve_named_batches(
347    data_vec: &SparseIoVec,
348    role: &str,
349    names: Option<&[Box<str>]>,
350) -> anyhow::Result<Option<Vec<usize>>> {
351    let Some(names) = names else { return Ok(None) };
352    let map = data_vec
353        .batch_name_map()
354        .ok_or_else(|| anyhow::anyhow!("{role} batches given but no batches are registered"))?;
355    let mut idx = Vec::with_capacity(names.len());
356    for n in names {
357        let Some(&b) = map.get(n) else {
358            anyhow::bail!(
359                "{role} batch `{n}` is not among the registered batches ({:?})",
360                map.keys().collect::<Vec<_>>(),
361            );
362        };
363        idx.push(b);
364    }
365    Ok(Some(idx))
366}
367
368/// A batch cannot be both an anchor (a counterfactual source) and bulk
369/// (barred from matching): the two roles contradict each other, and which
370/// one silently won would decide whether composition leaks into δ.
371/// Greedy default: when bulk batches are named and no anchor is given, every
372/// NON-bulk batch becomes the anchor frame.
373///
374/// This is the same discipline `senna update` applies to a carried
375/// pb_reference — only the new samples are adjusted, the established frame
376/// stays fixed. Concretely it makes bulk draw its counterfactual from the
377/// cells and be corrected toward them, while the cells self-match (their δ
378/// settles at the prior) and bulk, never being in the anchor set, cannot
379/// serve as anyone's counterfactual. Pooled mutual adjustment — where the
380/// cell frame drifts toward bulk — is what this avoids.
381fn greedy_anchor_for_bulk(
382    data_vec: &SparseIoVec,
383    anchors: Option<Vec<usize>>,
384    bulk: Option<&[usize]>,
385) -> Option<Vec<usize>> {
386    match (anchors, bulk) {
387        (Some(a), _) => Some(a),
388        (None, Some(b)) if !b.is_empty() => {
389            let all = data_vec.num_batches();
390            let frame: Vec<usize> = (0..all).filter(|i| !b.contains(i)).collect();
391            (!frame.is_empty()).then(|| {
392                info!(
393                    "Greedy bulk correction: {} bulk batch(es) corrected toward {} cell batch(es); \
394                     the cell frame is anchored and does not move",
395                    b.len(),
396                    frame.len()
397                );
398                frame
399            })
400        }
401        (None, _) => None,
402    }
403}
404
405fn ensure_disjoint_roles(anchors: Option<&[usize]>, bulk: Option<&[usize]>) -> anyhow::Result<()> {
406    if let (Some(a), Some(b)) = (anchors, bulk) {
407        if let Some(shared) = a.iter().find(|x| b.contains(x)) {
408            anyhow::bail!(
409                "batch index {shared} is named as both an anchor and a bulk batch; \
410                 the roles are mutually exclusive"
411            );
412        }
413    }
414    Ok(())
415}
416
417/// Attach per-panel observability to a freshly collected fine-level stat.
418///
419/// `size_ds[g, s] = Σ_{sources b measuring g} count[b, s]` where `count[b, s]`
420/// is the multiplicity-weighted mass batch/backends contribute to sample `s` —
421/// the factorized form, so the cost is `O(D·S·B + N)`, never `O(D·N)`. The
422/// per-(gene, batch) δ mask is 1 where any source in the batch measures the
423/// gene. Uses whatever group assignment currently stands on `data_vec`, i.e.
424/// exactly the one that filled the stat.
425///
426/// Leaves the stat untouched (the bitwise-historical path) when every backend
427/// covers every row, or when columns merge several backends (column-union /
428/// multiome), whose panel semantics are deliberate.
429fn attach_observability(stat: &mut CollapsedStat, data_vec: &SparseIoVec) -> anyhow::Result<()> {
430    let Some(coverage) = data_vec.row_coverage_by_backend() else {
431        return Ok(());
432    };
433    let ncols = data_vec.num_columns();
434    let mut sources = Vec::with_capacity(ncols);
435    for c in 0..ncols {
436        match data_vec.column_source(c) {
437            Some(b) => sources.push(b),
438            None => {
439                warn!(
440                    "panel observability skipped: column {c} merges several backends \
441                     (column-union alignment)"
442                );
443                return Ok(());
444            }
445        }
446    }
447
448    let num_genes = stat.num_genes();
449    let num_samples = stat.num_samples();
450    let num_sources = data_vec.len();
451    let cell_to_group = data_vec.get_group_membership(0..ncols)?;
452
453    // Multiplicity-weighted mass per (source, sample) and per-batch source use.
454    let mut count_bs = DMatrix::<f32>::zeros(num_sources, num_samples);
455    let batch_of = data_vec.get_batch_membership(0..ncols);
456    let num_batches = stat.num_batches();
457    let mut source_in_batch = vec![vec![false; num_batches]; num_sources];
458    for c in 0..ncols {
459        let s = cell_to_group[c];
460        if s < num_samples {
461            count_bs[(sources[c], s)] += data_vec.column_multiplicity(c);
462        }
463        if let Some(&b) = batch_of.get(c) {
464            if b < num_batches {
465                source_in_batch[sources[c]][b] = true;
466            }
467        }
468    }
469
470    let mut covered_rows: Vec<Vec<usize>> = Vec::with_capacity(coverage.len());
471    for cov in coverage.iter() {
472        anyhow::ensure!(
473            cov.len() == num_genes,
474            "row coverage has {} rows but the stat has {num_genes} genes",
475            cov.len(),
476        );
477        covered_rows.push((0..num_genes).filter(|&g| cov[g]).collect());
478    }
479    // One sample (a contiguous column of the column-major plane) per worker;
480    // a source without mass in the sample adds nothing and is skipped.
481    let mut size_ds = DMatrix::<f32>::zeros(num_genes, num_samples);
482    if num_genes > 0 {
483        size_ds
484            .as_mut_slice()
485            .par_chunks_mut(num_genes)
486            .enumerate()
487            .for_each(|(s, size_s)| {
488                for (src, rows) in covered_rows.iter().enumerate() {
489                    let mass = count_bs[(src, s)];
490                    if mass == 0.0 {
491                        continue;
492                    }
493                    for &g in rows {
494                        size_s[g] += mass;
495                    }
496                }
497            });
498    }
499
500    let mut mask_db = DMatrix::<f32>::zeros(num_genes, num_batches);
501    for (src, rows) in covered_rows.iter().enumerate() {
502        for (b, &used) in source_in_batch[src].iter().enumerate() {
503            if used {
504                for &g in rows {
505                    mask_db[(g, b)] = 1.0;
506                }
507            }
508        }
509    }
510
511    info!(
512        "panel observability attached: {} of {} (gene, sample) entries below full size",
513        size_ds
514            .column_iter()
515            .enumerate()
516            .map(|(s, col)| col.iter().filter(|&&v| v < stat.size_s[s]).count())
517            .sum::<usize>(),
518        num_genes * num_samples,
519    );
520    stat.size_ds = Some(size_ds);
521    stat.obs_mask_db = (mask_db.iter().any(|&v| v == 0.0)).then_some(mask_db);
522    Ok(())
523}
524
525pub struct EmptyArg {}
526
527#[cfg(debug_assertions)]
528use log::debug;
529
530/// Given a feature/projection matrix (factor x cells), we assign each
531/// cell to a sample and return pseudobulk (collapsed) matrices
532///
533/// (1) Register batches if needed (2) collapse columns/cells into samples
534///
535pub trait CollapsingOps {
536    ///
537    /// Collapse columns/cells into samples as allocated by
538    /// `assign_columns_to_samples`
539    ///
540    /// # Arguments
541    /// * `cells_per_group` - number of cells per sample (None: no down sampling)
542    /// * `knn_batches` - number of nearest neighbour batches
543    /// * `knn_cells` - number of nearest neighbors for building HNSW (default: 10)
544    /// * `reference` - reference batch for counterfactual inference
545    /// * `num_opt_iter` - number of optimization iterations (default: 100)
546    ///
547    fn collapse_columns(
548        &self,
549        knn_batches: Option<usize>,
550        knn_cells: Option<usize>,
551        reference_batch_names: Option<&[Box<str>]>,
552        num_opt_iter: Option<usize>,
553    ) -> anyhow::Result<CollapsedOut>;
554
555    /// Register batch information and build a `HnswMap` object for
556    /// each batch for fast nearest neighbor search within each batch
557    /// and store them in the `SparseIoVec`
558    ///
559    /// # Arguments
560    /// * `proj_kn` - random projection matrix
561    /// * `col_to_batch` - map: cell -> batch
562    fn build_hnsw_per_batch<T>(
563        &mut self,
564        proj_kn: &nalgebra::DMatrix<f32>,
565        col_to_batch: &[T],
566    ) -> anyhow::Result<()>
567    where
568        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString;
569
570    fn collect_basic_stat(&self, stat: &mut CollapsedStat) -> anyhow::Result<()>;
571
572    fn collect_batch_stat(&self, stat: &mut CollapsedStat) -> anyhow::Result<()>;
573
574    fn collect_matched_stat(
575        &self,
576        knn_batches: usize,
577        knn_cols: usize,
578        reference_indices: Option<&[usize]>,
579        stat: &mut CollapsedStat,
580    ) -> anyhow::Result<()>;
581}
582
583impl CollapsingOps for SparseIoVec {
584    fn build_hnsw_per_batch<T>(
585        &mut self,
586        proj_kn: &nalgebra::DMatrix<f32>,
587        col_to_batch: &[T],
588    ) -> anyhow::Result<()>
589    where
590        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
591    {
592        info!("creating batch-specific HNSW maps ...");
593        self.register_batches_dmatrix(proj_kn, col_to_batch)?;
594
595        info!(
596            "found {} columns across {} batches",
597            self.num_columns(),
598            self.num_batches()
599        );
600
601        Ok(())
602    }
603
604    fn collapse_columns(
605        &self,
606        knn_batches: Option<usize>,
607        knn_cells: Option<usize>,
608        reference_batch_names: Option<&[Box<str>]>,
609        num_opt_iter: Option<usize>,
610    ) -> anyhow::Result<CollapsedOut> {
611        let group_to_cols = self.take_grouped_columns().ok_or(anyhow::anyhow!(
612            "The columns were not assigned before. Call `assign_columns_to_groups`"
613        ))?;
614
615        let num_features = self.num_rows();
616        let num_groups = group_to_cols.len();
617        let num_batches = self.num_batches();
618
619        let mut stat = CollapsedStat::new(num_features, num_groups, num_batches);
620        info!("basic statistics across {} groups", num_groups);
621        self.collect_basic_stat(&mut stat)?;
622
623        if num_batches > 1 {
624            info!(
625                "batch-specific statistics across {} batches over {} samples",
626                num_batches, num_groups
627            );
628
629            let batch_name_map = self
630                .batch_name_map()
631                .ok_or(anyhow::anyhow!("unable to read batch names"))?;
632
633            let reference_indices = reference_batch_names.map(|x| {
634                x.iter()
635                    .filter_map(|b| batch_name_map.get(b))
636                    .copied()
637                    .collect::<Vec<_>>()
638            });
639
640            if let Some(r) = reference_indices.as_ref() {
641                if r.is_empty() {
642                    let ref_names = reference_batch_names
643                        .unwrap()
644                        .iter()
645                        .map(|x| x.to_string())
646                        .collect::<Vec<_>>()
647                        .join(",");
648
649                    let bat_names = self
650                        .batch_names()
651                        .unwrap()
652                        .iter()
653                        .map(|x| x.to_string())
654                        .collect::<Vec<_>>()
655                        .join(",");
656
657                    warn!("{} vs. {}", ref_names, bat_names);
658
659                    return Err(anyhow::anyhow!("no reference batch names matched!"));
660                }
661            }
662
663            self.collect_batch_stat(&mut stat)?;
664
665            info!(
666                "counterfactual inference across {} batches over {} samples",
667                num_batches, num_groups,
668            );
669
670            let knn_batches = knn_batches.unwrap_or(2);
671            let knn_cells = knn_cells.unwrap_or(DEFAULT_KNN);
672
673            self.collect_matched_stat(
674                knn_batches,
675                knn_cells,
676                reference_indices.as_deref(),
677                &mut stat,
678            )?;
679        } // if num_batches > 1
680
681        /////////////////////////////
682        // Resolve mean parameters //
683        /////////////////////////////
684
685        info!("optimizing the collapsed parameters...");
686        let (a0, b0) = (1_f32, 1_f32);
687        optimize(
688            &stat,
689            (a0, b0),
690            num_opt_iter.unwrap_or(DEFAULT_OPT_ITER),
691            "Optimizing",
692            CalibrateTarget::All,
693            false,
694        )
695    }
696
697    fn collect_basic_stat(&self, stat: &mut CollapsedStat) -> anyhow::Result<()> {
698        self.visit_columns_by_group(&collect_basic_stat_visitor, &EmptyArg {}, stat)
699    }
700
701    fn collect_batch_stat(&self, stat: &mut CollapsedStat) -> anyhow::Result<()> {
702        self.visit_columns_by_group(&collect_batch_stat_visitor, &EmptyArg {}, stat)
703    }
704
705    fn collect_matched_stat(
706        &self,
707        knn_batches: usize,
708        knn_cells: usize,
709        reference_indices: Option<&[usize]>,
710        stat: &mut CollapsedStat,
711    ) -> anyhow::Result<()> {
712        // The reference batches source the counterfactual and pin δ.
713        stat.anchor_batches = reference_indices.map(<[usize]>::to_vec).unwrap_or_default();
714        self.visit_columns_by_group(
715            &collect_matched_stat_visitor,
716            &KnnParams {
717                knn_batches,
718                knn_cells,
719                reference_indices,
720            },
721            stat,
722        )
723    }
724}
725
726pub trait MultilevelCollapsingOps {
727    type LevelOutput;
728
729    fn collapse_columns_multilevel<T>(
730        &mut self,
731        proj_kn: &DMatrix<f32>,
732        batch_membership: &[T],
733        params: &MultilevelParams,
734    ) -> anyhow::Result<Self::LevelOutput>
735    where
736        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString;
737
738    fn collapse_columns_multilevel_vec<T>(
739        &mut self,
740        proj_kn: &DMatrix<f32>,
741        batch_membership: &[T],
742        params: &MultilevelParams,
743    ) -> anyhow::Result<Vec<Self::LevelOutput>>
744    where
745        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString;
746}
747
748/// Same as `SparseIoVec::collapse_columns_multilevel_vec`, but also returns
749/// the per-level cell → pb mapping needed for hierarchical / nested
750/// chain sampling in downstream consumers (currently
751/// `graph-embedding-util`).
752pub fn collapse_columns_multilevel_with_hierarchy<T>(
753    data_vec: &mut SparseIoVec,
754    proj_kn: &DMatrix<f32>,
755    batch_membership: &[T],
756    params: &MultilevelParams,
757) -> anyhow::Result<MultilevelCollapseOut>
758where
759    T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
760{
761    let sort_dim = params.sort_dim;
762    let knn = params.knn_pb_samples;
763    let opt_iter = params.num_opt_iter;
764
765    data_vec.register_batch_membership(batch_membership);
766    let num_features = data_vec.num_rows();
767    let num_batches = data_vec.num_batches();
768    if num_batches >= 2 {
769        data_vec.build_hnsw_per_batch(proj_kn, batch_membership)?;
770    }
771
772    let level_dims = compute_level_sort_dims(sort_dim, params.num_levels);
773    let FinestCodes {
774        codes: fine_codes,
775        widths: level_dims,
776        tree: pb_tree,
777        strata_bits,
778    } = finest_codes(data_vec, proj_kn, &level_dims, params)?;
779    data_vec.assign_groups(&fine_codes, None);
780
781    let group_to_cols = data_vec
782        .take_grouped_columns()
783        .ok_or_else(|| anyhow::anyhow!("columns not assigned"))?
784        .clone();
785
786    let refine_params = &params.refine;
787
788    let anchor_batches =
789        resolve_named_batches(data_vec, "anchor", params.anchor_batches.as_deref())?;
790    let bulk_batches = resolve_named_batches(data_vec, "bulk", params.bulk_batches.as_deref())?;
791    ensure_disjoint_roles(anchor_batches.as_deref(), bulk_batches.as_deref())?;
792    // `summary_batches` are the batches whose columns are ALREADY summaries
793    // (a carried pb_reference, or bulk) and so must never be re-averaged.
794    // `anchor_batches` below is the MATCHING frame, which after the greedy
795    // default is the cells — and cells must still collapse into pseudobulks.
796    // Conflating the two turns every cell into its own pb-sample.
797    let summary_batches = anchor_batches.clone();
798    let anchor_batches = greedy_anchor_for_bulk(data_vec, anchor_batches, bulk_batches.as_deref());
799    let ctx = RefineCollectCtx {
800        fine_codes: &fine_codes,
801        group_to_cols_finest: &group_to_cols,
802        level_dims: &level_dims,
803        num_features,
804        num_batches,
805        knn,
806        opt_iter,
807        refine_params,
808        output_calibration: params.output_calibration,
809        anchor_batches: anchor_batches.as_deref(),
810        summary_batches: summary_batches.as_deref(),
811        bulk_batches: bulk_batches.as_deref(),
812        observe_panels: params.observe_panels,
813        keep_finest_stats: params.keep_finest_stats,
814        pb_tree: pb_tree.as_ref(),
815        cell_to_stratum: params.strata.as_deref(),
816        exclude_unmatched_from_delta: params.strata.is_some(),
817        strata_bits,
818    };
819    refine_and_collect_single_layer(data_vec, proj_kn, &ctx)
820}
821
822/// Variant of [`collapse_columns_multilevel_with_hierarchy`] that **skips
823/// the BBKNN + Poisson DC-SBM refinement**, instead synthesising the
824/// per-pb-sample group assignment from a caller-supplied
825/// `cell_to_pb_per_level` (finest-first; the same shape returned in
826/// [`MultilevelCollapseOut.cell_to_pb_per_level`] by the refining
827/// entry point). Typical use: `senna {topic, itopic, ce-topic} --from`
828/// inheriting a prior run's partition.
829///
830/// The finest level's pb-sample → group label is decided by majority vote
831/// across the cells in that pb-sample; each coarser level's label is then
832/// voted per group of the level below it, so the returned levels always
833/// nest, whether or not the inherited ones do. The downstream `optimize` step
834/// still runs per level, so the returned `CollapsedOut` posteriors
835/// reflect this run's batch model and priors — only the expensive
836/// clustering work is bypassed.
837pub fn collapse_columns_multilevel_with_partition<T>(
838    data_vec: &mut SparseIoVec,
839    proj_kn: &DMatrix<f32>,
840    batch_membership: &[T],
841    params: &MultilevelParams,
842    cell_to_pb_per_level: &[Vec<usize>],
843) -> anyhow::Result<MultilevelCollapseOut>
844where
845    T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
846{
847    let knn = params.knn_pb_samples;
848    let opt_iter = params.num_opt_iter;
849
850    data_vec.register_batch_membership(batch_membership);
851    let num_features = data_vec.num_rows();
852    let num_batches = data_vec.num_batches();
853    if num_batches >= 2 {
854        data_vec.build_hnsw_per_batch(proj_kn, batch_membership)?;
855    }
856
857    let level_dims = compute_level_sort_dims(params.sort_dim, params.num_levels);
858    anyhow::ensure!(
859        cell_to_pb_per_level.len() == level_dims.len(),
860        "inherited cell_to_pb has {} levels but --num-levels is {}; \
861         pass --num-levels to match the source run",
862        cell_to_pb_per_level.len(),
863        level_dims.len(),
864    );
865    // pb-samples are built from the INHERITED finest membership, so each
866    // pb-sample is one (batch, source finest group) intersection and the
867    // per-level vote below is unanimous by construction. Fresh marginal
868    // leaves would straddle a source partition whose high bits came from
869    // within-node residuals, and a modal vote over them would erode it.
870    // pb-samples are still needed for the cross-batch matched-stat path on
871    // multi-batch data; refinement is what we skip.
872    let inherited_finest = &cell_to_pb_per_level[0];
873    anyhow::ensure!(
874        inherited_finest.len() == proj_kn.ncols(),
875        "inherited cell_to_pb finest level has {} cells, data has {}",
876        inherited_finest.len(),
877        proj_kn.ncols()
878    );
879    let k_inherited = inherited_finest.iter().copied().max().map_or(0, |m| m + 1);
880    data_vec.assign_groups(&pad_numeric_labels(inherited_finest, k_inherited), None);
881
882    let anchor_batches =
883        resolve_named_batches(data_vec, "anchor", params.anchor_batches.as_deref())?;
884    let bulk_batches = resolve_named_batches(data_vec, "bulk", params.bulk_batches.as_deref())?;
885    ensure_disjoint_roles(anchor_batches.as_deref(), bulk_batches.as_deref())?;
886    // `summary_batches` are the batches whose columns are ALREADY summaries
887    // (a carried pb_reference, or bulk) and so must never be re-averaged.
888    // `anchor_batches` below is the MATCHING frame, which after the greedy
889    // default is the cells — and cells must still collapse into pseudobulks.
890    // Conflating the two turns every cell into its own pb-sample.
891    let summary_batches = anchor_batches.clone();
892    let anchor_batches = greedy_anchor_for_bulk(data_vec, anchor_batches, bulk_batches.as_deref());
893    let pb_samples = build_pb_samples(
894        data_vec,
895        proj_kn,
896        num_features,
897        summary_batches.as_deref().unwrap_or(&[]),
898        bulk_batches.as_deref().unwrap_or(&[]),
899        params.strata.as_deref(),
900    )?;
901    let num_pb = pb_samples.layout.cell_counts.len();
902    let ncols = proj_kn.ncols();
903    let pb_sample_to_cells = build_pb_sample_to_cells(&pb_samples.layout);
904
905    // Synthesize a RefinedAssignment from the inherited cell→pb
906    // membership per pb-sample at each level. The vote is unanimous at the
907    // finest level by construction; coarser levels vote in case the source
908    // hierarchy was not strictly nested.
909    let num_levels = level_dims.len();
910    for (lvl_idx, lvl) in cell_to_pb_per_level.iter().enumerate() {
911        anyhow::ensure!(
912            lvl.len() == ncols,
913            "inherited cell_to_pb level {} has {} cells, data has {}",
914            lvl_idx,
915            lvl.len(),
916            ncols
917        );
918    }
919    let (pbsamp_to_group, num_groups_per_level) =
920        nested_levels_by_vote(&pb_sample_to_cells, cell_to_pb_per_level);
921    let refined = split_anchored_finest_groups(
922        crate::alg::refine_multilevel::RefinedAssignment {
923            pbsamp_to_group,
924            num_groups_per_level,
925        },
926        &pb_samples.layout,
927    );
928
929    info!(
930        "Inherited partition: {} cells, {} pb-samples, finest k={} (skipped BBKNN + DC-SBM refinement)",
931        ncols, num_pb, refined.num_groups_per_level[0]
932    );
933
934    // From here the path matches refine_and_collect_single_layer's
935    // post-refinement tail: assign groups, collect stats, fit Gamma
936    // posteriors level-by-level via merge_stat.
937    let k_finest = refined.num_groups_per_level[0];
938    let mut cell_to_group_finest = vec![0usize; ncols];
939    for (pbsamp, cells) in pb_sample_to_cells.iter().enumerate() {
940        let g = refined.pbsamp_to_group[0][pbsamp];
941        for &c in cells {
942            cell_to_group_finest[c] = g;
943        }
944    }
945    let finest_str = pad_numeric_labels(&cell_to_group_finest, k_finest);
946    data_vec.assign_groups(&finest_str, None);
947    debug_assert_eq!(data_vec.num_groups(), k_finest);
948
949    let mut fine_stat = CollapsedStat::new(num_features, k_finest, num_batches);
950    fine_stat.exclude_unmatched_from_delta = params.strata.is_some();
951    info!(
952        "Collecting observed stats over {} groups × {} batches from {} pb-samples ...",
953        k_finest, num_batches, num_pb
954    );
955    collect_observed_stat_from_pb_samples(
956        data_vec,
957        &pb_samples.layout,
958        &pb_samples.gene_sums,
959        &refined.pbsamp_to_group[0],
960        &mut fine_stat,
961    )?;
962    if num_batches >= 2 {
963        let batch_knn = data_vec
964            .batch_knn_lookup()
965            .ok_or_else(|| anyhow::anyhow!("batch_knn_lookup not built"))?;
966        info!(
967            "Collecting cross-batch matched stats (knn={}) over {} pb-samples ...",
968            knn, num_pb
969        );
970        let matches = per_batch_sc_neighbors(
971            &pb_samples.layout,
972            batch_knn.as_slice(),
973            knn,
974            anchor_batches.as_deref(),
975        )?;
976        collect_matched_stat_coarse(
977            &pb_samples.layout,
978            &pb_samples.gene_sums,
979            &refined.pbsamp_to_group[0],
980            &matches,
981            anchor_batches.as_deref(),
982            &mut fine_stat,
983        )?;
984    }
985    if params.observe_panels {
986        attach_observability(&mut fine_stat, data_vec)?;
987    }
988
989    let mut results: Vec<CollapsedOut> = Vec::with_capacity(num_levels);
990    info!(
991        "Level 1/{}: inherited k={} (finest; {} cells)",
992        num_levels, k_finest, ncols
993    );
994    let finest_out = optimize(
995        &fine_stat,
996        (1.0, 1.0),
997        opt_iter,
998        &format!("Inherit L1/{}", num_levels),
999        CalibrateTarget::All,
1000        false,
1001    )?;
1002    results.push(finest_out);
1003
1004    let mut prev_stat = fine_stat;
1005    for level in 1..num_levels {
1006        let k_prev = refined.num_groups_per_level[level - 1];
1007        let k_level = refined.num_groups_per_level[level];
1008        let fine_to_coarse = fine_to_coarse_from_refined(
1009            &refined.pbsamp_to_group[level - 1],
1010            &refined.pbsamp_to_group[level],
1011            k_prev,
1012        );
1013        let coarse_stat = merge_stat(&prev_stat, &fine_to_coarse, k_level);
1014        info!(
1015            "Level {}/{}: inherited k={} (merged from {})",
1016            level + 1,
1017            num_levels,
1018            k_level,
1019            k_prev
1020        );
1021        let level_opt_iter = (opt_iter / 2).max(10);
1022        let out = optimize(
1023            &coarse_stat,
1024            (1.0, 1.0),
1025            level_opt_iter,
1026            &format!("Inherit L{}/{}", level + 1, num_levels),
1027            CalibrateTarget::All,
1028            false,
1029        )?;
1030        results.push(out);
1031        prev_stat = coarse_stat;
1032    }
1033    info!(
1034        "Fitted pseudobulk posteriors for {} inherited levels: k = {:?} (finest first)",
1035        num_levels, refined.num_groups_per_level
1036    );
1037
1038    // Re-derive cell_to_pb_per_level from the post-modal-vote groups so
1039    // the returned struct is self-consistent — small drift vs the
1040    // inherited values is expected when pb-samples spanned multiple
1041    // source groups (handled by majority).
1042    let mut cell_to_pb_per_level_out: Vec<Vec<usize>> = Vec::with_capacity(num_levels);
1043    for groups in refined.pbsamp_to_group.iter().take(num_levels) {
1044        let mut c2g = vec![0usize; ncols];
1045        for (pbsamp, cells) in pb_sample_to_cells.iter().enumerate() {
1046            let g = groups[pbsamp];
1047            for &c in cells {
1048                c2g[c] = g;
1049            }
1050        }
1051        cell_to_pb_per_level_out.push(c2g);
1052    }
1053
1054    Ok(MultilevelCollapseOut {
1055        levels: results,
1056        cell_to_pb_per_level: cell_to_pb_per_level_out,
1057        pb_tree: None,
1058    })
1059}
1060
1061/// Per-level pb-sample → group labels (compacted, finest first) and group
1062/// counts from an inherited per-level cell → group membership.
1063///
1064/// The finest level takes each pb-sample's modal label. Every coarser level
1065/// is voted per group of the level below it — the group takes the label most
1066/// of its cells carry, ties going to the smaller label — so each level nests
1067/// in the next whether or not the inherited hierarchy did, which is what
1068/// `fine_to_coarse_from_refined` and `merge_stat` rely on.
1069fn nested_levels_by_vote(
1070    pb_sample_to_cells: &[Vec<usize>],
1071    cell_to_group_per_level: &[Vec<usize>],
1072) -> (Vec<Vec<usize>>, Vec<usize>) {
1073    use rustc_hash::FxHashMap;
1074    let mut pbsamp_to_group: Vec<Vec<usize>> = Vec::with_capacity(cell_to_group_per_level.len());
1075    let mut num_groups_per_level: Vec<usize> = Vec::with_capacity(cell_to_group_per_level.len());
1076    for lvl in cell_to_group_per_level {
1077        let voted: Vec<usize> = match pbsamp_to_group.last() {
1078            None => pb_sample_to_cells
1079                .iter()
1080                .map(|cells| modal_group(cells, lvl))
1081                .collect(),
1082            Some(finer) => {
1083                let k_finer = num_groups_per_level.last().copied().unwrap_or(0);
1084                let mut votes: Vec<FxHashMap<usize, usize>> = vec![FxHashMap::default(); k_finer];
1085                for (cells, &g) in pb_sample_to_cells.iter().zip(finer) {
1086                    for &c in cells {
1087                        *votes[g].entry(lvl[c]).or_insert(0) += 1;
1088                    }
1089                }
1090                let winner: Vec<usize> = votes
1091                    .iter()
1092                    .map(|v| {
1093                        v.iter()
1094                            .max_by_key(|&(&label, &n)| (n, std::cmp::Reverse(label)))
1095                            .map_or(0, |(&label, _)| label)
1096                    })
1097                    .collect();
1098                finer.iter().map(|&g| winner[g]).collect()
1099            }
1100        };
1101        let (compact, k) = crate::alg::refine_multilevel::compact_labels(&voted);
1102        num_groups_per_level.push(k);
1103        pbsamp_to_group.push(compact);
1104    }
1105    (pbsamp_to_group, num_groups_per_level)
1106}
1107
1108/// Modal `lvl[c]` over `c ∈ cells`. Returns 0 when `cells` is empty.
1109/// Fast small-Vec path for the common case where pb-samples contain
1110/// just a handful of cells.
1111fn modal_group(cells: &[usize], lvl: &[usize]) -> usize {
1112    match cells {
1113        [] => 0,
1114        [c] => lvl[*c],
1115        _ => {
1116            use rustc_hash::FxHashMap;
1117            let mut counts: FxHashMap<usize, usize> = FxHashMap::default();
1118            for &c in cells {
1119                *counts.entry(lvl[c]).or_insert(0) += 1;
1120            }
1121            counts
1122                .into_iter()
1123                .max_by_key(|&(_, n)| n)
1124                .map(|(g, _)| g)
1125                .unwrap_or(0)
1126        }
1127    }
1128}
1129
1130impl MultilevelCollapsingOps for SparseIoVec {
1131    type LevelOutput = CollapsedOut;
1132
1133    fn collapse_columns_multilevel<T>(
1134        &mut self,
1135        proj_kn: &DMatrix<f32>,
1136        batch_membership: &[T],
1137        params: &MultilevelParams,
1138    ) -> anyhow::Result<CollapsedOut>
1139    where
1140        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
1141    {
1142        let mut results =
1143            self.collapse_columns_multilevel_vec(proj_kn, batch_membership, params)?;
1144        if results.is_empty() {
1145            return Err(anyhow::anyhow!("no levels processed"));
1146        }
1147        Ok(results.remove(0))
1148    }
1149
1150    fn collapse_columns_multilevel_vec<T>(
1151        &mut self,
1152        proj_kn: &DMatrix<f32>,
1153        batch_membership: &[T],
1154        params: &MultilevelParams,
1155    ) -> anyhow::Result<Vec<CollapsedOut>>
1156    where
1157        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
1158    {
1159        let sort_dim = params.sort_dim;
1160        let knn = params.knn_pb_samples;
1161        let opt_iter = params.num_opt_iter;
1162
1163        self.register_batch_membership(batch_membership);
1164        let num_features = self.num_rows();
1165        let num_batches = self.num_batches();
1166        if num_batches >= 2 {
1167            self.build_hnsw_per_batch(proj_kn, batch_membership)?;
1168        }
1169
1170        // Level dims: [finest, ..., coarsest]
1171        let level_dims = compute_level_sort_dims(sort_dim, params.num_levels);
1172
1173        info!(
1174            "Multi-level collapsing (fine→coarse): {} levels, sort_dims={:?}, {} batches",
1175            level_dims.len(),
1176            level_dims,
1177            num_batches,
1178        );
1179
1180        // Compute binary codes at finest resolution once
1181        let FinestCodes {
1182            codes: fine_codes,
1183            widths: level_dims,
1184            tree: pb_tree,
1185            strata_bits,
1186        } = finest_codes(self, proj_kn, &level_dims, params)?;
1187
1188        // Partition at finest level
1189        self.assign_groups(&fine_codes, None);
1190
1191        let group_to_cols = self
1192            .take_grouped_columns()
1193            .ok_or(anyhow::anyhow!("columns not assigned"))?
1194            .clone();
1195
1196        ////////////////////////////////////////////////////////////////////
1197        // Opt-in refinement path: BBKNN + Poisson DC-SBM over pb-samples //
1198        ////////////////////////////////////////////////////////////////////
1199
1200        let refine_params = &params.refine;
1201        let anchor_batches =
1202            resolve_named_batches(self, "anchor", params.anchor_batches.as_deref())?;
1203        let bulk_batches = resolve_named_batches(self, "bulk", params.bulk_batches.as_deref())?;
1204        ensure_disjoint_roles(anchor_batches.as_deref(), bulk_batches.as_deref())?;
1205        let summary_batches = anchor_batches.clone();
1206        let anchor_batches = greedy_anchor_for_bulk(self, anchor_batches, bulk_batches.as_deref());
1207        let ctx = RefineCollectCtx {
1208            fine_codes: &fine_codes,
1209            group_to_cols_finest: &group_to_cols,
1210            level_dims: &level_dims,
1211            num_features,
1212            num_batches,
1213            knn,
1214            opt_iter,
1215            refine_params,
1216            output_calibration: params.output_calibration,
1217            anchor_batches: anchor_batches.as_deref(),
1218            summary_batches: summary_batches.as_deref(),
1219            bulk_batches: bulk_batches.as_deref(),
1220            observe_panels: params.observe_panels,
1221            keep_finest_stats: params.keep_finest_stats,
1222            pb_tree: pb_tree.as_ref(),
1223            cell_to_stratum: params.strata.as_deref(),
1224            exclude_unmatched_from_delta: params.strata.is_some(),
1225            strata_bits,
1226        };
1227        refine_and_collect_single_layer(self, proj_kn, &ctx).map(|out| out.levels)
1228    }
1229}
1230
1231impl MultilevelCollapsingOps for SparseIoStack {
1232    type LevelOutput = Vec<CollapsedOut>;
1233
1234    fn collapse_columns_multilevel<T>(
1235        &mut self,
1236        proj_kn: &DMatrix<f32>,
1237        batch_membership: &[T],
1238        params: &MultilevelParams,
1239    ) -> anyhow::Result<Vec<CollapsedOut>>
1240    where
1241        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
1242    {
1243        let mut results =
1244            self.collapse_columns_multilevel_vec(proj_kn, batch_membership, params)?;
1245        if results.is_empty() {
1246            return Err(anyhow::anyhow!("no levels processed"));
1247        }
1248        Ok(results.remove(0))
1249    }
1250
1251    fn collapse_columns_multilevel_vec<T>(
1252        &mut self,
1253        proj_kn: &DMatrix<f32>,
1254        batch_membership: &[T],
1255        params: &MultilevelParams,
1256    ) -> anyhow::Result<Vec<Vec<CollapsedOut>>>
1257    where
1258        T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
1259    {
1260        Ok(
1261            collapse_stack_multilevel_with_hierarchy(self, proj_kn, batch_membership, params)?
1262                .levels,
1263        )
1264    }
1265}
1266
1267/// The `SparseIoStack` collapse, also returning the per-level cell → pb
1268/// membership (finest first) the layers share — the stack counterpart of
1269/// [`collapse_columns_multilevel_with_hierarchy`]. With
1270/// `params.keep_finest_stats` the finest level keeps its sufficient statistics,
1271/// which `CollapsedOut::observed_counts` reads.
1272pub fn collapse_stack_multilevel_with_hierarchy<T>(
1273    stack: &mut SparseIoStack,
1274    proj_kn: &DMatrix<f32>,
1275    batch_membership: &[T],
1276    params: &MultilevelParams,
1277) -> anyhow::Result<StackCollapseOut>
1278where
1279    T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
1280{
1281    let num_layers = stack.num_types();
1282    if num_layers == 0 {
1283        return Err(anyhow::anyhow!("empty SparseIoStack"));
1284    }
1285
1286    let sort_dim = params.sort_dim;
1287    let knn = params.knn_pb_samples;
1288    let opt_iter = params.num_opt_iter;
1289
1290    stack.register_batch_membership(batch_membership);
1291
1292    // Use first layer for num_batches (all layers share the same columns)
1293    let num_batches = stack.stack[0].num_batches();
1294    // The matches below are read off the first layer's lookup (the layers
1295    // share columns and projection); the other layers are given theirs so
1296    // that every layer of the stack carries one afterwards.
1297    if num_batches >= 2 {
1298        for layer in stack.stack.iter_mut() {
1299            layer.build_hnsw_per_batch(proj_kn, batch_membership)?;
1300        }
1301    }
1302
1303    let ncols = proj_kn.ncols();
1304    let refine_params = &params.refine;
1305    let level_dims = compute_level_sort_dims(sort_dim, params.num_levels);
1306    let finest_dim = level_dims[0];
1307    let kk = proj_kn.nrows().min(finest_dim).min(ncols);
1308    let codes = binary_sort_columns(proj_kn, kk)?;
1309    let (fine_codes, level_dims, strata_bits) = match params.strata.as_deref() {
1310        Some(strata) => {
1311            let (c, d, s) = apply_strata_to_codes(&codes, &level_dims, strata)?;
1312            (c, d, s)
1313        }
1314        None => (codes, level_dims, 0),
1315    };
1316    for layer in stack.stack.iter_mut() {
1317        layer.assign_groups(&fine_codes, None);
1318    }
1319    let group_to_cols = stack.stack[0]
1320        .take_grouped_columns()
1321        .ok_or(anyhow::anyhow!("columns not assigned"))?
1322        .clone();
1323    let num_features = stack.stack[0].num_rows();
1324    anyhow::ensure!(
1325        params.anchor_batches.is_none() && params.bulk_batches.is_none(),
1326        "anchor_batches / bulk_batches are not supported on the stack path — nothing \
1327         produces a carried reference or bulk input for stacked modalities"
1328    );
1329    let ctx = RefineCollectCtx {
1330        fine_codes: &fine_codes,
1331        group_to_cols_finest: &group_to_cols,
1332        level_dims: &level_dims,
1333        num_features,
1334        num_batches,
1335        knn,
1336        opt_iter,
1337        refine_params,
1338        output_calibration: params.output_calibration,
1339        anchor_batches: None,
1340        summary_batches: None,
1341        bulk_batches: None,
1342        observe_panels: false,
1343        keep_finest_stats: params.keep_finest_stats,
1344        pb_tree: None,
1345        cell_to_stratum: params.strata.as_deref(),
1346        exclude_unmatched_from_delta: params.strata.is_some(),
1347        strata_bits,
1348    };
1349    refine_and_collect_stack(stack, proj_kn, &ctx)
1350}
1351
1352#[cfg(test)]
1353#[path = "tests.rs"]
1354mod tests;