Skip to main content

crisol_plot_core/
axis.rs

1//! Bounds, axis scales, the data ↔ screen transform, and tick generation.
2
3pub use crisol_core::data::Bounds;
4
5/// How values map onto an axis.
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
9#[non_exhaustive]
10pub enum Scale {
11    /// Evenly spaced values.
12    #[default]
13    Linear,
14    /// Decades evenly spaced; values ≤ 0 are not drawn.
15    Log10,
16    /// A signed log scale: zero is the origin and both signs expand logarithmically.
17    SymmetricLog,
18    /// Seconds since the Unix epoch, formatted as calendar tick labels in UTC.
19    Time,
20    /// Evenly spaced category indices, labeled from the axis configuration's categories.
21    Category,
22}
23
24/// How many minor ticks sit between two major ticks.
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum Minor {
29    /// Chosen from the space between majors (5, 2, or none); 2…9 per decade on log axes.
30    #[default]
31    Auto,
32    /// No minor ticks.
33    Off,
34    /// This many subdivisions per major interval (2 = one minor tick in the middle).
35    Divisions(u8),
36}
37
38impl Scale {
39    /// Map a data value into scaled space.
40    pub fn forward(self, value: f64) -> f64 {
41        match self {
42            Self::Linear => value,
43            Self::Log10 => {
44                if value > 0.0 {
45                    value.log10()
46                } else {
47                    f64::NAN
48                }
49            }
50            Self::SymmetricLog => value.signum() * (1.0 + value.abs()).log10(),
51            Self::Time | Self::Category => value,
52        }
53    }
54
55    /// Map a scaled value back into data space.
56    pub fn inverse(self, value: f64) -> f64 {
57        match self {
58            Self::Linear | Self::Time | Self::Category => value,
59            Self::Log10 => 10f64.powf(value),
60            Self::SymmetricLog => value.signum() * (10f64.powf(value.abs()) - 1.0),
61        }
62    }
63}
64
65/// One tick: its position in scaled space, its label, and whether it is a major tick.
66#[derive(Clone, Debug, PartialEq)]
67pub struct Tick {
68    /// Position in scaled space.
69    pub value: f64,
70    /// The formatted label (empty for unlabeled minors).
71    pub label: String,
72    /// Whether the tick gets a label and a major grid line.
73    pub major: bool,
74}
75
76/// Overrides for tick placement, from the plot axis configuration.
77#[derive(Clone, Debug, Default, PartialEq)]
78pub struct TickRules<'a> {
79    /// Fixed major step (decades on log axes).
80    pub step: Option<f64>,
81    /// Minor ticks between majors.
82    pub minor: Minor,
83    /// Decimals of the labels; from the step when `None`.
84    pub decimals: Option<u8>,
85    /// Category labels.
86    pub categories: Option<&'a [String]>,
87}
88
89/// "Nice" ticks (1, 2, 5 × 10ⁿ) in `[min, max]` (scaled space), about `pixels / spacing`
90/// of them, with labels formatted to the step's precision, plus minor ticks.
91pub fn ticks<'a>(scale: Scale, min: f64, max: f64, pixels: f32, spacing: f32, rules: TickRules<'a>) -> Vec<Tick> {
92    if max <= min || !min.is_finite() || !max.is_finite() || !(max - min).is_finite() {
93        return Vec::new();
94    }
95    let target = f64::from((pixels / spacing).max(2.0));
96    match scale {
97        Scale::Linear => linear_ticks(min, max, target, pixels, rules),
98        Scale::Log10 => log_ticks(min, max, target, rules),
99        Scale::SymmetricLog => symmetric_log_ticks(min, max, target, pixels, rules),
100        Scale::Time => time_ticks(min, max, target, rules),
101        Scale::Category => category_ticks(min, max, rules),
102    }
103}
104
105/// The nice step for a span split into about `target` intervals.
106pub fn nice_step(span: f64, target: f64) -> f64 {
107    if !span.is_finite() || span <= 0.0 || !target.is_finite() {
108        return 1.0;
109    }
110    let raw = (span / target.max(1.0)).max(f64::MIN_POSITIVE);
111    let magnitude = 10f64.powf(raw.log10().floor()).max(f64::MIN_POSITIVE);
112    let residual = raw / magnitude;
113    let nice = if residual <= 1.0 {
114        1.0
115    } else if residual <= 2.0 {
116        2.0
117    } else if residual <= 5.0 {
118        5.0
119    } else {
120        10.0
121    };
122    let step = nice * magnitude;
123    if step.is_finite() && step > 0.0 { step } else { raw }
124}
125
126fn symmetric_log_ticks(min: f64, max: f64, target: f64, pixels: f32, rules: TickRules<'_>) -> Vec<Tick> {
127    let decimals = rules.decimals.unwrap_or(3) as usize;
128    let mut ticks = linear_ticks(min, max, target, pixels, rules);
129    for tick in &mut ticks {
130        let value = Scale::SymmetricLog.inverse(tick.value);
131        tick.label = format_number(value, decimals);
132    }
133    ticks
134}
135
136fn time_ticks(min: f64, max: f64, target: f64, rules: TickRules<'_>) -> Vec<Tick> {
137    let span = max - min;
138    let step = rules
139        .step
140        .filter(|step| *step > 0.0 && span / *step <= 500.0)
141        .unwrap_or_else(|| nice_time_step(span, target));
142    let first = (min / step).ceil() as i64;
143    let last = (max / step).floor() as i64;
144    let Some(count) = last.checked_sub(first) else {
145        return Vec::new();
146    };
147    if count > 1000 {
148        return Vec::new();
149    }
150    let mut ticks = Vec::new();
151    for index in first..=last {
152        let value = index as f64 * step;
153        ticks.push(Tick {
154            value,
155            label: format_timestamp(value, span),
156            major: true,
157        });
158    }
159    ticks
160}
161
162fn nice_time_step(span: f64, target: f64) -> f64 {
163    const STEPS: [f64; 19] = [
164        1.0,
165        2.0,
166        5.0,
167        10.0,
168        15.0,
169        30.0,
170        60.0,
171        300.0,
172        900.0,
173        1800.0,
174        3600.0,
175        10_800.0,
176        21_600.0,
177        43_200.0,
178        86_400.0,
179        172_800.0,
180        604_800.0,
181        2_592_000.0,
182        31_536_000.0,
183    ];
184    let ideal = span / target.max(1.0);
185    STEPS
186        .iter()
187        .copied()
188        .find(|step| *step >= ideal)
189        .unwrap_or(31_536_000.0)
190}
191
192fn format_timestamp(seconds: f64, span: f64) -> String {
193    let Some(time) = jiff::Timestamp::from_second(seconds as i64).ok() else {
194        return format_number(seconds, 0);
195    };
196    let format = if span >= 2.0 * 86_400.0 {
197        "%Y-%m-%d"
198    } else if span >= 86_400.0 {
199        "%m-%d %H:%M"
200    } else if span >= 3_600.0 {
201        "%H:%M"
202    } else {
203        "%H:%M:%S"
204    };
205    time.strftime(format).to_string()
206}
207
208fn format_number(value: f64, decimals: usize) -> String {
209    if decimals == 0 {
210        format!("{value:.0}")
211    } else {
212        format!("{value:.decimals$}")
213    }
214}
215
216fn category_ticks(min: f64, max: f64, rules: TickRules<'_>) -> Vec<Tick> {
217    let first = min.floor().max(0.0) as usize;
218    let last = max.ceil().max(0.0) as usize;
219    if last.saturating_sub(first) > 500 {
220        return Vec::new();
221    }
222    (first..=last)
223        .map(|index| Tick {
224            value: index as f64,
225            label: rules
226                .categories
227                .and_then(|categories| categories.get(index))
228                .cloned()
229                .unwrap_or_else(|| index.to_string()),
230            major: true,
231        })
232        .collect()
233}
234
235fn linear_ticks(min: f64, max: f64, target: f64, pixels: f32, rules: TickRules<'_>) -> Vec<Tick> {
236    let auto = nice_step(max - min, target);
237    // A fixed step that would draw thousands of ticks falls back to the automatic one.
238    let step = rules.step.filter(|step| (max - min) / step <= 500.0).unwrap_or(auto);
239    if !step.is_finite() || step <= 0.0 {
240        return Vec::new();
241    }
242    let decimals = rules
243        .decimals
244        .map_or_else(|| (-step.log10().floor()).max(0.0) as usize, usize::from)
245        .min(15);
246    let first = (min / step).ceil() as i64;
247    let last = (max / step).floor() as i64;
248    let Some(count) = last.checked_sub(first) else {
249        return Vec::new();
250    };
251    if count > 1000 {
252        return Vec::new();
253    }
254    let mut ticks: Vec<Tick> = (first..=last)
255        .map(|index| {
256            let value = index as f64 * step;
257            Tick {
258                value,
259                label: format_value(value, decimals, step),
260                major: true,
261            }
262        })
263        .collect();
264    let per_major = (step / (max - min)) as f32 * pixels;
265    let divisions = match rules.minor {
266        Minor::Off => 0,
267        Minor::Divisions(divisions) => u32::from(divisions),
268        Minor::Auto => {
269            // 4 subdivisions for 2-steps, 5 otherwise; fewer when they would crowd.
270            let digit = (step / 10f64.powf(step.log10().floor())).round();
271            let preferred = if digit == 2.0 { 4 } else { 5 };
272            [preferred, 2]
273                .into_iter()
274                .find(|divisions| per_major / *divisions as f32 >= 8.0)
275                .unwrap_or(0)
276        }
277    };
278    if divisions > 1
279        && count
280            .checked_add(2)
281            .and_then(|count| count.checked_mul(i64::from(divisions)))
282            .is_some_and(|count| count <= 4000)
283    {
284        for index in first.saturating_sub(1)..=last {
285            for part in 1..divisions {
286                let value = (index as f64 + f64::from(part) / f64::from(divisions)) * step;
287                if (min..=max).contains(&value) {
288                    ticks.push(Tick {
289                        value,
290                        label: String::new(),
291                        major: false,
292                    });
293                }
294            }
295        }
296    }
297    ticks
298}
299
300fn log_ticks(min: f64, max: f64, target: f64, rules: TickRules) -> Vec<Tick> {
301    // Decades are majors (every n-th labeled when crowded; the others keep their grid
302    // line); 2…9 are minors when there is room for them.
303    let first = min.floor() as i64;
304    let last = max.ceil() as i64;
305    let Some(count) = last.checked_sub(first) else {
306        return Vec::new();
307    };
308    if count > 300 {
309        return Vec::new();
310    }
311    let decades = count.max(1) as f64;
312    let every = rules.step.map_or_else(
313        || (decades / target).ceil().max(1.0) as i64,
314        |step| step.round().max(1.0) as i64,
315    );
316    let minors = match rules.minor {
317        Minor::Off => false,
318        Minor::Divisions(_) => true,
319        Minor::Auto => decades * 3.0 <= target,
320    };
321    // One notation for the whole axis: plain numbers only when every label is short.
322    let plain = min.ceil() >= -3.0 && max.floor() <= 4.0;
323    let mut ticks = Vec::new();
324    for exponent in first..=last {
325        let value = exponent as f64;
326        if (min..=max).contains(&value) {
327            let labeled = exponent.rem_euclid(every) == 0;
328            ticks.push(Tick {
329                value,
330                label: if labeled {
331                    format_power(exponent, plain)
332                } else {
333                    String::new()
334                },
335                major: labeled,
336            });
337        }
338        if minors {
339            for factor in 2..=9 {
340                let value = exponent as f64 + f64::from(factor).log10();
341                if (min..=max).contains(&value) {
342                    ticks.push(Tick {
343                        value,
344                        label: String::new(),
345                        major: false,
346                    });
347                }
348            }
349        }
350    }
351    ticks
352}
353
354fn format_power(exponent: i64, plain: bool) -> String {
355    if !plain {
356        return format!("1e{exponent}");
357    }
358    if exponent < 0 {
359        format!("{:.*}", exponent.unsigned_abs() as usize, 10f64.powi(exponent as i32))
360    } else {
361        10i64.pow(exponent as u32).to_string()
362    }
363}
364
365/// A value at the precision of `step`, switching to scientific notation for very large
366/// or very small magnitudes. `-0` prints as `0`.
367pub fn format_value(value: f64, decimals: usize, step: f64) -> String {
368    let decimals = decimals.min(15);
369    if value.abs() < step * 1e-9 {
370        // Same precision as its neighbors: "0.0" next to "0.2", never "-0".
371        return format!("{:.decimals$}", 0.0);
372    }
373    let magnitude = value.abs();
374    if magnitude >= 1e6 || (magnitude < 1e-4 && magnitude > 0.0) {
375        let digits = (step.abs().log10().floor() - magnitude.log10().floor()).abs().min(6.0) as usize;
376        return format!("{value:.digits$e}");
377    }
378    format!("{value:.decimals$}")
379}
380
381/// A readable value for tooltips: about 4 significant digits.
382pub fn format_readout(value: f64) -> String {
383    if !value.is_finite() {
384        return value.to_string();
385    }
386    let magnitude = value.abs();
387    if magnitude != 0.0 && !(1e-3..1e6).contains(&magnitude) {
388        return format!("{value:.3e}");
389    }
390    let decimals = if magnitude == 0.0 {
391        0
392    } else {
393        (3 - magnitude.log10().floor() as i32).clamp(0, 6) as usize
394    };
395    let text = format!("{value:.decimals$}");
396    if text.contains('.') {
397        text.trim_end_matches('0').trim_end_matches('.').to_owned()
398    } else {
399        text
400    }
401}
402
403#[cfg(test)]
404mod tests;