Skip to main content

legume_numeric/matrix/
feature_coarsening.rs

1//! Grouping features so a model answers for a group instead of each feature.
2//!
3//! **A coarsening is fixed; a module is learned.** That is the line senna
4//! draws between its two kinds of feature grouping, and the reason both words
5//! exist. A coarsening's membership is read off the data before training and
6//! never moves, which is what lets a decoder be keyed to it and what lets a
7//! continued fit inherit it verbatim. A module's membership is a parameter:
8//! the masked encoder's `--gene-modules` learns centroids and re-derives
9//! membership from them every step. Neither word should be used for the other,
10//! and a grouping that learns its membership is a module however it is built.
11//!
12//! What a coarsening fixes is the assignment, not the meaning: a group's
13//! embedding is the mean of its members' and moves at every step.
14//!
15//! A coarsening is built from the finest pseudobulks' counts by
16//! [`coarsen_features`]: features with no grouping evidence form one
17//! background group, and the rest are grouped by k-means on their residual
18//! profiles (see that function for the method).
19
20use crate::matrix::dmatrix_util::build_columns_par;
21use crate::matrix::kmeans::kmeans_centroids_seeded;
22use crate::matrix::rand_util::mix_seed;
23use crate::matrix::traits::SampleOps;
24use clap::Args;
25use log::{debug, info};
26use nalgebra::DMatrix;
27use rayon::prelude::*;
28use serde::{Deserialize, Serialize};
29
30type CscMat = nalgebra_sparse::CscMatrix<f32>;
31
32/// Maps D fine features to d coarse coarse features and back.
33#[derive(Clone, Serialize, Deserialize)]
34pub struct FeatureCoarsening {
35    /// For each original feature, the coarse group index it belongs to.
36    pub fine_to_coarse: Vec<usize>,
37    /// For each coarse group, the list of original feature indices.
38    pub coarse_to_fine: Vec<Vec<usize>>,
39    /// Number of coarse coarse features (d).
40    pub num_coarse: usize,
41}
42
43impl FeatureCoarsening {
44    /// Build the two-way map from the fine → coarse assignment alone.
45    ///
46    /// The one place the inverse is derived, and the one place a stray group
47    /// index is caught: every consumer indexes `coarse_to_fine` by the
48    /// assignment, so an out-of-range entry would otherwise panic at first use.
49    pub fn from_fine_to_coarse(
50        fine_to_coarse: Vec<usize>,
51        num_coarse: usize,
52    ) -> anyhow::Result<Self> {
53        let mut coarse_to_fine = vec![Vec::new(); num_coarse];
54        for (f, &c) in fine_to_coarse.iter().enumerate() {
55            anyhow::ensure!(
56                c < num_coarse,
57                "feature coarsening: feature {f} is assigned to group {c} of {num_coarse}"
58            );
59            coarse_to_fine[c].push(f);
60        }
61        Ok(Self {
62            fine_to_coarse,
63            coarse_to_fine,
64            num_coarse,
65        })
66    }
67
68    /// This coarsening carried onto a different fine axis, by name.
69    ///
70    /// `new_to_old[g]` is the position on this coarsening's axis of gene `g`
71    /// of the new axis, or `None` for a gene it never covered. A known gene
72    /// keeps its group. An unknown one joins the group whose known members it
73    /// most resembles, by cosine between `unit_profiles` — one unit vector per
74    /// gene of the NEW axis, in whatever reading of a profile the caller uses —
75    /// and each group's centroid of its known members' vectors. A gene with no
76    /// profile (a zero vector) carries nothing to place it by and goes to the
77    /// group with the most known members, which perturbs the fit least. A
78    /// group none of whose members survived cannot attract anything; it keeps
79    /// its index and stays empty of new genes, because whatever is keyed to
80    /// the groups (a decoder, say) still has a slot for it.
81    ///
82    /// The group count is unchanged by construction.
83    pub fn grow_by_profile(
84        &self,
85        new_to_old: &[Option<usize>],
86        unit_profiles: &[Vec<f32>],
87    ) -> anyhow::Result<FeatureCoarsening> {
88        let d_new = new_to_old.len();
89        anyhow::ensure!(
90            unit_profiles.len() == d_new,
91            "feature coarsening growth: {} profiles for {d_new} features",
92            unit_profiles.len(),
93        );
94        let k = self.num_coarse;
95        let n_pb = unit_profiles.first().map_or(0, Vec::len);
96
97        // Known genes keep their group; their unit profiles sum into the
98        // group's centroid, one contiguous column per group.
99        let mut fine_to_coarse = vec![usize::MAX; d_new];
100        let mut centroid = DMatrix::<f32>::zeros(n_pb, k);
101        let mut members = vec![0usize; k];
102        for (g, old) in new_to_old.iter().enumerate() {
103            let Some(p) = old else { continue };
104            anyhow::ensure!(
105                *p < self.fine_to_coarse.len(),
106                "feature coarsening growth: feature {g} maps to {p}, beyond the {} covered",
107                self.fine_to_coarse.len(),
108            );
109            let m = self.fine_to_coarse[*p];
110            fine_to_coarse[g] = m;
111            members[m] += 1;
112            for (c, v) in centroid.column_mut(m).iter_mut().zip(&unit_profiles[g]) {
113                *c += v;
114            }
115        }
116        let live: Vec<usize> = (0..k).filter(|&m| members[m] > 0).collect();
117        anyhow::ensure!(
118            !live.is_empty(),
119            "feature coarsening growth: no feature of the new axis is covered, so the groups \
120             cannot be placed on it"
121        );
122        let fallback = live
123            .iter()
124            .copied()
125            .max_by_key(|&m| members[m])
126            .expect("a live group exists");
127        let mut centroid = centroid.select_columns(&live);
128        for mut c in centroid.column_iter_mut() {
129            let nrm = c.norm();
130            if nrm > 0.0 {
131                c /= nrm;
132            }
133        }
134
135        // Unknown genes: one product of their unit profiles against the live
136        // centroids, then a row-wise argmax.
137        let new: Vec<usize> = (0..d_new).filter(|&g| new_to_old[g].is_none()).collect();
138        let u = DMatrix::from_fn(new.len(), n_pb, |i, j| unit_profiles[new[i]][j]);
139        let scores = u * centroid;
140        for (i, &g) in new.iter().enumerate() {
141            let row = scores.row(i);
142            let best = row
143                .iter()
144                .enumerate()
145                .max_by(|a, b| a.1.total_cmp(b.1))
146                .expect("a live group exists");
147            fine_to_coarse[g] = if row.iter().all(|&v| v == 0.0) {
148                fallback
149            } else {
150                live[best.0]
151            };
152        }
153        debug!(
154            "feature coarsening growth: {} of {d_new} features known, {} placed by profile into \
155             {k} groups ({} groups had no surviving member)",
156            d_new - new.len(),
157            new.len(),
158            k - live.len(),
159        );
160        Self::from_fine_to_coarse(fine_to_coarse, k)
161    }
162
163    /// Aggregate columns of an [N, D] matrix → [N, d] by summing
164    /// features within each coarse group.
165    pub fn aggregate_columns_nd(&self, data_nd: &DMatrix<f32>) -> DMatrix<f32> {
166        let n = data_nd.nrows();
167        build_columns_par(n, self.num_coarse, |c, col| {
168            for &fine in &self.coarse_to_fine[c] {
169                let src = data_nd.column(fine);
170                for (dst, src_v) in col.iter_mut().zip(src.iter()) {
171                    *dst += *src_v;
172                }
173            }
174        })
175    }
176
177    /// Aggregate rows of a [D, S] matrix → [d, S] by summing
178    /// features within each coarse group.
179    pub fn aggregate_rows_ds(&self, data_ds: &DMatrix<f32>) -> DMatrix<f32> {
180        let s = data_ds.ncols();
181        build_columns_par(self.num_coarse, s, |j, col| {
182            let src_col = data_ds.column(j);
183            for (fine, &coarse) in self.fine_to_coarse.iter().enumerate() {
184                col[coarse] += src_col[fine];
185            }
186        })
187    }
188
189    /// Expand log-probability dictionary [d, K] → [D, K].
190    ///
191    /// For fine feature `f` in group `c` (size `g`):
192    ///   `expanded[f, k] = coarse[c, k] - ln(g)`
193    ///
194    /// After exponentiation, probabilities split evenly within each group:
195    ///   `β[f, k] = β_coarse[c, k] / g`
196    pub fn expand_log_dict_dk(&self, log_dict_dk: &DMatrix<f32>, d_fine: usize) -> DMatrix<f32> {
197        let k = log_dict_dk.ncols();
198        build_columns_par(d_fine, k, |kk, col| {
199            let src_col = log_dict_dk.column(kk);
200            for (c, fine_indices) in self.coarse_to_fine.iter().enumerate() {
201                let val = src_col[c] - (fine_indices.len() as f32).ln();
202                for &f in fine_indices {
203                    col[f] = val;
204                }
205            }
206        })
207    }
208
209    /// Expand a per-group `[d, K]` table to `[D, K]` by giving every fine
210    /// feature its group's row unchanged.
211    ///
212    /// The counterpart to [`Self::expand_log_dict_dk`], for a table that is
213    /// NOT a log-probability and must not be split across the group's
214    /// members: factor loadings multiply a latent rather than carrying mass,
215    /// so a group's loading IS each of its features' loading. Where such a
216    /// model also has a per-feature offset, that offset is where the split
217    /// belongs.
218    pub fn expand_rows_dk(&self, table_dk: &DMatrix<f32>, d_fine: usize) -> DMatrix<f32> {
219        let k = table_dk.ncols();
220        build_columns_par(d_fine, k, |kk, col| {
221            let src_col = table_dk.column(kk);
222            for (c, fine_indices) in self.coarse_to_fine.iter().enumerate() {
223                for &f in fine_indices {
224                    col[f] = src_col[c];
225                }
226            }
227        })
228    }
229
230    /// Aggregate a sparse [D, n] CSC matrix → dense [d, n] by summing
231    /// rows within each coarse group. Efficient: O(nnz) work.
232    pub fn aggregate_sparse_csc(&self, data_dn: &CscMat) -> DMatrix<f32> {
233        let n = data_dn.ncols();
234        build_columns_par(self.num_coarse, n, |j, col| {
235            let src = data_dn.col(j);
236            for (&row, &val) in src.row_indices().iter().zip(src.values().iter()) {
237                col[self.fine_to_coarse[row]] += val;
238            }
239        })
240    }
241}
242
243////////////////////////////////////
244// Building a coarsening from counts //
245////////////////////////////////////
246
247/// A feature is informative when its homogeneity deviance exceeds its degrees
248/// of freedom by this many standard deviations (`(D − df)/√(2·df)`).
249const INFORMATIVE_Z: f64 = 5.0;
250/// Lloyd iterations of every k-means here.
251const KMEANS_ITER: usize = 30;
252/// Widest residual profile k-means runs on directly; a wider one is sketched
253/// down to [`SKETCH_DIM`] with a seeded Gaussian first.
254const MAX_PROFILE_DIM: usize = 1024;
255const SKETCH_DIM: usize = 64;
256
257/// Per feature, whether its counts carry grouping evidence: the Poisson
258/// deviance of row `g` of `counts` against the flat rate `E_gs = T_g·n_s/N`
259/// exceeds its `S − 1` degrees of freedom by [`INFORMATIVE_Z`] standard
260/// deviations. A feature never counted is not informative.
261pub fn informative_features(counts: &DMatrix<f32>, sizes: &[f32]) -> Vec<bool> {
262    let total_size: f64 = sizes.iter().map(|&n| f64::from(n)).sum();
263    let live: Vec<usize> = (0..sizes.len()).filter(|&s| sizes[s] > 0.0).collect();
264    if live.len() < 2 || total_size <= 0.0 {
265        return vec![false; counts.nrows()];
266    }
267    let df = (live.len() - 1) as f64;
268    (0..counts.nrows())
269        .into_par_iter()
270        .map(|g| {
271            let t: f64 = live.iter().map(|&s| f64::from(counts[(g, s)])).sum();
272            if t <= 0.0 {
273                return false;
274            }
275            let dev: f64 = live
276                .iter()
277                .map(|&s| {
278                    let n = f64::from(counts[(g, s)]);
279                    let e = t * f64::from(sizes[s]) / total_size;
280                    let log_term = if n > 0.0 { n * (n / e).ln() } else { 0.0 };
281                    2.0 * (log_term - (n - e))
282                })
283                .sum();
284            (dev - df) / (2.0 * df).sqrt() > INFORMATIVE_Z
285        })
286        .collect()
287}
288
289/// Unit-length Pearson residual profiles `(n − E)/√E` of the `rows` of
290/// `counts`, clipped to `±√S`, sketched to [`SKETCH_DIM`] when wider than
291/// [`MAX_PROFILE_DIM`]: one row per entry of `rows`, in that order.
292///
293/// This is the space [`coarsen_features`] and [`partition_features`] group
294/// the informative features in ([`informative_features`] picks them). It is
295/// public so a caller can group the same profiles another way, for example
296/// by cutting their nearest-neighbour graph, and stay consistent with the
297/// k-means partition here. `sizes` are the pseudobulk sizes the expected
298/// counts `E_gs = T_g·n_s/N` are taken against; `seed` keys the sketch.
299pub fn residual_profiles(
300    counts: &DMatrix<f32>,
301    sizes: &[f32],
302    rows: &[usize],
303    seed: u64,
304) -> DMatrix<f32> {
305    let n_pb = sizes.len();
306    let total_size: f32 = sizes.iter().sum();
307    let clip = (n_pb as f32).sqrt();
308    // Row totals, then the residuals: both walk `counts` one column at a
309    // time, the order it is stored in, and the residual columns are filled
310    // in parallel.
311    let mut totals = vec![0f32; rows.len()];
312    for col in counts.column_iter() {
313        for (t, &g) in totals.iter_mut().zip(rows) {
314            *t += col[g];
315        }
316    }
317    let mut z = DMatrix::<f32>::zeros(rows.len(), n_pb);
318    if !rows.is_empty() {
319        z.as_mut_slice()
320            .par_chunks_mut(rows.len())
321            .enumerate()
322            .for_each(|(s, z_col)| {
323                let col = counts.column(s);
324                for ((z_is, &t), &g) in z_col.iter_mut().zip(&totals).zip(rows) {
325                    let e = t * sizes[s] / total_size.max(f32::MIN_POSITIVE);
326                    if e > 0.0 {
327                        *z_is = ((col[g] - e) / e.sqrt()).clamp(-clip, clip);
328                    }
329                }
330            });
331    }
332    if n_pb > MAX_PROFILE_DIM {
333        let basis = DMatrix::<f32>::rnorm_seeded(n_pb, SKETCH_DIM, mix_seed(seed, 0x5343_4854));
334        z = (&z * basis) / (SKETCH_DIM as f32).sqrt();
335    }
336    unit_rows(&mut z);
337    z
338}
339
340fn unit_rows(z: &mut DMatrix<f32>) {
341    for mut row in z.row_iter_mut() {
342        let norm = row.norm();
343        if norm > 0.0 {
344            row /= norm;
345        }
346    }
347}
348
349/// Nested feature coarsenings of pseudobulk `counts` `[D × S]` with pseudobulk
350/// sizes `sizes` (cells per column), one per entry of `level_targets`
351/// (coarsest → finest, non-decreasing): at most `target` groups each,
352/// counting the reserved background group when uninformative features exist.
353///
354/// # Method
355///
356/// Most features of a real axis carry no grouping evidence: a feature that is
357/// barely detected, or detected at one flat rate everywhere, has counts a
358/// single rate explains, and grouping such features by distance chains them
359/// into one group that drags informative features in with it. So every feature
360/// is first tested for homogeneity ([`informative_features`]); the ones that
361/// fail form ONE background group, numbered last, at every level.
362///
363/// The informative features are grouped by k-means on their Pearson residuals
364/// `(n − E)/√E`, clipped and scaled to unit length, so a feature is placed by
365/// the SHAPE of its deviation from the flat rate with count noise in
366/// proportion; k-means keeps groups balanced by construction. Coarser levels
367/// cluster the finest centroids, so every level nests in the one below.
368/// Each level's group sizes are logged.
369///
370/// When a background group is reserved, the k-means budget is `target - 1`
371/// informative slots (and may be zero): `target == 1` then yields a single
372/// all-background coarsening rather than forcing an extra informative cluster.
373pub fn coarsen_features(
374    counts: &DMatrix<f32>,
375    sizes: &[f32],
376    level_targets: &[usize],
377    seed: u64,
378) -> anyhow::Result<Vec<FeatureCoarsening>> {
379    let d = counts.nrows();
380    anyhow::ensure!(
381        counts.ncols() == sizes.len(),
382        "{} count columns for {} pseudobulk sizes",
383        counts.ncols(),
384        sizes.len()
385    );
386    anyhow::ensure!(!level_targets.is_empty(), "no coarsening level requested");
387    anyhow::ensure!(
388        level_targets.windows(2).all(|w| w[0] <= w[1]),
389        "coarsening levels must run coarsest → finest: {level_targets:?}"
390    );
391    let informative = informative_features(counts, sizes);
392    let rows: Vec<usize> = (0..d).filter(|&g| informative[g]).collect();
393    let has_background = rows.len() < d;
394    // `target` is a total group budget; the background (when present) spends
395    // one slot, and the rest are informative k-means clusters (possibly zero).
396    let slots = |target: usize| target.max(1).saturating_sub(usize::from(has_background));
397    info!(
398        "feature coarsening: {} of {d} features informative, {} in the background group",
399        rows.len(),
400        d - rows.len()
401    );
402
403    // Finest level: k-means on the informative features' residual profiles.
404    let finest = *level_targets.last().expect("checked non-empty");
405    let k_fine = slots(finest).min(rows.len());
406    let (fine_label, centroids) = if rows.is_empty() || k_fine == 0 {
407        (Vec::new(), DMatrix::<f32>::zeros(0, 0))
408    } else {
409        let z = residual_profiles(counts, sizes, &rows, seed);
410        let (mut c, labels) = kmeans_centroids_seeded(&z, k_fine, KMEANS_ITER, seed);
411        unit_rows(&mut c);
412        (labels, c)
413    };
414    let n_fine = centroids.nrows();
415
416    // Coarser levels: k-means on the finest centroids, so every level nests.
417    let levels = level_targets
418        .iter()
419        .enumerate()
420        .map(|(l, &target)| {
421            let k = slots(target);
422            let to_level: Vec<usize> = if n_fine == 0 || k == 0 {
423                Vec::new()
424            } else if l + 1 == level_targets.len() || k >= n_fine {
425                (0..n_fine).collect()
426            } else {
427                kmeans_centroids_seeded(&centroids, k, KMEANS_ITER, mix_seed(seed, l as u64)).1
428            };
429            // A level with no informative slot is all background.
430            let level = if to_level.is_empty() {
431                level_from_labels(d, &[], &[], &[], has_background)
432            } else {
433                level_from_labels(d, &rows, &fine_label, &to_level, has_background)
434            };
435            info!(
436                "feature coarsening level {l} (target {target}): {}",
437                group_sizes(&level, has_background)
438            );
439            level
440        })
441        .collect();
442    Ok(levels)
443}
444
445/// A [`FeatureCoarsening`] from the informative rows' finest labels mapped to
446/// this level, with every other feature in one background group (numbered
447/// last). Group ids are compacted in order of first use.
448fn level_from_labels(
449    d: usize,
450    rows: &[usize],
451    fine_label: &[usize],
452    to_level: &[usize],
453    has_background: bool,
454) -> FeatureCoarsening {
455    let mut in_rows = vec![false; d];
456    let mut compact = std::collections::HashMap::<usize, usize>::new();
457    let mut fine_to_coarse = vec![0usize; d];
458    for (&g, &f) in rows.iter().zip(fine_label) {
459        in_rows[g] = true;
460        let next = compact.len();
461        fine_to_coarse[g] = *compact.entry(to_level[f]).or_insert(next);
462    }
463    let mut num_coarse = compact.len();
464    if has_background {
465        for (g, &inside) in in_rows.iter().enumerate() {
466            if !inside {
467                fine_to_coarse[g] = num_coarse;
468            }
469        }
470        num_coarse += 1;
471    }
472    let mut coarse_to_fine = vec![Vec::new(); num_coarse];
473    for (g, &c) in fine_to_coarse.iter().enumerate() {
474        coarse_to_fine[c].push(g);
475    }
476    FeatureCoarsening {
477        fine_to_coarse,
478        coarse_to_fine,
479        num_coarse,
480    }
481}
482
483/// The informative groups' sizes, the background (numbered last) reported
484/// apart: `"K informative group(s), sizes min / median / max, N singleton(s);
485/// background B"`.
486fn group_sizes(level: &FeatureCoarsening, has_background: bool) -> String {
487    let n_inf = level.num_coarse - usize::from(has_background);
488    let mut sizes: Vec<usize> = level.coarse_to_fine[..n_inf].iter().map(Vec::len).collect();
489    sizes.sort_unstable();
490    format!(
491        "{} informative group(s), sizes min {} / median {} / max {}, {} singleton(s); \
492         background {}",
493        sizes.len(),
494        sizes.first().copied().unwrap_or(0),
495        sizes.get(sizes.len() / 2).copied().unwrap_or(0),
496        sizes.last().copied().unwrap_or(0),
497        sizes.iter().filter(|&&n| n == 1).count(),
498        if has_background {
499            level.coarse_to_fine[n_inf].len()
500        } else {
501            0
502        }
503    )
504}
505
506/// Options of [`partition_features`]; the default is the plain single-level
507/// coarsening.
508#[derive(Clone, Debug, Default)]
509pub struct PartitionOptions {
510    /// Groups of fewer features hold **scattered** features — ones whose
511    /// profile matches no other, which k-means places alone. They join the
512    /// background, and the slots they held split the largest groups in two
513    /// (a split kept only when both halves reach this size). Re-clustering
514    /// without them instead only promotes the next outliers. `0` or `1`: off.
515    pub min_group_size: usize,
516    /// Per feature, a BLOCK no group may cross (e.g. a genomic window);
517    /// `u32::MAX` is an ordinary block id. Each block is partitioned on its
518    /// own with a share of the slots proportional to its informative
519    /// features (at least one). `None`: one block.
520    pub block: Option<Vec<u32>>,
521}
522
523/// A single-level partition of the features (see [`partition_features`]).
524#[derive(Clone, Debug)]
525pub struct FeaturePartition {
526    /// Group of every feature, `0..num_groups`; the background, when there is
527    /// one, is numbered last.
528    pub labels: Vec<usize>,
529    pub num_groups: usize,
530    /// The background group: flat features and scattered ones.
531    pub background: Option<usize>,
532    /// Per feature, [`informative_features`] (not flat), computed once here
533    /// so callers need not run the test again.
534    pub informative: Vec<bool>,
535}
536
537/// Salt of the k-means seed of a group split.
538const SPLIT_SEED_SALT: u64 = 0x5350_4c54;
539
540/// `k` k-means groups of `rows` by their residual profiles, as lists of row
541/// ids in first-use order (empty groups dropped); `k` is clamped to the row
542/// count.
543fn kmeans_groups(
544    counts: &DMatrix<f32>,
545    sizes: &[f32],
546    rows: &[usize],
547    k: usize,
548    seed: u64,
549) -> Vec<Vec<usize>> {
550    let k = k.min(rows.len());
551    if k == 0 {
552        return Vec::new();
553    }
554    let z = residual_profiles(counts, sizes, rows, seed);
555    let (_, labels) = kmeans_centroids_seeded(&z, k, KMEANS_ITER, seed);
556    let mut slot = vec![usize::MAX; k];
557    let mut groups: Vec<Vec<usize>> = Vec::new();
558    for (&r, &l) in rows.iter().zip(&labels) {
559        if slot[l] == usize::MAX {
560            slot[l] = groups.len();
561            groups.push(Vec::new());
562        }
563        groups[slot[l]].push(r);
564    }
565    groups
566}
567
568/// The informative groups of `rows` within a budget of `n_groups` (one slot
569/// kept for the background when it has members): the plain k-means, then,
570/// with `min_size > 1`, scattered groups set aside and the freed slots spent
571/// splitting the largest groups. Rows in no returned group are background.
572fn informative_groups(
573    counts: &DMatrix<f32>,
574    sizes: &[f32],
575    rows: &[usize],
576    informative: &[bool],
577    n_groups: usize,
578    seed: u64,
579    min_size: usize,
580) -> Vec<Vec<usize>> {
581    let inf: Vec<usize> = rows.iter().copied().filter(|&r| informative[r]).collect();
582    let has_empty = inf.len() < rows.len();
583    let slots = n_groups.max(1).saturating_sub(usize::from(has_empty));
584    let groups = kmeans_groups(counts, sizes, &inf, slots, seed);
585    if min_size <= 1 {
586        return groups;
587    }
588    let (mut groups, scattered): (Vec<Vec<usize>>, Vec<Vec<usize>>) =
589        groups.into_iter().partition(|g| g.len() >= min_size);
590    let has_bg = has_empty || !scattered.is_empty();
591    let mut free = n_groups.saturating_sub(groups.len() + usize::from(has_bg));
592    let mut heap: std::collections::BinaryHeap<(usize, usize)> = groups
593        .iter()
594        .enumerate()
595        .map(|(i, g)| (g.len(), i))
596        .collect();
597    while free > 0 {
598        let Some((len, i)) = heap.pop() else { break };
599        if len < 2 * min_size {
600            break;
601        }
602        let mut halves = kmeans_groups(
603            counts,
604            sizes,
605            &groups[i],
606            2,
607            mix_seed(seed, SPLIT_SEED_SALT + i as u64),
608        );
609        if halves.len() == 2 && halves.iter().all(|h| h.len() >= min_size) {
610            let b = halves.pop().expect("two halves");
611            groups[i] = halves.pop().expect("two halves");
612            heap.push((groups[i].len(), i));
613            heap.push((b.len(), groups.len()));
614            groups.push(b);
615            free -= 1;
616        }
617    }
618    groups
619}
620
621/// Proportional shares of `budget` slots over blocks with `weight` informative
622/// features each: at least one per block, the remainder to the blocks with the
623/// most features per slot. No block, no share.
624fn block_shares(weight: &[usize], budget: usize) -> Vec<usize> {
625    if weight.is_empty() {
626        return Vec::new();
627    }
628    let total: usize = weight.iter().sum();
629    let mut alloc: Vec<usize> = weight
630        .iter()
631        .map(|&c| (budget * c / total.max(1)).max(1))
632        .collect();
633    while alloc.iter().sum::<usize>() > budget {
634        let i = (0..alloc.len())
635            .max_by_key(|&i| alloc[i])
636            .expect("non-empty");
637        alloc[i] -= 1;
638    }
639    while alloc.iter().sum::<usize>() < budget {
640        let i = (0..alloc.len())
641            .max_by(|&a, &b| (weight[a] * alloc[b]).cmp(&(weight[b] * alloc[a])))
642            .expect("non-empty");
643        alloc[i] += 1;
644    }
645    alloc
646}
647
648/// A single-level partition of `counts` `[D × S]` into at most `n_groups`
649/// groups, the background counted: [`coarsen_features`] at one level, with
650/// the [`PartitionOptions`] applied and the background id and informative
651/// flags returned. Without options the labels are exactly the single-level
652/// coarsening's.
653pub fn partition_features(
654    counts: &DMatrix<f32>,
655    sizes: &[f32],
656    n_groups: usize,
657    seed: u64,
658    opts: &PartitionOptions,
659) -> anyhow::Result<FeaturePartition> {
660    let d = counts.nrows();
661    anyhow::ensure!(
662        counts.ncols() == sizes.len(),
663        "{} count columns for {} pseudobulk sizes",
664        counts.ncols(),
665        sizes.len()
666    );
667    let informative = informative_features(counts, sizes);
668    let min_size = opts.min_group_size;
669    let mut rows_of = std::collections::BTreeMap::<u32, Vec<usize>>::new();
670    match &opts.block {
671        Some(block) => {
672            anyhow::ensure!(
673                block.len() == d,
674                "{} block ids for {d} features",
675                block.len()
676            );
677            for (r, &b) in block.iter().enumerate() {
678                rows_of.entry(b).or_default().push(r);
679            }
680        }
681        None => {
682            rows_of.insert(0, (0..d).collect());
683        }
684    }
685
686    let groups: Vec<Vec<usize>> = if rows_of.len() <= 1 {
687        let rows: Vec<usize> = (0..d).collect();
688        informative_groups(counts, sizes, &rows, &informative, n_groups, seed, min_size)
689    } else {
690        let n_inf = |rows: &[usize]| rows.iter().filter(|&&r| informative[r]).count();
691        let live: Vec<(u32, usize)> = rows_of
692            .iter()
693            .map(|(&b, rows)| (b, n_inf(rows)))
694            .filter(|&(_, c)| c > 0)
695            .collect();
696        let budget = n_groups.saturating_sub(1);
697        anyhow::ensure!(
698            live.len() <= budget,
699            "{} blocks hold informative features but only {budget} group slots: widen the blocks",
700            live.len()
701        );
702        let weight: Vec<usize> = live.iter().map(|&(_, c)| c).collect();
703        let alloc = block_shares(&weight, budget);
704        live.iter()
705            .zip(&alloc)
706            .flat_map(|(&(b, _), &k)| {
707                let rows = &rows_of[&b];
708                // One more slot when the block has near-empty rows: it is spent
709                // on their background, which joins the shared one.
710                let has_empty = rows.len() > n_inf(rows);
711                informative_groups(
712                    counts,
713                    sizes,
714                    rows,
715                    &informative,
716                    k + usize::from(has_empty),
717                    mix_seed(seed, u64::from(b)),
718                    min_size,
719                )
720            })
721            .collect()
722    };
723
724    // Labels: the groups in order, then the background.
725    let bg = groups.len();
726    let mut labels = vec![bg; d];
727    for (i, g) in groups.iter().enumerate() {
728        for &r in g {
729            labels[r] = i;
730        }
731    }
732    let n_bg = d - groups.iter().map(Vec::len).sum::<usize>();
733    let n_flat = informative.iter().filter(|&&i| !i).count();
734    let mut group_sizes: Vec<usize> = groups.iter().map(Vec::len).collect();
735    group_sizes.sort_unstable();
736    info!(
737        "feature partition: {bg} group(s) over {} block(s), sizes min {} / median {} / max {}; \
738         background {n_bg} ({n_flat} flat, {} scattered)",
739        rows_of.len(),
740        group_sizes.first().copied().unwrap_or(0),
741        group_sizes.get(group_sizes.len() / 2).copied().unwrap_or(0),
742        group_sizes.last().copied().unwrap_or(0),
743        n_bg - n_flat,
744    );
745    Ok(FeaturePartition {
746        labels,
747        num_groups: bg + usize::from(n_bg > 0),
748        background: (n_bg > 0).then_some(bg),
749        informative,
750    })
751}
752
753/// Shared CLI arg for grouping co-expressed features before training.
754///
755/// One declaration, one wording, one default, flattened by every command that
756/// can train at reduced feature resolution — the same shape as
757/// data-beans' `alg::hvg::HvgCliArgs`, and read alongside it: selection decides which
758/// features weigh on the sketch, this decides how many distinct outputs the
759/// model answers for.
760#[derive(Args, Debug, Clone, Serialize, Deserialize)]
761#[serde(default = "crate::matrix::clap_defaults::clap_defaults")]
762pub struct FeatureCoarseningArgs {
763    #[arg(
764        long,
765        default_value_t = 1000,
766        value_name = "N",
767        help = "Group co-expressed features into at most N coarse features; 0 = every feature",
768        long_help = "Group co-expressed features into at most N coarse features,\n\
769                     so the model answers for a group instead of for each feature.\n\
770                     Groups come from the finest pseudobulk profiles, nested per\n\
771                     level with log-spaced widths. The dictionary is expanded back\n\
772                     to every feature on output, so what you read is unchanged.\n\
773                     \n\
774                     --no-feature-coarsening trains on every feature instead. So\n\
775                     does 0 here, kept because recorded runs and existing scripts\n\
776                     spell it that way.\n\
777                     \n\
778                     WHAT THE GROUPING APPLIES TO DEPENDS ON THE COMMAND:\n\
779                     \n\
780                     `topic` and `vae` group both sides. The encoder reads coarse\n\
781                     features and every decoder answers for them, so 0 makes each\n\
782                     per-step tensor as wide as the feature axis.\n\
783                     \n\
784                     `masked-topic`, `masked-vae` and `masked-sbp` group the decoder\n\
785                     targets only. The encoder keeps its feature-level context and\n\
786                     embedding either way.\n\
787                     \n\
788                     `joint-topic` groups per modality, or on the reference modality\n\
789                     and shares it, following --decoder-type.\n\
790                     \n\
791                     This is a COARSENING, not a module. senna tells the two kinds\n\
792                     of grouping apart by one question: does training move the\n\
793                     membership? A coarsening's does not. It is read off the data\n\
794                     before the first step and fixed for the life of the model,\n\
795                     which is what lets every decoder be keyed to it and what lets a\n\
796                     continued fit inherit it. A module's does: --gene-modules learns\n\
797                     its centroids, so which features group together changes as the\n\
798                     fit proceeds.\n\
799                     \n\
800                     What a coarsening fixes is the assignment, not the meaning. A\n\
801                     group's embedding is the mean of its members' and moves at every\n\
802                     step, so grouping the targets does not freeze what the model can\n\
803                     learn about a feature."
804    )]
805    pub max_coarse_features: usize,
806
807    #[arg(
808        long,
809        conflicts_with = "max_coarse_features",
810        help = "Train on every feature, with no grouping",
811        long_help = "Train on every feature. The named form of\n\
812                     --max-coarse-features 0, which reads as a request for zero\n\
813                     features when it means the opposite.\n\
814                     \n\
815                     Every per-step tensor is then as wide as the feature axis, so\n\
816                     the fit costs considerably more at the same epoch count. It is\n\
817                     also fixed for the life of a model: a continued fit inherits\n\
818                     the groups the source run trained on, so a chain that starts\n\
819                     ungrouped stays ungrouped and one that starts grouped cannot\n\
820                     be switched over partway."
821    )]
822    pub no_feature_coarsening: bool,
823}
824
825impl FeatureCoarseningArgs {
826    /// The cap, or `None` when the model trains on every feature.
827    ///
828    /// The one place either spelling of "off" is read, so no command repeats
829    /// the convention: the named switch and the zero mean the same thing here
830    /// and clap refuses both at once.
831    #[must_use]
832    pub fn cap(&self) -> Option<std::num::NonZeroUsize> {
833        if self.no_feature_coarsening {
834            return None;
835        }
836        std::num::NonZeroUsize::new(self.max_coarse_features)
837    }
838}
839
840#[cfg(test)]
841#[path = "feature_coarsening_tests.rs"]
842mod tests;