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