Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/facett

facett-plotters/src/boxplot.rs

//! **Box plot** — quartiles + whiskers + outliers, one box per named group.
//! The data→geometry math ([`Quartiles::from_sorted`] / [`Quartiles::compute`])
//! is a pure function with its own tests; [`BoxPlotView`] is the themeable
//! [`Facet`] that paints it and emits the underlying data as CSV/JSON.

use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, vec2};
use facett_core::clip::{ClipKind, ClipPayload, CopySource};
use facett_core::{Elm, FacetCaps, Semantics, a11y_node, theme};
use serde::{Deserialize, Serialize};

/// Five-number summary + the 1.5·IQR whisker fences and the points beyond them.
#[derive(Clone, Debug, PartialEq)]
pub struct Quartiles {
    pub min: f64,
    pub q1: f64,
    pub median: f64,
    pub q3: f64,
    pub max: f64,
    /// Lower whisker end: smallest datum ≥ `q1 - 1.5·IQR`.
    pub lower_fence: f64,
    /// Upper whisker end: largest datum ≤ `q3 + 1.5·IQR`.
    pub upper_fence: f64,
    /// Points outside the fences.
    pub outliers: Vec<f64>,
}

impl Quartiles {
    /// Compute from an arbitrary (unsorted) sample. Empty input → `None`.
    pub fn compute(values: &[f64]) -> Option<Self> {
        if values.is_empty() {
            return None;
        }
        let mut v: Vec<f64> = values.iter().copied().filter(|x| x.is_finite()).collect();
        if v.is_empty() {
            return None;
        }
        v.sort_by(|a, b| a.partial_cmp(b).unwrap());
        Some(Self::from_sorted(&v))
    }

    /// Compute from an already-sorted, finite, non-empty slice. Uses linear
    /// interpolation between order statistics (the "type-7"/`numpy` default), so
    /// it matches what analysts expect from Plotly/pandas.
    pub fn from_sorted(v: &[f64]) -> Self {
        debug_assert!(!v.is_empty());
        let pct = |p: f64| percentile_sorted(v, p);
        let q1 = pct(0.25);
        let median = pct(0.5);
        let q3 = pct(0.75);
        let iqr = q3 - q1;
        let lo = q1 - 1.5 * iqr;
        let hi = q3 + 1.5 * iqr;
        // Whisker ends snap to the most extreme data points still inside the fence.
        let lower_fence = *v.iter().find(|&&x| x >= lo).unwrap_or(&v[0]);
        let upper_fence = *v.iter().rev().find(|&&x| x <= hi).unwrap_or(v.last().unwrap());
        let outliers: Vec<f64> = v.iter().copied().filter(|&x| x < lo || x > hi).collect();
        Self {
            min: v[0],
            q1,
            median,
            q3,
            max: *v.last().unwrap(),
            lower_fence,
            upper_fence,
            outliers,
        }
    }
}

/// Linear-interpolated percentile of a sorted slice. `p ∈ 0..=1`.
pub fn percentile_sorted(sorted: &[f64], p: f64) -> f64 {
    let n = sorted.len();
    if n == 1 {
        return sorted[0];
    }
    let rank = p.clamp(0.0, 1.0) * (n as f64 - 1.0);
    let lo = rank.floor() as usize;
    let hi = rank.ceil() as usize;
    let frac = rank - lo as f64;
    sorted[lo] + (sorted[hi] - sorted[lo]) * frac
}

/// Persistent, observable interaction state (FC-3). The box plot's only mutable
/// state is which group box the pointer last hovered — an index into
/// [`BoxPlotView::summaries`]. Serialized so it round-trips headlessly.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct BoxPlotState {
    /// Index of the hovered box (into `summaries()`), or `None`.
    pub hover: Option<usize>,
}

/// FC-2 input surface. The box plot accepts one kind of input: the hovered box
/// changing (hit-tested *purely* in [`BoxPlotView::render`], applied in
/// [`BoxPlotView::update`]).
#[derive(Clone, Debug, PartialEq)]
pub enum BoxPlotMsg {
    /// Set (or clear, with `None`) the hovered box index.
    Hover(Option<usize>),
}

/// FC-8: the box plot does no I/O — an uninhabited effect.
#[derive(Clone, Debug)]
pub enum BoxPlotEffect {}

/// A box plot: named groups of raw samples.
pub struct BoxPlotView {
    pub title: String,
    /// `(group label, raw values)`.
    pub groups: Vec<(String, Vec<f64>)>,
    /// Observable interaction state (FC-3).
    pub state: BoxPlotState,
}

impl BoxPlotView {
    pub fn new(title: impl Into<String>, groups: Vec<(String, Vec<f64>)>) -> Self {
        Self { title: title.into(), groups, state: BoxPlotState::default() }
    }

    /// FC-3: read the complete observable interaction state.
    pub fn state(&self) -> &BoxPlotState {
        &self.state
    }

    /// FC-2/FC-8: the single mutation path. Apply one [`BoxPlotMsg`]; no effects.
    pub fn update(&mut self, msg: BoxPlotMsg) -> Vec<BoxPlotEffect> {
        match msg {
            BoxPlotMsg::Hover(h) => self.state.hover = h,
        }
        Vec::new()
    }

    /// Per-group quartiles (skipping empty groups), paired with the label.
    pub fn summaries(&self) -> Vec<(String, Quartiles)> {
        self.groups
            .iter()
            .filter_map(|(name, vals)| Quartiles::compute(vals).map(|q| (name.clone(), q)))
            .collect()
    }

    /// Global value range across every group (for the shared y-axis).
    fn value_range(&self) -> Option<(f64, f64)> {
        let mut r: Option<(f64, f64)> = None;
        for (_, vals) in &self.groups {
            for &x in vals {
                if x.is_finite() {
                    r = Some(match r {
                        None => (x, x),
                        Some((lo, hi)) => (lo.min(x), hi.max(x)),
                    });
                }
            }
        }
        r
    }

    /// CSV of the five-number summary per group (the `copy()` payload).
    fn to_csv(&self) -> String {
        let mut s = String::from("group,min,q1,median,q3,max,outliers\n");
        for (name, q) in self.summaries() {
            s.push_str(&format!(
                "{},{},{},{},{},{},{}\n",
                name, q.min, q.q1, q.median, q.q3, q.max, q.outliers.len()
            ));
        }
        s
    }
}

// ── typed copy (§16) — the chart dataset as CSV Text ──────────────────
impl CopySource for BoxPlotView {
    fn copy_kinds(&self) -> &[ClipKind] {
        &[ClipKind::Text]
    }
    fn copy_payload(&self) -> Option<ClipPayload> {
        let csv = self.to_csv();
        (!csv.is_empty()).then_some(ClipPayload::Text(csv))
    }
}

impl BoxPlotView {
    /// FC-9 pure view: paints the boxes + hover tooltip (from the *stored* hover)
    /// and **returns** the hovered-box change as a `Msg` — it never mutates `self`.
    fn render(&self, ui: &mut Ui) -> Vec<BoxPlotMsg> {
        let th = theme(ui);
        let summaries = self.summaries();
        let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
        let painter = ui.painter_at(rect);
        painter.rect_filled(rect, egui::CornerRadius::ZERO, th.bg);
        let Some((vmin, vmax)) = self.value_range() else {
            // ── render-lane emit: this Facet::ui path RAN ─────────────────────────
            #[cfg(feature = "testmatrix")]
            facett_core::testmatrix::emit(
                "facett-plotters::BoxPlotView::ui",
                "ui_render",
                summaries.is_empty(),
                &format!("drew=empty_hint groups={} summaries={}", self.groups.len(), summaries.len()),
            );
            painter.text(rect.center(), Align2::CENTER_CENTER, "no data", FontId::proportional(13.0), th.text_dim);
            return hover_msg(self.state.hover, None);
        };
        if summaries.is_empty() {
            // ── render-lane emit: this Facet::ui path RAN ─────────────────────────
            #[cfg(feature = "testmatrix")]
            facett_core::testmatrix::emit(
                "facett-plotters::BoxPlotView::ui",
                "ui_render",
                summaries.is_empty(),
                &format!("drew=empty_hint groups={} summaries={}", self.groups.len(), summaries.len()),
            );
            painter.text(rect.center(), Align2::CENTER_CENTER, "no data", FontId::proportional(13.0), th.text_dim);
            return hover_msg(self.state.hover, None);
        }
        let plot = rect.shrink2(vec2(28.0, 24.0));
        let span = (vmax - vmin).max(1e-9);
        let y_of = |v: f64| plot.bottom() - ((v - vmin) / span) as f32 * plot.height();

        let n = summaries.len();
        let slot = plot.width() / n as f32;
        let box_w = (slot * 0.5).min(60.0);
        let hover = resp.hover_pos();
        let mut new_hover: Option<usize> = None;
        let base = ui.id().with("boxplot");

        for (i, (name, q)) in summaries.iter().enumerate() {
            let cx = plot.left() + slot * (i as f32 + 0.5);
            let color = facett_core::hash_color(name);
            let stroke = Stroke::new(1.5_f32, th.accent);

            // Whiskers.
            painter.line_segment([Pos2::new(cx, y_of(q.lower_fence)), Pos2::new(cx, y_of(q.q1))], Stroke::new(1.0_f32, th.text_dim));
            painter.line_segment([Pos2::new(cx, y_of(q.q3)), Pos2::new(cx, y_of(q.upper_fence))], Stroke::new(1.0_f32, th.text_dim));
            // Whisker caps.
            let cap = box_w * 0.3;
            for &v in &[q.lower_fence, q.upper_fence] {
                painter.line_segment([Pos2::new(cx - cap, y_of(v)), Pos2::new(cx + cap, y_of(v))], Stroke::new(1.0_f32, th.text_dim));
            }
            // The box (q1..q3).
            let box_rect = Rect::from_min_max(Pos2::new(cx - box_w * 0.5, y_of(q.q3)), Pos2::new(cx + box_w * 0.5, y_of(q.q1)));
            painter.rect_filled(box_rect, egui::CornerRadius::same(2), color.gamma_multiply(0.55));
            painter.rect_stroke(box_rect, egui::CornerRadius::same(2), stroke, egui::StrokeKind::Middle);
            // AccessKit node over the box body (FC-4): role=Image, label = the
            // group name, numeric_value = the median (the box's headline stat).
            // Keyed on the group name (stable across reorder, FC-5).
            a11y_node(
                ui,
                base,
                name,
                Sense::hover(),
                box_rect,
                Semantics::image(name.clone()).value(q.median),
            );
            // Median line.
            painter.line_segment(
                [Pos2::new(box_rect.left(), y_of(q.median)), Pos2::new(box_rect.right(), y_of(q.median))],
                Stroke::new(2.0_f32, th.glow),
            );
            // Outliers.
            for &o in &q.outliers {
                painter.circle_stroke(Pos2::new(cx, y_of(o)), 2.5, Stroke::new(1.0_f32, th.point));
            }
            // Group label.
            painter.text(Pos2::new(cx, plot.bottom() + 12.0), Align2::CENTER_CENTER, name, FontId::proportional(11.0), th.text);

            // Pure hit-test: which slot is the cursor over this frame.
            if let Some(hp) = hover
                && hp.x >= cx - slot * 0.5 && hp.x < cx + slot * 0.5 && plot.y_range().contains(hp.y)
            {
                new_hover = Some(i);
            }
        }

        // Tooltip is painted from the *persisted* hover (set by `update` last frame),
        // keeping `render` a pure function of `&self`.
        if let Some(hp) = hover && let Some((name, q)) = self.state.hover.and_then(|i| summaries.get(i)) {
            paint_tooltip(
                &painter,
                &th,
                hp,
                &format!(
                    "{name}\nmax {:.3}\nq3  {:.3}\nmed {:.3}\nq1  {:.3}\nmin {:.3}\noutliers {}",
                    q.max, q.q3, q.median, q.q1, q.min, q.outliers.len()
                ),
            );
        }
        // ── render-lane emit: this Facet::ui path RAN ─────────────────────────
        #[cfg(feature = "testmatrix")]
        facett_core::testmatrix::emit(
            "facett-plotters::BoxPlotView::ui",
            "ui_render",
            !summaries.is_empty() && summaries.len() <= self.groups.len(),
            &format!("groups={} boxes={}", self.groups.len(), summaries.len()),
        );
        hover_msg(self.state.hover, new_hover)
    }
}

/// Emit a `Hover` message only when the hovered box actually changed (keeps the
/// FC-9 loop from re-applying an identical hover every frame).
fn hover_msg(current: Option<usize>, next: Option<usize>) -> Vec<BoxPlotMsg> {
    if current != next { vec![BoxPlotMsg::Hover(next)] } else { Vec::new() }
}

impl Elm for BoxPlotView {
    type Model = BoxPlotState;
    type Msg = BoxPlotMsg;
    type Effect = BoxPlotEffect;

    fn title(&self) -> &str {
        &self.title
    }
    fn state(&self) -> &BoxPlotState {
        &self.state
    }
    fn update(&mut self, msg: BoxPlotMsg) -> Vec<BoxPlotEffect> {
        BoxPlotView::update(self, msg)
    }
    fn view(&self, ui: &mut Ui) -> Vec<BoxPlotMsg> {
        facett_core::navgraph::declare_own_draw_order(ui); // atoms follow the data order (navgraph §9)
        self.render(ui)
    }
}

// Form 3 (`custom_state_json`): this view publishes a **richer** `state_json`
// (the derived five-number summary per group) than a plain `serde(state())`, so
// the macro's default is suppressed and the exact existing JSON is preserved.
facett_core::impl_facet_via_elm!(BoxPlotView, custom_state_json, {
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE.themeable().copyable().resizable()
    }
    fn copy(&mut self) -> Option<String> {
        Some(self.to_csv())
    }
    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "kind": "boxplot",
            "groups": self.summaries().iter().map(|(n, q)| serde_json::json!({
                "name": n, "min": q.min, "q1": q.q1, "median": q.median,
                "q3": q.q3, "max": q.max, "outliers": q.outliers.len(),
            })).collect::<Vec<_>>(),
        })
    }
});

/// Shared themed tooltip box used by the chart facets.
pub(crate) fn paint_tooltip(painter: &egui::Painter, th: &facett_core::Theme, at: Pos2, text: &str) {
    let font = FontId::proportional(11.0);
    let galley = painter.layout(text.to_string(), font, th.text, 240.0);
    let pad = vec2(6.0, 4.0);
    let pos = at + vec2(12.0, 12.0);
    let bg = Rect::from_min_size(pos, galley.size() + pad * 2.0);
    painter.rect_filled(bg, egui::CornerRadius::same(3), th.panel_bg);
    painter.rect_stroke(bg, egui::CornerRadius::same(3), Stroke::new(1.0_f32, th.panel_stroke), egui::StrokeKind::Middle);
    painter.galley(pos + pad, galley, Color32::WHITE);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn typed_copy_is_the_dataset_csv() {
        use facett_core::clip::{ClipKind, CopySource};
        let v = BoxPlotView::new("t", vec![("a".into(), vec![1.0, 2.0, 3.0])]);
        let p = v.copy_payload().expect("groups copy");
        assert_eq!(p.kind(), ClipKind::Text);
        assert_eq!(p.as_text(), v.to_csv());
    }

    #[test]
    fn percentile_matches_numpy_type7() {
        // numpy.percentile([1..=10], [25,50,75]) = 3.25, 5.5, 7.75
        let v: Vec<f64> = (1..=10).map(|x| x as f64).collect();
        assert!((percentile_sorted(&v, 0.25) - 3.25).abs() < 1e-9);
        assert!((percentile_sorted(&v, 0.50) - 5.5).abs() < 1e-9);
        assert!((percentile_sorted(&v, 0.75) - 7.75).abs() < 1e-9);
    }

    #[test]
    fn quartiles_basic_no_outliers() {
        let q = Quartiles::compute(&[1.0, 2.0, 3.0, 4.0, 5.0]).unwrap();
        assert_eq!(q.min, 1.0);
        assert_eq!(q.max, 5.0);
        assert_eq!(q.median, 3.0);
        assert_eq!(q.q1, 2.0);
        assert_eq!(q.q3, 4.0);
        assert!(q.outliers.is_empty());
        // fences cover the whole range when there are no outliers
        assert_eq!(q.lower_fence, 1.0);
        assert_eq!(q.upper_fence, 5.0);
    }

    #[test]
    fn quartiles_detects_high_outlier() {
        let mut data: Vec<f64> = (1..=10).map(|x| x as f64).collect();
        data.push(100.0); // far above q3 + 1.5 IQR
        let q = Quartiles::compute(&data).unwrap();
        assert!(q.outliers.contains(&100.0), "100 must be flagged as an outlier");
        assert!(q.upper_fence <= 10.0, "upper whisker snaps to in-fence data");
    }

    #[test]
    fn quartiles_empty_and_nonfinite() {
        assert!(Quartiles::compute(&[]).is_none());
        assert!(Quartiles::compute(&[f64::NAN, f64::INFINITY]).is_none());
    }

    #[test]
    fn single_value() {
        let q = Quartiles::compute(&[7.0]).unwrap();
        assert_eq!(q.median, 7.0);
        assert_eq!(q.q1, 7.0);
        assert_eq!(q.q3, 7.0);
        assert!(q.outliers.is_empty());
    }

    #[test]
    fn csv_has_header_and_row_per_group() {
        let v = BoxPlotView::new("t", vec![("a".into(), vec![1.0, 2.0, 3.0]), ("b".into(), vec![4.0, 5.0, 6.0])]);
        let csv = v.to_csv();
        assert!(csv.starts_with("group,min,q1,median,q3,max,outliers\n"));
        assert_eq!(csv.lines().count(), 3); // header + 2 groups
    }

    // ── Elm (FC-2/FC-3) harness properties ────────────────────────────────
    #[test]
    fn hover_transitions_are_observable() {
        let mut v = BoxPlotView::new(
            "t",
            vec![("a".into(), vec![1.0, 2.0, 3.0]), ("b".into(), vec![4.0, 5.0, 6.0])],
        );
        assert_eq!(v.state().hover, None);
        let snap = facett_core::harness::snapshot(&mut v, [BoxPlotMsg::Hover(Some(1))]);
        assert_eq!(snap.hover, Some(1), "hovering a box is observable in the snapshot");
        let snap = facett_core::harness::snapshot(&mut v, [BoxPlotMsg::Hover(None)]);
        assert_eq!(snap.hover, None, "leaving clears the hover");
    }

    #[test]
    fn drive_produces_no_effects() {
        let mut v = BoxPlotView::new("t", vec![("a".into(), vec![1.0, 2.0, 3.0])]);
        let effects = facett_core::harness::drive(&mut v, [BoxPlotMsg::Hover(Some(0)), BoxPlotMsg::Hover(None)]);
        assert!(effects.is_empty(), "the box plot does no I/O");
    }

    #[test]
    fn state_serde_round_trips() {
        let st = BoxPlotState { hover: Some(2) };
        let back: BoxPlotState = serde_json::from_value(serde_json::to_value(&st).unwrap()).unwrap();
        assert_eq!(st, back);
    }
}