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