use super::*;
#[derive(Debug, Clone, PartialEq)]
pub struct Look {
pub font: f64,
pub panel_only: bool,
pub kept: String,
pub removed: String,
}
impl Default for Look {
fn default() -> Self {
Self {
font: 8.0,
panel_only: false,
kept: BAR.into(),
removed: ACCENT.into(),
}
}
}
impl Look {
pub fn gray() -> Self {
Self {
kept: "#404040".into(),
removed: "#bfbfbf".into(),
..Self::default()
}
}
pub fn title_size(&self) -> f64 {
1.25 * self.font
}
fn head(&self, title: &str, key: bool) -> f64 {
if self.panel_only || (title.is_empty() && !key) {
0.0
} else {
1.4 * self.title_size()
}
}
fn heading(&self, c: &mut Canvas, (x, y, w): (f64, f64, f64), title: &str, key: bool) {
if self.head(title, key) == 0.0 {
return;
}
let s = self.font;
let base = y + 0.1 * s + 0.75 * self.title_size();
if !title.is_empty() {
c.bold(
x + 0.1 * s,
base,
title,
self.title_size(),
Anchor::Start,
INK,
);
}
if key {
let items = [(&self.kept, "kept"), (&self.removed, "removed")];
let sw = 0.8 * s;
let wide: f64 = items
.iter()
.map(|(_, n)| sw + 0.3 * s + text_width(n, s))
.sum::<f64>()
+ 0.8 * s;
let mut kx = x + w - 0.1 * s - wide;
for (colour, name) in items {
c.rect(kx, base - sw, sw, sw, colour);
c.text(kx + sw + 0.3 * s, base, name, s, Anchor::Start, INK);
kx += sw + 0.3 * s + text_width(name, s) + 0.8 * s;
}
}
}
}
pub fn fit_font(w: f64, h: f64) -> f64 {
(w.min(h) / 18.0).clamp(5.0, 8.0)
}
pub fn stacks(
axis: &Axis,
bins: usize,
values: &[f32],
kept: Option<&[bool]>,
) -> Vec<(usize, usize)> {
let k = axis.counts(values, bins, |i| kept.is_none_or(|m| m[i]));
let r = axis.counts(values, bins, |i| kept.is_some_and(|m| !m[i]));
k.into_iter().zip(r).collect()
}
fn channels(c: &str) -> Option<[f64; 3]> {
let h = c.strip_prefix('#').filter(|h| h.len() == 6)?;
let v = |k: usize| u8::from_str_radix(&h[k..k + 2], 16).ok().map(f64::from);
Some([v(0)?, v(2)?, v(4)?])
}
fn kept_floor(look: &Look) -> f64 {
let grey = |c: &[f64; 3]| c[0] == c[1] && c[1] == c[2];
match (channels(&look.kept), channels(&look.removed)) {
(Some(k), Some(r)) if grey(&k) && grey(&r) && k[0] < r[0] => {
((255.0 - r[0]) / (255.0 - k[0]) + 0.1).min(1.0)
}
_ => FLOOR,
}
}
const FLOOR: f64 = 0.12;
pub fn square_colour(look: &Look, kept: usize, removed: usize, most: usize) -> String {
let (full, floor) = if kept >= removed {
(&look.kept, kept_floor(look))
} else {
(&look.removed, FLOOR)
};
let n = kept + removed;
let Some(rgb) = channels(full).filter(|_| n < most) else {
return full.clone();
};
let t = floor + (1.0 - floor) * (n as f64).ln_1p() / (most as f64).ln_1p();
let mix = |v: f64| (255.0 - t * (255.0 - v)).round() as u8;
format!("#{:02x}{:02x}{:02x}", mix(rgb[0]), mix(rgb[1]), mix(rgb[2]))
}
pub type Area = (f64, f64, f64, f64);
fn thin(mut ticks: Vec<f64>, pos: impl Fn(f64) -> f64, room: impl Fn(f64, f64) -> f64) -> Vec<f64> {
while ticks.len() > 2
&& ticks
.windows(2)
.any(|p| (pos(p[1]) - pos(p[0])).abs() < room(p[0], p[1]))
{
ticks = ticks.into_iter().step_by(2).collect();
}
ticks
}
fn widest(ticks: &[f64], size: f64) -> f64 {
ticks
.iter()
.map(|&t| text_width(&short(t), size))
.fold(0.0, f64::max)
}
fn bottom(look: &Look, x_title: &str) -> f64 {
let s = look.font;
let title = if x_title.is_empty() { 0.0 } else { 1.3 * s };
0.35 * s + 0.3 * s + s + title + 0.1 * s
}
fn left(look: &Look, y_title: &str, label: f64) -> f64 {
let s = look.font;
let title = if y_title.is_empty() { 0.0 } else { 1.3 * s };
0.1 * s + title + label + 0.3 * s + 0.35 * s
}
fn right(look: &Look, axis: &Axis) -> f64 {
(widest(&axis.ticks(), look.font) / 2.0 + 0.1 * look.font).max(0.5 * look.font)
}
fn x_axis(c: &mut Canvas, look: &Look, axis: &Axis, (px, py, pw, ph): Area, title: &str) {
let s = look.font;
let base = py + ph;
c.line(px, base, px + pw, base, INK, 0.6);
let ticks = thin(
axis.ticks(),
|t| axis.frac(t) * pw,
|a, b| (text_width(&short(a), s) + text_width(&short(b), s)) / 2.0 + 0.5 * s,
);
let label = base + 0.35 * s + 0.3 * s + 0.75 * s;
for t in ticks {
let tx = px + axis.frac(t) * pw;
c.line(tx, base, tx, base + 0.35 * s, INK, 0.6);
c.text(tx, label, &short(t), s, Anchor::Middle, INK);
}
if !title.is_empty() {
c.text(
px + pw / 2.0,
label + 1.3 * s,
title,
s,
Anchor::Middle,
INK,
);
}
}
fn y_ticks(look: &Look, axis: &Axis, ph: f64) -> Vec<f64> {
thin(axis.ticks(), |t| axis.frac(t) * ph, |_, _| 1.2 * look.font)
}
fn y_axis(
c: &mut Canvas,
look: &Look,
(axis, ticks): (&Axis, &[f64]),
(px, py, _, ph): Area,
x0: f64,
title: &str,
) {
let s = look.font;
c.line(px, py, px, py + ph, INK, 0.6);
for &t in ticks {
let ty = py + ph - axis.frac(t) * ph;
c.line(px - 0.35 * s, ty, px, ty, INK, 0.6);
c.text(px - 0.65 * s, ty + 0.35 * s, &short(t), s, Anchor::End, INK);
}
if !title.is_empty() {
c.vtext(x0 + 0.1 * s + 0.75 * s, py + ph / 2.0, title, s, INK);
}
}
fn edge(c: &mut Canvas, (x1, y1, x2, y2): Area) {
c.dashed(x1, y1, x2, y2, INK, 0.8);
}
fn on_axis<'a>(axis: &'a Axis, edges: &'a [f64]) -> impl Iterator<Item = f64> + 'a {
(edges.iter())
.map(|&e| axis.frac(e))
.filter(|f| (0.0..=1.0).contains(f))
}
pub struct HistPanel<'a> {
pub axis: Axis,
pub bins: usize,
pub values: &'a [f32],
pub kept: Option<&'a [bool]>,
pub edges: Vec<f64>,
pub x_title: String,
pub y_title: String,
pub title: String,
}
impl HistPanel<'_> {
fn bins(&self) -> usize {
self.bins.max(1)
}
fn counts_axis(&self, look: &Look, ph: f64) -> (Axis, Vec<f64>) {
let s = stacks(&self.axis, self.bins(), self.values, self.kept);
let top = s.iter().map(|(k, r)| k + r).max().unwrap_or(0).max(1) as f64;
let axis = Axis::linear(0.0, top * 1.05);
let ticks = y_ticks(look, &axis, ph);
(axis, ticks)
}
pub fn plot_area(&self, look: &Look, (x, y, w, h): Area) -> Area {
let s = look.font;
let top = look.head(&self.title, self.kept.is_some()) + 0.5 * s;
let ph = (h - top - bottom(look, &self.x_title)).max(1.0);
let (_, ticks) = self.counts_axis(look, ph);
let l = left(look, &self.y_title, widest(&ticks, s));
let pw = (w - l - right(look, &self.axis)).max(1.0);
(x + l, y + top, pw, ph)
}
pub fn draw(&self, c: &mut Canvas, look: &Look, area: Area) {
let (x, y, w, _) = area;
look.heading(c, (x, y, w), &self.title, self.kept.is_some());
let (px, py, pw, ph) = self.plot_area(look, area);
let (counts, ticks) = self.counts_axis(look, ph);
let n = self.bins();
let bw = pw / n as f64;
let gap = if bw > 3.0 { 0.1 * bw } else { 0.0 };
let base = py + ph;
for (i, (k, r)) in stacks(&self.axis, n, self.values, self.kept)
.into_iter()
.enumerate()
{
let (hk, hr) = (counts.frac(k as f64) * ph, counts.frac(r as f64) * ph);
let bx = px + i as f64 * bw + gap / 2.0;
c.rect(bx, base - hk, bw - gap, hk, &look.kept);
c.rect(bx, base - hk - hr, bw - gap, hr, &look.removed);
}
for f in on_axis(&self.axis, &self.edges) {
let ex = px + f * pw;
edge(c, (ex, py, ex, base));
}
x_axis(c, look, &self.axis, (px, py, pw, ph), &self.x_title);
y_axis(
c,
look,
(&counts, &ticks),
(px, py, pw, ph),
x,
&self.y_title,
);
}
pub fn svg(&self, look: &Look, w: f64, h: f64) -> String {
let mut c = Canvas::new(w, h);
self.draw(&mut c, look, (0.0, 0.0, w, h));
c.finish()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Marginals {
pub top: bool,
pub right: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DensityLayout {
pub plot: Area,
pub top: Option<Area>,
pub right: Option<Area>,
}
pub struct DensityPanel<'a> {
pub x: Axis,
pub x_bins: usize,
pub y: Axis,
pub y_bins: usize,
pub xs: &'a [f32],
pub ys: &'a [f32],
pub kept: Option<&'a [bool]>,
pub x_edges: Vec<f64>,
pub y_edges: Vec<f64>,
pub x_title: String,
pub y_title: String,
pub title: String,
pub marginals: Marginals,
}
impl DensityPanel<'_> {
pub fn grid(&self) -> Vec<(usize, usize)> {
let (nx, ny) = (self.x_bins.max(1), self.y_bins.max(1));
let mut g = vec![(0, 0); nx * ny];
for (i, (&x, &y)) in self.xs.iter().zip(self.ys).enumerate() {
if !(x.is_finite() && y.is_finite()) {
continue;
}
let cell = &mut g[self.y.bin(y as f64, ny) * nx + self.x.bin(x as f64, nx)];
if self.kept.is_none_or(|m| m[i]) {
cell.0 += 1;
} else {
cell.1 += 1;
}
}
g
}
pub fn layout(&self, look: &Look, (x, y, w, h): Area) -> DensityLayout {
let s = look.font;
let Marginals { top, right: side } = self.marginals;
let head = look.head(&self.title, self.kept.is_some());
let pad = if top { 0.15 * s } else { 0.5 * s };
let avail_h = (h - head - pad - bottom(look, &self.x_title)).max(1.0);
let l = left(look, &self.y_title, widest(&self.y.ticks(), s));
let avail_w = (w - l - right(look, &self.x)).max(1.0);
let m = 0.2 * avail_w.min(avail_h);
let gap = 0.25 * s;
let room = |on: bool| if on { m + gap } else { 0.0 };
let (pw, ph) = (avail_w - room(side), avail_h - room(top));
let (px, py) = (x + l, y + head + pad + room(top));
DensityLayout {
plot: (px, py, pw, ph),
top: top.then_some((px, py - gap - m, pw, m)),
right: side.then_some((px + pw + gap, py, m, ph)),
}
}
pub fn draw(&self, c: &mut Canvas, look: &Look, area: Area) {
let (x, y, w, _) = area;
look.heading(c, (x, y, w), &self.title, self.kept.is_some());
let lay = self.layout(look, area);
let (px, py, pw, ph) = lay.plot;
let (nx, ny) = (self.x_bins.max(1), self.y_bins.max(1));
let (cw, ch) = (pw / nx as f64, ph / ny as f64);
let col = |i: usize| px + i as f64 * cw;
let row = |j: usize| py + ph - (j + 1) as f64 * ch;
let grid = self.grid();
let most = grid.iter().map(|(k, r)| k + r).max().unwrap_or(0);
for (n, &(k, r)) in grid.iter().enumerate() {
if k + r > 0 {
let fill = square_colour(look, k, r, most);
c.rect(col(n % nx), row(n / nx), cw, ch, &fill);
}
}
if let Some((_, ty, _, th)) = lay.top {
let st = stacks(&self.x, nx, self.xs, self.kept);
let most = st.iter().map(|(k, r)| k + r).max().unwrap_or(0).max(1) as f64;
let base = ty + th;
for (i, (k, r)) in st.into_iter().enumerate() {
let (lk, lr) = (k as f64 / most * th, r as f64 / most * th);
c.rect(col(i), base - lk, cw, lk, &look.kept);
c.rect(col(i), base - lk - lr, cw, lr, &look.removed);
}
}
if let Some((rx, _, rw, _)) = lay.right {
let st = stacks(&self.y, ny, self.ys, self.kept);
let most = st.iter().map(|(k, r)| k + r).max().unwrap_or(0).max(1) as f64;
for (j, (k, r)) in st.into_iter().enumerate() {
let (lk, lr) = (k as f64 / most * rw, r as f64 / most * rw);
c.rect(rx, row(j), lk, ch, &look.kept);
c.rect(rx + lk, row(j), lr, ch, &look.removed);
}
}
let y_top = lay.top.map_or(py, |t| t.1);
for f in on_axis(&self.x, &self.x_edges) {
let ex = px + f * pw;
edge(c, (ex, y_top, ex, py + ph));
}
let x_end = lay.right.map_or(px + pw, |r| r.0 + r.2);
for f in on_axis(&self.y, &self.y_edges) {
let ey = py + ph - f * ph;
edge(c, (px, ey, x_end, ey));
}
x_axis(c, look, &self.x, lay.plot, &self.x_title);
let ticks = y_ticks(look, &self.y, ph);
y_axis(c, look, (&self.y, &ticks), lay.plot, x, &self.y_title);
}
pub fn svg(&self, look: &Look, w: f64, h: f64) -> String {
let mut c = Canvas::new(w, h);
self.draw(&mut c, look, (0.0, 0.0, w, h));
c.finish()
}
}
#[cfg(test)]
mod tests;