Skip to main content

lichtung_plot/spec/
ticks.rs

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