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() {
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    if last - first > 1000 {
145        return Vec::new();
146    }
147    let mut ticks = Vec::new();
148    for index in first..=last {
149        let value = index as f64 * step;
150        ticks.push(Tick {
151            value,
152            label: format_timestamp(value, span),
153            major: true,
154        });
155    }
156    ticks
157}
158
159fn nice_time_step(span: f64, target: f64) -> f64 {
160    const STEPS: [f64; 19] = [
161        1.0,
162        2.0,
163        5.0,
164        10.0,
165        15.0,
166        30.0,
167        60.0,
168        300.0,
169        900.0,
170        1800.0,
171        3600.0,
172        10_800.0,
173        21_600.0,
174        43_200.0,
175        86_400.0,
176        172_800.0,
177        604_800.0,
178        2_592_000.0,
179        31_536_000.0,
180    ];
181    let ideal = span / target.max(1.0);
182    STEPS
183        .iter()
184        .copied()
185        .find(|step| *step >= ideal)
186        .unwrap_or(31_536_000.0)
187}
188
189fn format_timestamp(seconds: f64, span: f64) -> String {
190    let Some(time) = jiff::Timestamp::from_second(seconds as i64).ok() else {
191        return format_number(seconds, 0);
192    };
193    let format = if span >= 2.0 * 86_400.0 {
194        "%Y-%m-%d"
195    } else if span >= 86_400.0 {
196        "%m-%d %H:%M"
197    } else if span >= 3_600.0 {
198        "%H:%M"
199    } else {
200        "%H:%M:%S"
201    };
202    time.strftime(format).to_string()
203}
204
205fn format_number(value: f64, decimals: usize) -> String {
206    if decimals == 0 {
207        format!("{value:.0}")
208    } else {
209        format!("{value:.decimals$}")
210    }
211}
212
213fn category_ticks(min: f64, max: f64, rules: TickRules<'_>) -> Vec<Tick> {
214    let first = min.floor().max(0.0) as usize;
215    let last = max.ceil().max(0.0) as usize;
216    if last.saturating_sub(first) > 500 {
217        return Vec::new();
218    }
219    (first..=last)
220        .map(|index| Tick {
221            value: index as f64,
222            label: rules
223                .categories
224                .and_then(|categories| categories.get(index))
225                .cloned()
226                .unwrap_or_else(|| index.to_string()),
227            major: true,
228        })
229        .collect()
230}
231
232fn linear_ticks(min: f64, max: f64, target: f64, pixels: f32, rules: TickRules<'_>) -> Vec<Tick> {
233    let auto = nice_step(max - min, target);
234    // A fixed step that would draw thousands of ticks falls back to the automatic one.
235    let step = rules.step.filter(|step| (max - min) / step <= 500.0).unwrap_or(auto);
236    if !step.is_finite() || step <= 0.0 {
237        return Vec::new();
238    }
239    let decimals = rules
240        .decimals
241        .map_or_else(|| (-step.log10().floor()).max(0.0) as usize, usize::from)
242        .min(15);
243    let first = (min / step).ceil() as i64;
244    let last = (max / step).floor() as i64;
245    if last - first > 1000 {
246        return Vec::new();
247    }
248    let mut ticks: Vec<Tick> = (first..=last)
249        .map(|index| {
250            let value = index as f64 * step;
251            Tick {
252                value,
253                label: format_value(value, decimals, step),
254                major: true,
255            }
256        })
257        .collect();
258    let per_major = (step / (max - min)) as f32 * pixels;
259    let divisions = match rules.minor {
260        Minor::Off => 0,
261        Minor::Divisions(divisions) => u32::from(divisions),
262        Minor::Auto => {
263            // 4 subdivisions for 2-steps, 5 otherwise; fewer when they would crowd.
264            let digit = (step / 10f64.powf(step.log10().floor())).round();
265            let preferred = if digit == 2.0 { 4 } else { 5 };
266            [preferred, 2]
267                .into_iter()
268                .find(|divisions| per_major / *divisions as f32 >= 8.0)
269                .unwrap_or(0)
270        }
271    };
272    if divisions > 1 && (last - first + 2) * i64::from(divisions) <= 4000 {
273        for index in first - 1..=last {
274            for part in 1..divisions {
275                let value = (index as f64 + f64::from(part) / f64::from(divisions)) * step;
276                if (min..=max).contains(&value) {
277                    ticks.push(Tick {
278                        value,
279                        label: String::new(),
280                        major: false,
281                    });
282                }
283            }
284        }
285    }
286    ticks
287}
288
289fn log_ticks(min: f64, max: f64, target: f64, rules: TickRules) -> Vec<Tick> {
290    // Decades are majors (every n-th labeled when crowded; the others keep their grid
291    // line); 2…9 are minors when there is room for them.
292    let first = min.floor() as i64;
293    let last = max.ceil() as i64;
294    if last - first > 300 {
295        return Vec::new();
296    }
297    let decades = (last - first).max(1) as f64;
298    let every = rules.step.map_or_else(
299        || (decades / target).ceil().max(1.0) as i64,
300        |step| step.round().max(1.0) as i64,
301    );
302    let minors = match rules.minor {
303        Minor::Off => false,
304        Minor::Divisions(_) => true,
305        Minor::Auto => decades * 3.0 <= target,
306    };
307    // One notation for the whole axis: plain numbers only when every label is short.
308    let plain = min.ceil() >= -3.0 && max.floor() <= 4.0;
309    let mut ticks = Vec::new();
310    for exponent in first..=last {
311        let value = exponent as f64;
312        if (min..=max).contains(&value) {
313            let labeled = exponent.rem_euclid(every) == 0;
314            ticks.push(Tick {
315                value,
316                label: if labeled {
317                    format_power(exponent, plain)
318                } else {
319                    String::new()
320                },
321                major: labeled,
322            });
323        }
324        if minors {
325            for factor in 2..=9 {
326                let value = exponent as f64 + f64::from(factor).log10();
327                if (min..=max).contains(&value) {
328                    ticks.push(Tick {
329                        value,
330                        label: String::new(),
331                        major: false,
332                    });
333                }
334            }
335        }
336    }
337    ticks
338}
339
340fn format_power(exponent: i64, plain: bool) -> String {
341    if !plain {
342        return format!("1e{exponent}");
343    }
344    if exponent < 0 {
345        format!("{:.*}", exponent.unsigned_abs() as usize, 10f64.powi(exponent as i32))
346    } else {
347        10i64.pow(exponent as u32).to_string()
348    }
349}
350
351/// A value at the precision of `step`, switching to scientific notation for very large
352/// or very small magnitudes. `-0` prints as `0`.
353pub fn format_value(value: f64, decimals: usize, step: f64) -> String {
354    let decimals = decimals.min(15);
355    if value.abs() < step * 1e-9 {
356        // Same precision as its neighbors: "0.0" next to "0.2", never "-0".
357        return format!("{:.decimals$}", 0.0);
358    }
359    let magnitude = value.abs();
360    if magnitude >= 1e6 || (magnitude < 1e-4 && magnitude > 0.0) {
361        let digits = (step.abs().log10().floor() - magnitude.log10().floor()).abs().min(6.0) as usize;
362        return format!("{value:.digits$e}");
363    }
364    format!("{value:.decimals$}")
365}
366
367/// A readable value for tooltips: about 4 significant digits.
368pub fn format_readout(value: f64) -> String {
369    if !value.is_finite() {
370        return value.to_string();
371    }
372    let magnitude = value.abs();
373    if magnitude != 0.0 && !(1e-3..1e6).contains(&magnitude) {
374        return format!("{value:.3e}");
375    }
376    let decimals = if magnitude == 0.0 {
377        0
378    } else {
379        (3 - magnitude.log10().floor() as i32).clamp(0, 6) as usize
380    };
381    let text = format!("{value:.decimals$}");
382    if text.contains('.') {
383        text.trim_end_matches('0').trim_end_matches('.').to_owned()
384    } else {
385        text
386    }
387}
388
389#[cfg(test)]
390mod tests;