Skip to main content

lichtung_plot/spec/
ticks.rs

1use crate::{Error, Result};
2
3pub(crate) mod function;
4mod recipe;
5pub use function::{TickContext, TickPositions};
6
7/// One validated selection for generated numeric tick positions.
8///
9/// Targets allow nice-step deviation; maxima bound the complete in-domain list,
10/// including endpoint positions. Preferred intervals are tried before bounded
11/// coarser sources. Exact caller ticks take precedence over every selection.
12/// ```
13/// use lichtung_plot::coordinates::TickGeneration;
14/// let linear = TickGeneration::additive(0.25)?;
15/// let logarithmic = TickGeneration::log10_decades(2)?;
16/// assert_eq!(linear.additive_step(), Some(0.25));
17/// assert_eq!(logarithmic.decade_step(), Some(2));
18/// assert_eq!(TickGeneration::target(5)?.target_count(), Some(5));
19/// assert_eq!(TickGeneration::maximum(6)?.get_maximum_count(), Some(6));
20/// assert!(TickGeneration::default().is_automatic());
21/// assert!(TickGeneration::target(0).is_err());
22/// assert!(TickGeneration::maximum(10_001).is_ok());
23/// # Ok::<(), lichtung_plot::Error>(())
24/// ```
25///
26/// The choice and payload are private:
27/// ```compile_fail
28/// let _ = lichtung_plot::coordinates::TickGeneration::Target(0);
29/// ```
30/// Requests are owned and cloneable, not Copy:
31/// ```compile_fail
32/// use lichtung_plot::coordinates::TickGeneration;
33/// let request = TickGeneration::automatic();
34/// let moved = request;
35/// let _ = (moved, request);
36/// ```
37#[derive(Debug, Clone, Default, PartialEq)]
38pub struct TickGeneration {
39    primary: Primary,
40    maximum: Option<usize>,
41}
42
43// All admitted floating steps are finite and strictly positive.
44impl Eq for TickGeneration {}
45
46#[derive(Debug, Clone, Default, PartialEq)]
47enum Primary {
48    #[default]
49    Automatic,
50    Interval {
51        step: f64,
52        origin: f64,
53        space: TickSpace,
54        requirement: TickRequirement,
55        binding: IntervalBinding,
56    },
57    Target(usize),
58    ExactCount {
59        count: usize,
60        space: TickSpace,
61        singleton: TickSingleton,
62    },
63    Multiplicative {
64        anchor: f64,
65        ratio: f64,
66        requirement: TickRequirement,
67    },
68    Function(function::Function),
69}
70
71/// Coordinate space for generated positions.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum TickSpace {
74    /// Raw scientific data units.
75    Data,
76    /// Linear coordinates or logarithmic exponents.
77    Scale,
78}
79
80/// Whether a lattice is fixed or may try complete coarser candidates.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum TickRequirement {
83    /// Retain the complete requested lattice, including a valid empty result.
84    Fixed,
85    /// Try the requested lattice before the documented coarser source program.
86    Preferred,
87}
88
89/// Position of an exact singleton, in the selected coordinate space.
90#[derive(Debug, Clone, Copy)]
91pub enum TickSingleton {
92    /// Lower domain endpoint (default).
93    Lower,
94    /// Exact midpoint, rounded once.
95    Midpoint,
96    /// Upper domain endpoint.
97    Upper,
98    /// A finite in-domain position.
99    Position(f64),
100}
101impl PartialEq for TickSingleton {
102    fn eq(&self, other: &Self) -> bool {
103        match (self, other) {
104            (Self::Lower, Self::Lower)
105            | (Self::Midpoint, Self::Midpoint)
106            | (Self::Upper, Self::Upper) => true,
107            (Self::Position(a), Self::Position(b)) => a.to_bits() == b.to_bits(),
108            _ => false,
109        }
110    }
111}
112impl Eq for TickSingleton {}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115enum IntervalBinding {
116    Linear,
117    Log10,
118    Context,
119}
120
121impl TickGeneration {
122    /// Generate positions from the final domain and actual assigned span.
123    /// Clones share the immutable callback; exact ticks suppress it entirely.
124    pub fn function<F>(function: F) -> Self
125    where
126        F: for<'a> Fn(&TickContext<'a>) -> Result<TickPositions> + Send + Sync + 'static,
127    {
128        Self {
129            primary: Primary::Function(function::Function::new(function)),
130            maximum: None,
131        }
132    }
133
134    pub(crate) fn position_function(&self) -> Option<&function::Function> {
135        if let Primary::Function(function) = &self.primary {
136            Some(function)
137        } else {
138            None
139        }
140    }
141    /// Use renderer-owned automatic density and nice-step selection.
142    pub const fn automatic() -> Self {
143        Self {
144            primary: Primary::Automatic,
145            maximum: None,
146        }
147    }
148
149    /// Inspect whether the complete request is Automatic without an explicit cap.
150    pub const fn is_automatic(&self) -> bool {
151        matches!(self.primary, Primary::Automatic) && self.maximum.is_none()
152    }
153
154    /// Prefer a finite strictly positive additive step on a linear numeric axis.
155    pub fn additive(step: f64) -> Result<Self> {
156        if !step.is_finite() || step <= 0.0 {
157            return Err(Error::Data(
158                "tick interval must be finite and strictly positive".into(),
159            ));
160        }
161        Ok(Self {
162            primary: Primary::Interval {
163                step,
164                origin: 0.0,
165                space: TickSpace::Data,
166                requirement: TickRequirement::Preferred,
167                binding: IntervalBinding::Linear,
168            },
169            maximum: None,
170        })
171    }
172
173    /// Prefer a nonzero integral exponent step on a base-ten logarithmic axis.
174    pub fn log10_decades(decades: u32) -> Result<Self> {
175        if decades == 0 {
176            return Err(Error::Data(
177                "tick interval decades must be strictly positive".into(),
178            ));
179        }
180        Ok(Self {
181            primary: Primary::Interval {
182                step: f64::from(decades),
183                origin: 0.0,
184                space: TickSpace::Scale,
185                requirement: TickRequirement::Preferred,
186                binding: IntervalBinding::Log10,
187            },
188            maximum: None,
189        })
190    }
191
192    /// Select a finite positive interval and finite origin in the declared space.
193    pub fn interval(
194        step: f64,
195        origin: f64,
196        space: TickSpace,
197        requirement: TickRequirement,
198    ) -> Result<Self> {
199        if !step.is_finite() || step <= 0.0 || !origin.is_finite() {
200            return Err(Error::Data(
201                "tick interval needs a finite positive step and finite origin".into(),
202            ));
203        }
204        Ok(Self {
205            primary: Primary::Interval {
206                step,
207                origin: if origin == 0.0 { 0.0 } else { origin },
208                space,
209                requirement,
210                binding: IntervalBinding::Context,
211            },
212            maximum: None,
213        })
214    }
215
216    /// Inspect the retained step, origin, coordinate space and source requirement.
217    pub const fn interval_parameters(&self) -> Option<(f64, f64, TickSpace, TickRequirement)> {
218        if let Primary::Interval {
219            step,
220            origin,
221            space,
222            requirement,
223            ..
224        } = self.primary
225        {
226            Some((step, origin, space, requirement))
227        } else {
228            None
229        }
230    }
231
232    /// Select the positive anchored geometric lattice, retaining either ratio direction.
233    pub fn multiplicative(anchor: f64, ratio: f64, requirement: TickRequirement) -> Result<Self> {
234        if !anchor.is_finite()
235            || anchor <= 0.0
236            || !ratio.is_finite()
237            || ratio <= 0.0
238            || ratio.to_bits() == 1.0_f64.to_bits()
239        {
240            return Err(Error::Data("multiplicative ticks require a finite positive anchor and positive ratio other than one".into()));
241        }
242        Ok(Self {
243            primary: Primary::Multiplicative {
244                anchor,
245                ratio,
246                requirement,
247            },
248            maximum: None,
249        })
250    }
251
252    /// Inspect the supplied anchor, ratio direction and complete-source requirement.
253    pub const fn multiplicative_parameters(&self) -> Option<(f64, f64, TickRequirement)> {
254        if let Primary::Multiplicative {
255            anchor,
256            ratio,
257            requirement,
258        } = self.primary
259        {
260            Some((anchor, ratio, requirement))
261        } else {
262            None
263        }
264    }
265
266    pub(crate) fn validate_scale(&self, log: bool) -> Result<()> {
267        if let Primary::Interval { binding, .. } = self.primary {
268            if (binding == IntervalBinding::Linear && log)
269                || (binding == IntervalBinding::Log10 && !log)
270            {
271                return Err(Error::Data(
272                    "tick interval does not match the axis scale".into(),
273                ));
274            }
275        }
276        Ok(())
277    }
278
279    /// Request approximately `count` numeric positions, allowing nice-step deviation.
280    ///
281    /// Counts must be positive; one requests the original-domain midpoint.
282    /// Actual label fit can select a coarser complete source.
283    pub fn target(count: usize) -> Result<Self> {
284        Self::validate_count(count)?;
285        Ok(Self {
286            primary: Primary::Target(count),
287            maximum: None,
288        })
289    }
290
291    /// Bound generated in-domain positions, including endpoints, by `count`.
292    ///
293    /// Counts must be positive. The bound applies to complete generated
294    /// sources, not exact caller ticks; it never drops individual labels.
295    pub fn maximum(count: usize) -> Result<Self> {
296        Self::validate_count(count)?;
297        Ok(Self {
298            primary: Primary::Automatic,
299            maximum: Some(count),
300        })
301    }
302
303    fn validate_count(count: usize) -> Result<()> {
304        if count == 0 {
305            return Err(Error::Data("generated tick count must be positive".into()));
306        }
307        Ok(())
308    }
309
310    /// Inspect the target count, or None for another selection.
311    pub const fn target_count(&self) -> Option<usize> {
312        match self.primary {
313            Primary::Target(count) => Some(count),
314            _ => None,
315        }
316    }
317
318    /// Inspect the hard maximum count, or None for another selection.
319    pub const fn get_maximum_count(&self) -> Option<usize> {
320        self.maximum
321    }
322
323    /// Set or clear the positive generated cap, without replacing the locator.
324    pub fn maximum_count(mut self, maximum: Option<usize>) -> Result<Self> {
325        if let Some(maximum) = maximum {
326            Self::validate_count(maximum)?;
327            if self
328                .exact_parameters()
329                .is_some_and(|(count, _, _)| count > maximum)
330            {
331                return Err(Error::Data(
332                    "exact tick count exceeds the generated maximum".into(),
333                ));
334            }
335        }
336        self.maximum = maximum;
337        Ok(self)
338    }
339
340    /// Generate exactly count positions; zero is empty and one initially uses Lower.
341    pub const fn exact_count(count: usize, space: TickSpace) -> Self {
342        Self {
343            primary: Primary::ExactCount {
344                count,
345                space,
346                singleton: TickSingleton::Lower,
347            },
348            maximum: None,
349        }
350    }
351
352    /// Set exact-count singleton placement, retaining the complete request for n>=2.
353    pub fn singleton(mut self, position: TickSingleton) -> Result<Self> {
354        if let TickSingleton::Position(value) = position {
355            if !value.is_finite() {
356                return Err(Error::Data("tick singleton must be finite".into()));
357            }
358        }
359        let Primary::ExactCount { singleton, .. } = &mut self.primary else {
360            return Err(Error::Data(
361                "singleton placement requires an exact-count locator".into(),
362            ));
363        };
364        *singleton = position;
365        Ok(self)
366    }
367
368    pub(crate) const fn exact_parameters(&self) -> Option<(usize, TickSpace, TickSingleton)> {
369        if let Primary::ExactCount {
370            count,
371            space,
372            singleton,
373        } = self.primary
374        {
375            Some((count, space, singleton))
376        } else {
377            None
378        }
379    }
380
381    pub(crate) const fn is_interval(&self) -> bool {
382        matches!(self.primary, Primary::Interval { .. })
383    }
384
385    pub(crate) fn observe_feedback(
386        &self,
387        round: &mut crate::layout::kernel::FeedbackRound,
388    ) -> Result<()> {
389        round.observe_count(self.maximum.unwrap_or(0))?;
390        match &self.primary {
391            Primary::Automatic => round.observe_count(0),
392            Primary::Function(function) => {
393                round.observe_count(6)?;
394                round.observe_position_function(function)
395            }
396            Primary::Interval {
397                step,
398                origin,
399                space,
400                requirement,
401                binding,
402            } => {
403                round.observe_count(1)?;
404                round.observe_count(*binding as usize)?;
405                round.observe_number(*origin)?;
406                round.observe_count(*space as usize)?;
407                round.observe_count(*requirement as usize)?;
408                round.observe_number(*step)
409            }
410            Primary::Target(count) => {
411                round.observe_count(3)?;
412                round.observe_count(*count)
413            }
414            Primary::Multiplicative {
415                anchor,
416                ratio,
417                requirement,
418            } => {
419                round.observe_count(5)?;
420                round.observe_number(*anchor)?;
421                round.observe_number(*ratio)?;
422                round.observe_count(*requirement as usize)
423            }
424            Primary::ExactCount {
425                count,
426                space,
427                singleton,
428            } => {
429                round.observe_count(4)?;
430                round.observe_count(*count)?;
431                round.observe_count(*space as usize)?;
432                match singleton {
433                    TickSingleton::Lower => round.observe_count(0),
434                    TickSingleton::Midpoint => round.observe_count(1),
435                    TickSingleton::Upper => round.observe_count(2),
436                    TickSingleton::Position(value) => {
437                        round.observe_count(3)?;
438                        round.observe_count(usize::from(value.is_sign_negative()))?;
439                        round.observe_number(*value)
440                    }
441                }
442            }
443        }
444    }
445
446    /// Inspect the positive additive step, or None for another selection.
447    pub const fn additive_step(&self) -> Option<f64> {
448        match self.primary {
449            Primary::Interval {
450                step,
451                binding: IntervalBinding::Linear,
452                ..
453            } => Some(step),
454            _ => None,
455        }
456    }
457
458    /// Inspect the positive integral decade step, or None for another selection.
459    #[expect(
460        clippy::cast_possible_truncation,
461        clippy::cast_sign_loss,
462        reason = "Log10 binding is constructed only from a nonzero exactly represented u32"
463    )]
464    pub const fn decade_step(&self) -> Option<u32> {
465        match self.primary {
466            Primary::Interval {
467                step,
468                binding: IntervalBinding::Log10,
469                ..
470            } => Some(step as u32),
471            _ => None,
472        }
473    }
474}