data-beans 0.6.13

Sparse genomics data backends, QC, algorithms, and simulation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Full-screen nnz cutoff picker for `squeeze --interactive`.
//!
//! Shows the row and column nnz histograms with the current cutoff, and lets
//! the user move each cutoff with the keyboard while the drop counts update
//! live. Either histogram axis can be on a log, sqrt, or linear scale. On the
//! log scale the bins are the printed histogram's (`qc`), and drop counts
//! always use the squeeze's own rule, so all views agree.

use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Constraint, Flex, Layout, Rect};
use ratatui::style::Stylize;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Clear, LineGauge, Paragraph, Wrap};
use ratatui::Frame;

use super::ui::{
    header, help_line, input_line, median, panel, run_screen, Binned, HistPlot, Scale, Screen,
    ACCENTED, DIM, HIGHLIGHT, PLAIN,
};
use crate::qc::{below_nnz_cutoff, pct};

/// One axis (rows or columns): the sorted nnz counts, their histogram, and
/// the cutoff being edited.
pub struct AxisView {
    label: String,
    sorted: Vec<f32>,
    hist: Binned,
    /// Cutoffs the bin steps visit, ascending: 0, the first count of every
    /// bin past the lowest (the cutoff that drops the bars left of it), and
    /// one past the max (drops everything).
    stops: Vec<usize>,
    cutoff: usize,
    initial: usize,
    suggest: Option<usize>,
}

impl AxisView {
    pub fn new(label: &str, nnz: &[f32], cutoff: usize, suggest: Option<usize>) -> Self {
        let mut sorted = nnz.to_vec();
        sorted.sort_unstable_by(f32::total_cmp);
        let hist = Binned::new(&sorted, Scale::Log);
        let stops = Self::stops(&hist, &sorted);
        Self {
            label: label.to_string(),
            sorted,
            hist,
            stops,
            cutoff,
            initial: cutoff,
            suggest,
        }
    }

    fn stops(hist: &Binned, sorted: &[f32]) -> Vec<usize> {
        let max = sorted.last().map_or(0, |&x| x as usize);
        let mut stops: Vec<usize> = std::iter::once(0)
            .chain((hist.kmin + 1..=hist.kmax()).map(|k| hist.bins.lower_edge(k)))
            .chain(std::iter::once(max + 1))
            .collect();
        stops.dedup();
        stops
    }

    /// Re-bin the histogram on `scale`.
    fn set_scale(&mut self, scale: Scale) {
        self.hist = Binned::new(&self.sorted, scale);
        self.stops = Self::stops(&self.hist, &self.sorted);
    }

    fn total(&self) -> usize {
        self.sorted.len()
    }

    /// Number of entries `cutoff` drops, by the rule the squeeze applies.
    fn removed_at(&self, cutoff: usize) -> usize {
        self.sorted
            .partition_point(|&x| below_nnz_cutoff(x, cutoff))
    }

    fn removed(&self) -> usize {
        self.removed_at(self.cutoff)
    }

    fn max_value(&self) -> usize {
        self.sorted.last().map_or(0, |&x| x as usize)
    }

    /// Move the cutoff to the next (`dir > 0`) or previous stop, so one
    /// keypress moves the marker by exactly one bar.
    fn step_bin(&mut self, dir: i32) {
        self.cutoff = if dir > 0 {
            let i = self.stops.partition_point(|&s| s <= self.cutoff);
            self.stops.get(i).copied().unwrap_or(self.cutoff)
        } else {
            let i = self.stops.partition_point(|&s| s < self.cutoff);
            i.checked_sub(1).map_or(0, |i| self.stops[i])
        };
    }

    /// Nudge the cutoff by an exact amount.
    fn nudge(&mut self, delta: i64) {
        let cap = self.max_value() as i64 + 1;
        self.cutoff = (self.cutoff as i64 + delta).clamp(0, cap) as usize;
    }

    fn snap_to_suggestion(&mut self) {
        if let Some(s) = self.suggest {
            self.cutoff = s;
        }
    }

    fn reset(&mut self) {
        self.cutoff = self.initial;
    }

    fn stats_lines(&self) -> Vec<Line<'static>> {
        let dim = |t: &str| Span::styled(t.to_string(), DIM);
        let removed = self.removed();
        let suggestion = match self.suggest {
            Some(s) => dim(&format!(
                "   ◆ suggested {} (drops {:.2}%)",
                s,
                pct(self.removed_at(s), self.total())
            )),
            None => dim("   no trough suggestion"),
        };
        vec![
            Line::from(vec![
                dim("n "),
                Span::raw(self.total().to_string()),
                dim("   min "),
                Span::raw(self.sorted.first().map_or(0, |&x| x as usize).to_string()),
                dim("   median "),
                Span::raw(median(&self.sorted).to_string()),
                dim("   max "),
                Span::raw(self.max_value().to_string()),
            ]),
            Line::from(vec![
                dim("cutoff "),
                Span::styled(self.cutoff.to_string(), HIGHLIGHT),
                dim("   drops "),
                Span::styled(
                    format!(
                        "{} / {} ({:.2}%)",
                        removed,
                        self.total(),
                        pct(removed, self.total())
                    ),
                    ACCENTED,
                ),
                suggestion,
            ]),
        ]
    }

    fn render(&self, frame: &mut Frame, area: Rect, focused: bool, y_scale: Scale) {
        let block = panel(format!(" {} nnz ", self.label), focused);
        let inner = block.inner(area);
        frame.render_widget(block, area);

        let [stats, gauge, plot] = Layout::vertical([
            Constraint::Length(2),
            Constraint::Length(1),
            Constraint::Min(5),
        ])
        .areas(inner);
        frame.render_widget(Paragraph::new(self.stats_lines()), stats);

        let ratio = 1.0 - pct(self.removed(), self.total()) / 100.0;
        frame.render_widget(
            LineGauge::default()
                .ratio(ratio)
                .label(Line::from(format!("keeps {:>6.2}% ", 100.0 * ratio)))
                .filled_symbol("━")
                .unfilled_symbol("━")
                .filled_style(PLAIN)
                .unfilled_style(ACCENTED),
            gauge,
        );

        // Bars left of the cutoff's bin are what it drops.
        let bins = self.hist.bins;
        let cut_key = (self.cutoff > 0).then(|| bins.key(self.cutoff as f64));
        let style = |k: i32| match cut_key {
            Some(c) if k < c => ACCENTED,
            _ => PLAIN,
        };
        HistPlot {
            bins,
            kmin: self.hist.kmin,
            counts: &self.hist.counts,
            style: &style,
            subset: None,
            y_scale,
            pointer: cut_key,
            marks: self
                .suggest
                .map(|s| (bins.key(s as f64), "◆", PLAIN.bold()))
                .into_iter()
                .collect(),
        }
        .render(frame.buffer_mut(), plot);
    }
}

enum Mode {
    Browse,
    /// Typing an exact cutoff for the focused axis.
    Edit(String),
    /// Asking before an in-place write.
    ConfirmInPlace,
}

/// State of the picker, independent of the terminal so it can be tested.
pub struct CutoffPicker {
    title: String,
    axes: [AxisView; 2],
    focus: usize,
    x_scale: Scale,
    y_scale: Scale,
    /// When set, Enter asks before squeezing this file in place.
    in_place_target: Option<String>,
    mode: Mode,
    /// Set once the user is done: the row and column cutoffs, or `None` to
    /// cancel.
    decision: Option<Option<(usize, usize)>>,
}

impl CutoffPicker {
    pub fn new(
        title: &str,
        row: AxisView,
        column: AxisView,
        in_place_target: Option<&str>,
    ) -> Self {
        Self {
            title: title.to_string(),
            axes: [row, column],
            focus: 0,
            x_scale: Scale::Log,
            y_scale: Scale::Log,
            in_place_target: in_place_target.map(str::to_string),
            mode: Mode::Browse,
            decision: None,
        }
    }

    fn proceed(&mut self) {
        self.decision = Some(Some((self.axes[0].cutoff, self.axes[1].cutoff)));
    }

    fn render_confirm(&self, frame: &mut Frame, target: &str) {
        let area = frame.area();
        let width = (target.len() as u16 + 6).max(44).min(area.width);
        // Long paths wrap onto extra lines rather than getting cut off.
        let path_lines = (target.len() as u16).div_ceil(width.saturating_sub(2).max(1));
        let [popup] = Layout::horizontal([Constraint::Length(width)])
            .flex(Flex::Center)
            .areas(area);
        let [popup] = Layout::vertical([Constraint::Length(6 + path_lines)])
            .flex(Flex::Center)
            .areas(popup);
        let text = vec![
            Line::from("Squeeze in place? This permanently alters"),
            Line::from(target.to_string()).bold(),
            Line::from(format!(
                "row cutoff {}, column cutoff {}",
                self.axes[0].cutoff, self.axes[1].cutoff
            ))
            .style(DIM),
            help_line(&[("y", "yes"), ("n", "back")]),
        ];
        frame.render_widget(Clear, popup);
        frame.render_widget(
            Paragraph::new(text)
                .centered()
                .wrap(Wrap { trim: false })
                .block(
                    Block::bordered()
                        .border_type(BorderType::Double)
                        .border_style(ACCENTED)
                        .title(Line::from(" confirm ").style(HIGHLIGHT).centered()),
                ),
            popup,
        );
    }
}

impl Screen for CutoffPicker {
    fn done(&self) -> bool {
        self.decision.is_some()
    }

    fn interrupt(&mut self) {
        self.decision = Some(None);
    }

    fn handle_key(&mut self, key: KeyEvent) {
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let f = self.focus;
        match &mut self.mode {
            Mode::Edit(buf) => match key.code {
                KeyCode::Char(c) if c.is_ascii_digit() && buf.len() < 12 => buf.push(c),
                KeyCode::Backspace => {
                    buf.pop();
                }
                KeyCode::Enter => {
                    if let Ok(v) = buf.parse::<usize>() {
                        self.axes[f].cutoff = v;
                    }
                    self.mode = Mode::Browse;
                }
                KeyCode::Esc => self.mode = Mode::Browse,
                _ => {}
            },
            Mode::ConfirmInPlace => match key.code {
                KeyCode::Char('y' | 'Y') => self.proceed(),
                KeyCode::Char('n' | 'N') | KeyCode::Esc => self.mode = Mode::Browse,
                _ => {}
            },
            Mode::Browse => match key.code {
                KeyCode::Tab
                | KeyCode::BackTab
                | KeyCode::Up
                | KeyCode::Down
                | KeyCode::Char('k' | 'j') => self.focus = 1 - self.focus,
                KeyCode::Left if shift => self.axes[f].nudge(-1),
                KeyCode::Right if shift => self.axes[f].nudge(1),
                KeyCode::Left | KeyCode::Char('h') => self.axes[f].step_bin(-1),
                KeyCode::Right | KeyCode::Char('l') => self.axes[f].step_bin(1),
                KeyCode::Char('-' | ',') => self.axes[f].nudge(-1),
                KeyCode::Char('+' | '=' | '.') => self.axes[f].nudge(1),
                KeyCode::Char('s') => self.axes[f].snap_to_suggestion(),
                KeyCode::Char('x') => {
                    self.x_scale = self.x_scale.next();
                    for axis in &mut self.axes {
                        axis.set_scale(self.x_scale);
                    }
                }
                KeyCode::Char('y') => self.y_scale = self.y_scale.next(),
                KeyCode::Char('r') => self.axes[f].reset(),
                KeyCode::Char('e') => self.mode = Mode::Edit(String::new()),
                KeyCode::Char(c) if c.is_ascii_digit() => self.mode = Mode::Edit(c.to_string()),
                KeyCode::Enter => {
                    if self.in_place_target.is_some() {
                        self.mode = Mode::ConfirmInPlace;
                    } else {
                        self.proceed();
                    }
                }
                KeyCode::Char('q') | KeyCode::Esc => self.decision = Some(None),
                _ => {}
            },
        }
    }

    fn render(&mut self, frame: &mut Frame) {
        let [top, row_area, col_area, footer] = Layout::vertical([
            Constraint::Length(1),
            Constraint::Fill(1),
            Constraint::Fill(1),
            Constraint::Length(1),
        ])
        .areas(frame.area());

        let scales = format!("x {} · y {}", self.x_scale.name(), self.y_scale.name());
        frame.render_widget(header("squeeze", &self.title, &scales), top);
        for (i, area) in [row_area, col_area].into_iter().enumerate() {
            self.axes[i].render(frame, area, self.focus == i, self.y_scale);
        }

        let help = match &self.mode {
            Mode::Edit(buf) => input_line(
                &format!("{} cutoff: ", self.axes[self.focus].label),
                buf,
                &[("Enter", "set"), ("Esc", "back")],
            ),
            _ => help_line(&[
                ("←/→", "bin"),
                ("-/+", "±1"),
                ("0-9", "type"),
                ("s", "suggested"),
                ("r", "reset"),
                ("x/y", "scale"),
                ("Tab", "rows/cols"),
                ("Enter", "squeeze"),
                ("q", "cancel"),
            ]),
        };
        frame.render_widget(help, footer);

        if let (Mode::ConfirmInPlace, Some(target)) = (&self.mode, &self.in_place_target) {
            self.render_confirm(frame, target);
        }
    }
}

/// Run the picker full screen until the user proceeds (the row and column
/// cutoffs) or cancels (`None`).
pub fn choose_cutoffs(mut picker: CutoffPicker) -> anyhow::Result<Option<(usize, usize)>> {
    run_screen(&mut picker)?;
    Ok(picker.decision.flatten())
}

#[cfg(test)]
#[path = "tests/cutoff_tui.rs"]
mod tests;