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
//! Library-created borrowed numeric views; no geometry or mutable renderer escapes.

use super::format::NumericFormat;
use super::prefixes::selection::SelectedScale;
use super::set::FormattedSet;
use crate::{
    coordinates::{AxisRef, AxisScale},
    formatting::{NumericFactor, NumericLocale, NumericRate, NumericUnit},
    layout::FacetCell,
    plots::PlotKind,
    Result, Text,
};

/// Complete numeric consumer, independent of its selected typography.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NumericRole {
    /// Horizontal ticks.
    XAxis,
    /// Vertical ticks.
    YAxis,
    /// Continuous color guide.
    ContinuousColor,
    /// Active finite cell values.
    HeatmapValues,
    /// Available point-only estimates.
    CoefficientLabels,
    /// Eligible base/terminal totals.
    WaterfallTotals,
}
/// Whether a set is an intrinsic preference or a reached actual source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericPurpose {
    /// Low/mid/high preference, not a required unique source.
    IntrinsicProbe,
    /// Actual semantic occurrences.
    ActualSet,
}
/// Scientific domain provenance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericRangeOrigin {
    /// Locally automatic.
    Automatic,
    /// Caller-configured limits.
    Explicit,
    /// Parent-resolved scientific limits.
    ParentResolved,
}

/// Exact operand representation, retaining binary64 source bits and power exponents.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum NumericOperand<'a> {
    /// The represented finite ordinary operand.
    Binary64(f64),
    /// A mathematical power, not a rounded physical `powf` result.
    PowerOfTen {
        /// The exact represented exponent.
        exponent: f64,
    },
    /// Exact anchored geometric operand, retaining its original ratio direction.
    Multiplicative {
        /// Supplied positive binary64 anchor.
        anchor: f64,
        /// Supplied positive binary64 ratio, other than one.
        ratio: f64,
        /// Exact signed integral index in canonical ASCII decimal.
        index: &'a str,
    },
}

/// Raw semantic identity, before display aliases.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum NumericIdentity<'a> {
    /// A generated position in its original complete source order.
    Tick {
        /// Owning coordinate.
        axis: AxisRef,
        /// Original occurrence.
        source_index: usize,
    },
    /// A final-domain guide position.
    GuideTick {
        /// Original occurrence.
        source_index: usize,
    },
    /// Raw cell keys.
    HeatmapCell {
        /// Raw row level.
        row: &'a str,
        /// Raw column level.
        column: &'a str,
    },
    /// Raw available estimate category.
    EstimateRow {
        /// Raw category level.
        category: &'a str,
    },
    /// Base total.
    WaterfallBase,
    /// Terminal total.
    WaterfallTerminal,
    /// An intrinsic low/mid/high preference.
    Probe {
        /// Probe occurrence.
        index: usize,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct OwnerInfo {
    pub(crate) kind: Option<PlotKind>,
    pub(crate) canvas: Option<(usize, usize)>,
    // The selection program consumes renderer levels; public occurrence
    // identities and callbacks expose the actual bound keys.
    pub(crate) facet: Option<FacetCell>,
    pub(crate) original_facet: Option<FacetCell>,
    pub(crate) shared: bool,
    pub(crate) scope: Option<String>,
}

/// Semantic producer description, never a kernel/backend handle.
#[derive(Debug, Clone)]
pub struct NumericOwner<'a>(pub(crate) &'a OwnerInfo);
impl<'a> NumericOwner<'a> {
    /// The local family, or absence for a genuinely shared heterogeneous owner.
    pub const fn plot_kind(&self) -> Option<PlotKind> {
        self.0.kind
    }
    /// Explicit Canvas anchor coordinate.
    pub const fn canvas_cell(&self) -> Option<(usize, usize)> {
        self.0.canvas
    }
    /// Raw facet levels.
    pub fn facet_cell(&self) -> Option<&'a FacetCell> {
        self.0.original_facet.as_ref()
    }
    /// Whether this one result is shared by contributing owners.
    pub const fn is_shared(&self) -> bool {
        self.0.shared
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Identity {
    Tick(AxisRef, usize),
    GuideTick(usize),
    Heatmap(String, String),
    Estimate(String),
    Base,
    Terminal,
    Probe(usize),
}
impl Identity {
    fn view(&self) -> NumericIdentity<'_> {
        match self {
            Self::Tick(axis, index) => NumericIdentity::Tick {
                axis: *axis,
                source_index: *index,
            },
            Self::GuideTick(index) => NumericIdentity::GuideTick {
                source_index: *index,
            },
            Self::Heatmap(row, column) => NumericIdentity::HeatmapCell { row, column },
            Self::Estimate(category) => NumericIdentity::EstimateRow { category },
            Self::Base => NumericIdentity::WaterfallBase,
            Self::Terminal => NumericIdentity::WaterfallTerminal,
            Self::Probe(index) => NumericIdentity::Probe { index: *index },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ContextValue {
    pub(crate) operand: super::operand::Operand,
    pub(crate) identity: Identity,
}
impl ContextValue {
    fn operand(&self) -> NumericOperand<'_> {
        match &self.operand {
            super::operand::Operand::Binary64(bits) => {
                NumericOperand::Binary64(f64::from_bits(*bits))
            }
            super::operand::Operand::PowerOfTen(bits) => NumericOperand::PowerOfTen {
                exponent: f64::from_bits(*bits),
            },
            super::operand::Operand::Multiplicative(value) => NumericOperand::Multiplicative {
                anchor: f64::from_bits(value.anchor_bits),
                ratio: f64::from_bits(value.ratio_bits),
                index: &value.index_text,
            },
        }
    }
}

/// One exact source occurrence in a complete set.
#[derive(Debug, Clone)]
pub struct NumericValue<'a>(pub(crate) &'a ContextValue);
impl<'a> NumericValue<'a> {
    /// Original ordinary or mathematical operand.
    pub fn operand(&self) -> NumericOperand<'a> {
        self.0.operand()
    }
    /// Original semantic identity.
    pub fn identity(&self) -> NumericIdentity<'a> {
        self.0.identity.view()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DomainInfo {
    pub(crate) limits: (u64, u64),
    pub(crate) data: Option<(u64, u64)>,
    pub(crate) scale: AxisScale,
    pub(crate) origin: NumericRangeOrigin,
}

/// Final scientific domain, without CSS geometry or invented logarithmic inverses.
#[derive(Debug, Clone)]
pub struct NumericDomain<'a>(pub(crate) &'a DomainInfo);
impl<'a> NumericDomain<'a> {
    /// Lower mathematical endpoint.
    pub fn lower(&self) -> NumericOperand<'a> {
        endpoint(self.0.limits.0, self.0.scale)
    }
    /// Upper mathematical endpoint.
    pub fn upper(&self) -> NumericOperand<'a> {
        endpoint(self.0.limits.1, self.0.scale)
    }
    /// Raw bounds only when genuinely retained as finite endpoints.
    pub fn data_limits(&self) -> Option<(f64, f64)> {
        self.0
            .data
            .map(|(a, b)| (f64::from_bits(a), f64::from_bits(b)))
    }
    /// Resolved scientific scale coordinates.
    pub fn scale_limits(&self) -> (f64, f64) {
        (
            f64::from_bits(self.0.limits.0),
            f64::from_bits(self.0.limits.1),
        )
    }
    /// Scientific projection scale.
    pub const fn scale(&self) -> AxisScale {
        self.0.scale
    }
    /// Original domain provenance.
    pub const fn origin(&self) -> NumericRangeOrigin {
        self.0.origin
    }
}
fn endpoint<'a>(bits: u64, scale: AxisScale) -> NumericOperand<'a> {
    if scale == AxisScale::Log10 {
        NumericOperand::PowerOfTen {
            exponent: f64::from_bits(bits),
        }
    } else {
        NumericOperand::Binary64(f64::from_bits(bits))
    }
}

/// Resolved exact factors and literal selected affixes for one member/common set.
#[derive(Debug, Clone)]
pub struct NumericFactors<'a> {
    pub(crate) multiplier: f64,
    pub(crate) decimal_scale: i16,
    pub(crate) rate: NumericRate,
    pub(crate) scale: &'a SelectedScale,
    pub(crate) unit: Option<&'a NumericUnit>,
}
impl<'a> NumericFactors<'a> {
    /// Exact represented public multiplier.
    pub const fn multiplier(&self) -> f64 {
        self.multiplier
    }
    /// Exact decimal shift.
    pub const fn decimal_scale(&self) -> i16 {
        self.decimal_scale
    }
    /// Explicit rate factor.
    pub const fn rate(&self) -> NumericRate {
        self.rate
    }
    /// A resolved divisor, never AutomaticDecimal.
    pub const fn divisor(&self) -> &'a NumericFactor {
        &self.scale.divisor
    }
    /// Selected literal prefix, not the outer literal affix.
    pub fn prefix(&self) -> &'a str {
        &self.scale.prefix
    }
    /// Selected literal suffix, not the outer literal affix.
    pub fn suffix(&self) -> &'a str {
        &self.scale.suffix
    }
    /// Explicit unit policy.
    pub const fn unit(&self) -> Option<&'a NumericUnit> {
        self.unit
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ContextInfo {
    pub(crate) owner: OwnerInfo,
    pub(crate) role: NumericRole,
    pub(crate) purpose: NumericPurpose,
    pub(crate) values: Vec<ContextValue>,
    pub(crate) domain: Option<DomainInfo>,
    pub(crate) generation: Option<crate::coordinates::TickGeneration>,
    pub(crate) window: Option<[(u64, u64); 2]>,
}

/// Ordered complete semantic input and nonrecursive built-in helper.
#[derive(Debug, Clone)]
pub struct NumericSetContext<'a> {
    pub(crate) info: &'a ContextInfo,
    pub(crate) values: &'a [NumericValue<'a>],
    pub(crate) format: &'a NumericFormat,
    pub(crate) metadata: &'a FormattedSet,
    pub(crate) operands: &'a [super::operand::Operand],
    pub(crate) required: bool,
    pub(crate) helper: &'a std::cell::OnceCell<FormattedSet>,
}
impl<'a> NumericSetContext<'a> {
    /// Semantic producer.
    pub fn owner(&self) -> NumericOwner<'a> {
        NumericOwner(&self.info.owner)
    }
    /// Actual consumer.
    pub const fn role(&self) -> NumericRole {
        self.info.role
    }
    /// Preference versus actual source.
    pub const fn purpose(&self) -> NumericPurpose {
        self.info.purpose
    }
    /// Every original occurrence, including duplicates, in source order.
    pub const fn values(&self) -> &'a [NumericValue<'a>] {
        self.values
    }
    /// Resolved domain when this owner has one.
    pub fn domain(&self) -> Option<NumericDomain<'a>> {
        self.info.domain.as_ref().map(NumericDomain)
    }
    /// Explicit selected locale.
    pub fn locale(&self) -> &'a NumericLocale {
        self.format.locale_ref()
    }
    /// Common resolved factor/affix only when every member agrees.
    pub fn common_factors(&self) -> Option<NumericFactors<'a>> {
        let first = self.metadata.scales.first()?;
        self.metadata
            .scales
            .iter()
            .all(|scale| scale == first)
            .then(|| self.factors(0))
    }
    /// Built-in conversion of this same complete set, bypassing only the function.
    pub fn format_builtin(&self) -> Result<NumericLabels> {
        let builtin = self.builtin()?;
        Ok(NumericLabels {
            labels: crate::data::source::collect_source(
                builtin
                    .labels
                    .iter()
                    .map(|label| crate::data::source::copy_source_string(label)),
            )?,
            explanation: builtin
                .explanation
                .as_ref()
                .map(Text::try_copy)
                .transpose()?,
        })
    }
    fn builtin(&self) -> Result<&FormattedSet> {
        if self.helper.get().is_none() {
            let result = self.format.function_helper(
                self.operands,
                &self.metadata.scales,
                self.required,
                self.info.purpose == NumericPurpose::IntrinsicProbe,
            )?;
            self.helper.set(result).map_err(|_| {
                crate::Error::Render("numeric helper was initialized recursively".into())
            })?;
        }
        self.helper
            .get()
            .ok_or_else(|| crate::Error::Render("numeric helper result is missing".into()))
    }
    fn factors(&self, index: usize) -> NumericFactors<'a> {
        let (multiplier, decimal_scale, rate) = self.format.factor_inputs();
        NumericFactors {
            multiplier,
            decimal_scale,
            rate,
            scale: &self.metadata.scales[index],
            unit: self.metadata.unit.as_ref(),
        }
    }
}

/// One original occurrence, retaining its complete set and helper precision.
#[derive(Debug, Clone)]
pub struct NumericValueContext<'a> {
    pub(crate) set: &'a NumericSetContext<'a>,
    pub(crate) index: usize,
}
impl<'a> NumericValueContext<'a> {
    /// The complete enclosing semantic set.
    pub const fn set(&self) -> &NumericSetContext<'a> {
        self.set
    }
    /// Original occurrence index.
    pub const fn index(&self) -> usize {
        self.index
    }
    /// Original operand and identity.
    pub fn value(&self) -> &NumericValue<'a> {
        &self.set.values[self.index]
    }
    /// Resolved member factor, even with PerValue selection.
    pub fn factors(&self) -> NumericFactors<'a> {
        self.set.factors(self.index)
    }
    /// Built-in text under the enclosing complete set's precision/factors.
    pub fn format_builtin(&self) -> Result<String> {
        crate::data::source::copy_source_string(&self.set.builtin()?.labels[self.index])
    }
}

/// Owned final callback strings and an optional replacement common explanation.
#[derive(Debug, Clone)]
pub struct NumericLabels {
    labels: Vec<String>,
    explanation: Option<Text>,
}
impl NumericLabels {
    /// Retain final strings without postformatting.
    pub const fn new(labels: Vec<String>) -> Self {
        Self {
            labels,
            explanation: None,
        }
    }
    /// Replace the one configured/generated explanation, retaining ordinary Text semantics.
    #[must_use]
    pub fn explanation(mut self, value: impl Into<Text>) -> Self {
        self.explanation = Some(value.into());
        self
    }
    /// Final strings in occurrence order.
    pub fn labels(&self) -> &[String] {
        &self.labels
    }
    /// Optional replacement explanation.
    pub const fn get_explanation(&self) -> Option<&Text> {
        self.explanation.as_ref()
    }
    /// Consume the owned result.
    pub fn into_parts(self) -> (Vec<String>, Option<Text>) {
        (self.labels, self.explanation)
    }
}