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
//! Complete raw keys and ordered key columns, independent of display aliases.

use std::{
    hash::{Hash, Hasher},
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
};

use super::{
    binding::VectorSource, DataSourceInfo, Date, Duration, ExactInteger, LocalTimestamp, Timestamp,
};
mod encoding;
use crate::{
    errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
    CategoryValues, Error, Result,
};
pub(crate) use encoding::key_bytes;

/// The original identity of a bound external or native key.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum RawKey {
    /// A complete string, without display normalization.
    String(String),
    /// An exact integer of arbitrary magnitude.
    Integer(ExactInteger),
    /// A Boolean, independent of integer positions.
    Boolean(bool),
    /// An original floating-point key with exact binary64 bits.
    Float(f64),
    /// A complete, possibly nested tuple key.
    Tuple(Vec<RawKey>),
    /// A calendar day.
    Date(Date),
    /// An exact instant.
    Instant(Timestamp),
    /// An elapsed duration.
    Duration(Duration),
    /// A local timestamp with no timezone interpretation.
    LocalTimestamp(LocalTimestamp),
    /// A complete interval key.
    Interval(IntervalKey),
    /// A captured identity whose external key cannot be transferred exactly.
    Unavailable(UnavailableKey),
}

impl From<String> for RawKey {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}
impl From<&str> for RawKey {
    fn from(value: &str) -> Self {
        Self::String(value.to_owned())
    }
}

impl From<&String> for RawKey {
    fn from(value: &String) -> Self {
        Self::String(value.clone())
    }
}

impl From<ExactInteger> for RawKey {
    fn from(value: ExactInteger) -> Self {
        Self::Integer(value)
    }
}
macro_rules! integer_keys {
    ($($type:ty),+) => {$(
        impl From<$type> for RawKey {
            fn from(value:$type)->Self {Self::Integer(value.into())}
        }
    )+};
}
integer_keys!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
impl From<bool> for RawKey {
    fn from(value: bool) -> Self {
        Self::Boolean(value)
    }
}
impl From<f64> for RawKey {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}
impl<A: Into<RawKey>, B: Into<RawKey>> From<(A, B)> for RawKey {
    fn from((first, second): (A, B)) -> Self {
        Self::Tuple(vec![first.into(), second.into()])
    }
}

impl PartialEq for RawKey {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::String(a), Self::String(b)) => a == b,
            (Self::Integer(a), Self::Integer(b)) => a == b,
            (Self::Boolean(a), Self::Boolean(b)) => a == b,
            (Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(),
            (Self::Tuple(a), Self::Tuple(b)) => a == b,
            (Self::Date(a), Self::Date(b)) => a == b,
            (Self::Instant(a), Self::Instant(b)) => a == b,
            (Self::Duration(a), Self::Duration(b)) => a == b,
            (Self::LocalTimestamp(a), Self::LocalTimestamp(b)) => a == b,
            (Self::Interval(a), Self::Interval(b)) => a == b,
            (Self::Unavailable(a), Self::Unavailable(b)) => a == b,
            _ => false,
        }
    }
}

impl Eq for RawKey {}

impl Hash for RawKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        match self {
            Self::String(value) => value.hash(state),
            Self::Integer(value) => value.hash(state),
            Self::Boolean(value) => value.hash(state),
            Self::Float(value) => value.to_bits().hash(state),
            Self::Tuple(value) => value.hash(state),
            Self::Date(value) => value.hash(state),
            Self::Instant(value) => value.hash(state),
            Self::Duration(value) => value.hash(state),
            Self::LocalTimestamp(value) => value.hash(state),
            Self::Interval(value) => value.hash(state),
            Self::Unavailable(value) => value.hash(state),
        }
    }
}

/// Which endpoints of an interval key are included.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntervalClosed {
    /// Left endpoint only.
    Left,
    /// Right endpoint only.
    Right,
    /// Both endpoints.
    Both,
    /// Neither endpoint.
    Neither,
}

/// A complete interval identity with exact endpoints and closure.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IntervalKey {
    left: Box<RawKey>,
    right: Box<RawKey>,
    closed: IntervalClosed,
}

impl IntervalKey {
    /// Capture the endpoints of a validated external interval.
    pub fn new(left: RawKey, right: RawKey, closed: IntervalClosed) -> Result<Self> {
        let ordered = match (&left, &right) {
            (RawKey::Integer(a), RawKey::Integer(b)) => a <= b,
            (RawKey::Float(a), RawKey::Float(b)) => a <= b,
            (RawKey::Date(a), RawKey::Date(b)) => a <= b,
            (RawKey::Duration(a), RawKey::Duration(b)) => a <= b,
            (RawKey::LocalTimestamp(a), RawKey::LocalTimestamp(b)) => a <= b,
            (RawKey::Instant(a), RawKey::Instant(b)) => a.unix_ns() <= b.unix_ns(),
            _ => false,
        };
        if !ordered {
            return Err(Error::Data(
                "interval key requires compatible ordered endpoints".into(),
            ));
        }
        Ok(Self {
            left: Box::new(left),
            right: Box::new(right),
            closed,
        })
    }
    /// Original left endpoint.
    pub fn left(&self) -> &RawKey {
        &self.left
    }
    /// Original right endpoint.
    pub fn right(&self) -> &RawKey {
        &self.right
    }
    /// Original endpoint closure.
    pub const fn closed(&self) -> IntervalClosed {
        self.closed
    }
}

static NEXT_UNAVAILABLE_KEY: AtomicU64 = AtomicU64::new(0);

/// An immutable identity for an actually bound, non-transferable key.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UnavailableKey {
    identity: u64,
    reason: Arc<str>,
}

impl UnavailableKey {
    /// Capture one unavailable key's identity at the actual binding boundary.
    #[doc(hidden)]
    pub fn new(reason: impl Into<String>) -> Result<Self> {
        let identity = NEXT_UNAVAILABLE_KEY
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
                value.checked_add(1)
            })
            .map_err(|_| Error::Data("raw key identity space exhausted".into()))?;
        Ok(Self {
            identity,
            reason: Arc::from(reason.into()),
        })
    }
    pub(crate) fn identity(&self) -> u64 {
        self.identity
    }

    /// Why this actual key cannot be transferred.
    pub fn reason(&self) -> &str {
        &self.reason
    }
}

/// A nullable, owned vector of complete raw keys.
#[derive(Debug, Clone)]
pub struct RawKeyValues {
    name: Arc<str>,
    codes: Arc<[Option<u32>]>,
    levels: Arc<[RawKey]>,
    source: VectorSource,
}

impl RawKeyValues {
    /// Capture complete keys in original slot order.
    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = RawKey>) -> Result<Self> {
        Self::nullable(name, values.into_iter().map(Some))
    }

    /// Capture nullable keys in original slot order.
    pub fn nullable(
        name: impl Into<String>,
        values: impl IntoIterator<Item = Option<RawKey>>,
    ) -> Result<Self> {
        let name = name.into();
        let mut levels = Vec::new();
        let mut indices = std::collections::HashMap::new();
        let codes = super::source::collect_source(values.into_iter().map(|value| {
            let Some(value) = value else { return Ok(None) };
            if let Some(&index) = indices.get(&value) {
                return Ok(Some(index));
            }
            let index = u32::try_from(levels.len()).map_err(|_| {
                Error::Data(
                    format!("raw key column {name:?} exceeds the distinct-key limit").into(),
                )
            })?;
            super::source::reserve_source(&mut levels, 1)?;
            crate::operation::check()?;
            indices.try_reserve(1).map_err(|error| {
                Error::Data(format!("raw key dictionary storage: {error}").into())
            })?;
            indices.insert(value.clone(), index);
            levels.push(value);
            Ok(Some(index))
        }))?;
        crate::operation::check()?;
        Ok(Self {
            name: Arc::from(name),
            source: VectorSource::direct_nullable(codes.len(), codes.iter().any(Option::is_none)),
            codes: codes.into(),
            levels: levels.into(),
        })
    }
    /// Semantic column name.
    pub fn name(&self) -> &str {
        &self.name
    }
    pub(crate) fn with_name(mut self, name: &str) -> Self {
        self.name = Arc::from(name);
        self
    }
    /// Number of original slots.
    pub fn len(&self) -> usize {
        self.codes.len()
    }
    /// Whether no slots were supplied.
    pub fn is_empty(&self) -> bool {
        self.codes.is_empty()
    }
    /// Read a slot without conflating missing and out of bounds.
    pub fn get(&self, index: usize) -> Option<Option<&RawKey>> {
        self.codes
            .get(index)
            .map(|code| code.and_then(|code| self.levels.get(code as usize)))
    }
    /// Iterate the actual original keys and missing slots.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&RawKey>> + '_ {
        (0..self.len()).map(|index| self.get(index).expect("in-bounds raw key slot"))
    }
    /// Original validity.
    pub fn is_valid(&self, index: usize) -> Option<bool> {
        self.codes.get(index).map(Option::is_some)
    }
    /// Retain the actual original selected source of this key variable.
    #[doc(hidden)]
    pub fn with_source(mut self, source: DataSourceInfo) -> Result<Self> {
        self.source = VectorSource::repeated(source, 1, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.codes[slot].is_some(),
        )?;
        Ok(self)
    }

    pub(crate) fn with_vector_source(mut self, source: VectorSource) -> Self {
        self.source = source;
        self
    }

    /// Original captured source.
    #[doc(hidden)]
    pub fn get_source(&self) -> &DataSourceInfo {
        self.source.info()
    }

    pub(crate) fn vector_source(&self) -> &VectorSource {
        &self.source
    }

    pub(crate) fn has_nulls(&self) -> bool {
        self.codes.iter().any(Option::is_none)
    }

    /// Original source member corresponding to a logical slot.
    #[doc(hidden)]
    pub fn source_slot(&self, index: usize) -> Option<usize> {
        (index < self.len()).then(|| self.source.slot(index))
    }

    pub(crate) fn select(&self, indices: &[usize]) -> Result<Self> {
        let mut selected = Self::nullable(
            self.name(),
            indices.iter().map(|&index| {
                self.get(index)
                    .expect("validated raw key selection")
                    .cloned()
            }),
        )?;
        selected.source = self.source.select(indices)?;
        Ok(selected)
    }

    /// Distinct keys in first-observed order.
    pub fn levels(&self) -> &[RawKey] {
        &self.levels
    }
}

impl PartialEq for RawKeyValues {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.codes == other.codes && self.levels == other.levels
    }
}
impl Eq for RawKeyValues {}

/// An actual string or raw-key column.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyValues {
    /// An actual string category column.
    Strings(CategoryValues),
    /// A column of complete raw keys.
    Raw(RawKeyValues),
}
impl KeyValues {
    pub(crate) fn key_at(&self, slot: usize) -> Option<RawKey> {
        match self {
            Self::Strings(values) => values.get(slot).flatten().map(RawKey::from),
            Self::Raw(values) => values.get(slot).flatten().cloned(),
        }
    }

    pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
        Ok(match self {
            Self::Strings(values) => Self::Strings(values.select(indices)?),
            Self::Raw(values) => Self::Raw(values.select(indices)?),
        })
    }

    /// Construct the true logical column of generated identities, preserving
    /// string categories when every supplied identity is a string.
    #[doc(hidden)]
    pub fn repeated_keys(name: &str, keys: &[RawKey], rows: usize) -> Result<Self> {
        if keys.iter().all(|key| matches!(key, RawKey::String(_))) {
            Ok(Self::Strings(CategoryValues::new(
                name,
                (0..rows).flat_map(|_| {
                    keys.iter().map(|key| match key {
                        RawKey::String(value) => value.as_str(),
                        _ => unreachable!("all keys are strings"),
                    })
                }),
            )?))
        } else {
            Ok(Self::Raw(RawKeyValues::new(
                name,
                (0..rows).flat_map(|_| keys.iter().cloned()),
            )?))
        }
    }

    /// Read an actual string category column.
    pub const fn get_strings(&self) -> Option<&CategoryValues> {
        if let Self::Strings(values) = self {
            Some(values)
        } else {
            None
        }
    }
    /// Read an actual raw-key column.
    pub const fn get_raw(&self) -> Option<&RawKeyValues> {
        if let Self::Raw(values) = self {
            Some(values)
        } else {
            None
        }
    }
    /// Number of original slots.
    pub fn len(&self) -> usize {
        match self {
            Self::Strings(values) => values.len(),
            Self::Raw(values) => values.len(),
        }
    }
    /// Whether no original slots were supplied.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Actual slot validity, independent of key type.
    pub fn is_valid(&self, index: usize) -> Option<bool> {
        match self {
            Self::Strings(values) => values.is_valid(index),
            Self::Raw(values) => values.is_valid(index),
        }
    }
}

/// One named key column; the complete field key is independent of its values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedKeyValues {
    /// The actual field identity.
    pub key: RawKey,
    /// The actual original column.
    pub values: KeyValues,
}

/// An ordered collection of aligned key columns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyColumns(Arc<[NamedKeyValues]>);

impl KeyColumns {
    /// Capture aligned columns, preserving the supplied field order.
    pub fn new(columns: Vec<NamedKeyValues>) -> Result<Self> {
        let length = columns.first().map_or(0, |column| column.values.len());
        let mut fields = std::collections::HashSet::new();
        for column in &columns {
            if column.values.len() != length {
                return Err(Error::Data(
                    Diagnostic::new(
                        DiagnosticKind::ShapeMismatch {
                            expected: vec![length],
                            actual: vec![column.values.len()],
                        },
                        "key columns must have the same length",
                    )
                    .with_context(
                        ErrorContext::new()
                            .with_operation(OperationPhase::Bind)
                            .with_binding(column.key.clone()),
                    ),
                ));
            }
            if !fields.insert(&column.key) {
                return Err(Error::Data("duplicate key column identity".into()));
            }
        }
        Ok(Self(columns.into()))
    }
    /// The actual ordered fields and values.
    pub fn columns(&self) -> &[NamedKeyValues] {
        &self.0
    }
    /// Number of key columns.
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether no key columns were supplied.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    pub(crate) fn row_keys(&self, index: usize) -> Option<Vec<RawKey>> {
        self.0
            .iter()
            .map(|column| match &column.values {
                KeyValues::Strings(values) => values.get(index)?.map(RawKey::from),
                KeyValues::Raw(values) => values.get(index)?.cloned(),
            })
            .collect()
    }

    /// Find a column by its complete field key.
    pub fn get(&self, key: &RawKey) -> Result<&KeyValues> {
        self.0
            .iter()
            .find(|column| &column.key == key)
            .map(|column| &column.values)
            .ok_or_else(|| {
                Error::Data(
                    Diagnostic::new(
                        DiagnosticKind::UnknownKey {
                            key: Some(key.clone()),
                        },
                        format!("no key column {key:?}"),
                    )
                    .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
                )
            })
    }
}