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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Categorical beeswarm plot with a continuous color scale.

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

use crate::alpha::{marks::ObservationAlpha, AlphaTarget, AlphaUnitKind};
use crate::builder::PlotDescription;
use crate::layout::{Layout, PhysicalTextAlignment, PixelRect};
use crate::render::backend::{with_clip, Backend, GradientStop, LineStyle, Point2D};
use crate::spec::{PlotMeasureContext, PlotRenderResult};
use crate::Error;

#[derive(Debug)]
pub(crate) struct PreparedBeeswarm {
    pub(crate) x_data: (f64, f64),
    rows: Vec<(usize, f64, f64, ObservationAlpha)>,
    colors: Vec<crate::theme::OpaqueColor>,
    selection: crate::theme::ContinuousColorScale,
    scale: crate::theme::ContinuousColors,
    colorbar_stops: Vec<GradientStop>,
    values: Option<crate::numeric::set::FormattedSet>,
    format: Option<std::sync::Arc<crate::numeric::format::NumericFormat>>,
    pub(crate) color_label: crate::Text,
}

fn retained<'v>(
    registered: Option<&'v crate::orchestrator::registration::PlotRegistration<'_>>,
) -> Result<(&'v PreparedBeeswarm, &'v [String]), Error> {
    if registered.is_none() {
        return Err(Error::Render(
            "Beeswarm requires root-prepared source rows".into(),
        ));
    }
    match crate::layout::interior::preference::panel(registered, "Beeswarm")?.as_ref() {
        crate::orchestrator::registration::FamilyRef::Beeswarm(marks) => Ok((
            marks,
            &registered
                .expect("prepared Beeswarm occurrence")
                .axes
                .categories(1)
                .expect("prepared Beeswarm categories")
                .raw,
        )),
        _ => Err(Error::Render(
            "Beeswarm requires root-prepared source rows".into(),
        )),
    }
}

pub(crate) fn intrinsic_body_minimum(
    chart: &PlotDescription,
    registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
    intrinsic: &crate::orchestrator::root::PlotIntrinsics,
    operation: &crate::font::canonical::OperationContext,
    theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<(f64, f64), Error> {
    let (prepared, levels) = retained(registered)?;
    if levels.is_empty() || prepared.rows.is_empty() || prepared.rows.len() != prepared.colors.len()
    {
        return Err(Error::Render(
            "Beeswarm source rows and prepared points differ".into(),
        ));
    }
    let point = chart.point_style(
        theme,
        (0, 0, 0),
        theme.marks.get_points().get_radii().get_beeswarm(),
    );
    let ink = crate::alpha::marks::point_ink(
        &point,
        prepared
            .rows
            .iter()
            .map(|&(_, x, _, alpha)| (x, 0.0, alpha)),
    )?;

    let pitch = 2.0 * quanta_pixels(packing_radius(chart, theme)?);
    for &(category, _, _, _) in &prepared.rows {
        if category >= levels.len() {
            return Err(Error::Render(
                "Beeswarm point category exceeds prepared levels".into(),
            ));
        }
    }
    let count = u32::try_from(levels.len())
        .map_err(|_| Error::Render("Beeswarm category count exceeds spatial range".into()))?;
    let height = pitch * f64::from(count);
    if !height.is_finite() {
        return Err(Error::Render(
            "Beeswarm category hard span overflowed".into(),
        ));
    }
    let mut numeric = ink.map_or(0.0, |ink| ink.dimensions().0);
    if chart.zero_line_visible() && prepared.x_data.0 <= 0.0 && prepared.x_data.1 >= 0.0 {
        numeric = numeric.max(crate::render::geometry::line_ink_width(
            &theme
                .marks
                .get_strokes()
                .get_references()
                .get_beeswarm_reference()
                .backend_style(),
        )?);
    }
    let axes = crate::orchestrator::root::coordinate_intrinsic(
        intrinsic,
        &crate::orchestrator::root::intrinsic_inputs(registered, theme, operation)?,
    )?
    .minimum(crate::orchestrator::registration::axis_tick_labels_visible(
        registered, 1,
    ));
    Ok((
        axes.0.max(
            if registered.expect("prepared occurrence").raw_windows()[0].is_none() {
                numeric
            } else {
                0.0
            },
        ),
        axes.1.max(height),
    ))
}

fn quanta_pixels(value: i64) -> f64 {
    value as f64 / 1024.0
}

fn packing_radius(
    chart: &PlotDescription,
    theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<i64, Error> {
    let mut style = chart.point_style(
        theme,
        (0, 0, 0),
        theme.marks.get_points().get_radii().get_beeswarm(),
    );
    // A data-alpha binding retains every observation's full glyph in the
    // scientific packing input, independent of which bytes are transparent.
    if !chart.alpha_inputs().get(AlphaTarget::Point).is_theme() {
        style.color = style.color.alpha(255);
    }
    packing::radius(&style)
}

pub(crate) fn prepare(
    chart: &crate::builder::PlotDescription,
    data: crate::data::PlotData<'_, '_>,
    selection: crate::theme::ContinuousColorScale,
    numeric: crate::numeric::source::NumericBinding<'_>,
    materialization: crate::orchestrator::registration::ContinuousMaterialization,
) -> Result<(PreparedBeeswarm, Vec<String>), Error> {
    let alpha = chart.prepare_alpha(AlphaTarget::Point, AlphaUnitKind::Observation, &[])?;
    let category_col = chart
        .y_col()
        .ok_or_else(|| Error::Data("beeswarm: categorical row column not set".into()))?;
    let x_col = chart
        .x_col()
        .ok_or_else(|| Error::Data("beeswarm: x column not set".into()))?;
    let color_col = chart
        .color_col()
        .ok_or_else(|| Error::Data("beeswarm: continuous color column not set".into()))?;
    let categories = crate::data::strict_strings(data, category_col, "beeswarm")?;
    let xs = crate::data::strict_finite_f64(data, x_col, "beeswarm")?;
    let colors = crate::data::strict_finite_f64(data, color_col, "beeswarm")?;
    if categories.len() != xs.len() || xs.len() != colors.len() || xs.is_empty() {
        return Err(Error::Data(
            "beeswarm: category/x/color columns must have equal non-zero lengths".into(),
        ));
    }
    let levels = crate::data::source::source_levels(&categories)?;
    data.validate_row_source()?;

    let x_data = crate::data::min_max(xs.iter().copied(), "beeswarm")?;
    let color_range = selection.prepared_domain(&colors, "beeswarm")?.as_pair();
    let mut indices = crate::data::source::collect_source(
        levels.iter().enumerate().map(|(i, s)| Ok((s.as_str(), i))),
    )?;
    crate::data::source::sort_source_by(&mut indices, |a, b| a.0.cmp(b.0));
    let mut rows =
        crate::data::source::collect_source(
            categories.iter().zip(&xs).zip(&colors).enumerate().map(
                |(row, ((category, x), color))| {
                    let index = indices
                        .binary_search_by_key(&category.as_str(), |entry| entry.0)
                        .map_err(|_| Error::Data("beeswarm: category identity missing".into()))?;
                    Ok((
                        indices[index].1,
                        *x,
                        *color,
                        ObservationAlpha::resolve(data, &alpha, row)?,
                    ))
                },
            ),
        )?;
    crate::data::source::sort_source_by(&mut rows, |a, b| {
        a.0.cmp(&b.0)
            .then_with(|| a.3.source_row.cmp(&b.3.source_row))
    });
    let format = chart.color_label_format_spec().cloned();
    numeric.check_data(data)?;
    let values =
        if materialization == crate::orchestrator::registration::ContinuousMaterialization::Local {
            Some(crate::decorations::legend::descriptor::domain_presentation(
                color_range,
                selection.get_center(),
                format.as_deref().map(|format| {
                    (
                        format,
                        numeric,
                        if selection.get_domain().is_some() {
                            crate::NumericRangeOrigin::Explicit
                        } else {
                            crate::NumericRangeOrigin::Automatic
                        },
                    )
                }),
            )?)
        } else {
            None
        };
    let scale = crate::theme::ContinuousColors::selected(color_range, &selection)?;
    let samples = crate::data::source::collect_source(rows.iter().map(|row| Ok(row.2)))?;
    let colorbar_stops = scale.guide_stops(&samples)?;
    let colors = crate::data::source::collect_source(rows.iter().map(|row| scale.color(row.2)))?;
    Ok((
        PreparedBeeswarm {
            x_data,
            rows,
            colors,
            values,
            format,
            scale,
            selection,
            colorbar_stops,
            color_label: chart.prepare_color_label(None)?,
        },
        levels,
    ))
}

impl PreparedBeeswarm {
    pub(crate) fn alpha_guide(
        &self,
        chart: &crate::builder::PlotDescription,
        theme: &crate::theme::ResolvedTheme,
        guide: &mut crate::decorations::legend::alpha::AlphaGuideBuilder<'_>,
    ) -> crate::Result<()> {
        let point = chart.point_style(
            theme,
            (0, 0, 0),
            theme.marks.get_points().get_radii().get_beeswarm(),
        );
        for &(_, _, _, alpha) in &self.rows {
            guide.point(
                crate::decorations::legend::alpha::AlphaGlyphRole::Primary,
                alpha,
                point.clone(),
                false,
            )?;
        }
        Ok(())
    }

    pub(crate) fn guide_samples(&self) -> Result<Vec<f64>, Error> {
        crate::data::source::collect_source(self.rows.iter().map(|row| Ok(row.2)))
    }

    fn guide_stops(&self) -> Result<Vec<GradientStop>, Error> {
        crate::data::source::collect_source(self.colorbar_stops.iter().copied().map(Ok))
    }

    pub(crate) fn install_shared_domain(
        &mut self,
        descriptor: &crate::decorations::legend::descriptor::ContinuousDescriptor,
    ) -> Result<(), Error> {
        let values = Some(descriptor.numeric.try_copy()?);
        let scale =
            crate::theme::ContinuousColors::selected(descriptor.domain, &descriptor.selection)?;
        let colorbar_stops =
            crate::data::source::collect_source(descriptor.stops.iter().copied().map(Ok))?;
        self.values = values;
        self.selection = descriptor.selection.clone();
        self.scale = scale;
        self.colorbar_stops = colorbar_stops;
        for (color, &(_, _, value, _)) in self.colors.iter_mut().zip(&self.rows) {
            *color = self.scale.color(value)?;
        }
        Ok(())
    }

    pub(crate) fn continuous_semantics(
        &self,
    ) -> crate::decorations::legend::descriptor::ContinuousSemantics {
        crate::decorations::legend::descriptor::ContinuousSemantics {
            domain: self.scale.domain(),
            selection: self.selection.clone(),
            missing: None,
            format: self.format.clone(),
        }
    }

    pub(crate) fn guide_descriptor(
        &self,
        field: &str,
    ) -> Result<Option<crate::decorations::legend::descriptor::ContinuousDescriptor>, Error> {
        let Some(values) = &self.values else {
            return Ok(None);
        };
        Ok(Some(
            crate::decorations::legend::descriptor::ContinuousDescriptor {
                field: crate::data::source::copy_source_string(field)?,
                title: crate::data::source::source_arc(self.color_label.try_copy()?)?,
                stops: self.guide_stops()?,
                selection: self.selection.clone(),
                center: self.selection.get_center(),
                missing: None,
                domain: self.scale.domain(),
                exact: self.selection.get_domain().is_some(),
                format: self.format.clone(),
                numeric: values.try_copy()?,
            },
        ))
    }
}

pub(crate) fn natural_body_height(
    chart: &PlotDescription,
    registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
    intrinsic: &crate::orchestrator::root::PlotIntrinsics,
    operation: &crate::font::canonical::OperationContext,
    theme: &crate::text::TextRequestContext<'_, '_>,
    width: f64,
    selected_range: Option<(f64, f64)>,
) -> Result<f64, Error> {
    if registered.is_none() {
        return Err(Error::Render("natural Beeswarm rows missing".into()));
    }
    let crate::orchestrator::registration::FamilyRef::Beeswarm(marks) =
        crate::layout::interior::preference::panel(registered, "natural Beeswarm")?.as_ref()
    else {
        return Err(Error::Render("natural Beeswarm rows missing".into()));
    };
    let axes = registered
        .and_then(|registered| registered.axes.coordinate())
        .ok_or_else(|| Error::Render("natural Beeswarm axes missing".into()))?;
    let range = selected_range.unwrap_or_else(|| {
        chart
            .x_axis_spec()
            .window
            .map_or(axes.ranges()[0], crate::layout::RawWindow::pair)
    });
    let projection = crate::layout::Projection::new(range, (0.0, 1.0), (0.0, width, 0.0, 1.0));
    let radius = packing_radius(chart, theme)?;
    let packed = packing::pack(
        marks
            .rows
            .iter()
            .map(|&(category, value, color, alpha)| (category, value, color, alpha.source_row)),
        &projection,
        radius,
    )?;
    let hard = intrinsic_body_minimum(chart, registered, intrinsic, operation, theme)?;
    let height = quanta_pixels(packed.hard_pitch)
        .max(2.0 * theme.typography.axes.tick_label.font_size)
        * axes
            .categories(1)
            .expect("prepared Beeswarm categories")
            .raw
            .len() as f64;
    Ok(height.max(hard.1).max(3.0 * width / 4.0))
}

pub(crate) fn measure(
    chart: &PlotDescription,
    context: &PlotMeasureContext<'_, '_>,
    request: &crate::text::TextRequestContext<'_, '_>,
) -> Result<PlotRenderResult, crate::layout::fit::PlanError> {
    let (prepared, levels) = retained(Some(context.registered))?;
    let theme = request;

    let minimum = intrinsic_body_minimum(
        chart,
        Some(context.registered),
        context.intrinsic(),
        context.operation,
        theme,
    )?;
    let (panel, colorbar) =
        if crate::orchestrator::registration::continuous_guide_suppressed(Some(context.registered))
            || crate::orchestrator::registration::continuous_guide_use(
                chart,
                Some(context.registered),
            ) != crate::decorations::legend::discrete::scoped::GuideUse::Local
            || context.guides.use_kind
                != crate::decorations::legend::discrete::scoped::GuideUse::Local
        {
            (context.assignment.local.body, None)
        } else {
            let guide_scope = context
                .fit_scope()
                .child(crate::layout::AddressRole::OutsideGuideRight, 0)?;
            let descriptor =
                crate::orchestrator::registration::guide_descriptor(Some(context.registered))?
                    .ok_or_else(|| {
                        Error::Render("native Beeswarm guide was not prepared".into())
                    })?;
            let (body, guide) = crate::layout::interior::guide::native_right(
                descriptor,
                context.assignment.local.body,
                minimum.0,
                theme,
                &guide_scope,
                context.assignment.local.content_height.then_some(context),
            )?;
            (body, Some(guide))
        };
    let axes = context
        .registered
        .axes
        .coordinate()
        .ok_or_else(|| Error::Render("Beeswarm axes require preparation".into()))?;
    let range = context.axis_range(crate::layout::AxisSide::Bottom)?;
    let projection =
        crate::layout::Projection::new(range, (0.0, levels.len() as f64), panel.as_tuple());
    let source = context.registered.source;
    let pair = [axes.axis(source, 0), axes.axis(source, 1)];
    let assigned = context
        .axis_pair(crate::orchestrator::assignment::AxisPairScope::Pair)?
        .axes;
    let x = assigned[0].layout_ticks(
        Vec::new(),
        &projection,
        crate::layout::AxisSide::Bottom,
        theme,
        context.fit_scope(),
        context.registered.axis_numeric_binding(context.operation)?,
    )?;
    let radius = packing_radius(chart, theme)?;
    let packed = packing::pack(
        prepared
            .rows
            .iter()
            .map(|&(category, value, color, alpha)| (category, value, color, alpha.source_row)),
        &projection,
        radius,
    )?;
    let labels = &axes
        .categories(1)
        .ok_or_else(|| Error::Render("Beeswarm category labels missing".into()))?;
    let labels = &labels.ticks;
    let mut hard_pitch = packed.hard_pitch;
    let width = context.assignment.local.axis_label_width.max(1.0 / 1024.0);
    let tick_appearance = theme.tick_text_appearance(crate::layout::AxisSide::Left);
    if crate::orchestrator::registration::axis_tick_labels_visible(Some(context.registered), 1)
        && !tick_appearance.hidden()
        && !tick_appearance.layout.is_some_and(|request| {
            request
                .instructions()
                .visibility
                .as_ref()
                .is_some_and(crate::TextVisibility::reduces)
        })
    {
        let mut heights = crate::data::source::collect_source(labels.iter().map(|_| Ok(0.0)))?;
        for index in pair[1]
            .authored()
            .expect("coordinate authored intent")
            .category_labels
            .indices(labels.len())
        {
            let plan = crate::layout::fit::measured(crate::layout::fit::text(
                theme,
                &labels[index].label,
                tick_appearance,
                width,
                PhysicalTextAlignment::End,
                "y-axis tick label",
                &context
                    .fit_scope()
                    .child(crate::layout::AddressRole::AxisLeft, 0)?,
            ))?;
            if !plan.lines.is_empty() {
                heights[index] = plan.occupied_size().1 + 2.0 * crate::layout::LABEL_CLEARANCE;
            }
        }
        let span = crate::layout::category_label_span(
            &pair[1]
                .authored()
                .expect("coordinate authored intent")
                .category_labels,
            labels.len(),
            |index| Ok(heights[index]),
        )?;
        hard_pitch = hard_pitch.max(crate::layout::kernel::ceil_spatial_quanta(
            span / labels.len() as f64,
        )?);
    }
    let preferred = hard_pitch.max(crate::layout::kernel::ceil_spatial_quanta(
        2.0 * theme.typography.axes.tick_label.font_size,
    )?);
    let tracks = crate::data::source::collect_source(levels.iter().map(|_| {
        Ok(crate::layout::kernel::TrackSpec {
            min: hard_pitch,
            preferred,
            max: None,
            flexible: true,
        })
    }))?;
    let bands = crate::layout::interior::tracks::assign(
        &tracks,
        (panel.y0, panel.y1),
        0.0,
        false,
        context.fit_scope(),
    )?;
    let ticks =
        crate::data::source::collect_source(labels.iter().zip(&bands).map(|(label, band)| {
            let middle = f64::midpoint(band.0, band.1);
            Ok(crate::layout::AxisTick::new(
                (middle - panel.y0) / panel.height() * levels.len() as f64,
                crate::data::source::copy_source_string(&label.label)?,
            ))
        }))?;
    let layout = Layout {
        projection,
        x_axis: crate::layout::Axis {
            label: axes.copy_label(context.registered, 0)?,
            ticks: x.ticks,
            tick_labels_visible: true,
            category_labels: pair[0]
                .authored()
                .expect("coordinate authored intent")
                .category_labels
                .clone(),
            source: x.source,
            numeric: x.numeric,
            explicit_ticks: pair[0].exact_ticks()?.is_some(),
            assigned_tick_width: None,
            assigned_cells: None,
        },
        y_axis: crate::layout::Axis {
            label: axes.copy_label(context.registered, 1)?,
            ticks,
            tick_labels_visible: crate::orchestrator::registration::axis_tick_labels_visible(
                Some(context.registered),
                1,
            ),
            category_labels: pair[1]
                .authored()
                .expect("coordinate authored intent")
                .category_labels
                .clone(),
            source: crate::layout::TickSource::SUPPLIED,
            numeric: None,
            explicit_ticks: false,
            assigned_tick_width: Some(width),
            assigned_cells: Some(crate::data::source::collect_source(
                bands.iter().map(|band| Ok(*band)),
            )?),
        },
    };
    let x_range = layout.projection.x_range();
    let zero = if chart.zero_line_visible() && x_range.0 <= 0.0 && x_range.1 >= 0.0 {
        let (x, y0) = layout.projection.project(0.0, 0.0);
        let (_, y1) = layout.projection.project(0.0, levels.len() as f64);
        Some((
            [Point2D::new(x, y0), Point2D::new(x, y1)],
            theme
                .marks
                .get_strokes()
                .get_references()
                .get_beeswarm_reference()
                .backend_style(),
        ))
    } else {
        None
    };
    let points = crate::data::source::collect_source(
        packed
            .points
            .iter()
            .zip(&prepared.colors)
            .zip(&prepared.rows)
            .map(|((point, &color), row)| {
                let band = bands[point.category];
                let middle =
                    crate::layout::kernel::nearest_spatial_quanta(f64::midpoint(band.0, band.1))?;
                let y = middle
                    .checked_add(point.offset)
                    .ok_or_else(|| Error::Render("Beeswarm arranged point overflow".into()))?;
                Ok((
                    Point2D::new(quanta_pixels(point.x), quanta_pixels(y)),
                    row.3.point(chart.point_style(
                        theme,
                        color.as_rgb(),
                        theme.marks.get_points().get_radii().get_beeswarm(),
                    )),
                ))
            }),
    )?;
    let mut payload = BeeswarmPayload {
        clip: layout.projection.panel_box(),
        zero,
        points,
        source_rows: crate::data::source::collect_source(
            packed
                .points
                .iter()
                .map(|point| Ok((point.category, point.source_row))),
        )?,
        domain_expansions: [None; 2],
        colorbar: colorbar
            .as_ref()
            .map(|guide| select_colorbar(guide, panel, theme))
            .transpose()?,
    };
    let geometry = payload.geometry()?;
    let mut full = crate::render::geometry::GeometrySnapshot::new();

    for (point, style) in &payload.points {
        full.scatter_with_clip(std::slice::from_ref(point), style, None)?;
    }
    let panel = layout.projection.panel_box();
    if let Some(bounds) = full
        .bounds()
        .iter()
        .copied()
        .reduce(crate::render::geometry::GeometryBox::union)
    {
        if bounds.bottom < panel.y0 || bounds.top > panel.y1 {
            return Err(context
                .fit_scope()
                .failure(
                    crate::layout::fit::FitKind::SpecializedGeometry,
                    "Beeswarm painted ink exceeds its assigned category panel",
                )
                .into());
        }
    }
    // A structural zero reference intentionally terminates at the frame;
    // its caps do not impose category-track overflow on data points.
    if let Some((line, style)) = &payload.zero {
        full.line(line, style, None)?;
    }
    if let Some(bounds) = full
        .bounds()
        .iter()
        .copied()
        .reduce(crate::render::geometry::GeometryBox::union)
    {
        if context.registered.raw_windows()[0].is_none() {
            let levels = u32::try_from(levels.len()).map_err(|_| {
                Error::Render("Beeswarm category count exceeds spatial range".into())
            })?;
            payload.domain_expansions = crate::layout::interior::automatic_absolute_ink_expansions(
                [prepared.x_data, (0.0, f64::from(levels))],
                &layout.projection,
                bounds,
                [true, false],
                context.fit_scope(),
            )?;
        }
    }
    let mut result = PlotRenderResult::new(
        layout,
        crate::orchestrator::registration::guide_descriptor(Some(context.registered))?,
    );
    result.y_domain = crate::spec::AxisDomain::Categorical;
    result.y_tick_keys =
        Some(crate::data::source::collect_source(levels.iter().map(
            |level| crate::data::source::copy_source_string(level),
        ))?);
    result.axes = Some(result.layout.measure_axes_with_inputs(
        theme,
        context.fit_scope(),
        context.semantic_inputs(crate::orchestrator::assignment::AxisPairScope::Pair)?,
        || crate::layout::CoordinateLayoutInputs::new(theme),
    )?);
    if let Some(bar) = &payload.colorbar {
        for call in &bar.calls {
            if let crate::decorations::legend::LegendCall::Text(text) = call {
                crate::data::source::reserve_source(&mut result.producer_text, 1)?;
                result.producer_text.push(text.clone());
            }
        }
    }
    result.marks = Some(crate::data::source::source_arc(
        crate::layout::interior::SelectedMarkPlan {
            payload: crate::layout::interior::MarkPayload::Beeswarm(payload),
            geometry,
        },
    )?);
    Ok(result)
}

#[derive(Debug)]
pub(crate) struct BeeswarmPayload {
    clip: PixelRect,
    zero: Option<([Point2D; 2], LineStyle)>,
    points: Vec<(Point2D, crate::render::backend::PointStyle)>,
    source_rows: Vec<(usize, usize)>,
    colorbar: Option<crate::decorations::legend::LegendDrawPlan>,
    pub(crate) domain_expansions: [Option<crate::layout::interior::DomainExpansion>; 2],
}

impl BeeswarmPayload {
    pub(crate) fn observe_sources(
        &self,
        round: &mut crate::layout::kernel::FeedbackRound,
    ) -> Result<(), Error> {
        round.observe_count(self.source_rows.len())?;
        for &(category, row) in &self.source_rows {
            round.observe_count(category)?;
            round.observe_count(row)?;
        }
        Ok(())
    }
    pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
        with_clip(backend, self.clip, |backend| {
            if let Some((line, style)) = &self.zero {
                backend.draw_line(line, style)?;
            }
            for (point, style) in &self.points {
                backend.draw_scatter(&[*point], style)?;
            }
            Ok(())
        })?;
        if let Some(bar) = &self.colorbar {
            bar.draw(backend)?;
        }
        Ok(())
    }

    fn geometry(&self) -> Result<crate::render::geometry::GeometrySnapshot, Error> {
        let mut geometry = crate::render::geometry::GeometrySnapshot::new();
        let clip = crate::render::backend::validate_clip_region(self.clip)?.panel();
        if let Some((line, style)) = &self.zero {
            geometry.line(line, style, Some(clip))?;
        }
        for (point, style) in &self.points {
            geometry.scatter(&[*point], style, clip)?;
        }
        if let Some(bar) = &self.colorbar {
            bar.geometry(&mut geometry)?;
        }
        Ok(geometry)
    }
}

fn select_colorbar(
    guide: &crate::decorations::legend::Legend,
    panel: PixelRect,
    theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<crate::decorations::legend::LegendDrawPlan, Error> {
    let bounds = guide.box_at(
        panel.x1 + theme.legend_outside_gap()?,
        panel.y0 + (panel.height() - guide.compute_box_height()) / 2.0,
    );
    let (x, y) = bounds.anchor();
    guide.select(x, y)
}

mod packing;