lichtung-plot 0.2.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
//! Explicit source units, exact selectors and immutable prepared lookup.

use std::sync::Arc;

use super::{collect_input, numeric_key, validated_alpha, AlphaValues};
use crate::data::source::{collect_source, sort_source_by, source_arc};
use crate::{
    data::{Bounds, KeyColumns, KeyValues, NamedKeyValues, RawKey, RawKeyValues},
    CategoryValues, Error, Result,
};

/// One complete explicit alpha-unit binding for a Plot paint target.
///
/// Default is [`Self::theme`]. Observation values align with all original input
/// slots, independently of diagnostic [`crate::data::SourceRows`] IDs. Series/aggregate
/// values are explicitly keyed; they are never reduced from observation alpha.
/// Each actual unit must resolve before fonts, even when its alpha is zero.
///
/// ```
/// use lichtung_plot::{CategoryValues, scales::{AlphaEncoding, AlphaValues}};
/// let strokes = AlphaEncoding::keyed(
///     [CategoryValues::new("series", ["control", "treated"])?],
///     AlphaValues::new("reliability", [0.5, 0.9])?,
/// )?;
/// assert!(!strokes.is_theme());
/// assert_eq!(strokes.values().unwrap().get(1), Some(0.9));
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// ```compile_fail
/// use lichtung_plot::scales::AlphaEncoding;
/// fn private(value: AlphaEncoding) { let _ = value.binding; }
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AlphaEncoding {
    binding: Binding,
}

#[derive(Debug, Clone, Default, PartialEq)]
enum Binding {
    #[default]
    Theme,
    Fixed(f64),
    Observations(AlphaValues),
    Single(AlphaValues),
    Keyed(Arc<SelectorTable>, AlphaValues),
    Bins(Arc<BinTable>, AlphaValues),
}

impl Eq for Binding {}

#[derive(Debug)]
struct SelectorTable {
    columns: KeyColumns,
    member_keys: Option<RawKeyValues>,
    fields: Vec<RawKey>,
    rows: Vec<Vec<Vec<u8>>>,
    order: Vec<usize>,
}

#[derive(Debug, PartialEq, Eq)]
struct BinTable {
    facets: SelectorTable,
    original_bounds: Bounds,
    member_keys: RawKeyValues,
    bounds: Vec<[u64; 2]>,
    order: Vec<usize>,
}

impl PartialEq for SelectorTable {
    fn eq(&self, other: &Self) -> bool {
        self.fields == other.fields
            && self.rows == other.rows
            && self.order == other.order
            && self.columns.len() == other.columns.len()
            && self.columns.columns().iter().all(|column| {
                other
                    .columns
                    .get(&column.key)
                    .is_ok_and(|values| *values == column.values)
            })
    }
}

impl Eq for SelectorTable {}

/// The actual producer supplies its semantic class and complete required schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AlphaUnitKind {
    Observation,
    Series,
    Aggregate,
    Bin,
    Single,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedAlpha {
    encoding: AlphaEncoding,
    unit: AlphaUnitKind,
    original_len: usize,
}

/// Retain the selected declaration member, if any, independently of its coefficient.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ResolvedAlpha {
    pub(crate) index: Option<usize>,
    pub(crate) alpha: f64,
}

impl Eq for ResolvedAlpha {}

impl TryFrom<f64> for AlphaEncoding {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::fixed(value)
    }
}

impl AlphaEncoding {
    /// Reset a target to its independently owned normal role/exact paint alpha.
    #[must_use]
    pub const fn theme() -> Self {
        Self {
            binding: Binding::Theme,
        }
    }

    /// Replace the target's opacity with one fixed, validated coefficient.
    pub fn fixed(alpha: f64) -> Result<Self> {
        Ok(Self {
            binding: Binding::Fixed(validated_alpha(alpha)?),
        })
    }

    /// Inspect a fixed coefficient, independently of any bound data.
    #[must_use]
    pub const fn get_fixed(&self) -> Option<f64> {
        match self.binding {
            Binding::Fixed(alpha) => Some(alpha),
            _ => None,
        }
    }

    /// Bind coefficients to every original observation/record slot, including filtered rows.
    #[must_use]
    pub fn observations(values: AlphaValues) -> Self {
        Self {
            binding: Binding::Observations(values),
        }
    }

    /// Explicitly broadcast exactly one value to every actual target unit.
    pub fn single(values: AlphaValues) -> Result<Self> {
        if values.len() != 1 {
            return Err(Error::Data(
                "single alpha requires exactly one value".into(),
            ));
        }
        Ok(Self {
            binding: Binding::Single(values),
        })
    }

    /// Bind explicit actual series/aggregate tuples to aligned values.
    ///
    /// Require at least one unique named, nonnull selector column and unique
    /// complete tuples. Column order is canonicalized by raw field name. During
    /// attachment, fields must include all actual unit keys and may additionally
    /// select owning facets. Lookup is exact, without partial-key fallback; unused
    /// pooled tuples create no marks, guide text or font requirements.
    pub fn keyed(
        keys: impl IntoIterator<Item = CategoryValues>,
        values: AlphaValues,
    ) -> Result<Self> {
        let mut table = SelectorTable::new(keys, values.len())?;
        if table.fields.is_empty() {
            return Err(Error::Data(
                "keyed alpha requires at least one selector field".into(),
            ));
        }
        if table
            .order
            .windows(2)
            .any(|pair| table.rows[pair[0]] == table.rows[pair[1]])
        {
            return Err(Error::Data(
                "keyed alpha contains duplicate selector tuples".into(),
            ));
        }
        table.member_keys = Some(RawKeyValues::new(
            "alpha keys",
            (0..values.len()).map(|slot| {
                let keys = table
                    .columns
                    .row_keys(slot)
                    .expect("validated actual selector row");
                if let [key] = keys.as_slice() {
                    key.clone()
                } else {
                    RawKey::Tuple(keys)
                }
            }),
        )?);
        Ok(Self {
            binding: Binding::Keyed(source_arc(table)?, values),
        })
    }

    /// Bind exact Histogram intervals and optional owning facet keys to values.
    ///
    /// Each pair must be finite lower < upper; bounds, facets and alpha lengths
    /// must agree. Complete interval/facet keys must be unique. Signed zero has one
    /// identity. Actual prepared edges must match exactly; no sample reduction,
    /// edge adjustment or approximate lookup is performed.
    pub fn bins(
        bounds: Bounds,
        facets: impl IntoIterator<Item = CategoryValues>,
        values: AlphaValues,
    ) -> Result<Self> {
        if bounds.lower().len() != values.len() || bounds.upper().len() != values.len() {
            return Err(Error::Data(
                "alpha bin bounds must align with the alpha values".into(),
            ));
        }
        let facets = SelectorTable::new(facets, values.len())?;
        let original_bounds = bounds;
        let bounds = collect_source((0..values.len()).map(|index| {
            let low = original_bounds.lower().get(index).flatten();
            let high = original_bounds.upper().get(index).flatten();
            match (low, high) {
                (Some(low), Some(high)) if low.is_finite() && high.is_finite() && low < high => {
                    Ok([numeric_key(low), numeric_key(high)])
                }
                _ => Err(Error::Data(
                    format!(
                    "alpha bin at index {index} requires finite nonmissing lower < upper bounds"
                )
                    .into(),
                )),
            }
        }))?;
        let mut order = collect_source((0..values.len()).map(Ok))?;
        sort_source_by(&mut order, |a, b| {
            facets.rows[*a]
                .cmp(&facets.rows[*b])
                .then(bounds[*a].cmp(&bounds[*b]))
        })?;
        if order.windows(2).any(|pair| {
            facets.rows[pair[0]] == facets.rows[pair[1]] && bounds[pair[0]] == bounds[pair[1]]
        }) {
            return Err(Error::Data(
                "alpha bins contain duplicate exact interval/facet keys".into(),
            ));
        }
        let member_keys = RawKeyValues::new(
            "alpha bins",
            (0..values.len()).map(|slot| {
                let mut key = vec![
                    RawKey::Float(
                        original_bounds
                            .lower()
                            .get(slot)
                            .flatten()
                            .expect("validated lower bound"),
                    ),
                    RawKey::Float(
                        original_bounds
                            .upper()
                            .get(slot)
                            .flatten()
                            .expect("validated upper bound"),
                    ),
                ];
                key.extend(
                    facets
                        .columns
                        .row_keys(slot)
                        .expect("validated actual selector row"),
                );
                RawKey::Tuple(key)
            }),
        )?;
        Ok(Self {
            binding: Binding::Bins(
                source_arc(BinTable {
                    facets,
                    original_bounds,
                    member_keys,
                    bounds,
                    order,
                })?,
                values,
            ),
        })
    }

    pub(crate) fn member_keys(&self) -> Option<&RawKeyValues> {
        match &self.binding {
            Binding::Keyed(table, _) => table.member_keys.as_ref(),
            Binding::Bins(table, _) => Some(&table.member_keys),
            _ => None,
        }
    }

    /// Whether this binding uses the normal role/exact alpha without mapped values.
    #[must_use]
    pub const fn is_theme(&self) -> bool {
        matches!(self.binding, Binding::Theme)
    }

    /// Complete owned values, or None for Theme or Fixed.
    #[must_use]
    pub const fn values(&self) -> Option<&AlphaValues> {
        match &self.binding {
            Binding::Theme | Binding::Fixed(_) => None,
            Binding::Observations(values)
            | Binding::Single(values)
            | Binding::Keyed(_, values)
            | Binding::Bins(_, values) => Some(values),
        }
    }

    /// Inspect an observation-aligned native binding.
    #[must_use]
    pub const fn get_observations(&self) -> Option<&AlphaValues> {
        match &self.binding {
            Binding::Observations(values) => Some(values),
            _ => None,
        }
    }

    /// Inspect the one actual value of an explicitly broadcast binding.
    #[must_use]
    pub const fn get_single(&self) -> Option<&AlphaValues> {
        match &self.binding {
            Binding::Single(values) => Some(values),
            _ => None,
        }
    }

    /// Read the complete supplied key columns in their original field and
    /// member order, along with their materialized coefficients.
    #[must_use]
    pub fn get_keyed(&self) -> Option<(&KeyColumns, &AlphaValues)> {
        match &self.binding {
            Binding::Keyed(table, values) => Some((&table.columns, values)),
            _ => None,
        }
    }

    /// Read the original supplied interval endpoints and facet keys.
    #[must_use]
    pub fn get_bins(&self) -> Option<(&Bounds, &KeyColumns, &AlphaValues)> {
        match &self.binding {
            Binding::Bins(table, values) => {
                Some((&table.original_bounds, &table.facets.columns, values))
            }
            _ => None,
        }
    }

    /// Validate even absent optional components' binding kind/schema before fonts.
    /// Actual producers resolve every consumed unit through the returned value.
    pub(crate) fn prepare(
        &self,
        unit: AlphaUnitKind,
        original_len: usize,
        required_fields: &[RawKey],
        facet_fields: &[RawKey],
    ) -> Result<PreparedAlpha> {
        match &self.binding {
            Binding::Theme | Binding::Fixed(_) | Binding::Single(_) => {}
            Binding::Observations(values) if unit == AlphaUnitKind::Observation => {
                if values.len() != original_len {
                    use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
                    return Err(Error::Data(Diagnostic::new(DiagnosticKind::ShapeMismatch {
                        expected: vec![original_len], actual: vec![values.len()],
                    }, format!("observation alpha {:?} has length {}, expected all {original_len} original input slots", values.name(), values.len()))
                        .with_context(ErrorContext::new().with_operation(OperationPhase::Prepare))));
                }
            }
            Binding::Keyed(table, _)
                if matches!(unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) =>
            {
                table.validate_schema(required_fields, facet_fields)?;
            }
            Binding::Bins(table, _) if unit == AlphaUnitKind::Bin => {
                table.facets.validate_schema(&[], facet_fields)?;
            }
            _ => {
                return Err(Error::Data(
                    format!("alpha binding does not support {unit:?} units").into(),
                ))
            }
        }
        Ok(PreparedAlpha {
            encoding: self.clone(),
            unit,
            original_len,
        })
    }
}

impl SelectorTable {
    fn new(keys: impl IntoIterator<Item = CategoryValues>, len: usize) -> Result<Self> {
        let keys = collect_input(keys)?;
        let columns = collect_source(keys.iter().map(|column| {
            let source = column.get_source();
            let source_field = source
                .selected_keys()
                .filter(|keys| keys.len() == 1 && source.generation().is_none())
                .and_then(|_| source.field(0));
            let values = match column.key_values() {
                KeyValues::Strings(values) => {
                    // The selector's target field is not its supplier's field.
                    // Keep the original supplying column on readback even when
                    // the target has a different name or complete raw identity.
                    KeyValues::Strings(if let Some((key, name)) = source_field {
                        values.with_field_name(&name).with_field_key(key, name)
                    } else {
                        values
                    })
                }
                KeyValues::Raw(values) => KeyValues::Raw(if let Some((_, name)) = source_field {
                    values.with_name(&name)
                } else {
                    values
                }),
            };
            Ok(NamedKeyValues {
                key: column.original_field(),
                values,
            })
        }))?;
        let mut keys = collect_source(keys.into_iter().map(|column| {
            let field = column.original_field();
            Ok((crate::data::key_bytes(&field)?, field, column))
        }))?;
        sort_source_by(&mut keys, |a, b| a.0.cmp(&b.0))?;
        let fields = collect_source(keys.iter().map(|(_, field, column)| {
            if column.len() != len {
                return Err(Error::Data(
                    format!(
                        "alpha selector {:?} has length {}, expected {len}",
                        column.name(),
                        column.len()
                    )
                    .into(),
                ));
            }
            Ok(field.clone())
        }))?;
        if fields.windows(2).any(|pair| pair[0] == pair[1]) {
            return Err(Error::Data(
                "alpha selector field names must be unique".into(),
            ));
        }
        let rows = collect_source((0..len).map(|index| {
            collect_source(keys.iter().map(|(_, _, column)| {
                let raw = column.key_at(index).ok_or_else(|| {
                    Error::Data(
                        format!(
                            "alpha selector {:?} is missing at index {index}",
                            column.name()
                        )
                        .into(),
                    )
                })?;
                crate::data::key_bytes(&raw)
            }))
        }))?;
        let mut order = collect_source((0..len).map(Ok))?;
        sort_source_by(&mut order, |a, b| rows[*a].cmp(&rows[*b]))?;
        Ok(Self {
            columns: KeyColumns::new(columns)?,
            member_keys: None,
            fields,
            rows,
            order,
        })
    }

    fn validate_schema(&self, required: &[RawKey], facets: &[RawKey]) -> Result<()> {
        for field in &self.fields {
            if !required.contains(field) && !facets.contains(field) {
                return Err(Error::Data(
                    format!("alpha selector {field:?} is not an actual unit or owning facet field")
                        .into(),
                ));
            }
        }
        for field in required {
            if !self.fields.iter().any(|name| name == field) {
                return Err(Error::Data(
                    format!("alpha binding is missing required unit field {field:?}").into(),
                ));
            }
        }
        Ok(())
    }

    fn tuple(&self, keys: &[(RawKey, RawKey)]) -> Result<Vec<Vec<u8>>> {
        for (index, (field, value)) in keys.iter().enumerate() {
            if keys[..index]
                .iter()
                .any(|(other, raw)| other == field && raw != value)
            {
                return Err(Error::Data(
                    format!("actual alpha unit has conflicting raw values for field {field:?}")
                        .into(),
                ));
            }
        }
        collect_source(self.fields.iter().map(|field| {
            keys.iter()
                .find(|(name, _)| name == field)
                .ok_or_else(|| {
                    Error::Data(
                        format!("actual alpha unit has no value for selector field {field:?}")
                            .into(),
                    )
                })
                .and_then(|(_, raw)| crate::data::key_bytes(raw))
        }))
    }

    fn compare_row(&self, index: usize, tuple: &[Vec<u8>]) -> std::cmp::Ordering {
        self.rows[index].as_slice().cmp(tuple)
    }
}

impl PreparedAlpha {
    pub(crate) fn selector_fields(&self) -> &[RawKey] {
        match &self.encoding.binding {
            Binding::Keyed(table, _) => &table.fields,
            Binding::Bins(table, _) => &table.facets.fields,
            Binding::Theme | Binding::Fixed(_) | Binding::Observations(_) | Binding::Single(_) => {
                &[]
            }
        }
    }

    fn resolved(&self, index: usize) -> Result<Option<ResolvedAlpha>> {
        if let Some(alpha) = self.encoding.get_fixed() {
            return Ok(Some(ResolvedAlpha { index: None, alpha }));
        }
        self.encoding
            .values()
            .map(|values| {
                values
                    .get(index)
                    .map(|alpha| ResolvedAlpha {
                        index: Some(index),
                        alpha,
                    })
                    .ok_or_else(|| {
                        Error::Data(
                            format!(
                                "alpha source {:?} has no original slot {index}",
                                values.name()
                            )
                            .into(),
                        )
                    })
            })
            .transpose()
    }

    fn constant(&self) -> Option<Result<Option<ResolvedAlpha>>> {
        match &self.encoding.binding {
            Binding::Theme => Some(Ok(None)),
            Binding::Fixed(_) | Binding::Single(_) => Some(self.resolved(0)),
            _ => None,
        }
    }

    pub(crate) fn observation(
        &self,
        index: usize,
        source_row: usize,
    ) -> Result<Option<ResolvedAlpha>> {
        if self.unit != AlphaUnitKind::Observation {
            return Err(Error::Data(
                "alpha source requires an observation unit".into(),
            ));
        }
        if index >= self.original_len {
            return Err(Error::Data(format!(
                "alpha original slot {index} is outside length {} at diagnostic source row {source_row}",
                self.original_len,
            ).into()));
        }
        self.constant()
            .unwrap_or_else(|| self.resolved(index))
            .map_err(|error| {
                Error::Data(format!("{error} at diagnostic source row {source_row}").into())
            })
    }

    pub(crate) fn single(&self) -> Result<Option<ResolvedAlpha>> {
        if self.unit != AlphaUnitKind::Single {
            return Err(Error::Data("alpha source requires a single unit".into()));
        }
        self.resolved(0)
    }

    pub(crate) fn keyed(&self, keys: &[(RawKey, RawKey)]) -> Result<Option<ResolvedAlpha>> {
        if !matches!(self.unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) {
            return Err(Error::Data(
                "alpha source requires a series or aggregate unit".into(),
            ));
        }
        if let Some(value) = self.constant() {
            return value;
        }
        let Binding::Keyed(table, _) = &self.encoding.binding else {
            unreachable!("prepared keyed binding")
        };
        let tuple = table.tuple(keys)?;
        let position = table
            .order
            .binary_search_by(|&index| table.compare_row(index, &tuple))
            .map_err(|_| {
                Error::Data(
                    format!("alpha binding has no value for actual raw unit {keys:?}").into(),
                )
            })?;
        self.resolved(table.order[position])
    }

    pub(crate) fn bin(
        &self,
        bounds: (f64, f64),
        facets: &[(RawKey, RawKey)],
    ) -> Result<Option<ResolvedAlpha>> {
        if self.unit != AlphaUnitKind::Bin {
            return Err(Error::Data("alpha source requires a bin unit".into()));
        }
        if !bounds.0.is_finite() || !bounds.1.is_finite() || bounds.0 >= bounds.1 {
            return Err(Error::Data(
                "actual alpha bin must have finite lower < upper bounds".into(),
            ));
        }
        if let Some(value) = self.constant() {
            return value;
        }
        let Binding::Bins(table, _) = &self.encoding.binding else {
            unreachable!("prepared bin binding")
        };
        let tuple = table.facets.tuple(facets)?;
        let key = [numeric_key(bounds.0), numeric_key(bounds.1)];
        let position = table
            .order
            .binary_search_by(|&index| {
                table
                    .facets
                    .compare_row(index, &tuple)
                    .then(table.bounds[index].cmp(&key))
            })
            .map_err(|_| {
                Error::Data(
                    format!(
                        "alpha binding has no value for exact actual bin {bounds:?} in {facets:?}"
                    )
                    .into(),
                )
            })?;
        self.resolved(table.order[position])
    }
}

#[cfg(test)]
mod tests;