lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use crate::{Error, Result};

pub(crate) mod function;
pub use function::{TickContext, TickPositions};

/// One validated selection for generated numeric tick positions.
///
/// Targets allow nice-step deviation; maxima bound the complete in-domain list,
/// including endpoint positions. Preferred intervals are tried before bounded
/// coarser sources. Exact caller ticks take precedence over every selection.
/// ```
/// use lichtung_plot::coordinates::TickGeneration;
/// let linear = TickGeneration::additive(0.25)?;
/// let logarithmic = TickGeneration::log10_decades(2)?;
/// assert_eq!(linear.additive_step(), Some(0.25));
/// assert_eq!(logarithmic.decade_step(), Some(2));
/// assert_eq!(TickGeneration::target(5)?.target_count(), Some(5));
/// assert_eq!(TickGeneration::maximum(6)?.get_maximum_count(), Some(6));
/// assert!(TickGeneration::default().is_automatic());
/// assert!(TickGeneration::target(0).is_err());
/// assert!(TickGeneration::maximum(10_001).is_ok());
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// The choice and payload are private:
/// ```compile_fail
/// let _ = lichtung_plot::coordinates::TickGeneration::Target(0);
/// ```
/// Requests are owned and cloneable, not Copy:
/// ```compile_fail
/// use lichtung_plot::coordinates::TickGeneration;
/// let request = TickGeneration::automatic();
/// let moved = request;
/// let _ = (moved, request);
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TickGeneration {
    primary: Primary,
    maximum: Option<usize>,
}

// All admitted floating steps are finite and strictly positive.
impl Eq for TickGeneration {}

#[derive(Debug, Clone, Default, PartialEq)]
enum Primary {
    #[default]
    Automatic,
    Interval {
        step: f64,
        origin: f64,
        space: TickSpace,
        requirement: TickRequirement,
        binding: IntervalBinding,
    },
    Target(usize),
    ExactCount {
        count: usize,
        space: TickSpace,
        singleton: TickSingleton,
    },
    Multiplicative {
        anchor: f64,
        ratio: f64,
        requirement: TickRequirement,
    },
    Function(function::Function),
}

/// Coordinate space for generated positions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TickSpace {
    /// Raw scientific data units.
    Data,
    /// Linear coordinates or logarithmic exponents.
    Scale,
}

/// Whether a lattice is fixed or may try complete coarser candidates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TickRequirement {
    /// Retain the complete requested lattice, including a valid empty result.
    Fixed,
    /// Try the requested lattice before the documented coarser source program.
    Preferred,
}

/// Position of an exact singleton, in the selected coordinate space.
#[derive(Debug, Clone, Copy)]
pub enum TickSingleton {
    /// Lower domain endpoint (default).
    Lower,
    /// Exact midpoint, rounded once.
    Midpoint,
    /// Upper domain endpoint.
    Upper,
    /// A finite in-domain position.
    Position(f64),
}
impl PartialEq for TickSingleton {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Lower, Self::Lower)
            | (Self::Midpoint, Self::Midpoint)
            | (Self::Upper, Self::Upper) => true,
            (Self::Position(a), Self::Position(b)) => a.to_bits() == b.to_bits(),
            _ => false,
        }
    }
}
impl Eq for TickSingleton {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IntervalBinding {
    Linear,
    Log10,
    Context,
}

impl TickGeneration {
    /// Generate positions from the final domain and actual assigned span.
    /// Clones share the immutable callback; exact ticks suppress it entirely.
    pub fn function<F>(function: F) -> Self
    where
        F: for<'a> Fn(&TickContext<'a>) -> Result<TickPositions> + Send + Sync + 'static,
    {
        Self {
            primary: Primary::Function(function::Function::new(function)),
            maximum: None,
        }
    }

    pub(crate) fn position_function(&self) -> Option<&function::Function> {
        if let Primary::Function(function) = &self.primary {
            Some(function)
        } else {
            None
        }
    }
    /// Use renderer-owned automatic density and nice-step selection.
    pub const fn automatic() -> Self {
        Self {
            primary: Primary::Automatic,
            maximum: None,
        }
    }

    /// Inspect whether the complete request is Automatic without an explicit cap.
    pub const fn is_automatic(&self) -> bool {
        matches!(self.primary, Primary::Automatic) && self.maximum.is_none()
    }

    /// Prefer a finite strictly positive additive step on a linear numeric axis.
    pub fn additive(step: f64) -> Result<Self> {
        if !step.is_finite() || step <= 0.0 {
            return Err(Error::Data(
                "tick interval must be finite and strictly positive".into(),
            ));
        }
        Ok(Self {
            primary: Primary::Interval {
                step,
                origin: 0.0,
                space: TickSpace::Data,
                requirement: TickRequirement::Preferred,
                binding: IntervalBinding::Linear,
            },
            maximum: None,
        })
    }

    /// Prefer a nonzero integral exponent step on a base-ten logarithmic axis.
    pub fn log10_decades(decades: u32) -> Result<Self> {
        if decades == 0 {
            return Err(Error::Data(
                "tick interval decades must be strictly positive".into(),
            ));
        }
        Ok(Self {
            primary: Primary::Interval {
                step: f64::from(decades),
                origin: 0.0,
                space: TickSpace::Scale,
                requirement: TickRequirement::Preferred,
                binding: IntervalBinding::Log10,
            },
            maximum: None,
        })
    }

    /// Select a finite positive interval and finite origin in the declared space.
    pub fn interval(
        step: f64,
        origin: f64,
        space: TickSpace,
        requirement: TickRequirement,
    ) -> Result<Self> {
        if !step.is_finite() || step <= 0.0 || !origin.is_finite() {
            return Err(Error::Data(
                "tick interval needs a finite positive step and finite origin".into(),
            ));
        }
        Ok(Self {
            primary: Primary::Interval {
                step,
                origin: if origin == 0.0 { 0.0 } else { origin },
                space,
                requirement,
                binding: IntervalBinding::Context,
            },
            maximum: None,
        })
    }

    /// Inspect the retained step, origin, coordinate space and source requirement.
    pub const fn interval_parameters(&self) -> Option<(f64, f64, TickSpace, TickRequirement)> {
        if let Primary::Interval {
            step,
            origin,
            space,
            requirement,
            ..
        } = self.primary
        {
            Some((step, origin, space, requirement))
        } else {
            None
        }
    }

    /// Select the positive anchored geometric lattice, retaining either ratio direction.
    pub fn multiplicative(anchor: f64, ratio: f64, requirement: TickRequirement) -> Result<Self> {
        if !anchor.is_finite()
            || anchor <= 0.0
            || !ratio.is_finite()
            || ratio <= 0.0
            || ratio.to_bits() == 1.0_f64.to_bits()
        {
            return Err(Error::Data("multiplicative ticks require a finite positive anchor and positive ratio other than one".into()));
        }
        Ok(Self {
            primary: Primary::Multiplicative {
                anchor,
                ratio,
                requirement,
            },
            maximum: None,
        })
    }

    /// Inspect the supplied anchor, ratio direction and complete-source requirement.
    pub const fn multiplicative_parameters(&self) -> Option<(f64, f64, TickRequirement)> {
        if let Primary::Multiplicative {
            anchor,
            ratio,
            requirement,
        } = self.primary
        {
            Some((anchor, ratio, requirement))
        } else {
            None
        }
    }

    pub(crate) fn validate_scale(&self, log: bool) -> Result<()> {
        if let Primary::Interval { binding, .. } = self.primary {
            if (binding == IntervalBinding::Linear && log)
                || (binding == IntervalBinding::Log10 && !log)
            {
                return Err(Error::Data(
                    "tick interval does not match the axis scale".into(),
                ));
            }
        }
        Ok(())
    }

    /// Request approximately `count` numeric positions, allowing nice-step deviation.
    ///
    /// Counts must be positive; one requests the original-domain midpoint.
    /// Actual label fit can select a coarser complete source.
    pub fn target(count: usize) -> Result<Self> {
        Self::validate_count(count)?;
        Ok(Self {
            primary: Primary::Target(count),
            maximum: None,
        })
    }

    /// Bound generated in-domain positions, including endpoints, by `count`.
    ///
    /// Counts must be positive. The bound applies to complete generated
    /// sources, not exact caller ticks; it never drops individual labels.
    pub fn maximum(count: usize) -> Result<Self> {
        Self::validate_count(count)?;
        Ok(Self {
            primary: Primary::Automatic,
            maximum: Some(count),
        })
    }

    fn validate_count(count: usize) -> Result<()> {
        if count == 0 {
            return Err(Error::Data("generated tick count must be positive".into()));
        }
        Ok(())
    }

    /// Inspect the target count, or None for another selection.
    pub const fn target_count(&self) -> Option<usize> {
        match self.primary {
            Primary::Target(count) => Some(count),
            _ => None,
        }
    }

    /// Inspect the hard maximum count, or None for another selection.
    pub const fn get_maximum_count(&self) -> Option<usize> {
        self.maximum
    }

    /// Set or clear the positive generated cap, without replacing the locator.
    pub fn maximum_count(mut self, maximum: Option<usize>) -> Result<Self> {
        if let Some(maximum) = maximum {
            Self::validate_count(maximum)?;
            if self
                .exact_parameters()
                .is_some_and(|(count, _, _)| count > maximum)
            {
                return Err(Error::Data(
                    "exact tick count exceeds the generated maximum".into(),
                ));
            }
        }
        self.maximum = maximum;
        Ok(self)
    }

    /// Generate exactly count positions; zero is empty and one initially uses Lower.
    pub const fn exact_count(count: usize, space: TickSpace) -> Self {
        Self {
            primary: Primary::ExactCount {
                count,
                space,
                singleton: TickSingleton::Lower,
            },
            maximum: None,
        }
    }

    /// Set exact-count singleton placement, retaining the complete request for n>=2.
    pub fn singleton(mut self, position: TickSingleton) -> Result<Self> {
        if let TickSingleton::Position(value) = position {
            if !value.is_finite() {
                return Err(Error::Data("tick singleton must be finite".into()));
            }
        }
        let Primary::ExactCount { singleton, .. } = &mut self.primary else {
            return Err(Error::Data(
                "singleton placement requires an exact-count locator".into(),
            ));
        };
        *singleton = position;
        Ok(self)
    }

    pub(crate) const fn exact_parameters(&self) -> Option<(usize, TickSpace, TickSingleton)> {
        if let Primary::ExactCount {
            count,
            space,
            singleton,
        } = self.primary
        {
            Some((count, space, singleton))
        } else {
            None
        }
    }

    pub(crate) const fn is_interval(&self) -> bool {
        matches!(self.primary, Primary::Interval { .. })
    }

    pub(crate) fn observe_feedback(
        &self,
        round: &mut crate::layout::kernel::FeedbackRound,
    ) -> Result<()> {
        round.observe_count(self.maximum.unwrap_or(0))?;
        match &self.primary {
            Primary::Automatic => round.observe_count(0),
            Primary::Function(function) => {
                round.observe_count(6)?;
                round.observe_position_function(function)
            }
            Primary::Interval {
                step,
                origin,
                space,
                requirement,
                binding,
            } => {
                round.observe_count(1)?;
                round.observe_count(*binding as usize)?;
                round.observe_number(*origin)?;
                round.observe_count(*space as usize)?;
                round.observe_count(*requirement as usize)?;
                round.observe_number(*step)
            }
            Primary::Target(count) => {
                round.observe_count(3)?;
                round.observe_count(*count)
            }
            Primary::Multiplicative {
                anchor,
                ratio,
                requirement,
            } => {
                round.observe_count(5)?;
                round.observe_number(*anchor)?;
                round.observe_number(*ratio)?;
                round.observe_count(*requirement as usize)
            }
            Primary::ExactCount {
                count,
                space,
                singleton,
            } => {
                round.observe_count(4)?;
                round.observe_count(*count)?;
                round.observe_count(*space as usize)?;
                match singleton {
                    TickSingleton::Lower => round.observe_count(0),
                    TickSingleton::Midpoint => round.observe_count(1),
                    TickSingleton::Upper => round.observe_count(2),
                    TickSingleton::Position(value) => {
                        round.observe_count(3)?;
                        round.observe_count(usize::from(value.is_sign_negative()))?;
                        round.observe_number(*value)
                    }
                }
            }
        }
    }

    /// Inspect the positive additive step, or None for another selection.
    pub const fn additive_step(&self) -> Option<f64> {
        match self.primary {
            Primary::Interval {
                step,
                binding: IntervalBinding::Linear,
                ..
            } => Some(step),
            _ => None,
        }
    }

    /// Inspect the positive integral decade step, or None for another selection.
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "Log10 binding is constructed only from a nonzero exactly represented u32"
    )]
    pub const fn decade_step(&self) -> Option<u32> {
        match self.primary {
            Primary::Interval {
                step,
                binding: IntervalBinding::Log10,
                ..
            } => Some(step as u32),
            _ => None,
        }
    }
}