Skip to main content

data_beans/figure/
mod.rs

1//! Figures (feature `figure`): each one drawn once as SVG, written as a
2//! vector PDF and a PNG by [`save`], returned as PNG bytes by [`png`] for an
3//! agent, and shown as an image inside the full-screen views where the
4//! terminal has an image protocol ([`term`], feature `tui`). What is saved
5//! is what was on screen.
6//!
7//! The drawing is faba's (`src/figure/`): a [`Canvas`] in points on white,
8//! greys for context and one accent for what a threshold removes. Panels
9//! here read values on an [`Axis`] (linear, or log on `ln(shift + x)`), the
10//! axis the printed histograms and the views' histograms bin on too.
11//!
12//! Text is set in the system's Helvetica, Arial or DejaVu Sans; a host with
13//! none of them installed writes figures without their labels.
14
15pub mod qc;
16pub mod stat;
17#[cfg(feature = "tui")]
18pub mod term;
19
20use std::fmt::Write as _;
21
22/// Text and axes.
23pub const INK: &str = "#1a1a1a";
24/// Bars.
25pub const BAR: &str = "#4d4d4d";
26/// Secondary text and axis labels.
27pub const MUTED: &str = "#6b6b6b";
28/// Bars behind a front subset.
29pub const FAINT: &str = "#cfcfcf";
30/// Gridlines.
31pub const GRID: &str = "#ececec";
32/// The one accent, as on screen: what a threshold removes, the cursor.
33pub const ACCENT: &str = "#d97757";
34const FONT: &str = "Helvetica, Arial, 'DejaVu Sans', sans-serif";
35
36/// Escape text for SVG content and attributes.
37pub fn esc(s: &str) -> String {
38    let mut out = String::with_capacity(s.len());
39    for c in s.chars() {
40        match c {
41            '&' => out.push_str("&"),
42            '<' => out.push_str("&lt;"),
43            '>' => out.push_str("&gt;"),
44            '"' => out.push_str("&quot;"),
45            '\'' => out.push_str("&apos;"),
46            _ => out.push(c),
47        }
48    }
49    out
50}
51
52#[derive(Debug, Clone, Copy)]
53pub enum Anchor {
54    Start,
55    Middle,
56    End,
57}
58
59impl Anchor {
60    fn svg(self) -> &'static str {
61        match self {
62            Anchor::Start => "start",
63            Anchor::Middle => "middle",
64            Anchor::End => "end",
65        }
66    }
67}
68
69/// An SVG drawing in points, white background.
70pub struct Canvas {
71    width: f64,
72    height: f64,
73    body: String,
74}
75
76impl Canvas {
77    pub fn new(width: f64, height: f64) -> Self {
78        let mut c = Self {
79            width,
80            height,
81            body: String::new(),
82        };
83        c.rect(0.0, 0.0, width, height, "#ffffff");
84        c
85    }
86
87    /// A filled rectangle; empty ones (zero or negative size) are skipped,
88    /// as SVG renderers reject them.
89    pub fn rect(&mut self, x: f64, y: f64, w: f64, h: f64, fill: &str) {
90        // Written to two decimals: what would read as zero is skipped too.
91        if !(w >= 0.005 && h >= 0.005 && w.is_finite() && h.is_finite()) {
92            return;
93        }
94        let _ = writeln!(
95            self.body,
96            r#"<rect x="{x:.2}" y="{y:.2}" width="{w:.2}" height="{h:.2}" fill="{fill}"/>"#
97        );
98    }
99
100    /// A rectangle at `opacity`.
101    pub fn shade(&mut self, x: f64, y: f64, w: f64, h: f64, fill: &str, opacity: f64) {
102        if !(w >= 0.005 && h >= 0.005 && w.is_finite() && h.is_finite()) {
103            return;
104        }
105        let _ = writeln!(
106            self.body,
107            r#"<rect x="{x:.2}" y="{y:.2}" width="{w:.2}" height="{h:.2}" fill="{fill}" fill-opacity="{opacity:.3}"/>"#
108        );
109    }
110
111    pub fn line(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, stroke: &str, width: f64) {
112        let _ = writeln!(
113            self.body,
114            r#"<line x1="{x1:.2}" y1="{y1:.2}" x2="{x2:.2}" y2="{y2:.2}" stroke="{stroke}" stroke-width="{width}"/>"#
115        );
116    }
117
118    pub fn dashed(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, stroke: &str, width: f64) {
119        let _ = writeln!(
120            self.body,
121            r#"<line x1="{x1:.2}" y1="{y1:.2}" x2="{x2:.2}" y2="{y2:.2}" stroke="{stroke}" stroke-width="{width}" stroke-dasharray="3 2"/>"#
122        );
123    }
124
125    /// A filled dot.
126    pub fn dot(&mut self, x: f64, y: f64, r: f64, fill: &str, opacity: f64) {
127        let _ = writeln!(
128            self.body,
129            r#"<circle cx="{x:.2}" cy="{y:.2}" r="{r:.2}" fill="{fill}" fill-opacity="{opacity:.2}"/>"#
130        );
131    }
132
133    /// A dot with a ring around it.
134    pub fn ringed(&mut self, x: f64, y: f64, r: f64, fill: &str, ring: &str) {
135        let _ = writeln!(
136            self.body,
137            r#"<circle cx="{x:.2}" cy="{y:.2}" r="{r:.2}" fill="{fill}" stroke="{ring}" stroke-width="0.9"/>"#
138        );
139    }
140
141    /// A triangle pointing up, its tip at `(x, y)`.
142    pub fn pointer(&mut self, x: f64, y: f64, size: f64, fill: &str) {
143        let _ = writeln!(
144            self.body,
145            r#"<path d="M{:.2},{:.2} L{:.2},{:.2} L{x:.2},{y:.2} Z" fill="{fill}"/>"#,
146            x - size,
147            y + 1.6 * size,
148            x + size,
149            y + 1.6 * size
150        );
151    }
152
153    pub fn text(&mut self, x: f64, y: f64, s: &str, size: f64, anchor: Anchor, fill: &str) {
154        let _ = writeln!(
155            self.body,
156            r#"<text x="{x:.2}" y="{y:.2}" font-family="{FONT}" font-size="{size}" text-anchor="{}" fill="{fill}">{}</text>"#,
157            anchor.svg(),
158            esc(s)
159        );
160    }
161
162    pub fn bold(&mut self, x: f64, y: f64, s: &str, size: f64, anchor: Anchor, fill: &str) {
163        let _ = writeln!(
164            self.body,
165            r#"<text x="{x:.2}" y="{y:.2}" font-family="{FONT}" font-size="{size}" font-weight="bold" text-anchor="{}" fill="{fill}">{}</text>"#,
166            anchor.svg(),
167            esc(s)
168        );
169    }
170
171    /// Text turned to read bottom to top, centred on `(x, y)`.
172    pub fn vtext(&mut self, x: f64, y: f64, s: &str, size: f64, fill: &str) {
173        self.turned(x, y, s, size, -90.0, Anchor::Middle, fill);
174    }
175
176    /// Text turned by `degrees`, anchored at `(x, y)`.
177    #[allow(clippy::too_many_arguments)]
178    pub fn turned(
179        &mut self,
180        x: f64,
181        y: f64,
182        s: &str,
183        size: f64,
184        degrees: f64,
185        anchor: Anchor,
186        fill: &str,
187    ) {
188        let _ = writeln!(
189            self.body,
190            r#"<text transform="translate({x:.2} {y:.2}) rotate({degrees})" font-family="{FONT}" font-size="{size}" text-anchor="{}" fill="{fill}">{}</text>"#,
191            anchor.svg(),
192            esc(s)
193        );
194    }
195
196    /// An open line through `points`, dashed when asked.
197    pub fn polyline(&mut self, points: &[(f64, f64)], stroke: &str, width: f64, dashed: bool) {
198        let pts: Vec<String> = points
199            .iter()
200            .map(|(x, y)| format!("{x:.2},{y:.2}"))
201            .collect();
202        let dash = if dashed {
203            r#" stroke-dasharray="4 3""#
204        } else {
205            ""
206        };
207        let _ = writeln!(
208            self.body,
209            r#"<polyline points="{}" fill="none" stroke="{stroke}" stroke-width="{width}"{dash}/>"#,
210            pts.join(" ")
211        );
212    }
213
214    /// Swatches and their names in a row from `(x, y)`; the x after the last.
215    pub fn legend(&mut self, mut x: f64, y: f64, items: &[(&str, &str)]) -> f64 {
216        for (colour, name) in items {
217            self.rect(x, y - 8.0, 9.0, 9.0, colour);
218            self.text(x + 13.0, y, name, 9.5, Anchor::Start, INK);
219            x += 26.0 + text_width(name, 9.5);
220        }
221        x
222    }
223
224    pub fn finish(self) -> String {
225        format!(
226            r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">
227{body}</svg>
228"#,
229            w = self.width,
230            h = self.height,
231            body = self.body
232        )
233    }
234}
235
236/// About how wide `s` sets at `size` points, for laying out legends.
237pub fn text_width(s: &str, size: f64) -> f64 {
238    s.chars().count() as f64 * size * 0.55
239}
240
241/// A number as a short label: `1.2k`, `35`, `0.05`.
242pub fn short(v: f64) -> String {
243    let a = v.abs();
244    let trim = |s: String| {
245        if s.contains('.') {
246            s.trim_end_matches('0').trim_end_matches('.').to_string()
247        } else {
248            s
249        }
250    };
251    if a >= 1e6 {
252        format!("{}M", trim(format!("{:.1}", v / 1e6)))
253    } else if a >= 1e4 {
254        format!("{}k", trim(format!("{:.0}", v / 1e3)))
255    } else if a >= 1e3 {
256        format!("{}k", trim(format!("{:.1}", v / 1e3)))
257    } else if a >= 10.0 || a == 0.0 {
258        format!("{v:.0}")
259    } else if a >= 1.0 {
260        trim(format!("{v:.1}"))
261    } else {
262        trim(format!("{v:.3}"))
263    }
264}
265
266pub use crate::qc::Axis;
267
268/// Bins across a panel: about one per 6 points, from 20 to 60.
269pub fn bins_for(width: f64) -> usize {
270    ((width / 6.0) as usize).clamp(20, 60)
271}
272
273/// The box a panel draws its data in, inside `(x, y, w, h)`: room on the
274/// left for y labels, above for the title and subtitle, below for ticks
275/// and the x title.
276pub fn plot_area(x: f64, y: f64, w: f64, h: f64) -> (f64, f64, f64, f64) {
277    let (left, right, top, bottom) = (44.0, 10.0, 34.0, 32.0);
278    (
279        x + left,
280        y + top,
281        (w - left - right).max(1.0),
282        (h - top - bottom).max(1.0),
283    )
284}
285
286/// A panel's title and subtitle.
287fn heading(c: &mut Canvas, x: f64, y: f64, title: &str, subtitle: &str) {
288    c.bold(x, y + 12.0, title, 11.0, Anchor::Start, INK);
289    c.text(x, y + 25.0, subtitle, 9.0, Anchor::Start, MUTED);
290}
291
292/// The x axis under a plot area: baseline, tick stubs and labels, title.
293fn x_axis(c: &mut Canvas, axis: &Axis, (px, py, pw, ph): (f64, f64, f64, f64), title: &str) {
294    c.line(px, py + ph, px + pw, py + ph, INK, 0.6);
295    for t in axis.ticks() {
296        let tx = px + axis.frac(t) * pw;
297        c.line(tx, py + ph, tx, py + ph + 3.0, INK, 0.6);
298        c.text(tx, py + ph + 12.0, &short(t), 8.0, Anchor::Middle, MUTED);
299    }
300    c.text(
301        px + pw / 2.0,
302        py + ph + 25.0,
303        title,
304        8.5,
305        Anchor::Middle,
306        MUTED,
307    );
308}
309
310/// A histogram of `values` in layers drawn back to front, each the values
311/// its mask takes (all of them for `None`) in its colour; with an edge, a
312/// dashed line and its label; with a cursor, a pointer under the axis.
313pub struct Hist<'a> {
314    pub title: String,
315    pub subtitle: String,
316    pub x_title: String,
317    pub axis: Axis,
318    pub values: &'a [f32],
319    pub layers: Vec<(Option<&'a [bool]>, &'static str)>,
320    pub edge: Option<(f64, String)>,
321    pub cursor: Option<f64>,
322}
323
324impl Hist<'_> {
325    pub fn draw(&self, c: &mut Canvas, x: f64, y: f64, w: f64, h: f64) {
326        heading(c, x, y, &self.title, &self.subtitle);
327        let (px, py, pw, ph) = plot_area(x, y, w, h);
328        let n = bins_for(pw);
329        let layers: Vec<(Vec<usize>, &str)> = self
330            .layers
331            .iter()
332            .map(|(mask, colour)| {
333                let counts = self
334                    .axis
335                    .counts(self.values, n, |i| mask.is_none_or(|m| m[i]));
336                (counts, *colour)
337            })
338            .collect();
339        let top = layers
340            .iter()
341            .flat_map(|(c, _)| c.iter().copied())
342            .max()
343            .unwrap_or(0)
344            .max(1) as f64;
345        let y_axis = Axis::linear(0.0, top * 1.08);
346        for t in y_axis.ticks() {
347            let gy = py + ph - y_axis.frac(t) * ph;
348            if t > 0.0 {
349                c.line(px, gy, px + pw, gy, GRID, 0.6);
350            }
351            c.text(px - 4.0, gy + 3.0, &short(t), 8.0, Anchor::End, MUTED);
352        }
353        let bw = pw / n as f64;
354        let gap = if bw > 3.0 { 0.12 * bw } else { 0.0 };
355        for (counts, colour) in &layers {
356            for (i, &k) in counts.iter().enumerate() {
357                let bh = y_axis.frac(k as f64) * ph;
358                c.rect(
359                    px + i as f64 * bw + gap / 2.0,
360                    py + ph - bh,
361                    bw - gap,
362                    bh,
363                    colour,
364                );
365            }
366        }
367        x_axis(c, &self.axis, (px, py, pw, ph), &self.x_title);
368        if let Some((v, label)) = &self.edge {
369            let ex = px + self.axis.frac(*v).clamp(0.0, 1.0) * pw;
370            c.dashed(ex, py - 2.0, ex, py + ph, ACCENT, 1.1);
371            let (anchor, dx) = if ex > px + 0.8 * pw {
372                (Anchor::End, -3.0)
373            } else {
374                (Anchor::Start, 3.0)
375            };
376            c.text(ex + dx, py + 7.0, label, 8.5, anchor, ACCENT);
377        }
378        if let Some(v) = self.cursor {
379            let cx = px + self.axis.frac(v).clamp(0.0, 1.0) * pw;
380            c.pointer(cx, py + ph + 1.0, 3.5, ACCENT);
381        }
382    }
383}
384
385/// One point of a [`Scatter`]: where, its fill, and whether it is ringed.
386pub struct Point {
387    pub x: f32,
388    pub y: f32,
389    pub fill: &'static str,
390    pub ringed: bool,
391}
392
393/// Points over two axes, with an edge on either; past [`Scatter::DOTS`]
394/// points, a density grid in grey with the ringed points' cells over it in
395/// the accent.
396pub struct Scatter<'a> {
397    pub title: String,
398    pub subtitle: String,
399    pub x_title: String,
400    pub y_title: String,
401    pub x: Axis,
402    pub y: Axis,
403    pub points: &'a [Point],
404    pub x_edge: Option<f64>,
405    pub y_edge: Option<f64>,
406    /// Swatches in the corner: colour and name.
407    pub key: Vec<(&'static str, String)>,
408}
409
410impl Scatter<'_> {
411    /// More points than this draw as a density grid.
412    pub const DOTS: usize = 20_000;
413
414    pub fn draw(&self, c: &mut Canvas, x: f64, y: f64, w: f64, h: f64) {
415        heading(c, x, y, &self.title, &self.subtitle);
416        let (px, py, pw, ph) = plot_area(x, y, w, h);
417        let at = |p: &Point| {
418            (
419                px + self.x.frac(p.x as f64) * pw,
420                py + ph - self.y.frac(p.y as f64) * ph,
421            )
422        };
423        for t in self.y.ticks() {
424            let gy = py + ph - self.y.frac(t) * ph;
425            c.line(px, gy, px + pw, gy, GRID, 0.6);
426            c.text(px - 4.0, gy + 3.0, &short(t), 8.0, Anchor::End, MUTED);
427        }
428        for t in self.x.ticks() {
429            let gx = px + self.x.frac(t) * pw;
430            c.line(gx, py, gx, py + ph, GRID, 0.6);
431        }
432        c.vtext(x + 9.0, py + ph / 2.0, &self.y_title, 8.5, MUTED);
433        if self.points.len() <= Self::DOTS {
434            for p in self.points.iter().filter(|p| !p.ringed) {
435                let (sx, sy) = at(p);
436                c.dot(sx, sy, 1.6, p.fill, 0.85);
437            }
438            for p in self.points.iter().filter(|p| p.ringed) {
439                let (sx, sy) = at(p);
440                c.ringed(sx, sy, 2.3, p.fill, ACCENT);
441            }
442        } else {
443            let (gw, gh) = (((pw / 3.0) as usize).max(1), ((ph / 3.0) as usize).max(1));
444            let mut all = vec![0usize; gw * gh];
445            let mut ringed = vec![0usize; gw * gh];
446            for p in self.points {
447                let (fx, fy) = (self.x.frac(p.x as f64), self.y.frac(p.y as f64));
448                if !(fx.is_finite() && fy.is_finite()) {
449                    continue;
450                }
451                let gx = ((fx * gw as f64) as usize).min(gw - 1);
452                let gy = ((fy * gh as f64) as usize).min(gh - 1);
453                all[gy * gw + gx] += 1;
454                if p.ringed {
455                    ringed[gy * gw + gx] += 1;
456                }
457            }
458            let most = all.iter().copied().max().unwrap_or(1).max(1) as f64;
459            let (cw, ch) = (pw / gw as f64, ph / gh as f64);
460            for (k, (&a, &r)) in all.iter().zip(&ringed).enumerate() {
461                if a == 0 {
462                    continue;
463                }
464                let (gx, gy) = ((k % gw) as f64, (k / gw) as f64);
465                let opacity = 0.2 + 0.8 * (a as f64).ln_1p() / most.ln_1p();
466                let colour = if r * 2 >= a { ACCENT } else { BAR };
467                c.shade(
468                    px + gx * cw,
469                    py + ph - (gy + 1.0) * ch,
470                    cw,
471                    ch,
472                    colour,
473                    opacity,
474                );
475            }
476        }
477        if let Some(v) = self.x_edge {
478            let ex = px + self.x.frac(v).clamp(0.0, 1.0) * pw;
479            c.dashed(ex, py, ex, py + ph, ACCENT, 1.1);
480        }
481        if let Some(v) = self.y_edge {
482            let ey = py + ph - self.y.frac(v).clamp(0.0, 1.0) * ph;
483            c.dashed(px, ey, px + pw, ey, ACCENT, 1.1);
484        }
485        x_axis(c, &self.x, (px, py, pw, ph), &self.x_title);
486        let mut ky = py + ph - 6.0 - 12.0 * self.key.len().saturating_sub(1) as f64;
487        for (colour, name) in &self.key {
488            let kx = px + pw - 8.0 - text_width(name, 8.0) - 12.0;
489            c.rect(kx, ky - 7.0, 8.0, 8.0, colour);
490            c.text(kx + 11.0, ky, name, 8.0, Anchor::Start, MUTED);
491            ky += 12.0;
492        }
493    }
494}
495
496/// The light-to-dark ramp a value from 0 to 1 takes, in five steps.
497pub fn ramp(f: f64) -> &'static str {
498    const STEPS: [&str; 5] = ["#bdcbdb", "#93a8bf", "#6984a2", "#3f5f84", "#18365c"];
499    STEPS[((f.clamp(0.0, 1.0) * 5.0) as usize).min(4)]
500}
501
502/// Pixels per point in a saved PNG.
503const PNG_SCALE: f32 = 2.0;
504
505/// `svg` as PNG bytes, `scale` pixels per point, on white.
506pub use legume_tui::graphics::figure::png;
507use legume_tui::graphics::figure::{pixmap, svg_tree};
508
509/// The files a figure saved under `name` is written as: `name` itself when
510/// it ends in `.pdf`, `.png` or `.svg`, else `name.pdf` and `name.png`.
511pub fn saved_paths(name: &str) -> Vec<String> {
512    if [".pdf", ".png", ".svg"].iter().any(|e| name.ends_with(e)) {
513        vec![name.to_string()]
514    } else {
515        vec![format!("{name}.pdf"), format!("{name}.png")]
516    }
517}
518
519/// Write `svg` under `name` (see [`saved_paths`]); the paths written. A
520/// file already there is never replaced: the save is refused instead.
521pub fn save(svg: &str, name: &str) -> anyhow::Result<Vec<String>> {
522    let paths = saved_paths(name);
523    if let Some(there) = paths.iter().find(|p| std::path::Path::new(p).exists()) {
524        anyhow::bail!("{there} is already there; not replacing it");
525    }
526    let tree = svg_tree(svg)?;
527    for path in &paths {
528        if let Some(dir) = std::path::Path::new(path)
529            .parent()
530            .filter(|d| !d.as_os_str().is_empty())
531        {
532            std::fs::create_dir_all(dir)?;
533        }
534        if path.ends_with(".pdf") {
535            let pdf = svg2pdf::to_pdf(&tree, Default::default(), Default::default())
536                .map_err(|e| anyhow::anyhow!("PDF conversion failed: {e:?}"))?;
537            std::fs::write(path, pdf)?;
538        } else if path.ends_with(".png") {
539            std::fs::write(path, pixmap(&tree, PNG_SCALE)?.encode_png()?)?;
540        } else {
541            std::fs::write(path, svg)?;
542        }
543    }
544    Ok(paths)
545}
546
547/// Whether a save under `name` would replace a file already there.
548pub fn taken(name: &str) -> bool {
549    saved_paths(name)
550        .iter()
551        .any(|p| std::path::Path::new(p).exists())
552}
553
554/// `name`, or failing that the first of `{name}_2`, `{name}_3`, … that no
555/// save would replace a file under.
556pub fn free_name(name: &str) -> String {
557    let (stem, ext) = [".pdf", ".png", ".svg"]
558        .iter()
559        .find_map(|e| name.strip_suffix(e).map(|s| (s, *e)))
560        .unwrap_or((name, ""));
561    (1..)
562        .map(|n| match n {
563            1 => format!("{stem}{ext}"),
564            n => format!("{stem}_{n}{ext}"),
565        })
566        .find(|p| !taken(p))
567        .expect("some suffix is free")
568}
569
570#[cfg(test)]
571mod tests;