Skip to main content

data_beans/
qc.rs

1use crate::sparse_data_visitors::*;
2use crate::sparse_io::*;
3use crate::sparse_io_vector::*;
4
5use indicatif::ParallelProgressIterator;
6use legume_numeric::matrix::sparse_stat::{SparseColumnRunningStatistics, SparseRunningStatistics};
7use legume_numeric::matrix::traits::RunningStatOps;
8use legume_numeric::matrix::utils::partition_by_membership;
9use log::warn;
10use rayon::prelude::*;
11use std::sync::{Arc, Mutex};
12
13// The axis every histogram reads values on: legume-tui's with the views
14// (feature `tui`), else a copy of it here. The binary compiles its own copy
15// of this module and reads only part of the axis.
16#[cfg(not(feature = "tui"))]
17#[allow(dead_code)]
18pub mod axis;
19#[cfg(not(feature = "tui"))]
20pub use axis::Axis;
21#[cfg(feature = "tui")]
22pub use legume_tui::hist::Axis;
23
24use rustc_hash::FxHashMap as HashMap;
25
26#[derive(Clone)]
27pub struct SqueezeCutoffs {
28    pub row: usize,
29    pub column: usize,
30}
31
32/// Whether a row or column with `nnz` non-zeros falls below `cutoff` and is
33/// squeezed out. Every preview of a cutoff counts with this rule, so what it
34/// reports matches what [`squeeze_by_nnz`] removes.
35pub fn below_nnz_cutoff(nnz: f32, cutoff: usize) -> bool {
36    (nnz as usize) < cutoff
37}
38
39/// squeeze out rows and columns with excessive zero values
40///
41/// The two cutoffs apply independently, each to the non-zeros counted over
42/// the whole matrix before anything is removed: a row is kept by its count
43/// across every column, the removed ones included, and a column likewise.
44/// So a kept row can end below `cutoffs.row` among the kept columns (all
45/// zero, even), and squeezing the result again can remove more.
46pub fn squeeze_by_nnz(
47    data: &dyn SparseIo<IndexIter = Vec<usize>>,
48    cutoffs: SqueezeCutoffs,
49    block_size: Option<usize>,
50    preload: bool,
51) -> anyhow::Result<()> {
52    // Without a shape there are no counts to compare with the cutoffs.
53    anyhow::ensure!(
54        data.num_rows().is_some() && data.num_columns().is_some(),
55        "missing shape information"
56    );
57    let (col_stat, row_stat) = collect_column_row_stat(data, block_size)?;
58
59    fn nnz_index(nnz: &[f32], cutoff: usize) -> Option<Vec<usize>> {
60        let ret: Vec<usize> = nnz
61            .iter()
62            .enumerate()
63            .filter(|&(_, &x)| !below_nnz_cutoff(x, cutoff))
64            .map(|(i, _)| i)
65            .collect();
66
67        (!ret.is_empty()).then_some(ret)
68    }
69
70    let row_nnz_vec = row_stat.count_positives();
71    let col_nnz_vec = col_stat.count_positives();
72    let row_idx = nnz_index(&row_nnz_vec, cutoffs.row);
73    let col_idx = nnz_index(&col_nnz_vec, cutoffs.column);
74
75    if row_idx.is_none() {
76        warn!(
77            "No rows can be kept with this cutoff {}!\n\
78	     \n\
79	     We will stop squeezing on the rows.\n\
80	     \n",
81            cutoffs.row
82        );
83    }
84
85    if col_idx.is_none() {
86        warn!(
87            "No columns can be kept with this cutoff {}!\n\
88	     \n\
89	     We will stop squeezing on the columns.\n\
90	     \n",
91            cutoffs.column
92        );
93    }
94
95    // A side on which nothing falls below its cutoff is left whole, and the
96    // backend as it is when that is both.
97    let row_idx = row_idx.filter(|kept| kept.len() < row_nnz_vec.len());
98    let col_idx = col_idx.filter(|kept| kept.len() < col_nnz_vec.len());
99    if row_idx.is_none() && col_idx.is_none() {
100        return Ok(());
101    }
102
103    let file = data.get_backend_file_name();
104    let backend = data.backend_type();
105
106    let mut data = open_sparse_matrix(file, &backend)?;
107    if preload {
108        data.preload_columns()?;
109    }
110    data.subset_columns_rows(col_idx.as_ref(), row_idx.as_ref())
111}
112
113/// collect row-wise sufficient statistics for Q/C
114/// * `data` - `SparseIoVec` across many data matrices
115/// * `block_size` - a block size for each parallelized job
116pub fn collect_row_stat_across_vec(
117    data: &SparseIoVec,
118    block_size: Option<usize>,
119) -> anyhow::Result<SparseRunningStatistics<f32>> {
120    let mut row_stat = SparseRunningStatistics::new(data.num_rows());
121    data.visit_columns_by_block(
122        &row_stat_vec_visitor,
123        &EmptyArgs {},
124        &mut row_stat,
125        block_size,
126    )?;
127    Ok(row_stat)
128}
129
130/// collect row statistics for each group of columns
131/// * `data` - `SparseIo`
132/// * `column_membership` - a hashmap assign columns to groups
133/// * `block_size` - a block size for each parallelized job
134#[allow(clippy::type_complexity)]
135pub fn collect_stratified_row_stat_across_vec(
136    data: &SparseIoVec,
137    column_membership: &HashMap<Box<str>, Box<str>>,
138    block_size: Option<usize>,
139) -> anyhow::Result<(Vec<Box<str>>, Vec<SparseRunningStatistics<f32>>)> {
140    let column_names = data.column_names()?;
141    let default = "".to_string().into_boxed_str();
142    let membership = column_names
143        .into_iter()
144        .map(|k| column_membership.get(&k).unwrap_or(&default).clone())
145        .collect::<Vec<_>>();
146
147    let partitions = partition_by_membership(&membership, None);
148    let mut group_names = Vec::with_capacity(partitions.len());
149    let mut group_stats = Vec::with_capacity(partitions.len());
150    let num_features = data.num_rows();
151
152    for (k, cols) in partitions {
153        let jobs = create_jobs(cols.len(), num_features, block_size);
154        let mut row_stat = SparseRunningStatistics::new(data.num_rows());
155        let arc_stat = Arc::new(Mutex::new(&mut row_stat));
156
157        jobs.par_iter()
158            .progress_with(styled_progress_bar(jobs.len() as u64, "blocks"))
159            .for_each(|&(lb, ub)| {
160                let cols_sub = cols[lb..ub].iter().cloned();
161                let csc = data
162                    .read_columns_csc(cols_sub)
163                    .expect("failed to read data");
164                let mut stat = arc_stat.lock().expect("failed to lock row_stat");
165                stat.add_csc(&csc);
166            });
167
168        group_names.push(k);
169        group_stats.push(row_stat);
170    }
171
172    Ok((group_names, group_stats))
173}
174
175/// collect row-wise sufficient statistics for Q/C
176/// * `data` - `SparseIo`
177/// * `block_size` - a block size for each parallelized job
178pub fn collect_row_stat(
179    data: &dyn SparseIo<IndexIter = Vec<usize>>,
180    block_size: Option<usize>,
181) -> anyhow::Result<SparseRunningStatistics<f32>> {
182    let nrows = data.num_rows().unwrap_or(0);
183    fold_column_blocks(
184        data,
185        block_size,
186        || SparseRunningStatistics::new(nrows),
187        |stat, csc, _| stat.add_csc(csc),
188        |stat, other| stat.merge(&other),
189    )
190}
191
192/// Column blocks folded into one accumulator at a leaf of
193/// [`fold_in_fixed_order`] by a streaming pass over `n_blocks` of them. A
194/// leaf is folded on one thread and allocates one accumulator the size of
195/// the feature axis, so the pass is cut into at most a few hundred leaves:
196/// each block is its own leaf, and its own task, up to that many blocks,
197/// and a longer pass shares an accumulator among neighbouring blocks. The
198/// leaf depends on the number of blocks alone, as the fold's order must.
199pub(crate) fn blocks_per_leaf(n_blocks: usize) -> usize {
200    const LEAVES: usize = 256;
201    n_blocks.div_ceil(LEAVES).max(1)
202}
203
204/// Fold `items` into one accumulator over a fixed binary tree: a run of at
205/// most `leaf` items is folded in order into a fresh accumulator; a longer
206/// run is halved, the halves folded on separate rayon tasks and merged left
207/// into right.
208///
209/// The grouping of the floating-point sums then depends on `items.len()` and
210/// `leaf` alone, not on the thread count or on how rayon schedules the work,
211/// so the result is the same bits run to run. (A plain rayon `fold`/`reduce`
212/// splits where work stealing happens to split.)
213pub(crate) fn fold_in_fixed_order<T, A, I, F, M>(
214    items: &[T],
215    leaf: usize,
216    init: &I,
217    fold: &F,
218    merge: &M,
219) -> anyhow::Result<A>
220where
221    T: Sync,
222    A: Send,
223    I: Fn() -> A + Sync,
224    F: Fn(&mut A, &T) -> anyhow::Result<()> + Sync,
225    M: Fn(&mut A, A) + Sync,
226{
227    if items.len() <= leaf.max(1) {
228        let mut acc = init();
229        for item in items {
230            fold(&mut acc, item)?;
231        }
232        return Ok(acc);
233    }
234    let (left, right) = items.split_at(items.len() / 2);
235    let (left, right) = rayon::join(
236        || fold_in_fixed_order(left, leaf, init, fold, merge),
237        || fold_in_fixed_order(right, leaf, init, fold, merge),
238    );
239    let mut acc = left?;
240    merge(&mut acc, right?);
241    Ok(acc)
242}
243
244/// Read the columns of `data` block by block in parallel and fold the blocks
245/// in a fixed order ([`fold_in_fixed_order`]): `add(acc, csc, lb)` folds a
246/// block, given the index of its first column, into the accumulator of its
247/// leaf (a fresh `init()`), and `merge` joins two accumulators. Sums that
248/// run across blocks, as a row's do, are then the same bits on any number of
249/// threads. A backend without a shape has no blocks.
250///
251/// # Errors
252/// If a block cannot be read.
253fn fold_column_blocks<A, I, F, M>(
254    data: &dyn SparseIo<IndexIter = Vec<usize>>,
255    block_size: Option<usize>,
256    init: I,
257    add: F,
258    merge: M,
259) -> anyhow::Result<A>
260where
261    A: Send,
262    I: Fn() -> A + Sync,
263    F: Fn(&mut A, &CscMatrix<f32>, usize) + Sync,
264    M: Fn(&mut A, A) + Sync,
265{
266    let ncols = data.num_columns().unwrap_or(0);
267    let nrows = data.num_rows().unwrap_or(0);
268    let jobs = create_jobs(ncols, nrows, block_size);
269    let prog_bar = styled_progress_bar(jobs.len() as u64, "blocks");
270    fold_in_fixed_order(
271        &jobs,
272        blocks_per_leaf(jobs.len()),
273        &init,
274        &|acc, &(lb, ub)| {
275            let csc = data.read_columns_csc((lb..ub).collect())?;
276            add(acc, &csc, lb);
277            prog_bar.inc(1);
278            Ok(())
279        },
280        &merge,
281    )
282}
283
284/// The rows of `select_rows` (those within `nrows`) as a mask over all
285/// rows, and empty statistics of `ncols` columns over them: the rows
286/// selected are the denominator of the mean.
287pub fn masked_column_stat(
288    ncols: usize,
289    nrows: usize,
290    select_rows: &[usize],
291) -> (Vec<bool>, SparseColumnRunningStatistics<f32>) {
292    let mut mask = vec![false; nrows];
293    for &r in select_rows {
294        if r < nrows {
295            mask[r] = true;
296        }
297    }
298    let selected = mask.iter().filter(|x| **x).count();
299    (mask, SparseColumnRunningStatistics::new(ncols, selected))
300}
301
302/// collect column-wise sufficient statistics for Q/C
303/// * `data` - `SparseIoVec` across many data matrices
304/// * `select_rows` - selected row indices
305/// * `block_size` - a block size for each parallelized job
306pub fn collect_column_stat_across_vec(
307    data: &SparseIoVec,
308    select_rows: Option<&[usize]>,
309    block_size: Option<usize>,
310) -> anyhow::Result<SparseColumnRunningStatistics<f32>> {
311    let ncols = data.num_columns();
312    let nrows_total = data.num_rows();
313
314    let (row_mask, mut col_stat) = match select_rows {
315        Some(sel) => {
316            let (mask, stat) = masked_column_stat(ncols, nrows_total, sel);
317            (Some(mask), stat)
318        }
319        None => (None, SparseColumnRunningStatistics::new(ncols, nrows_total)),
320    };
321    data.visit_columns_by_block(&col_stat_visitor, &row_mask, &mut col_stat, block_size)?;
322    Ok(col_stat)
323}
324
325/// collect column-wise and row-wise sufficient statistics for Q/C, reading
326/// every block once ([`collect_column_stat`] and [`collect_row_stat`])
327/// * `data` - `SparseIo`
328/// * `block_size` - a block size for each parallelized job
329pub fn collect_column_row_stat(
330    data: &dyn SparseIo<IndexIter = Vec<usize>>,
331    block_size: Option<usize>,
332) -> anyhow::Result<(
333    SparseColumnRunningStatistics<f32>,
334    SparseRunningStatistics<f32>,
335)> {
336    let ncols = data.num_columns().unwrap_or(0);
337    let nrows = data.num_rows().unwrap_or(0);
338    // A column's statistics are written once, by the block that holds it,
339    // so the order the blocks reach the lock in does not show in them.
340    let col_stat = Mutex::new(SparseColumnRunningStatistics::<f32>::new(ncols, nrows));
341    let row_stat = fold_column_blocks(
342        data,
343        block_size,
344        || SparseRunningStatistics::<f32>::new(nrows),
345        |row_stat, csc, lb| {
346            col_stat
347                .lock()
348                .expect("failed to lock the column statistics")
349                .add_csc(csc, lb);
350            row_stat.add_csc(csc);
351        },
352        |row_stat, other| row_stat.merge(&other),
353    )?;
354    let col_stat = col_stat
355        .into_inner()
356        .expect("failed to unlock the column statistics");
357    Ok((col_stat, row_stat))
358}
359
360/// collect column-wise sufficient statistics for Q/C
361/// * `data` - `SparseIo`
362/// * `block_size` - a block size for each parallelized job
363pub fn collect_column_stat(
364    data: &dyn SparseIo<IndexIter = Vec<usize>>,
365    block_size: Option<usize>,
366) -> anyhow::Result<SparseColumnRunningStatistics<f32>> {
367    let ncols = data.num_columns().unwrap_or(0);
368    let nrows = data.num_rows().unwrap_or(0);
369    // A column's statistics are written once, by the block that holds it,
370    // so the order the blocks reach the lock in does not show in them.
371    let col_stat = Mutex::new(SparseColumnRunningStatistics::<f32>::new(ncols, nrows));
372    fold_column_blocks(
373        data,
374        block_size,
375        || (),
376        |_, csc, lb| {
377            col_stat
378                .lock()
379                .expect("failed to lock the column statistics")
380                .add_csc(csc, lb)
381        },
382        |_, _| (),
383    )?;
384    Ok(col_stat
385        .into_inner()
386        .expect("failed to unlock the column statistics"))
387}
388
389struct EmptyArgs {}
390
391fn row_stat_vec_visitor(
392    job: (usize, usize),
393    data: &SparseIoVec,
394    _: &EmptyArgs,
395    arc_stat: Arc<Mutex<&mut SparseRunningStatistics<f32>>>,
396) -> anyhow::Result<()> {
397    let (lb, ub) = job;
398    let csc = data.read_columns_csc(lb..ub)?;
399
400    let mut stat = arc_stat.lock().expect("failed to lock row_stat");
401    stat.add_csc(&csc);
402    Ok(())
403}
404
405fn col_stat_visitor(
406    job: (usize, usize),
407    data: &SparseIoVec,
408    row_mask: &Option<Vec<bool>>,
409    arc_stat: Arc<Mutex<&mut SparseColumnRunningStatistics<f32>>>,
410) -> anyhow::Result<()> {
411    let (lb, ub) = job;
412    let csc = data.read_columns_csc(lb..ub)?;
413    let mut stat = arc_stat.lock().expect("failed to lock col_stat");
414    match row_mask {
415        Some(mask) => stat.add_csc_masked(&csc, lb, mask),
416        None => stat.add_csc(&csc, lb),
417    }
418    Ok(())
419}
420
421//////////////////////////////////////////////////////////////////////////////////
422// Automatic nnz-cutoff selection + ASCII histogram (shared by `squeeze` and by //
423// callers that want cell-calling on a per-column nnz vector).                   //
424//////////////////////////////////////////////////////////////////////////////////
425
426/// Bin width of the trough search, in natural-log units (~5% per bin).
427const TROUGH_BIN: f64 = 0.05;
428/// Gaussian smoothing of the binned density, in bins.
429const TROUGH_SMOOTH_BINS: f64 = 3.0;
430/// A cut needs the trough at most this fraction of the lower of its two peaks.
431const TROUGH_MAX_DEPTH: f64 = 0.25;
432/// Ambient and cell peaks sit at least a decade apart; closer modes (a doublet
433/// bump, a low-complexity cell type) are not an empty↔cell boundary.
434const TROUGH_MIN_PEAK_RATIO: f64 = 10.0;
435/// Each side of a cut must hold at least this many columns (or 0.1% of all).
436const TROUGH_MIN_SIDE: usize = 20;
437
438/// Suggest an nnz cutoff at the **deepest trough** of the nnz distribution,
439/// the gap between the ambient (empty barcode) peak and the cell peak.
440/// Columns with `nnz >= cutoff` are kept.
441///
442/// The density lives on the log axis, where ambient and cells form two
443/// peaks decades apart; in linear units the cell peak is spread so thin
444/// that the trough in front of it vanishes. The bins, though, come from
445/// the actual counts: each integer count `v` spreads its mass over its own
446/// interval `[v - 1/2, v + 1/2)` mapped to `ln(1 + ·)`, so small counts,
447/// whose log spacing exceeds a bin, leave no empty bins to pass for troughs.
448///
449/// A cut is proposed only when the smoothed density at the trough is at most
450/// [`TROUGH_MAX_DEPTH`] of the lower of the two peaks it separates, the
451/// peaks are at least [`TROUGH_MIN_PEAK_RATIO`] apart, and each side holds
452/// enough columns. Unimodal data — already-called cells included — gets
453/// `None`, whatever its tails look like. Deterministic, no RNG.
454pub fn suggest_nnz_cutoff(nnz: &[f32]) -> Option<usize> {
455    let n = nnz.len();
456    let min_side = TROUGH_MIN_SIDE.max(n / 1000);
457    if n < 2 * min_side {
458        return None;
459    }
460
461    let mut vals: Vec<u64> = nnz.iter().map(|&x| x.max(0.0).round() as u64).collect();
462    vals.sort_unstable();
463    let (vmin, vmax) = (vals[0], vals[n - 1]);
464    if vmin == vmax {
465        return None;
466    }
467
468    // Count `v`'s interval `[v - 1/2, v + 1/2)` on the `ln(1 + ·)` axis.
469    let edge = |v: u64, half: f64| (v as f64 + 1.0 + half).ln();
470    let lo = edge(vmin, -0.5);
471    let nbins = ((edge(vmax, 0.5) - lo) / TROUGH_BIN).ceil() as usize;
472    let mut hist = vec![0.0_f64; nbins];
473    let mut i = 0;
474    while i < n {
475        let v = vals[i];
476        let mut j = i;
477        while j < n && vals[j] == v {
478            j += 1;
479        }
480        let a = (edge(v, -0.5) - lo) / TROUGH_BIN;
481        let b = (edge(v, 0.5) - lo) / TROUGH_BIN;
482        let mass = (j - i) as f64 / (b - a);
483        for (k, h) in hist
484            .iter_mut()
485            .enumerate()
486            .take((b.ceil() as usize).min(nbins))
487            .skip(a.floor() as usize)
488        {
489            let overlap = b.min(k as f64 + 1.0) - a.max(k as f64);
490            if overlap > 0.0 {
491                *h += mass * overlap;
492            }
493        }
494        i = j;
495    }
496
497    // Gaussian smoothing (finite ±3σ kernel, so a real gap stays exactly 0).
498    let radius = (3.0 * TROUGH_SMOOTH_BINS).ceil() as isize;
499    let kernel: Vec<f64> = (-radius..=radius)
500        .map(|d| (-0.5 * (d as f64 / TROUGH_SMOOTH_BINS).powi(2)).exp())
501        .collect();
502    let smooth: Vec<f64> = (0..nbins as isize)
503        .map(|k| {
504            (-radius..=radius)
505                .filter_map(|d| {
506                    let t = k + d;
507                    (0..nbins as isize)
508                        .contains(&t)
509                        .then(|| hist[t as usize] * kernel[(d + radius) as usize])
510                })
511                .sum()
512        })
513        .collect();
514
515    // Mass left of each bin, and the running peaks from either end.
516    let mut below = vec![0.0_f64; nbins + 1];
517    for k in 0..nbins {
518        below[k + 1] = below[k] + hist[k];
519    }
520    let mut left_peak = vec![(0.0_f64, 0usize); nbins];
521    for k in 0..nbins {
522        let prev = if k > 0 { left_peak[k - 1] } else { (-1.0, 0) };
523        left_peak[k] = if smooth[k] > prev.0 {
524            (smooth[k], k)
525        } else {
526            prev
527        };
528    }
529    let mut right_peak = vec![(0.0_f64, 0usize); nbins];
530    for k in (0..nbins).rev() {
531        let next = if k + 1 < nbins {
532            right_peak[k + 1]
533        } else {
534            (-1.0, k)
535        };
536        right_peak[k] = if smooth[k] >= next.0 {
537            (smooth[k], k)
538        } else {
539            next
540        };
541    }
542
543    let min_bins_apart = TROUGH_MIN_PEAK_RATIO.ln() / TROUGH_BIN;
544    let total = below[nbins];
545    let mut best: Option<(f64, usize, usize)> = None; // (depth, first, last) of the deepest run
546    for t in 1..nbins.saturating_sub(1) {
547        let (l_mass, r_mass) = (below[t], total - below[t + 1]);
548        if l_mass < min_side as f64 || r_mass < min_side as f64 {
549            continue;
550        }
551        let ((l_h, l_k), (r_h, r_k)) = (left_peak[t - 1], right_peak[t + 1]);
552        if ((r_k - l_k) as f64) < min_bins_apart || l_h <= 0.0 || r_h <= 0.0 {
553            continue;
554        }
555        let depth = smooth[t] / l_h.min(r_h);
556        match best {
557            Some((d, first, last)) if depth == d && last + 1 == t => best = Some((d, first, t)),
558            Some((d, _, _)) if depth >= d => {}
559            _ => best = Some((depth, t, t)),
560        }
561    }
562
563    let Some((depth, first, last)) = best else {
564        log::info!("nnz cell-calling: no two peaks a decade apart → unimodal, no cutoff");
565        return None;
566    };
567    // Middle of the deepest run (an exact-zero gap is a run, not a point).
568    let x = lo + ((first + last) as f64 / 2.0 + 0.5) * TROUGH_BIN;
569    let cutoff = (x.exp() - 1.0).ceil().max(1.0) as usize;
570    let favors_cut = depth <= TROUGH_MAX_DEPTH;
571    log::info!(
572        "nnz cell-calling: deepest trough at nnz {} (depth {:.3}) → {}",
573        cutoff,
574        depth,
575        if favors_cut {
576            format!("bimodal, cutoff at nnz {cutoff}")
577        } else {
578            "unimodal, no cutoff".to_string()
579        }
580    );
581    favors_cut.then_some(cutoff)
582}
583
584/// `part` as a percentage of `total` (0 when there is nothing).
585pub fn pct(part: usize, total: usize) -> f64 {
586    if total > 0 {
587        100.0 * part as f64 / total as f64
588    } else {
589        0.0
590    }
591}
592
593/// Median of an ascending slice (0 when empty).
594pub fn median_of_sorted(sorted: &[f32]) -> f32 {
595    let n = sorted.len();
596    match n {
597        0 => 0.0,
598        _ if n.is_multiple_of(2) => (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0,
599        _ => sorted[n / 2],
600    }
601}
602
603/// One bin of a printed histogram that holds values, with the real range
604/// of the values that fell into it.
605struct HistBin {
606    val_min: f32,
607    val_max: f32,
608    count: usize,
609    is_cutoff: bool,
610}
611
612/// Bins of a printed histogram across its values' range.
613const PRINTED_BINS: usize = 40;
614
615/// A histogram of `values` on the log [`Axis`] every histogram shares, its
616/// bins that hold values with their real ranges. Works on any non-negative
617/// statistic (nnz, sum, mean, sd); the ranges stay exact `f32` so
618/// count-like stats still print as integers.
619fn create_log_histogram(values: &[f32], cutoff: usize) -> Vec<HistBin> {
620    // The axis reaches a cutoff that is set; with none (cutoff == 0) it
621    // spans the values alone.
622    let axis = Axis::fit(values, true);
623    let axis = if cutoff > 0 {
624        axis.including(cutoff as f64)
625    } else {
626        axis
627    };
628    let mut bins: Vec<(usize, f32, f32)> =
629        vec![(0, f32::INFINITY, f32::NEG_INFINITY); PRINTED_BINS];
630    for &val in values.iter().filter(|v| v.is_finite()) {
631        let b = &mut bins[axis.bin(val as f64, PRINTED_BINS)];
632        b.0 += 1;
633        b.1 = b.1.min(val);
634        b.2 = b.2.max(val);
635    }
636    // Mark the first bin at or above the cutoff that holds values, so the
637    // arrow always renders. With no cutoff (cutoff == 0, e.g. the
638    // `histogram` command) nothing is marked.
639    let cutoff_bin = (cutoff > 0)
640        .then(|| {
641            let at = axis.bin(cutoff as f64, PRINTED_BINS);
642            (at..PRINTED_BINS).find(|&k| bins[k].0 > 0)
643        })
644        .flatten();
645    bins.into_iter()
646        .enumerate()
647        .filter(|(_, b)| b.0 > 0)
648        .map(|(k, (count, val_min, val_max))| HistBin {
649            val_min,
650            val_max,
651            count,
652            is_cutoff: Some(k) == cutoff_bin,
653        })
654        .collect()
655}
656
657/// Format a statistic value compactly: whole numbers (nnz, integer counts)
658/// print without a decimal point; fractional values (mean, sd) get
659/// `decimals` places.
660pub fn fmt_stat(v: f32, decimals: usize) -> String {
661    if v.fract() == 0.0 {
662        (v as i64).to_string()
663    } else {
664        format!("{:.*}", decimals, v)
665    }
666}
667
668/// A value as a printed histogram's range shows it: whole numbers as they
669/// are, others to three significant digits (0.000412, 0.0731, 2.45).
670fn fmt_sig(v: f32) -> String {
671    if v.fract() == 0.0 {
672        return (v as i64).to_string();
673    }
674    let places = (2 - (v.abs() as f64).log10().floor() as i32).max(0) as usize;
675    format!("{:.*}", places, v)
676}
677
678/// Print summary statistics + an ASCII log-binned histogram of a per-row or
679/// per-column statistic vector (`metric` names it, e.g. "nnz", "sum", "mean").
680/// A non-zero `cutoff` marks the cutoff bin and reports how much it removes;
681/// an optional `suggested` value reports the trough suggestion.
682///
683/// Used by `data-beans histogram`, whose result it is; `qc --qc-histogram`
684/// prints the same on stderr ([`eprint_nnz_summary`]).
685pub fn print_nnz_summary(
686    label: &str,
687    metric: &str,
688    values: &[f32],
689    cutoff: usize,
690    suggested: Option<usize>,
691) {
692    let _ = write_nnz_summary(
693        &mut std::io::stdout().lock(),
694        label,
695        metric,
696        values,
697        cutoff,
698        suggested,
699    );
700}
701
702/// [`print_nnz_summary`] on stderr: for a histogram that is a diagnostic
703/// beside a command's result (`qc --qc-histogram`, senna's and pinto's QC),
704/// not the result itself, so stdout carries only the result.
705pub fn eprint_nnz_summary(
706    label: &str,
707    metric: &str,
708    values: &[f32],
709    cutoff: usize,
710    suggested: Option<usize>,
711) {
712    let _ = write_nnz_summary(
713        &mut std::io::stderr().lock(),
714        label,
715        metric,
716        values,
717        cutoff,
718        suggested,
719    );
720}
721
722/// [`print_nnz_summary`] to `out`.
723pub fn write_nnz_summary(
724    out: &mut impl std::io::Write,
725    label: &str,
726    metric: &str,
727    values: &[f32],
728    cutoff: usize,
729    suggested: Option<usize>,
730) -> std::io::Result<()> {
731    const MAX_BAR_WIDTH: usize = 50; // Maximum width for histogram bars
732
733    let total = values.len();
734    let below_cutoff = values
735        .iter()
736        .filter(|&&x| below_nnz_cutoff(x, cutoff))
737        .count();
738    let pct_removed = pct(below_cutoff, total);
739
740    // Calculate basic statistics
741    let min = values.iter().copied().fold(f32::INFINITY, f32::min);
742    let max = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
743    // Summed in f64: an f32 sum stops growing once it dwarfs its addends.
744    let sum: f64 = values.iter().map(|&v| v as f64).sum();
745    let mean = if total > 0 { sum / total as f64 } else { 0.0 };
746
747    let mut sorted = values.to_vec();
748    sorted.sort_unstable_by(f32::total_cmp);
749    let median = median_of_sorted(&sorted);
750
751    writeln!(out, "{} {} distribution:", label, metric)?;
752    writeln!(out, "  Total: {}", total)?;
753    writeln!(
754        out,
755        "  Min: {}, Max: {}, Mean: {:.2}, Median: {:.2}",
756        fmt_stat(min, 2),
757        fmt_stat(max, 2),
758        mean,
759        median
760    )?;
761    if cutoff > 0 {
762        writeln!(
763            out,
764            "  Cutoff: {} (removes {} / {} = {:.2}%)",
765            cutoff, below_cutoff, total, pct_removed
766        )?;
767    }
768    if let Some(s) = suggested {
769        let below_s = values.iter().filter(|&&x| below_nnz_cutoff(x, s)).count();
770        let pct_s = pct(below_s, total);
771        writeln!(
772            out,
773            "  Suggested cutoff (histogram trough of {}): {} (would remove {} / {} = {:.2}%)",
774            metric, s, below_s, total, pct_s
775        )?;
776    }
777
778    // Log-spaced bins, tracking the real value range per bin
779    let hist = create_log_histogram(values, cutoff);
780
781    // Scale bar width on log10(count+1) so a few outlier bins don't flatten the rest
782    let max_log_count = hist
783        .iter()
784        .map(|b| ((b.count as f64) + 1.0).log10())
785        .fold(0.0_f64, f64::max)
786        .max(1e-9);
787
788    writeln!(
789        out,
790        "  Histogram (x: {m} in log-spaced bins, each its range; bar: log10(count+1)):",
791        m = metric
792    )?;
793    for b in hist {
794        let marker = if b.is_cutoff { " <-- CUTOFF" } else { "" };
795        let log_count = ((b.count as f64) + 1.0).log10();
796        let bar_width = ((log_count / max_log_count) * MAX_BAR_WIDTH as f64).round() as usize;
797        let bar_width = if b.count > 0 { bar_width.max(1) } else { 0 };
798        let bar = "█".repeat(bar_width);
799        let range = if b.val_min == b.val_max {
800            fmt_sig(b.val_min)
801        } else {
802            format!("{}-{}", fmt_sig(b.val_min), fmt_sig(b.val_max))
803        };
804        writeln!(out, "    {:>17}: {:>6} {}{}", range, b.count, bar, marker)?;
805    }
806    Ok(())
807}
808
809/// Cut, in place, the rows and columns of the backend at `backend_file`
810/// with fewer than `row` and `column` non-zeros: the `--squeeze` of the
811/// commands that build or derive a backend. The path is one the caller
812/// resolved and finalizes itself, so nothing is zipped here.
813pub fn squeeze_in_place(
814    backend_file: &str,
815    row: usize,
816    column: usize,
817    block_size: Option<usize>,
818) -> anyhow::Result<()> {
819    log::info!("Squeeze the backend data {backend_file}");
820    let (backend, file) = crate::hdf5_io::resolve_backend_file(backend_file, None)?;
821    let data = crate::sparse_io::open_sparse_matrix(&file, &backend)?;
822    squeeze_by_nnz(
823        data.as_ref(),
824        SqueezeCutoffs { row, column },
825        block_size,
826        true,
827    )?;
828    let data = crate::sparse_io::open_sparse_matrix(&file, &backend)?;
829    log::info!(
830        "after squeeze -- data: {} rows x {} columns",
831        data.num_rows().unwrap_or_default(),
832        data.num_columns().unwrap_or_default()
833    );
834    Ok(())
835}
836
837#[cfg(test)]
838mod tests;