lichtung-plot 0.3.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
//! Actual component membership and declared alpha-only symbol explanations.

use std::sync::Arc;

use crate::alpha::{
    marks::ObservationAlpha, AlphaEncoding, AlphaInputs, AlphaSemantics, AlphaTarget,
    AlphaUnitKind, AlphaValues, ResolvedAlpha,
};
use crate::builder::PlotDescription;
use crate::data::source::{
    collect_source, copy_source_string, reserve_source, reserve_source_string, source_arc,
};
use crate::layout::ComponentAddress;
use crate::render::backend::{FillStyle, LineStyle, PointStyle};
use crate::theme::{Color, OpaqueColor};
use crate::{plots::PlotKind, Error, Result};

use super::discrete::{
    shared_slice, GuideSectionBody, GuideSectionIdentity, PreparedGuideEntry, PreparedGuideSection,
};
use super::source::{
    AlphaExplanation, AlphaExplanationMask, GuideExplanation, GuideExplanationMask, RgbExplanation,
    StyleExplanation,
};
use super::{identity::AlphaGuideMember, GuideEntryIdentity, ResolvedGuideKey};
use crate::data::category::{shared_text, RawField};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AlphaSectionIdentity {
    pub(crate) field: RawField,
    pub(crate) semantics: AlphaSemantics,
    pub(crate) target: AlphaTarget,
    pub(crate) unit: AlphaUnitKind,
}

/// Roles establish a producer's deterministic component order, independently of
/// row order, alpha magnitude or category labels. All active glyphs are retained.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum AlphaGlyphRole {
    Primary,
    Outlier,
    RawOverlay,
    MandatoryStrip,
    LeftEndpoint,
    RightEndpoint,
    Line,
    Summary,
    Median,
    Fill,
    Highlight,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AlphaUnit {
    Observation { slot: usize, source_row: usize },
    Keyed(Arc<[(String, String)]>),
    Bin([u64; 2]),
    Single,
}

impl AlphaUnit {
    pub(crate) const fn observation(alpha: ObservationAlpha) -> Self {
        Self::Observation {
            slot: alpha.slot,
            source_row: alpha.source_row,
        }
    }

    pub(crate) fn bin(bounds: (f64, f64)) -> Self {
        let key = |value: f64| if value == 0.0 { 0 } else { value.to_bits() };
        Self::Bin([key(bounds.0), key(bounds.1)])
    }

    pub(crate) fn keyed(keys: &[(&str, &str)]) -> Result<Self> {
        let mut keys =
            collect_source(keys.iter().map(|&(field, value)| {
                Ok((copy_source_string(field)?, copy_source_string(value)?))
            }))?;
        crate::data::source::sort_source_by(&mut keys, |left, right| left.0.cmp(&right.0))?;
        keys.dedup();
        Ok(Self::Keyed(shared_slice(keys)?))
    }

    pub(crate) fn series(
        plot: &PlotDescription,
        identity: Option<&crate::data::CollectivePair>,
    ) -> Result<Self> {
        let group = plot
            .group_name()
            .zip(identity.and_then(|pair| pair.group.as_deref()));
        let hue = plot
            .hue_name()
            .zip(identity.and_then(|pair| pair.hue.as_deref()));
        match (group, hue) {
            (Some(group), Some(hue)) => Self::keyed(&[group, hue]),
            (Some(group), None) => Self::keyed(&[group]),
            (None, Some(hue)) => Self::keyed(&[hue]),
            (None, None) => Self::keyed(&[]),
        }
    }

    pub(crate) fn aggregate(
        plot: &PlotDescription,
        category: &str,
        series: Option<&str>,
    ) -> Result<Self> {
        let field = plot
            .x_col()
            .and_then(|key| plot.data_column(key))
            .ok_or_else(|| Error::Render("alpha aggregate guide has no category field".into()))?;
        let category = (field.name(), category);
        if let Some(series) = plot.group_name().zip(series) {
            Self::keyed(&[category, series])
        } else {
            Self::keyed(&[category])
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AlphaActualMember {
    pub(crate) unit: AlphaUnit,
    pub(crate) value: ResolvedAlpha,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AlphaGlyphSource {
    role: AlphaGlyphRole,
    pub(crate) key: ResolvedGuideKey,
    pub(crate) members: Arc<[AlphaActualMember]>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AlphaGuideSource {
    pub(crate) target: AlphaTarget,
    pub(crate) unit: AlphaUnitKind,
    pub(crate) producer: PlotKind,
    pub(crate) owner: ComponentAddress,
    pub(crate) scope: Option<Arc<str>>,
    pub(crate) input: AlphaEncoding,
    pub(crate) neutral: OpaqueColor,
    pub(crate) glyphs: Arc<[AlphaGlyphSource]>,
}

/// Complete scientific alpha identity survives Hidden and Undeclared policies.
/// Explanatory sections borrow these same sources; they are not another census.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedAlphaInputs {
    pub(crate) inputs: AlphaInputs,
    pub(crate) sources: Arc<[AlphaGuideSource]>,
}

impl PreparedAlphaInputs {
    pub(crate) fn sections(
        &self,
        labels: &crate::formatting::Labels,
    ) -> Result<Vec<PreparedGuideSection>> {
        let mut sections = Vec::new();
        reserve_source(&mut sections, self.sources.len())?;
        for source in self.sources.iter() {
            let values = source.input.values().expect("actual source retains values");
            if values.semantics() == AlphaSemantics::Undeclared {
                continue;
            }
            sections.push(alpha_section(labels, source, values)?);
        }
        Ok(sections)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedAlphaSection {
    pub(crate) declaration: AlphaValues,
    pub(crate) entries: Arc<[PreparedGuideEntry]>,
    pub(crate) sources: Arc<[AlphaGuideSource]>,
}

impl PreparedAlphaSection {
    pub(crate) fn source_occurrences(&self) -> Result<usize> {
        self.sources
            .iter()
            .flat_map(|source| source.glyphs.iter())
            .try_fold(0_usize, |count, glyph| {
                count
                    .checked_add(glyph.members.len())
                    .ok_or_else(|| Error::Render("alpha guide membership count overflow".into()))
            })
    }

    pub(super) fn merge(&self, other: &Self, context: &str) -> Result<Arc<Self>> {
        if !self.declaration.same_declaration(&other.declaration) || !compatible_glyphs(self, other)
        {
            return Err(Error::Render(format!("{context} requires compatible semantic titles, labels, and styles: alpha declarations and complete projected glyphs must match").into()));
        }
        let mut entries = collect_source(self.entries.iter().cloned().map(Ok))?;
        for entry in other.entries.iter() {
            if let Some(existing) = entries
                .iter()
                .find(|existing| existing.identity == entry.identity)
            {
                if existing.display_label != entry.display_label || existing.key != entry.key {
                    return Err(Error::Render(format!("{context} requires compatible semantic titles, labels, and styles: alpha member labels and glyphs must match").into()));
                }
            } else {
                reserve_source(&mut entries, 1)?;
                entries.push(entry.clone());
            }
        }
        crate::data::source::sort_source_by(&mut entries, |left, right| {
            ordinal(left).cmp(&ordinal(right))
        })?;
        let mut sources = collect_source(self.sources.iter().cloned().map(Ok))?;
        reserve_source(&mut sources, other.sources.len())?;
        sources.extend_from_slice(&other.sources);
        source_arc(Self {
            declaration: self.declaration.clone(),
            entries: shared_slice(entries)?,
            sources: shared_slice(sources)?,
        })
    }
}

fn ordinal(entry: &PreparedGuideEntry) -> u32 {
    let GuideEntryIdentity::AlphaMember(member) = &entry.identity else {
        unreachable!("alpha section retains alpha entry identities")
    };
    member.ordinal
}

fn compatible_glyphs(left: &PreparedAlphaSection, right: &PreparedAlphaSection) -> bool {
    fn glyphs(section: &PreparedAlphaSection) -> Option<&[AlphaGlyphSource]> {
        section.sources.first().map(|source| source.glyphs.as_ref())
    }
    let (Some(left), Some(right)) = (glyphs(left), glyphs(right)) else {
        return false;
    };
    left.iter()
        .all(|glyph| right.iter().any(|other| other.key == glyph.key))
        && right
            .iter()
            .all(|glyph| left.iter().any(|other| other.key == glyph.key))
}

struct PendingGlyph {
    role: AlphaGlyphRole,
    key: ResolvedGuideKey,
    members: Vec<AlphaActualMember>,
}

struct PendingTarget {
    unit: AlphaUnitKind,
    glyphs: Vec<PendingGlyph>,
}

pub(crate) struct AlphaGuideBuilder<'a> {
    plot: &'a PlotDescription,
    scope: Option<&'a str>,
    owner: &'a ComponentAddress,
    neutral: OpaqueColor,
    targets: [Option<PendingTarget>; 3],
}

impl<'a> AlphaGuideBuilder<'a> {
    pub(crate) fn new(
        plot: &'a PlotDescription,
        scope: Option<&'a str>,
        theme: &crate::theme::ResolvedTheme,
        owner: &'a ComponentAddress,
    ) -> Self {
        let paint = theme.typography.guides.legend_label.get_color();
        Self {
            plot,
            scope,
            owner,
            neutral: OpaqueColor::rgb(paint.red(), paint.green(), paint.blue()),
            targets: [None, None, None],
        }
    }

    pub(crate) fn enabled(&self, target: AlphaTarget) -> bool {
        self.plot.alpha_inputs().get(target).values().is_some()
    }

    pub(crate) fn any_enabled(&self) -> bool {
        [AlphaTarget::Point, AlphaTarget::Line, AlphaTarget::Fill]
            .into_iter()
            .any(|target| self.enabled(target))
    }

    pub(crate) fn point(
        &mut self,
        role: AlphaGlyphRole,
        alpha: ObservationAlpha,
        mut style: PointStyle,
        mapped_shape: bool,
    ) -> Result<()> {
        if !self.enabled(AlphaTarget::Point) {
            return Ok(());
        }
        style.color = Color::from(self.neutral);
        if mapped_shape {
            style.shape = crate::style::PointShape::Circle;
        }
        let key = ResolvedGuideKey {
            explanation: GuideExplanation::Projected(GuideExplanationMask {
                alpha: AlphaExplanationMask {
                    point_fill: Some(AlphaExplanation::Explained),
                    point_outline: style.outline.as_ref().map(|_| AlphaExplanation::Constant),
                    ..AlphaExplanationMask::default()
                },
                point_fill: Some(RgbExplanation::NeutralizedColor),
                point_outline: style.outline.as_ref().map(|_| RgbExplanation::Constant),
                point_shape: Some(if mapped_shape {
                    StyleExplanation::NeutralizedGroup
                } else {
                    StyleExplanation::Constant
                }),
                line_stroke: None,
                fill_paint: None,
                fill_outline: None,
                line_pattern: None,
            }),
            point: Some(style),
            ..ResolvedGuideKey::default()
        };
        self.push(
            AlphaTarget::Point,
            AlphaUnitKind::Observation,
            role,
            AlphaUnit::Observation {
                slot: alpha.slot,
                source_row: alpha.source_row,
            },
            alpha.value,
            key,
        )
    }

    pub(crate) fn line(
        &mut self,
        role: AlphaGlyphRole,
        unit: AlphaUnitKind,
        identity: AlphaUnit,
        alpha: Option<ResolvedAlpha>,
        mut style: LineStyle,
        mapped_pattern: bool,
    ) -> Result<()> {
        if !self.enabled(AlphaTarget::Line) {
            return Ok(());
        }
        style.color = Color::from(self.neutral);
        if mapped_pattern {
            style.pattern = crate::style::LinePattern::Solid;
        }
        let key = ResolvedGuideKey {
            explanation: GuideExplanation::Projected(GuideExplanationMask {
                alpha: AlphaExplanationMask {
                    line_stroke: Some(AlphaExplanation::Explained),
                    ..AlphaExplanationMask::default()
                },
                line_stroke: Some(RgbExplanation::NeutralizedColor),
                line_pattern: Some(if mapped_pattern {
                    StyleExplanation::NeutralizedGroup
                } else {
                    StyleExplanation::Constant
                }),
                point_fill: None,
                point_outline: None,
                fill_paint: None,
                fill_outline: None,
                point_shape: None,
            }),
            line: Some(style),
            ..ResolvedGuideKey::default()
        };
        self.push(AlphaTarget::Line, unit, role, identity, alpha, key)
    }

    pub(crate) fn fill(
        &mut self,
        role: AlphaGlyphRole,
        unit: AlphaUnitKind,
        identity: AlphaUnit,
        alpha: Option<ResolvedAlpha>,
        mut style: FillStyle,
        mapped_outline: bool,
    ) -> Result<()> {
        if !self.enabled(AlphaTarget::Fill) {
            return Ok(());
        }
        style.color = Color::from(self.neutral);
        if mapped_outline {
            style.stroke = Color::from(self.neutral).with_alpha(style.stroke.get_alpha());
        }
        let outline = style.stroke_width > 0.0;
        let key = ResolvedGuideKey {
            explanation: GuideExplanation::Projected(GuideExplanationMask {
                alpha: AlphaExplanationMask {
                    fill_paint: Some(AlphaExplanation::Explained),
                    fill_outline: outline.then_some(AlphaExplanation::Constant),
                    ..AlphaExplanationMask::default()
                },
                fill_paint: Some(RgbExplanation::NeutralizedColor),
                fill_outline: outline.then_some(if mapped_outline {
                    RgbExplanation::NeutralizedColor
                } else {
                    RgbExplanation::Constant
                }),
                point_fill: None,
                point_outline: None,
                line_stroke: None,
                point_shape: None,
                line_pattern: None,
            }),
            fill: Some(style),
            ..ResolvedGuideKey::default()
        };
        self.push(AlphaTarget::Fill, unit, role, identity, alpha, key)
    }

    fn push(
        &mut self,
        target: AlphaTarget,
        unit: AlphaUnitKind,
        role: AlphaGlyphRole,
        identity: AlphaUnit,
        alpha: Option<ResolvedAlpha>,
        key: ResolvedGuideKey,
    ) -> Result<()> {
        let value = alpha.ok_or_else(|| {
            Error::Render("actual alpha guide component has no retained member".into())
        })?;
        let pending = self.targets[target.index()].get_or_insert_with(|| PendingTarget {
            unit,
            glyphs: Vec::new(),
        });
        if pending.unit != unit {
            return Err(Error::Render(
                "one alpha target has conflicting scientific units".into(),
            ));
        }
        let index = if let Some(index) = pending
            .glyphs
            .iter()
            .position(|glyph| glyph.role == role && glyph.key == key)
        {
            index
        } else {
            reserve_source(&mut pending.glyphs, 1)?;
            pending.glyphs.push(PendingGlyph {
                role,
                key,
                members: Vec::new(),
            });
            pending.glyphs.len() - 1
        };
        let members = &mut pending.glyphs[index].members;
        if members.len() == members.capacity() {
            let additional = members.capacity().max(1);
            reserve_source(members, additional)?;
        }
        members.push(AlphaActualMember {
            unit: identity,
            value,
        });
        Ok(())
    }

    pub(crate) fn finish(self) -> Result<Arc<PreparedAlphaInputs>> {
        let mut sources = Vec::new();
        reserve_source(&mut sources, self.targets.iter().flatten().count())?;
        for (target, pending) in [AlphaTarget::Point, AlphaTarget::Line, AlphaTarget::Fill]
            .into_iter()
            .zip(self.targets)
        {
            let Some(mut pending) = pending else { continue };
            // Preserve first actual component order between distinct keys of
            // one role; an unstable sort could change the selected geometry.
            for index in 1..pending.glyphs.len() {
                let mut current = index;
                while current > 0 && pending.glyphs[current - 1].role > pending.glyphs[current].role
                {
                    pending.glyphs.swap(current - 1, current);
                    current -= 1;
                }
            }
            let input = self.plot.alpha_inputs().get(target);
            let glyphs = collect_source(pending.glyphs.into_iter().map(|glyph| {
                Ok(AlphaGlyphSource {
                    role: glyph.role,
                    key: glyph.key,
                    members: shared_slice(glyph.members)?,
                })
            }))?;
            sources.push(AlphaGuideSource {
                target,
                unit: pending.unit,
                producer: self.plot.kind(),
                owner: self.owner.clone(),
                scope: self.scope.map(shared_text).transpose()?,
                input: input.clone(),
                neutral: self.neutral,
                glyphs: shared_slice(glyphs)?,
            });
        }
        source_arc(PreparedAlphaInputs {
            inputs: self.plot.alpha_inputs().clone(),
            sources: shared_slice(sources)?,
        })
    }
}

fn alpha_section(
    labels: &crate::formatting::Labels,
    source: &AlphaGuideSource,
    values: &AlphaValues,
) -> Result<PreparedGuideSection> {
    let examples = values.guide_examples(
        source
            .glyphs
            .iter()
            .flat_map(|glyph| glyph.members.iter().map(|member| member.value)),
    )?;
    let prototype = &source
        .glyphs
        .first()
        .ok_or_else(|| Error::Render("alpha section has no actual component glyph".into()))?
        .key;
    let entries = collect_source(examples.into_iter().map(|example| {
        let label = if values.semantics() == AlphaSemantics::Categorical {
            labels.resolve(example.label)?
        } else {
            copy_source_string(example.label)?
        };
        Ok(PreparedGuideEntry {
            identity: GuideEntryIdentity::AlphaMember(AlphaGuideMember {
                key: example.key,
                ordinal: u32::try_from(example.ordinal)
                    .map_err(|_| Error::Render("alpha guide ordinal overflow".into()))?,
            }),
            display_label: source_arc(crate::Text::from(label))?,
            key: sample_key(prototype, source.target, example.alpha),
            sources: shared_slice(Vec::new())?,
        })
    }))?;
    let identity = AlphaSectionIdentity {
        field: values.guide_field()?,
        semantics: values.semantics(),
        target: source.target,
        unit: source.unit,
    };
    let title = title(labels, values.raw_name(), source.target, source.unit)?;
    Ok(PreparedGuideSection {
        identity: GuideSectionIdentity::Alpha(identity),
        display_title: crate::data::source::source_arc(crate::Text::from(title))?,
        body: GuideSectionBody::Alpha(source_arc(PreparedAlphaSection {
            declaration: values.clone(),
            entries: shared_slice(entries)?,
            sources: shared_slice(collect_source(std::iter::once(Ok(source.clone())))?)?,
        })?),
    })
}

fn sample_key(prototype: &ResolvedGuideKey, target: AlphaTarget, alpha: f64) -> ResolvedGuideKey {
    let mut key = prototype.clone();
    match target {
        AlphaTarget::Point => {
            let point = key
                .point
                .as_mut()
                .expect("point alpha has its actual glyph");
            point.color = point.color.with_alpha(alpha);
        }
        AlphaTarget::Line => {
            let line = key.line.as_mut().expect("line alpha has its actual glyph");
            line.color = line.color.with_alpha(alpha);
        }
        AlphaTarget::Fill => {
            let fill = key.fill.as_mut().expect("fill alpha has its actual glyph");
            fill.color = fill.color.with_alpha(alpha);
        }
    }
    key
}

fn title(
    labels: &crate::formatting::Labels,
    source: &str,
    target: AlphaTarget,
    unit: AlphaUnitKind,
) -> Result<String> {
    let target = match target {
        AlphaTarget::Point => "point",
        AlphaTarget::Line => "line",
        AlphaTarget::Fill => "fill",
    };
    let unit = match unit {
        AlphaUnitKind::Observation => "observation",
        AlphaUnitKind::Series => "series",
        AlphaUnitKind::Aggregate => "aggregate",
        AlphaUnitKind::Bin => "bin",
        AlphaUnitKind::Single => "single",
    };
    let mut title = labels.resolve(source)?;
    let extra = unit
        .len()
        .checked_add(target.len())
        .and_then(|count| count.checked_add(" (  alpha)".len()))
        .ok_or_else(|| Error::Render("alpha guide title length overflow".into()))?;
    reserve_source_string(&mut title, extra)?;
    title.push_str(" (");
    title.push_str(unit);
    title.push(' ');
    title.push_str(target);
    title.push_str(" alpha)");
    Ok(title)
}