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