Skip to main content

lichtung_plot/numeric/
context.rs

1//! Library-created borrowed numeric views; no geometry or mutable renderer escapes.
2
3use super::format::NumericFormat;
4use super::prefixes::selection::SelectedScale;
5use super::set::FormattedSet;
6use crate::{
7    AxisScale, FacetCell, NumericFactor, NumericLocale, NumericRate, NumericUnit, PlotKind, Result,
8    Text,
9};
10
11/// Scientific coordinate axis.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum CoordinateAxis {
14    /// Horizontal coordinate.
15    X,
16    /// Vertical coordinate.
17    Y,
18}
19/// Complete numeric consumer, independent of its selected typography.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum NumericRole {
22    /// Horizontal ticks.
23    XAxis,
24    /// Vertical ticks.
25    YAxis,
26    /// Continuous color guide.
27    ContinuousColor,
28    /// Active finite cell values.
29    HeatmapValues,
30    /// Available point-only estimates.
31    CoefficientLabels,
32    /// Eligible base/terminal totals.
33    WaterfallTotals,
34}
35/// Whether a set is an intrinsic preference or a reached actual source.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum NumericPurpose {
38    /// Low/mid/high preference, not a required unique source.
39    IntrinsicProbe,
40    /// Actual semantic occurrences.
41    ActualSet,
42}
43/// Scientific domain provenance.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum NumericRangeOrigin {
46    /// Locally automatic.
47    Automatic,
48    /// Caller-configured limits.
49    Explicit,
50    /// Parent-resolved scientific limits.
51    ParentResolved,
52}
53
54/// Exact operand representation, retaining binary64 source bits and power exponents.
55#[derive(Debug, Clone, Copy)]
56pub enum NumericOperand<'a> {
57    /// The represented finite ordinary operand.
58    Binary64(f64),
59    /// A mathematical power, not a rounded physical `powf` result.
60    PowerOfTen {
61        /// The exact represented exponent.
62        exponent: f64,
63    },
64    /// Exact anchored geometric operand, retaining its original ratio direction.
65    Multiplicative {
66        /// Supplied positive binary64 anchor.
67        anchor: f64,
68        /// Supplied positive binary64 ratio, other than one.
69        ratio: f64,
70        /// Exact signed integral index in canonical ASCII decimal.
71        index: &'a str,
72    },
73}
74
75/// Raw semantic identity, before display aliases.
76#[derive(Debug, Clone)]
77pub enum NumericIdentity<'a> {
78    /// A generated position in its original complete source order.
79    Tick {
80        /// Owning coordinate.
81        axis: CoordinateAxis,
82        /// Original occurrence.
83        source_index: usize,
84    },
85    /// A final-domain guide position.
86    GuideTick {
87        /// Original occurrence.
88        source_index: usize,
89    },
90    /// Raw cell keys.
91    HeatmapCell {
92        /// Raw row level.
93        row: &'a str,
94        /// Raw column level.
95        column: &'a str,
96    },
97    /// Raw available estimate category.
98    EstimateRow {
99        /// Raw category level.
100        category: &'a str,
101    },
102    /// Base total.
103    WaterfallBase,
104    /// Terminal total.
105    WaterfallTerminal,
106    /// An intrinsic low/mid/high preference.
107    Probe {
108        /// Probe occurrence.
109        index: usize,
110    },
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub(crate) struct OwnerInfo {
115    pub(crate) kind: Option<PlotKind>,
116    pub(crate) canvas: Option<(usize, usize)>,
117    pub(crate) facet: Option<FacetCell>,
118    pub(crate) shared: bool,
119    pub(crate) scope: Option<String>,
120}
121
122/// Semantic producer description, never a kernel/backend handle.
123#[derive(Debug, Clone)]
124pub struct NumericOwner<'a>(pub(crate) &'a OwnerInfo);
125impl<'a> NumericOwner<'a> {
126    /// The local family, or absence for a genuinely shared heterogeneous owner.
127    pub const fn plot_kind(&self) -> Option<PlotKind> {
128        self.0.kind
129    }
130    /// Explicit Canvas anchor coordinate.
131    pub const fn canvas_cell(&self) -> Option<(usize, usize)> {
132        self.0.canvas
133    }
134    /// Raw facet levels.
135    pub fn facet_cell(&self) -> Option<&'a FacetCell> {
136        self.0.facet.as_ref()
137    }
138    /// Whether this one result is shared by contributing owners.
139    pub const fn is_shared(&self) -> bool {
140        self.0.shared
141    }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub(crate) enum Identity {
146    Tick(CoordinateAxis, usize),
147    GuideTick(usize),
148    Heatmap(String, String),
149    Estimate(String),
150    Base,
151    Terminal,
152    Probe(usize),
153}
154impl Identity {
155    fn view(&self) -> NumericIdentity<'_> {
156        match self {
157            Self::Tick(axis, index) => NumericIdentity::Tick {
158                axis: *axis,
159                source_index: *index,
160            },
161            Self::GuideTick(index) => NumericIdentity::GuideTick {
162                source_index: *index,
163            },
164            Self::Heatmap(row, column) => NumericIdentity::HeatmapCell { row, column },
165            Self::Estimate(category) => NumericIdentity::EstimateRow { category },
166            Self::Base => NumericIdentity::WaterfallBase,
167            Self::Terminal => NumericIdentity::WaterfallTerminal,
168            Self::Probe(index) => NumericIdentity::Probe { index: *index },
169        }
170    }
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub(crate) struct ContextValue {
175    pub(crate) operand: super::operand::Operand,
176    pub(crate) identity: Identity,
177}
178impl ContextValue {
179    fn operand(&self) -> NumericOperand<'_> {
180        match &self.operand {
181            super::operand::Operand::Binary64(bits) => {
182                NumericOperand::Binary64(f64::from_bits(*bits))
183            }
184            super::operand::Operand::PowerOfTen(bits) => NumericOperand::PowerOfTen {
185                exponent: f64::from_bits(*bits),
186            },
187            super::operand::Operand::Multiplicative(value) => NumericOperand::Multiplicative {
188                anchor: f64::from_bits(value.anchor_bits),
189                ratio: f64::from_bits(value.ratio_bits),
190                index: &value.index_text,
191            },
192        }
193    }
194}
195
196/// One exact source occurrence in a complete set.
197#[derive(Debug, Clone)]
198pub struct NumericValue<'a>(pub(crate) &'a ContextValue);
199impl<'a> NumericValue<'a> {
200    /// Original ordinary or mathematical operand.
201    pub fn operand(&self) -> NumericOperand<'a> {
202        self.0.operand()
203    }
204    /// Original semantic identity.
205    pub fn identity(&self) -> NumericIdentity<'a> {
206        self.0.identity.view()
207    }
208}
209
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub(crate) struct DomainInfo {
212    pub(crate) limits: (u64, u64),
213    pub(crate) data: Option<(u64, u64)>,
214    pub(crate) scale: AxisScale,
215    pub(crate) origin: NumericRangeOrigin,
216}
217
218/// Final scientific domain, without CSS geometry or invented logarithmic inverses.
219#[derive(Debug, Clone)]
220pub struct NumericDomain<'a>(pub(crate) &'a DomainInfo);
221impl<'a> NumericDomain<'a> {
222    /// Lower mathematical endpoint.
223    pub fn lower(&self) -> NumericOperand<'a> {
224        endpoint(self.0.limits.0, self.0.scale)
225    }
226    /// Upper mathematical endpoint.
227    pub fn upper(&self) -> NumericOperand<'a> {
228        endpoint(self.0.limits.1, self.0.scale)
229    }
230    /// Raw bounds only when genuinely retained as finite endpoints.
231    pub fn data_limits(&self) -> Option<(f64, f64)> {
232        self.0
233            .data
234            .map(|(a, b)| (f64::from_bits(a), f64::from_bits(b)))
235    }
236    /// Resolved scientific scale coordinates.
237    pub fn scale_limits(&self) -> (f64, f64) {
238        (
239            f64::from_bits(self.0.limits.0),
240            f64::from_bits(self.0.limits.1),
241        )
242    }
243    /// Scientific projection scale.
244    pub const fn scale(&self) -> AxisScale {
245        self.0.scale
246    }
247    /// Original domain provenance.
248    pub const fn origin(&self) -> NumericRangeOrigin {
249        self.0.origin
250    }
251}
252fn endpoint<'a>(bits: u64, scale: AxisScale) -> NumericOperand<'a> {
253    if scale == AxisScale::Log10 {
254        NumericOperand::PowerOfTen {
255            exponent: f64::from_bits(bits),
256        }
257    } else {
258        NumericOperand::Binary64(f64::from_bits(bits))
259    }
260}
261
262/// Resolved exact factors and literal selected affixes for one member/common set.
263#[derive(Debug, Clone)]
264pub struct NumericFactors<'a> {
265    pub(crate) multiplier: f64,
266    pub(crate) decimal_scale: i16,
267    pub(crate) rate: NumericRate,
268    pub(crate) scale: &'a SelectedScale,
269    pub(crate) unit: Option<&'a NumericUnit>,
270}
271impl<'a> NumericFactors<'a> {
272    /// Exact represented public multiplier.
273    pub const fn multiplier(&self) -> f64 {
274        self.multiplier
275    }
276    /// Exact decimal shift.
277    pub const fn decimal_scale(&self) -> i16 {
278        self.decimal_scale
279    }
280    /// Explicit rate factor.
281    pub const fn rate(&self) -> NumericRate {
282        self.rate
283    }
284    /// A resolved divisor, never AutomaticDecimal.
285    pub const fn divisor(&self) -> &'a NumericFactor {
286        &self.scale.divisor
287    }
288    /// Selected literal prefix, not the outer literal affix.
289    pub fn prefix(&self) -> &'a str {
290        &self.scale.prefix
291    }
292    /// Selected literal suffix, not the outer literal affix.
293    pub fn suffix(&self) -> &'a str {
294        &self.scale.suffix
295    }
296    /// Explicit unit policy.
297    pub const fn unit(&self) -> Option<&'a NumericUnit> {
298        self.unit
299    }
300}
301
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub(crate) struct ContextInfo {
304    pub(crate) owner: OwnerInfo,
305    pub(crate) role: NumericRole,
306    pub(crate) purpose: NumericPurpose,
307    pub(crate) values: Vec<ContextValue>,
308    pub(crate) domain: Option<DomainInfo>,
309    pub(crate) generation: Option<crate::TickGeneration>,
310    pub(crate) window: Option<[(u64, u64); 2]>,
311}
312
313/// Ordered complete semantic input and nonrecursive built-in helper.
314#[derive(Debug, Clone)]
315pub struct NumericSetContext<'a> {
316    pub(crate) info: &'a ContextInfo,
317    pub(crate) values: &'a [NumericValue<'a>],
318    pub(crate) format: &'a NumericFormat,
319    pub(crate) metadata: &'a FormattedSet,
320    pub(crate) operands: &'a [super::operand::Operand],
321    pub(crate) required: bool,
322    pub(crate) helper: &'a std::cell::OnceCell<FormattedSet>,
323}
324impl<'a> NumericSetContext<'a> {
325    /// Semantic producer.
326    pub fn owner(&self) -> NumericOwner<'a> {
327        NumericOwner(&self.info.owner)
328    }
329    /// Actual consumer.
330    pub const fn role(&self) -> NumericRole {
331        self.info.role
332    }
333    /// Preference versus actual source.
334    pub const fn purpose(&self) -> NumericPurpose {
335        self.info.purpose
336    }
337    /// Every original occurrence, including duplicates, in source order.
338    pub const fn values(&self) -> &'a [NumericValue<'a>] {
339        self.values
340    }
341    /// Resolved domain when this owner has one.
342    pub fn domain(&self) -> Option<NumericDomain<'a>> {
343        self.info.domain.as_ref().map(NumericDomain)
344    }
345    /// Explicit selected locale.
346    pub fn locale(&self) -> &'a NumericLocale {
347        self.format.locale_ref()
348    }
349    /// Common resolved factor/affix only when every member agrees.
350    pub fn common_factors(&self) -> Option<NumericFactors<'a>> {
351        let first = self.metadata.scales.first()?;
352        self.metadata
353            .scales
354            .iter()
355            .all(|scale| scale == first)
356            .then(|| self.factors(0))
357    }
358    /// Built-in conversion of this same complete set, bypassing only the function.
359    pub fn format_builtin(&self) -> Result<NumericLabels> {
360        let builtin = self.builtin()?;
361        Ok(NumericLabels {
362            labels: crate::data::source::collect_source(
363                builtin
364                    .labels
365                    .iter()
366                    .map(|label| crate::data::source::copy_source_string(label)),
367            )?,
368            explanation: builtin
369                .explanation
370                .as_ref()
371                .map(Text::try_copy)
372                .transpose()?,
373        })
374    }
375    fn builtin(&self) -> Result<&FormattedSet> {
376        if self.helper.get().is_none() {
377            let result = self.format.function_helper(
378                self.operands,
379                &self.metadata.scales,
380                self.required,
381                self.info.purpose == NumericPurpose::IntrinsicProbe,
382            )?;
383            self.helper.set(result).map_err(|_| {
384                crate::Error::Render("numeric helper was initialized recursively".into())
385            })?;
386        }
387        self.helper
388            .get()
389            .ok_or_else(|| crate::Error::Render("numeric helper result is missing".into()))
390    }
391    fn factors(&self, index: usize) -> NumericFactors<'a> {
392        let (multiplier, decimal_scale, rate) = self.format.factor_inputs();
393        NumericFactors {
394            multiplier,
395            decimal_scale,
396            rate,
397            scale: &self.metadata.scales[index],
398            unit: self.metadata.unit.as_ref(),
399        }
400    }
401}
402
403/// One original occurrence, retaining its complete set and helper precision.
404#[derive(Debug, Clone)]
405pub struct NumericValueContext<'a> {
406    pub(crate) set: &'a NumericSetContext<'a>,
407    pub(crate) index: usize,
408}
409impl<'a> NumericValueContext<'a> {
410    /// The complete enclosing semantic set.
411    pub const fn set(&self) -> &NumericSetContext<'a> {
412        self.set
413    }
414    /// Original occurrence index.
415    pub const fn index(&self) -> usize {
416        self.index
417    }
418    /// Original operand and identity.
419    pub fn value(&self) -> &NumericValue<'a> {
420        &self.set.values[self.index]
421    }
422    /// Resolved member factor, even with PerValue selection.
423    pub fn factors(&self) -> NumericFactors<'a> {
424        self.set.factors(self.index)
425    }
426    /// Built-in text under the enclosing complete set's precision/factors.
427    pub fn format_builtin(&self) -> Result<String> {
428        crate::data::source::copy_source_string(&self.set.builtin()?.labels[self.index])
429    }
430}
431
432/// Owned final callback strings and an optional replacement common explanation.
433#[derive(Debug, Clone)]
434pub struct NumericLabels {
435    labels: Vec<String>,
436    explanation: Option<Text>,
437}
438impl NumericLabels {
439    /// Retain final strings without postformatting.
440    pub const fn new(labels: Vec<String>) -> Self {
441        Self {
442            labels,
443            explanation: None,
444        }
445    }
446    /// Replace the one configured/generated explanation, retaining ordinary Text semantics.
447    #[must_use]
448    pub fn explanation(mut self, value: impl Into<Text>) -> Self {
449        self.explanation = Some(value.into());
450        self
451    }
452    /// Final strings in occurrence order.
453    pub fn labels(&self) -> &[String] {
454        &self.labels
455    }
456    /// Optional replacement explanation.
457    pub const fn get_explanation(&self) -> Option<&Text> {
458        self.explanation.as_ref()
459    }
460    /// Consume the owned result.
461    pub fn into_parts(self) -> (Vec<String>, Option<Text>) {
462        (self.labels, self.explanation)
463    }
464}