Skip to main content

data_beans/interactive/
cutoff_tui.rs

1//! Full-screen nnz cutoff picker for `squeeze --interactive`.
2//!
3//! Shows the row and column nnz histograms with the current cutoff, and lets
4//! the user move each cutoff with the keyboard while the drop counts update
5//! live. Either histogram axis can be on a log, sqrt, or linear scale. On the
6//! log scale the bins are the printed histogram's (`qc`), and drop counts
7//! always use the squeeze's own rule, so all views agree.
8
9use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
10use ratatui::layout::{Constraint, Flex, Layout, Rect};
11use ratatui::style::Stylize;
12use ratatui::text::{Line, Span};
13use ratatui::widgets::{Block, BorderType, Clear, LineGauge, Paragraph, Wrap};
14use ratatui::Frame;
15
16use super::ui::{
17    header, help_line, input_line, median, panel, run_screen, Binned, HistPlot, Scale, Screen,
18    ACCENTED, DIM, HIGHLIGHT, PLAIN,
19};
20use crate::qc::{below_nnz_cutoff, pct};
21
22/// One axis (rows or columns): the sorted nnz counts, their histogram, and
23/// the cutoff being edited.
24pub struct AxisView {
25    label: String,
26    sorted: Vec<f32>,
27    hist: Binned,
28    /// Cutoffs the bin steps visit, ascending: 0, the first count of every
29    /// bin past the lowest (the cutoff that drops the bars left of it), and
30    /// one past the max (drops everything).
31    stops: Vec<usize>,
32    cutoff: usize,
33    initial: usize,
34    suggest: Option<usize>,
35}
36
37impl AxisView {
38    pub fn new(label: &str, nnz: &[f32], cutoff: usize, suggest: Option<usize>) -> Self {
39        let mut sorted = nnz.to_vec();
40        sorted.sort_unstable_by(f32::total_cmp);
41        let hist = Binned::new(&sorted, Scale::Log);
42        let stops = Self::stops(&hist, &sorted);
43        Self {
44            label: label.to_string(),
45            sorted,
46            hist,
47            stops,
48            cutoff,
49            initial: cutoff,
50            suggest,
51        }
52    }
53
54    fn stops(hist: &Binned, sorted: &[f32]) -> Vec<usize> {
55        let max = sorted.last().map_or(0, |&x| x as usize);
56        let mut stops: Vec<usize> = std::iter::once(0)
57            .chain((hist.kmin + 1..=hist.kmax()).map(|k| hist.bins.lower_edge(k)))
58            .chain(std::iter::once(max + 1))
59            .collect();
60        stops.dedup();
61        stops
62    }
63
64    /// Re-bin the histogram on `scale`.
65    fn set_scale(&mut self, scale: Scale) {
66        self.hist = Binned::new(&self.sorted, scale);
67        self.stops = Self::stops(&self.hist, &self.sorted);
68    }
69
70    fn total(&self) -> usize {
71        self.sorted.len()
72    }
73
74    /// Number of entries `cutoff` drops, by the rule the squeeze applies.
75    fn removed_at(&self, cutoff: usize) -> usize {
76        self.sorted
77            .partition_point(|&x| below_nnz_cutoff(x, cutoff))
78    }
79
80    fn removed(&self) -> usize {
81        self.removed_at(self.cutoff)
82    }
83
84    fn max_value(&self) -> usize {
85        self.sorted.last().map_or(0, |&x| x as usize)
86    }
87
88    /// Move the cutoff to the next (`dir > 0`) or previous stop, so one
89    /// keypress moves the marker by exactly one bar.
90    fn step_bin(&mut self, dir: i32) {
91        self.cutoff = if dir > 0 {
92            let i = self.stops.partition_point(|&s| s <= self.cutoff);
93            self.stops.get(i).copied().unwrap_or(self.cutoff)
94        } else {
95            let i = self.stops.partition_point(|&s| s < self.cutoff);
96            i.checked_sub(1).map_or(0, |i| self.stops[i])
97        };
98    }
99
100    /// Nudge the cutoff by an exact amount.
101    fn nudge(&mut self, delta: i64) {
102        let cap = self.max_value() as i64 + 1;
103        self.cutoff = (self.cutoff as i64 + delta).clamp(0, cap) as usize;
104    }
105
106    fn snap_to_suggestion(&mut self) {
107        if let Some(s) = self.suggest {
108            self.cutoff = s;
109        }
110    }
111
112    fn reset(&mut self) {
113        self.cutoff = self.initial;
114    }
115
116    fn stats_lines(&self) -> Vec<Line<'static>> {
117        let dim = |t: &str| Span::styled(t.to_string(), DIM);
118        let removed = self.removed();
119        let suggestion = match self.suggest {
120            Some(s) => dim(&format!(
121                "   ◆ suggested {} (drops {:.2}%)",
122                s,
123                pct(self.removed_at(s), self.total())
124            )),
125            None => dim("   no trough suggestion"),
126        };
127        vec![
128            Line::from(vec![
129                dim("n "),
130                Span::raw(self.total().to_string()),
131                dim("   min "),
132                Span::raw(self.sorted.first().map_or(0, |&x| x as usize).to_string()),
133                dim("   median "),
134                Span::raw(median(&self.sorted).to_string()),
135                dim("   max "),
136                Span::raw(self.max_value().to_string()),
137            ]),
138            Line::from(vec![
139                dim("cutoff "),
140                Span::styled(self.cutoff.to_string(), HIGHLIGHT),
141                dim("   drops "),
142                Span::styled(
143                    format!(
144                        "{} / {} ({:.2}%)",
145                        removed,
146                        self.total(),
147                        pct(removed, self.total())
148                    ),
149                    ACCENTED,
150                ),
151                suggestion,
152            ]),
153        ]
154    }
155
156    fn render(&self, frame: &mut Frame, area: Rect, focused: bool, y_scale: Scale) {
157        let block = panel(format!(" {} nnz ", self.label), focused);
158        let inner = block.inner(area);
159        frame.render_widget(block, area);
160
161        let [stats, gauge, plot] = Layout::vertical([
162            Constraint::Length(2),
163            Constraint::Length(1),
164            Constraint::Min(5),
165        ])
166        .areas(inner);
167        frame.render_widget(Paragraph::new(self.stats_lines()), stats);
168
169        let ratio = 1.0 - pct(self.removed(), self.total()) / 100.0;
170        frame.render_widget(
171            LineGauge::default()
172                .ratio(ratio)
173                .label(Line::from(format!("keeps {:>6.2}% ", 100.0 * ratio)))
174                .filled_symbol("━")
175                .unfilled_symbol("━")
176                .filled_style(PLAIN)
177                .unfilled_style(ACCENTED),
178            gauge,
179        );
180
181        // Bars left of the cutoff's bin are what it drops.
182        let bins = self.hist.bins;
183        let cut_key = (self.cutoff > 0).then(|| bins.key(self.cutoff as f64));
184        let style = |k: i32| match cut_key {
185            Some(c) if k < c => ACCENTED,
186            _ => PLAIN,
187        };
188        HistPlot {
189            bins,
190            kmin: self.hist.kmin,
191            counts: &self.hist.counts,
192            style: &style,
193            subset: None,
194            y_scale,
195            pointer: cut_key,
196            marks: self
197                .suggest
198                .map(|s| (bins.key(s as f64), "◆", PLAIN.bold()))
199                .into_iter()
200                .collect(),
201        }
202        .render(frame.buffer_mut(), plot);
203    }
204}
205
206enum Mode {
207    Browse,
208    /// Typing an exact cutoff for the focused axis.
209    Edit(String),
210    /// Asking before an in-place write.
211    ConfirmInPlace,
212}
213
214/// State of the picker, independent of the terminal so it can be tested.
215pub struct CutoffPicker {
216    title: String,
217    axes: [AxisView; 2],
218    focus: usize,
219    x_scale: Scale,
220    y_scale: Scale,
221    /// When set, Enter asks before squeezing this file in place.
222    in_place_target: Option<String>,
223    mode: Mode,
224    /// Set once the user is done: the row and column cutoffs, or `None` to
225    /// cancel.
226    decision: Option<Option<(usize, usize)>>,
227}
228
229impl CutoffPicker {
230    pub fn new(
231        title: &str,
232        row: AxisView,
233        column: AxisView,
234        in_place_target: Option<&str>,
235    ) -> Self {
236        Self {
237            title: title.to_string(),
238            axes: [row, column],
239            focus: 0,
240            x_scale: Scale::Log,
241            y_scale: Scale::Log,
242            in_place_target: in_place_target.map(str::to_string),
243            mode: Mode::Browse,
244            decision: None,
245        }
246    }
247
248    fn proceed(&mut self) {
249        self.decision = Some(Some((self.axes[0].cutoff, self.axes[1].cutoff)));
250    }
251
252    fn render_confirm(&self, frame: &mut Frame, target: &str) {
253        let area = frame.area();
254        let width = (target.len() as u16 + 6).max(44).min(area.width);
255        // Long paths wrap onto extra lines rather than getting cut off.
256        let path_lines = (target.len() as u16).div_ceil(width.saturating_sub(2).max(1));
257        let [popup] = Layout::horizontal([Constraint::Length(width)])
258            .flex(Flex::Center)
259            .areas(area);
260        let [popup] = Layout::vertical([Constraint::Length(6 + path_lines)])
261            .flex(Flex::Center)
262            .areas(popup);
263        let text = vec![
264            Line::from("Squeeze in place? This permanently alters"),
265            Line::from(target.to_string()).bold(),
266            Line::from(format!(
267                "row cutoff {}, column cutoff {}",
268                self.axes[0].cutoff, self.axes[1].cutoff
269            ))
270            .style(DIM),
271            help_line(&[("y", "yes"), ("n", "back")]),
272        ];
273        frame.render_widget(Clear, popup);
274        frame.render_widget(
275            Paragraph::new(text)
276                .centered()
277                .wrap(Wrap { trim: false })
278                .block(
279                    Block::bordered()
280                        .border_type(BorderType::Double)
281                        .border_style(ACCENTED)
282                        .title(Line::from(" confirm ").style(HIGHLIGHT).centered()),
283                ),
284            popup,
285        );
286    }
287}
288
289impl Screen for CutoffPicker {
290    fn done(&self) -> bool {
291        self.decision.is_some()
292    }
293
294    fn interrupt(&mut self) {
295        self.decision = Some(None);
296    }
297
298    fn handle_key(&mut self, key: KeyEvent) {
299        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
300        let f = self.focus;
301        match &mut self.mode {
302            Mode::Edit(buf) => match key.code {
303                KeyCode::Char(c) if c.is_ascii_digit() && buf.len() < 12 => buf.push(c),
304                KeyCode::Backspace => {
305                    buf.pop();
306                }
307                KeyCode::Enter => {
308                    if let Ok(v) = buf.parse::<usize>() {
309                        self.axes[f].cutoff = v;
310                    }
311                    self.mode = Mode::Browse;
312                }
313                KeyCode::Esc => self.mode = Mode::Browse,
314                _ => {}
315            },
316            Mode::ConfirmInPlace => match key.code {
317                KeyCode::Char('y' | 'Y') => self.proceed(),
318                KeyCode::Char('n' | 'N') | KeyCode::Esc => self.mode = Mode::Browse,
319                _ => {}
320            },
321            Mode::Browse => match key.code {
322                KeyCode::Tab
323                | KeyCode::BackTab
324                | KeyCode::Up
325                | KeyCode::Down
326                | KeyCode::Char('k' | 'j') => self.focus = 1 - self.focus,
327                KeyCode::Left if shift => self.axes[f].nudge(-1),
328                KeyCode::Right if shift => self.axes[f].nudge(1),
329                KeyCode::Left | KeyCode::Char('h') => self.axes[f].step_bin(-1),
330                KeyCode::Right | KeyCode::Char('l') => self.axes[f].step_bin(1),
331                KeyCode::Char('-' | ',') => self.axes[f].nudge(-1),
332                KeyCode::Char('+' | '=' | '.') => self.axes[f].nudge(1),
333                KeyCode::Char('s') => self.axes[f].snap_to_suggestion(),
334                KeyCode::Char('x') => {
335                    self.x_scale = self.x_scale.next();
336                    for axis in &mut self.axes {
337                        axis.set_scale(self.x_scale);
338                    }
339                }
340                KeyCode::Char('y') => self.y_scale = self.y_scale.next(),
341                KeyCode::Char('r') => self.axes[f].reset(),
342                KeyCode::Char('e') => self.mode = Mode::Edit(String::new()),
343                KeyCode::Char(c) if c.is_ascii_digit() => self.mode = Mode::Edit(c.to_string()),
344                KeyCode::Enter => {
345                    if self.in_place_target.is_some() {
346                        self.mode = Mode::ConfirmInPlace;
347                    } else {
348                        self.proceed();
349                    }
350                }
351                KeyCode::Char('q') | KeyCode::Esc => self.decision = Some(None),
352                _ => {}
353            },
354        }
355    }
356
357    fn render(&mut self, frame: &mut Frame) {
358        let [top, row_area, col_area, footer] = Layout::vertical([
359            Constraint::Length(1),
360            Constraint::Fill(1),
361            Constraint::Fill(1),
362            Constraint::Length(1),
363        ])
364        .areas(frame.area());
365
366        let scales = format!("x {} · y {}", self.x_scale.name(), self.y_scale.name());
367        frame.render_widget(header("squeeze", &self.title, &scales), top);
368        for (i, area) in [row_area, col_area].into_iter().enumerate() {
369            self.axes[i].render(frame, area, self.focus == i, self.y_scale);
370        }
371
372        let help = match &self.mode {
373            Mode::Edit(buf) => input_line(
374                &format!("{} cutoff: ", self.axes[self.focus].label),
375                buf,
376                &[("Enter", "set"), ("Esc", "back")],
377            ),
378            _ => help_line(&[
379                ("←/→", "bin"),
380                ("-/+", "±1"),
381                ("0-9", "type"),
382                ("s", "suggested"),
383                ("r", "reset"),
384                ("x/y", "scale"),
385                ("Tab", "rows/cols"),
386                ("Enter", "squeeze"),
387                ("q", "cancel"),
388            ]),
389        };
390        frame.render_widget(help, footer);
391
392        if let (Mode::ConfirmInPlace, Some(target)) = (&self.mode, &self.in_place_target) {
393            self.render_confirm(frame, target);
394        }
395    }
396}
397
398/// Run the picker full screen until the user proceeds (the row and column
399/// cutoffs) or cancels (`None`).
400pub fn choose_cutoffs(mut picker: CutoffPicker) -> anyhow::Result<Option<(usize, usize)>> {
401    run_screen(&mut picker)?;
402    Ok(picker.decision.flatten())
403}
404
405#[cfg(test)]
406#[path = "tests/cutoff_tui.rs"]
407mod tests;