lichtung-plot 0.1.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! `lichtung-plot::plots::boxplot` — box-and-whisker plot.
//!
//! Groups the data by `x_col` (categorical) and draws a box per
//! group: Q1..Q3 with median line, whiskers at 1.5*IQR.
//! This is display geometry only and performs no inferential logic.
//!
//! Explicit pairwise comparisons are rendered as stacked brackets above their
//! named categorical groups. Omnibus results are not interpreted as pairs.

#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_lossless,
    clippy::cast_precision_loss,
    clippy::too_many_lines
)]

use crate::Error;

use crate::builder::PlotDescription;
use crate::data::PlotData;
use crate::layout::interior::MeasuredCoordinateMarks;
use crate::plots::categorical_distribution::{self, DistributionPayload, PreparedDistribution};
use crate::render::backend::Point2D;
use crate::spec::PlotMeasureContext;
use crate::RawOverlay;

#[derive(Debug, PartialEq)]
struct BoxSummary {
    lo_whisker: f64,
    q1: f64,
    median: f64,
    q3: f64,
    hi_whisker: f64,
}

#[derive(Debug)]
struct BoxStats {
    x_index: usize,
    group_index: usize,
    lo_whisker: f64,
    q1: f64,
    median: f64,
    q3: f64,
    hi_whisker: f64,
    fliers: Vec<crate::plots::distribution_sample::DistributionObservation>,
}

#[derive(Debug)]
pub(crate) struct PreparedBoxplot {
    pub(crate) sample: crate::plots::distribution_sample::DistributionSample,
    stats: Vec<BoxStats>,
    pub(crate) range: (f64, f64),
}

pub(crate) fn intrinsic_body_minimum(
    chart: &PlotDescription,
    registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
    theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<(f64, f64), Error> {
    let PreparedDistribution::Boxplot(prepared) = categorical_distribution::retained(
        registered.map(|registered| registered.family.as_ref()),
    )?
    else {
        return Err(Error::Render(
            "Boxplot intrinsic requires prepared summaries".into(),
        ));
    };
    let sample = &prepared.sample;
    let x_levels = &registered
        .expect("prepared Boxplot occurrence")
        .axes
        .categories(0)
        .expect("prepared distribution categories")
        .raw;
    if x_levels.is_empty() || prepared.stats.len() != sample.groups.len() {
        return Err(Error::Render(
            "Boxplot summary and populated groups differ".into(),
        ));
    }
    let group_count = sample.group_levels.len();
    let thickness = if group_count > 0 {
        (0.72 / group_count as f64).min(0.32)
    } else {
        0.5
    };
    let fill = theme
        .marks
        .get_fills()
        .get_bodies()
        .get_box_body()
        .backend_style((0, 0, 0));
    let overlay = chart.raw_overlay_spec();
    let point_style = if overlay.is_visible() {
        chart.distribution_point_style(theme.marks.get_points().get_raw_overlay(), (0, 0, 0))
    } else {
        chart.point_style(
            theme,
            theme.marks.get_neutral_paints().get_box_flier().as_rgb(),
            theme.marks.get_points().get_radii().get_box_flier(),
        )
    };
    let mut pitch = 1.0_f64 / 1024.0;
    let mut numeric = 0.0_f64;
    for (stat, group) in prepared.stats.iter().zip(&sample.groups) {
        let fill = crate::alpha::marks::fill_style(group.fill_alpha, fill.clone());
        let body = crate::render::geometry::rectangular_fill_ink_bounds(&fill)?;
        let (_, out_y) = crate::render::geometry::rectangular_fill_ink_outset(&fill)?;
        let summary = crate::render::geometry::line_ink_width(&crate::alpha::marks::line_style(
            group.line_alpha,
            theme
                .marks
                .get_strokes()
                .get_summaries()
                .get_summary()
                .backend_style(),
        ))?;
        numeric = numeric.max(summary).max(out_y);
        if stat.x_index != group.x_index
            || stat.group_index != group.group_index
            || group.x_index >= x_levels.len()
        {
            return Err(Error::Render(
                "Boxplot summary is outside its prepared category slot".into(),
            ));
        }
        let center = crate::plots::distribution_sample::center(group, group_count);
        let offset = center - (group.x_index as f64 + 0.5);
        let half = thickness / 2.0;
        let left_room = 0.5 + offset - half;
        let right_room = 0.5 - offset - half;
        if left_room <= 0.0 || right_room <= 0.0 {
            return Err(Error::Render(
                "Boxplot body exceeds prepared category slot".into(),
            ));
        }
        pitch = pitch.max((1.0 / 1024.0) / thickness);
        if let Some(ink) = body {
            pitch = pitch.max((-ink.left).max(0.0) / left_room);
            pitch = pitch.max(ink.right.max(0.0) / right_room);
        }
        if summary > 0.0 {
            // The median spans the complete box; its independently resolved
            // stroke may remain visible when the body has no painted ink.
            pitch = pitch.max((summary / 2.0) / left_room);
            pitch = pitch.max((summary / 2.0) / right_room);
        }
        let observations = if overlay.is_visible() {
            &group.observations
        } else {
            &stat.fliers
        };
        if let Some(ink) = crate::alpha::marks::point_ink(
            &point_style,
            observations.iter().map(|observation| {
                let x = crate::plots::distribution_sample::overlay_x(
                    overlay,
                    center,
                    thickness,
                    observation.alpha.source_row,
                );
                (x, observation.value, observation.alpha)
            }),
        )? {
            let left = ink.ranges[0].0 - (group.x_index as f64 + 0.5);
            let right = ink.ranges[0].1 - (group.x_index as f64 + 0.5);
            pitch = pitch.max((-ink.bounds.left).max(0.0) / (0.5 + left));
            pitch = pitch.max(ink.bounds.right.max(0.0) / (0.5 - right));
            numeric = numeric.max(ink.dimensions().1);
        }
    }
    let count = u32::try_from(x_levels.len())
        .map_err(|_| Error::Render("Boxplot category count exceeds coordinate range".into()))?;
    let category_span = pitch * f64::from(count);
    if !category_span.is_finite() {
        return Err(Error::Render(
            "Boxplot category hard span overflowed".into(),
        ));
    }
    Ok((
        category_span,
        if registered.expect("prepared occurrence").raw_windows()[1].is_none() {
            numeric
        } else {
            0.0
        },
    ))
}

pub(crate) fn prepare(
    chart: &crate::builder::PlotDescription,
    data: PlotData<'_, '_>,
    facet: Option<crate::data::FacetAxisSources<'_>>,
) -> Result<(PreparedBoxplot, Vec<String>, Vec<String>), Error> {
    let (sample, categories, hue_levels) =
        crate::plots::distribution_sample::prepare_scoped(chart, data, "boxplot", facet)?;

    // Display stats per group: Q1, median, Q3, lower whisker, upper whisker.
    let stats = crate::data::source::collect_source(sample.groups.iter().map(
        |group| -> Result<BoxStats, Error> {
            let mut ys = crate::data::source::collect_source(
                group.observations.iter().map(|o| Ok(o.value)),
            )?;
            let summary = box_summary_with_source(&mut ys)?;
            let mut fliers = Vec::new();
            crate::data::source::reserve_source(&mut fliers, group.observations.len())?;
            fliers.extend(group.observations.iter().copied().filter(|observation| {
                observation.value < summary.lo_whisker || observation.value > summary.hi_whisker
            }));
            // Preserve the former value-sorted flier paint order, retaining
            // distinct original occurrences when values coincide.
            crate::data::source::sort_source_by(&mut fliers, |a, b| {
                a.value
                    .total_cmp(&b.value)
                    .then_with(|| a.alpha.slot.cmp(&b.alpha.slot))
            });
            Ok(BoxStats {
                x_index: group.x_index,
                group_index: group.group_index,
                lo_whisker: summary.lo_whisker,
                q1: summary.q1,
                median: summary.median,
                q3: summary.q3,
                hi_whisker: summary.hi_whisker,
                fliers,
            })
        },
    ))?;

    let y_min = stats.iter().fold(f64::INFINITY, |min, stat| {
        stat.fliers
            .iter()
            .map(|observation| observation.value)
            .fold(min.min(stat.lo_whisker), f64::min)
    });
    let y_max = stats.iter().fold(f64::NEG_INFINITY, |max, stat| {
        stat.fliers
            .iter()
            .map(|observation| observation.value)
            .fold(max.max(stat.hi_whisker), f64::max)
    });

    Ok((
        PreparedBoxplot {
            sample,
            stats,
            range: (y_min, y_max),
        },
        categories,
        hue_levels,
    ))
}

impl PreparedBoxplot {
    pub(crate) fn alpha_guide(
        &self,
        chart: &crate::builder::PlotDescription,
        theme: &crate::theme::ResolvedTheme,
        guide: &mut crate::decorations::legend::alpha::AlphaGuideBuilder<'_>,
    ) -> crate::Result<()> {
        use crate::alpha::AlphaUnitKind;
        use crate::decorations::legend::alpha::{AlphaGlyphRole, AlphaUnit};
        let fill = theme.marks.get_fills().get_bodies().get_box_body();
        let overlay = chart.raw_overlay_spec();
        for (group, stat) in self.sample.groups.iter().zip(&self.stats) {
            let unit = AlphaUnit::aggregate(chart, &group.label, group.group_label.as_deref())?;
            guide.fill(
                AlphaGlyphRole::Fill,
                AlphaUnitKind::Aggregate,
                unit.clone(),
                group.fill_alpha,
                fill.backend_style((0, 0, 0)),
                fill.get_outline()
                    .is_some_and(|outline| outline.mapped_width().is_some()),
            )?;
            guide.line(
                AlphaGlyphRole::Summary,
                AlphaUnitKind::Aggregate,
                unit,
                group.line_alpha,
                theme
                    .marks
                    .get_strokes()
                    .get_summaries()
                    .get_summary()
                    .backend_style(),
                false,
            )?;
            if overlay == RawOverlay::Hidden {
                let point = chart.point_style(
                    theme,
                    (0, 0, 0),
                    theme.marks.get_points().get_radii().get_box_flier(),
                );
                for observation in &stat.fliers {
                    guide.point(
                        AlphaGlyphRole::Outlier,
                        observation.alpha,
                        point.clone(),
                        false,
                    )?;
                }
            } else {
                let point = chart.distribution_point_style(
                    theme.marks.get_points().get_raw_overlay(),
                    (0, 0, 0),
                );
                for observation in &group.observations {
                    guide.point(
                        AlphaGlyphRole::RawOverlay,
                        observation.alpha,
                        point.clone(),
                        false,
                    )?;
                }
            }
        }
        Ok(())
    }
}

pub(crate) fn measure_marks(
    chart: &PlotDescription,
    context: &PlotMeasureContext<'_, '_>,
    request: &crate::text::TextRequestContext<'_, '_>,
    layout: &crate::layout::Layout,
) -> Result<MeasuredCoordinateMarks, crate::layout::fit::PlanError> {
    let PreparedDistribution::Boxplot(prepared) =
        categorical_distribution::retained(Some(context.family()?))?
    else {
        return Err(Error::Render("boxplot requires retained box summaries".into()).into());
    };
    let theme = request;
    theme.text.prepared_font_environment()?;
    let data = context.data()?;
    let sample = &prepared.sample;
    let stats = &prepared.stats;
    let x_levels = &context
        .registered
        .axes
        .categories(0)
        .expect("prepared distribution categories")
        .raw;
    let group_levels = &sample.group_levels;
    let group_active = !group_levels.is_empty();
    let base_y_range = layout.projection.y_range();
    let mut rendered_maxima =
        crate::data::source::collect_source((0..x_levels.len()).map(|_| Ok(f64::NEG_INFINITY)))?;
    let mut grouped_maxima = crate::data::source::collect_source((0..x_levels.len()).map(|_| {
        crate::data::source::collect_source(
            (0..group_levels.len().max(1)).map(|_| Ok(f64::NEG_INFINITY)),
        )
    }))?;
    for stat in stats {
        let maximum = stat
            .fliers
            .iter()
            .map(|observation| observation.value)
            .fold(stat.hi_whisker, f64::max);
        rendered_maxima[stat.x_index] = rendered_maxima[stat.x_index].max(maximum);
        grouped_maxima[stat.x_index][stat.group_index] = maximum;
    }
    let overlay = chart.raw_overlay_spec();
    let panel = context.assignment.local.body;
    let colors = {
        let retained = categorical_distribution::retained(Some(context.family()?))?;
        retained.resolved_colors(
            chart,
            &context.registered.axes,
            context
                .registered
                .categorical
                .as_ref()
                .expect("prepared color binding"),
            theme,
            data.source_resources(),
            false,
        )?
    };
    let significance = if group_levels.is_empty() {
        crate::significance::plan(
            context.registered,
            context.registered.significance_annotations(),
            x_levels,
            &rendered_maxima,
            base_y_range,
            panel,
            theme,
            context.fit_scope(),
        )?
    } else {
        crate::significance::plan_grouped(
            context.registered,
            context.registered.significance_annotations(),
            x_levels,
            group_levels,
            &grouped_maxima,
            0.72,
            base_y_range,
            panel,
            false,
            theme,
            context.fit_scope(),
        )?
    };
    let proj = &layout.projection;
    let box_w_data = if group_active {
        (0.72 / group_levels.len() as f64).min(0.32)
    } else {
        0.5
    };

    let mut payload = DistributionPayload::new(layout.projection.panel_box());
    for (i, stat) in stats.iter().enumerate() {
        let group = &sample.groups[i];
        let color = colors.color(group.hue_label.as_deref().unwrap_or(&group.label))?;
        let fill = crate::alpha::marks::fill_style(
            group.fill_alpha,
            theme
                .marks
                .get_fills()
                .get_bodies()
                .get_box_body()
                .backend_style(color),
        );
        let style = crate::alpha::marks::line_style(
            group.line_alpha,
            theme
                .marks
                .get_strokes()
                .get_summaries()
                .get_summary()
                .backend_style(),
        );

        let x_center_data =
            crate::plots::distribution_sample::center(&sample.groups[i], group_levels.len());
        let (xc, _) = proj.project(x_center_data, 0.0);
        let box_w_px = (proj.project(box_w_data, 0.0).0 - proj.project(0.0, 0.0).0).abs();
        let (_, y_lo) = proj.project(x_center_data, stat.lo_whisker);
        let (_, y_q1) = proj.project(x_center_data, stat.q1);
        let (_, y_med) = proj.project(x_center_data, stat.median);
        let (_, y_q3) = proj.project(x_center_data, stat.q3);
        let (_, y_hi) = proj.project(x_center_data, stat.hi_whisker);
        for (source, projected, context) in [
            ((stat.q1, stat.q3), (y_q1, y_q3), "boxplot polygon"),
            (
                (stat.lo_whisker, stat.q1),
                (y_lo, y_q1),
                "boxplot lower whisker",
            ),
            (
                (stat.q3, stat.hi_whisker),
                (y_q3, y_hi),
                "boxplot upper whisker",
            ),
        ] {
            proj.validate_span(
                crate::layout::AxisSide::Left,
                source,
                projected,
                source.0 < source.1,
                context,
            )?;
        }

        // Box.
        let pts = crate::data::source::collect_source(
            [
                Point2D::new(xc - box_w_px / 2.0, y_q1),
                Point2D::new(xc - box_w_px / 2.0, y_q3),
                Point2D::new(xc + box_w_px / 2.0, y_q3),
                Point2D::new(xc + box_w_px / 2.0, y_q1),
            ]
            .into_iter()
            .map(Ok),
        )?;
        payload.polygon(pts, fill)?;

        // Median line.
        payload.line(
            &[
                Point2D::new(xc - box_w_px / 2.0, y_med),
                Point2D::new(xc + box_w_px / 2.0, y_med),
            ],
            &style,
        )?;

        // Whiskers.
        payload.line(&[Point2D::new(xc, y_q3), Point2D::new(xc, y_hi)], &style)?;
        payload.line(&[Point2D::new(xc, y_q1), Point2D::new(xc, y_lo)], &style)?;
        let cap = box_w_px * 0.3;
        payload.line(
            &[Point2D::new(xc - cap, y_hi), Point2D::new(xc + cap, y_hi)],
            &style,
        )?;
        payload.line(
            &[Point2D::new(xc - cap, y_lo), Point2D::new(xc + cap, y_lo)],
            &style,
        )?;

        if overlay == RawOverlay::Hidden {
            let flier_style = chart.point_style(
                theme,
                theme.marks.get_neutral_paints().get_box_flier().as_rgb(),
                theme.marks.get_points().get_radii().get_box_flier(),
            );
            let flier_points =
                crate::data::source::collect_source(stat.fliers.iter().map(|observation| {
                    let (x_px, y_px) = proj.project(x_center_data, observation.value);
                    Ok(Point2D::new(x_px, y_px))
                }))?;
            if !flier_points.is_empty() {
                payload.scatter(
                    flier_points,
                    &flier_style,
                    stat.fliers.iter().map(|observation| observation.alpha),
                )?;
            }
        }
    }
    if overlay.is_visible() {
        for group in &sample.groups {
            let center = crate::plots::distribution_sample::center(group, group_levels.len());
            let points = crate::data::source::collect_source(group.observations.iter().map(
                |observation| {
                    let x = crate::plots::distribution_sample::overlay_x(
                        overlay,
                        center,
                        box_w_data,
                        observation.alpha.source_row,
                    );
                    let (x, y) = proj.project(x, observation.value);
                    Ok(Point2D::new(x, y))
                },
            ))?;
            payload.scatter(
                points,
                &chart.distribution_point_style(
                    theme.marks.get_points().get_raw_overlay(),
                    colors.color(group.hue_label.as_deref().unwrap_or(&group.label))?,
                ),
                group
                    .observations
                    .iter()
                    .map(|observation| observation.alpha),
            )?;
        }
    }
    let mut result = payload.retain(layout, context)?;
    result.significance = Some(significance);
    Ok(result)
}

fn box_summary_with_source(values: &mut [f64]) -> Result<BoxSummary, Error> {
    if values.is_empty() || values.iter().any(|v| !v.is_finite()) {
        return Err(Error::Data(
            "boxplot: samples must be finite and nonempty".into(),
        ));
    }
    crate::data::source::sort_numeric_source(values);
    let q1 = crate::stats::distribution::sorted_quantile(values, 0.25);
    let median = crate::stats::distribution::sorted_quantile(values, 0.5);
    let q3 = crate::stats::distribution::sorted_quantile(values, 0.75);
    let iqr = q3 - q1;
    let lo_fence = q1 - 1.5 * iqr;
    let hi_fence = q3 + 1.5 * iqr;

    let lo_whisker = values
        .iter()
        .copied()
        .find(|value| *value >= lo_fence)
        .unwrap_or(q1);
    let hi_whisker = values
        .iter()
        .rev()
        .copied()
        .find(|value| *value <= hi_fence)
        .unwrap_or(q3);
    Ok(BoxSummary {
        lo_whisker,
        q1,
        median,
        q3,
        hi_whisker,
    })
}