Skip to main content

data_beans/figure/
panel.rs

1//! Panels for papers: a histogram and a 2D density, each laid out inside
2//! exactly the box given, all text at one size ([`Look::font`]), on the
3//! same [`Axis`] the other figures read values on.
4
5use super::*;
6
7/// How a panel is drawn: text size, what is drawn besides the plot, and
8/// the colours of kept and removed values.
9#[derive(Debug, Clone, PartialEq)]
10pub struct Look {
11    /// Text size in points, as printed: ticks, axis titles and the key.
12    pub font: f64,
13    /// Only the plot, its axes, ticks and axis titles: no title or key.
14    pub panel_only: bool,
15    /// Kept values at full depth, as `#rrggbb`.
16    pub kept: String,
17    /// Removed values at full depth, as `#rrggbb`.
18    pub removed: String,
19}
20
21impl Default for Look {
22    fn default() -> Self {
23        Self {
24            font: 8.0,
25            panel_only: false,
26            kept: BAR.into(),
27            removed: ACCENT.into(),
28        }
29    }
30}
31
32impl Look {
33    /// Kept dark grey, removed light grey.
34    pub fn gray() -> Self {
35        Self {
36            kept: "#404040".into(),
37            removed: "#bfbfbf".into(),
38            ..Self::default()
39        }
40    }
41
42    /// The size a title is set at: a little larger than the rest.
43    pub fn title_size(&self) -> f64 {
44        1.25 * self.font
45    }
46
47    /// The height of the row a title and key take, none when panel only
48    /// or there is neither.
49    fn head(&self, title: &str, key: bool) -> f64 {
50        if self.panel_only || (title.is_empty() && !key) {
51            0.0
52        } else {
53            1.4 * self.title_size()
54        }
55    }
56
57    /// The title at the left of the row from `(x, y)` and, with `key`, the
58    /// kept and removed swatches at its right, `w` across.
59    fn heading(&self, c: &mut Canvas, (x, y, w): (f64, f64, f64), title: &str, key: bool) {
60        if self.head(title, key) == 0.0 {
61            return;
62        }
63        let s = self.font;
64        let base = y + 0.1 * s + 0.75 * self.title_size();
65        if !title.is_empty() {
66            c.bold(
67                x + 0.1 * s,
68                base,
69                title,
70                self.title_size(),
71                Anchor::Start,
72                INK,
73            );
74        }
75        if key {
76            let items = [(&self.kept, "kept"), (&self.removed, "removed")];
77            let sw = 0.8 * s;
78            let wide: f64 = items
79                .iter()
80                .map(|(_, n)| sw + 0.3 * s + text_width(n, s))
81                .sum::<f64>()
82                + 0.8 * s;
83            let mut kx = x + w - 0.1 * s - wide;
84            for (colour, name) in items {
85                c.rect(kx, base - sw, sw, sw, colour);
86                c.text(kx + sw + 0.3 * s, base, name, s, Anchor::Start, INK);
87                kx += sw + 0.3 * s + text_width(name, s) + 0.8 * s;
88            }
89        }
90    }
91}
92
93/// Text size for a panel `w` x `h` points: about an eighteenth of its
94/// shorter side, from 5 to 8 points.
95pub fn fit_font(w: f64, h: f64) -> f64 {
96    (w.min(h) / 18.0).clamp(5.0, 8.0)
97}
98
99/// Kept and removed values in each of `bins` bins of `axis`; without a
100/// mask every value is kept. Values that are not finite are left out.
101pub fn stacks(
102    axis: &Axis,
103    bins: usize,
104    values: &[f32],
105    kept: Option<&[bool]>,
106) -> Vec<(usize, usize)> {
107    let k = axis.counts(values, bins, |i| kept.is_none_or(|m| m[i]));
108    let r = axis.counts(values, bins, |i| kept.is_some_and(|m| !m[i]));
109    k.into_iter().zip(r).collect()
110}
111
112/// `#rrggbb` as its three channels.
113fn channels(c: &str) -> Option<[f64; 3]> {
114    let h = c.strip_prefix('#').filter(|h| h.len() == 6)?;
115    let v = |k: usize| u8::from_str_radix(&h[k..k + 2], 16).ok().map(f64::from);
116    Some([v(0)?, v(2)?, v(4)?])
117}
118
119/// How far from white the emptiest square of `look.kept` starts: in grays,
120/// where only the depth tells kept from removed, past the removed colour,
121/// so a kept square is always the darker; else as a removed one does.
122fn kept_floor(look: &Look) -> f64 {
123    let grey = |c: &[f64; 3]| c[0] == c[1] && c[1] == c[2];
124    match (channels(&look.kept), channels(&look.removed)) {
125        (Some(k), Some(r)) if grey(&k) && grey(&r) && k[0] < r[0] => {
126            ((255.0 - r[0]) / (255.0 - k[0]) + 0.1).min(1.0)
127        }
128        _ => FLOOR,
129    }
130}
131
132/// How far from white the emptiest removed square starts.
133const FLOOR: f64 = 0.12;
134
135/// The colour of a square holding `kept` and `removed` values, where the
136/// fullest square holds `most`: the majority's colour, mixed from white
137/// deeper as the square holds more (on a log scale).
138pub fn square_colour(look: &Look, kept: usize, removed: usize, most: usize) -> String {
139    let (full, floor) = if kept >= removed {
140        (&look.kept, kept_floor(look))
141    } else {
142        (&look.removed, FLOOR)
143    };
144    let n = kept + removed;
145    let Some(rgb) = channels(full).filter(|_| n < most) else {
146        return full.clone();
147    };
148    let t = floor + (1.0 - floor) * (n as f64).ln_1p() / (most as f64).ln_1p();
149    let mix = |v: f64| (255.0 - t * (255.0 - v)).round() as u8;
150    format!("#{:02x}{:02x}{:02x}", mix(rgb[0]), mix(rgb[1]), mix(rgb[2]))
151}
152
153/// A box: left, top, width, height.
154pub type Area = (f64, f64, f64, f64);
155
156/// Ticks thinned, every other one dropped, until each `pos` is at least
157/// `room` from the next.
158fn thin(mut ticks: Vec<f64>, pos: impl Fn(f64) -> f64, room: impl Fn(f64, f64) -> f64) -> Vec<f64> {
159    while ticks.len() > 2
160        && ticks
161            .windows(2)
162            .any(|p| (pos(p[1]) - pos(p[0])).abs() < room(p[0], p[1]))
163    {
164        ticks = ticks.into_iter().step_by(2).collect();
165    }
166    ticks
167}
168
169/// The widest of the labels of `ticks`.
170fn widest(ticks: &[f64], size: f64) -> f64 {
171    ticks
172        .iter()
173        .map(|&t| text_width(&short(t), size))
174        .fold(0.0, f64::max)
175}
176
177/// The room below a plot: ticks, their labels and the x title.
178fn bottom(look: &Look, x_title: &str) -> f64 {
179    let s = look.font;
180    let title = if x_title.is_empty() { 0.0 } else { 1.3 * s };
181    0.35 * s + 0.3 * s + s + title + 0.1 * s
182}
183
184/// The room left of a plot whose tick labels are `label` wide: the y
185/// title, the labels and the ticks.
186fn left(look: &Look, y_title: &str, label: f64) -> f64 {
187    let s = look.font;
188    let title = if y_title.is_empty() { 0.0 } else { 1.3 * s };
189    0.1 * s + title + label + 0.3 * s + 0.35 * s
190}
191
192/// The room right of a plot, for half the widest x label.
193fn right(look: &Look, axis: &Axis) -> f64 {
194    (widest(&axis.ticks(), look.font) / 2.0 + 0.1 * look.font).max(0.5 * look.font)
195}
196
197/// The x axis under `(px, py, pw, ph)`: baseline, ticks, labels and title.
198fn x_axis(c: &mut Canvas, look: &Look, axis: &Axis, (px, py, pw, ph): Area, title: &str) {
199    let s = look.font;
200    let base = py + ph;
201    c.line(px, base, px + pw, base, INK, 0.6);
202    let ticks = thin(
203        axis.ticks(),
204        |t| axis.frac(t) * pw,
205        |a, b| (text_width(&short(a), s) + text_width(&short(b), s)) / 2.0 + 0.5 * s,
206    );
207    let label = base + 0.35 * s + 0.3 * s + 0.75 * s;
208    for t in ticks {
209        let tx = px + axis.frac(t) * pw;
210        c.line(tx, base, tx, base + 0.35 * s, INK, 0.6);
211        c.text(tx, label, &short(t), s, Anchor::Middle, INK);
212    }
213    if !title.is_empty() {
214        c.text(
215            px + pw / 2.0,
216            label + 1.3 * s,
217            title,
218            s,
219            Anchor::Middle,
220            INK,
221        );
222    }
223}
224
225/// The y ticks of `axis` that fit up a plot `ph` high.
226fn y_ticks(look: &Look, axis: &Axis, ph: f64) -> Vec<f64> {
227    thin(axis.ticks(), |t| axis.frac(t) * ph, |_, _| 1.2 * look.font)
228}
229
230/// The y axis left of `(px, py, pw, ph)`: line, ticks, labels and the
231/// title, turned, from `x0`.
232fn y_axis(
233    c: &mut Canvas,
234    look: &Look,
235    (axis, ticks): (&Axis, &[f64]),
236    (px, py, _, ph): Area,
237    x0: f64,
238    title: &str,
239) {
240    let s = look.font;
241    c.line(px, py, px, py + ph, INK, 0.6);
242    for &t in ticks {
243        let ty = py + ph - axis.frac(t) * ph;
244        c.line(px - 0.35 * s, ty, px, ty, INK, 0.6);
245        c.text(px - 0.65 * s, ty + 0.35 * s, &short(t), s, Anchor::End, INK);
246    }
247    if !title.is_empty() {
248        c.vtext(x0 + 0.1 * s + 0.75 * s, py + ph / 2.0, title, s, INK);
249    }
250}
251
252/// A dashed edge.
253fn edge(c: &mut Canvas, (x1, y1, x2, y2): Area) {
254    c.dashed(x1, y1, x2, y2, INK, 0.8);
255}
256
257/// Where each of `edges` falls on `axis`, 0 to 1, those outside it left
258/// out: drawn at an end they would read as a cut at the end's value.
259fn on_axis<'a>(axis: &'a Axis, edges: &'a [f64]) -> impl Iterator<Item = f64> + 'a {
260    (edges.iter())
261        .map(|&e| axis.frac(e))
262        .filter(|f| (0.0..=1.0).contains(f))
263}
264
265/// A histogram of `values` on `axis` in `bins` bins, kept stacked under
266/// removed, with dashed lines at `edges`. Values that are not finite are
267/// left out: clamp infinities to the axis ends before passing them.
268pub struct HistPanel<'a> {
269    pub axis: Axis,
270    pub bins: usize,
271    pub values: &'a [f32],
272    /// Which values are kept; `None` keeps them all.
273    pub kept: Option<&'a [bool]>,
274    pub edges: Vec<f64>,
275    pub x_title: String,
276    /// Empty for none.
277    pub y_title: String,
278    /// Empty for none; never drawn with [`Look::panel_only`].
279    pub title: String,
280}
281
282impl HistPanel<'_> {
283    /// The count axis and its ticks for a plot `ph` high.
284    /// Its bins, one at least.
285    fn bins(&self) -> usize {
286        self.bins.max(1)
287    }
288
289    fn counts_axis(&self, look: &Look, ph: f64) -> (Axis, Vec<f64>) {
290        let s = stacks(&self.axis, self.bins(), self.values, self.kept);
291        let top = s.iter().map(|(k, r)| k + r).max().unwrap_or(0).max(1) as f64;
292        let axis = Axis::linear(0.0, top * 1.05);
293        let ticks = y_ticks(look, &axis, ph);
294        (axis, ticks)
295    }
296
297    /// Where the bars go inside `area`.
298    pub fn plot_area(&self, look: &Look, (x, y, w, h): Area) -> Area {
299        let s = look.font;
300        let top = look.head(&self.title, self.kept.is_some()) + 0.5 * s;
301        let ph = (h - top - bottom(look, &self.x_title)).max(1.0);
302        let (_, ticks) = self.counts_axis(look, ph);
303        let l = left(look, &self.y_title, widest(&ticks, s));
304        let pw = (w - l - right(look, &self.axis)).max(1.0);
305        (x + l, y + top, pw, ph)
306    }
307
308    /// Draw into `area` of `c`.
309    pub fn draw(&self, c: &mut Canvas, look: &Look, area: Area) {
310        let (x, y, w, _) = area;
311        look.heading(c, (x, y, w), &self.title, self.kept.is_some());
312        let (px, py, pw, ph) = self.plot_area(look, area);
313        let (counts, ticks) = self.counts_axis(look, ph);
314        let n = self.bins();
315        let bw = pw / n as f64;
316        let gap = if bw > 3.0 { 0.1 * bw } else { 0.0 };
317        let base = py + ph;
318        for (i, (k, r)) in stacks(&self.axis, n, self.values, self.kept)
319            .into_iter()
320            .enumerate()
321        {
322            let (hk, hr) = (counts.frac(k as f64) * ph, counts.frac(r as f64) * ph);
323            let bx = px + i as f64 * bw + gap / 2.0;
324            c.rect(bx, base - hk, bw - gap, hk, &look.kept);
325            c.rect(bx, base - hk - hr, bw - gap, hr, &look.removed);
326        }
327        for f in on_axis(&self.axis, &self.edges) {
328            let ex = px + f * pw;
329            edge(c, (ex, py, ex, base));
330        }
331        x_axis(c, look, &self.axis, (px, py, pw, ph), &self.x_title);
332        y_axis(
333            c,
334            look,
335            (&counts, &ticks),
336            (px, py, pw, ph),
337            x,
338            &self.y_title,
339        );
340    }
341
342    /// The panel alone as SVG, `w` x `h` points.
343    pub fn svg(&self, look: &Look, w: f64, h: f64) -> String {
344        let mut c = Canvas::new(w, h);
345        self.draw(&mut c, look, (0.0, 0.0, w, h));
346        c.finish()
347    }
348}
349
350/// Which marginal histograms a [`DensityPanel`] has.
351#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
352pub struct Marginals {
353    /// x above the plot.
354    pub top: bool,
355    /// y right of the plot, bars growing rightwards.
356    pub right: bool,
357}
358
359/// Where a [`DensityPanel`]'s parts go.
360#[derive(Debug, Clone, Copy, PartialEq)]
361pub struct DensityLayout {
362    /// The squares.
363    pub plot: Area,
364    /// The x marginal: the plot's x span, above it.
365    pub top: Option<Area>,
366    /// The y marginal: the plot's y span, right of it.
367    pub right: Option<Area>,
368}
369
370/// Sites over two axes as squares, each coloured by [`square_colour`],
371/// with dashed lines at the edges and optional marginal histograms on the
372/// same axes and bins, without tick labels of their own. Values that are
373/// not finite are left out: clamp infinities to the axis ends before
374/// passing them.
375pub struct DensityPanel<'a> {
376    pub x: Axis,
377    pub x_bins: usize,
378    pub y: Axis,
379    pub y_bins: usize,
380    pub xs: &'a [f32],
381    pub ys: &'a [f32],
382    /// Which sites are kept; `None` keeps them all.
383    pub kept: Option<&'a [bool]>,
384    pub x_edges: Vec<f64>,
385    pub y_edges: Vec<f64>,
386    pub x_title: String,
387    pub y_title: String,
388    /// Empty for none; never drawn with [`Look::panel_only`].
389    pub title: String,
390    pub marginals: Marginals,
391}
392
393impl DensityPanel<'_> {
394    /// Kept and removed sites per square, row by row from the bottom:
395    /// square `(i, j)` (x bin `i`, y bin `j`) at `j * x_bins + i`. A site
396    /// with either value not finite is left out.
397    pub fn grid(&self) -> Vec<(usize, usize)> {
398        let (nx, ny) = (self.x_bins.max(1), self.y_bins.max(1));
399        let mut g = vec![(0, 0); nx * ny];
400        for (i, (&x, &y)) in self.xs.iter().zip(self.ys).enumerate() {
401            if !(x.is_finite() && y.is_finite()) {
402                continue;
403            }
404            let cell = &mut g[self.y.bin(y as f64, ny) * nx + self.x.bin(x as f64, nx)];
405            if self.kept.is_none_or(|m| m[i]) {
406                cell.0 += 1;
407            } else {
408                cell.1 += 1;
409            }
410        }
411        g
412    }
413
414    /// Where the plot and its marginals go inside `area`.
415    pub fn layout(&self, look: &Look, (x, y, w, h): Area) -> DensityLayout {
416        let s = look.font;
417        let Marginals { top, right: side } = self.marginals;
418        let head = look.head(&self.title, self.kept.is_some());
419        let pad = if top { 0.15 * s } else { 0.5 * s };
420        let avail_h = (h - head - pad - bottom(look, &self.x_title)).max(1.0);
421        let l = left(look, &self.y_title, widest(&self.y.ticks(), s));
422        let avail_w = (w - l - right(look, &self.x)).max(1.0);
423        let m = 0.2 * avail_w.min(avail_h);
424        let gap = 0.25 * s;
425        let room = |on: bool| if on { m + gap } else { 0.0 };
426        let (pw, ph) = (avail_w - room(side), avail_h - room(top));
427        let (px, py) = (x + l, y + head + pad + room(top));
428        DensityLayout {
429            plot: (px, py, pw, ph),
430            top: top.then_some((px, py - gap - m, pw, m)),
431            right: side.then_some((px + pw + gap, py, m, ph)),
432        }
433    }
434
435    /// Draw into `area` of `c`.
436    pub fn draw(&self, c: &mut Canvas, look: &Look, area: Area) {
437        let (x, y, w, _) = area;
438        look.heading(c, (x, y, w), &self.title, self.kept.is_some());
439        let lay = self.layout(look, area);
440        let (px, py, pw, ph) = lay.plot;
441        let (nx, ny) = (self.x_bins.max(1), self.y_bins.max(1));
442        let (cw, ch) = (pw / nx as f64, ph / ny as f64);
443        let col = |i: usize| px + i as f64 * cw;
444        let row = |j: usize| py + ph - (j + 1) as f64 * ch;
445        let grid = self.grid();
446        let most = grid.iter().map(|(k, r)| k + r).max().unwrap_or(0);
447        for (n, &(k, r)) in grid.iter().enumerate() {
448            if k + r > 0 {
449                let fill = square_colour(look, k, r, most);
450                c.rect(col(n % nx), row(n / nx), cw, ch, &fill);
451            }
452        }
453        if let Some((_, ty, _, th)) = lay.top {
454            let st = stacks(&self.x, nx, self.xs, self.kept);
455            let most = st.iter().map(|(k, r)| k + r).max().unwrap_or(0).max(1) as f64;
456            let base = ty + th;
457            for (i, (k, r)) in st.into_iter().enumerate() {
458                let (lk, lr) = (k as f64 / most * th, r as f64 / most * th);
459                c.rect(col(i), base - lk, cw, lk, &look.kept);
460                c.rect(col(i), base - lk - lr, cw, lr, &look.removed);
461            }
462        }
463        if let Some((rx, _, rw, _)) = lay.right {
464            let st = stacks(&self.y, ny, self.ys, self.kept);
465            let most = st.iter().map(|(k, r)| k + r).max().unwrap_or(0).max(1) as f64;
466            for (j, (k, r)) in st.into_iter().enumerate() {
467                let (lk, lr) = (k as f64 / most * rw, r as f64 / most * rw);
468                c.rect(rx, row(j), lk, ch, &look.kept);
469                c.rect(rx + lk, row(j), lr, ch, &look.removed);
470            }
471        }
472        let y_top = lay.top.map_or(py, |t| t.1);
473        for f in on_axis(&self.x, &self.x_edges) {
474            let ex = px + f * pw;
475            edge(c, (ex, y_top, ex, py + ph));
476        }
477        let x_end = lay.right.map_or(px + pw, |r| r.0 + r.2);
478        for f in on_axis(&self.y, &self.y_edges) {
479            let ey = py + ph - f * ph;
480            edge(c, (px, ey, x_end, ey));
481        }
482        x_axis(c, look, &self.x, lay.plot, &self.x_title);
483        let ticks = y_ticks(look, &self.y, ph);
484        y_axis(c, look, (&self.y, &ticks), lay.plot, x, &self.y_title);
485    }
486
487    /// The panel alone as SVG, `w` x `h` points.
488    pub fn svg(&self, look: &Look, w: f64, h: f64) -> String {
489        let mut c = Canvas::new(w, h);
490        self.draw(&mut c, look, (0.0, 0.0, w, h));
491        c.finish()
492    }
493}
494
495#[cfg(test)]
496mod tests;