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

use std::sync::Arc;

use super::{collect_input, numeric_key, validated_name, AlphaValues};
use crate::data::source::{collect_source, copy_source_string, sort_source_by, source_arc};
use crate::{Bounds, 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::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::{AlphaEncoding, AlphaValues, CategoryValues};
/// let strokes = AlphaEncoding::keyed(
///     [CategoryValues::new("series", ["control", "treated"])?],
///     AlphaValues::new("reliability", [128, 230])?,
/// )?;
/// assert!(!strokes.is_theme());
/// assert_eq!(strokes.values().unwrap().get(1), Some(230));
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// ```compile_fail
/// use lichtung_plot::AlphaEncoding;
/// fn private(value: AlphaEncoding) { let _ = value.binding; }
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AlphaEncoding {
    binding: Binding,
}

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

#[derive(Debug, PartialEq, Eq)]
struct SelectorTable {
    fields: Vec<String>,
    rows: Vec<Vec<String>>,
    order: Vec<usize>,
}

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

/// 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 independently of its possibly zero byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ResolvedAlpha {
    pub(crate) index: usize,
    pub(crate) alpha: u8,
}

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,
        }
    }

    /// Bind bytes 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 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(),
            ));
        }
        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.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "the public constructor consumes exact bounds while retaining normalized interval keys"
    )]
    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 bounds = collect_source((0..values.len()).map(|index| {
            let low = bounds.lower().get(index).flatten();
            let high = 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"
                ))),
            }
        }))?;
        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(),
            ));
        }
        Ok(Self {
            binding: Binding::Bins(
                source_arc(BinTable {
                    facets,
                    bounds,
                    order,
                })?,
                values,
            ),
        })
    }

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

    /// 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: &[&str],
        facet_fields: &[&str],
    ) -> Result<PreparedAlpha> {
        match &self.binding {
            Binding::Theme | Binding::Single(_) => {}
            Binding::Observations(values) if unit == AlphaUnitKind::Observation => {
                if values.len() != original_len {
                    return Err(Error::Data(format!(
                        "observation alpha {:?} has length {}, expected all {original_len} original input slots",
                        values.name(), values.len(),
                    )));
                }
            }
            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"
                )))
            }
        }
        Ok(PreparedAlpha {
            encoding: self.clone(),
            unit,
            original_len,
        })
    }
}

impl SelectorTable {
    fn new(keys: impl IntoIterator<Item = CategoryValues>, len: usize) -> Result<Self> {
        let mut keys = collect_input(keys)?;
        sort_source_by(&mut keys, |a, b| a.name().cmp(b.name()));
        let fields = collect_source(keys.iter().map(|column| {
            if column.len() != len {
                return Err(Error::Data(format!(
                    "alpha selector {:?} has length {}, expected {len}",
                    column.name(),
                    column.len()
                )));
            }
            validated_name(copy_source_string(column.name())?)
        }))?;
        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.get(index).flatten().ok_or_else(|| {
                    Error::Data(format!(
                        "alpha selector {:?} is missing at index {index}",
                        column.name()
                    ))
                })?;
                copy_source_string(raw)
            }))
        }))?;
        let mut order = collect_source((0..len).map(Ok))?;
        sort_source_by(&mut order, |a, b| rows[*a].cmp(&rows[*b]));
        Ok(Self {
            fields,
            rows,
            order,
        })
    }

    fn validate_schema(&self, required: &[&str], facets: &[&str]) -> Result<()> {
        for field in &self.fields {
            if !required.contains(&field.as_str()) && !facets.contains(&field.as_str()) {
                return Err(Error::Data(format!(
                    "alpha selector {field:?} is not an actual unit or owning facet field"
                )));
            }
        }
        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:?}"
                )));
            }
        }
        Ok(())
    }

    fn tuple<'a>(&self, keys: &[(&str, &'a str)]) -> Result<Vec<&'a str>> {
        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:?}"
                )));
            }
        }
        collect_source(self.fields.iter().map(|field| {
            keys.iter()
                .find(|(name, _)| *name == field)
                .map(|(_, raw)| *raw)
                .ok_or_else(|| {
                    Error::Data(format!(
                        "actual alpha unit has no value for selector field {field:?}"
                    ))
                })
        }))
    }

    fn compare_row(&self, index: usize, tuple: &[&str]) -> std::cmp::Ordering {
        self.rows[index]
            .iter()
            .map(String::as_str)
            .cmp(tuple.iter().copied())
    }
}

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

    fn resolved(&self, index: usize) -> Result<Option<ResolvedAlpha>> {
        self.encoding
            .values()
            .map(|values| {
                values
                    .get(index)
                    .map(|alpha| ResolvedAlpha { index, alpha })
                    .ok_or_else(|| {
                        Error::Data(format!(
                            "alpha source {:?} has no original slot {index}",
                            values.name()
                        ))
                    })
            })
            .transpose()
    }

    fn constant(&self) -> Option<Result<Option<ResolvedAlpha>>> {
        match &self.encoding.binding {
            Binding::Theme => Some(Ok(None)),
            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,
            )));
        }
        self.constant()
            .unwrap_or_else(|| self.resolved(index))
            .map_err(|error| Error::Data(format!("{error} at diagnostic source row {source_row}")))
    }

    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: &[(&str, &str)]) -> 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:?}"
                ))
            })?;
        self.resolved(table.order[position])
    }

    pub(crate) fn bin(
        &self,
        bounds: (f64, f64),
        facets: &[(&str, &str)],
    ) -> 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:?}"
                ))
            })?;
        self.resolved(table.order[position])
    }
}

#[cfg(test)]
mod tests;