crisol-plot-core 1.16.1

Crisol plot core: the egui-free math behind the plot, axis ticks, analysis, filters, and decimation.
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
//! Bounds, axis scales, the data ↔ screen transform, and tick generation.

pub use crisol_core::data::Bounds;

/// How values map onto an axis.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Scale {
    /// Evenly spaced values.
    #[default]
    Linear,
    /// Decades evenly spaced; values ≤ 0 are not drawn.
    Log10,
    /// A signed log scale: zero is the origin and both signs expand logarithmically.
    SymmetricLog,
    /// Seconds since the Unix epoch, formatted as calendar tick labels in UTC.
    Time,
    /// Evenly spaced category indices, labeled from the axis configuration's categories.
    Category,
}

/// How many minor ticks sit between two major ticks.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Minor {
    /// Chosen from the space between majors (5, 2, or none); 2…9 per decade on log axes.
    #[default]
    Auto,
    /// No minor ticks.
    Off,
    /// This many subdivisions per major interval (2 = one minor tick in the middle).
    Divisions(u8),
}

impl Scale {
    /// Map a data value into scaled space.
    pub fn forward(self, value: f64) -> f64 {
        match self {
            Self::Linear => value,
            Self::Log10 => {
                if value > 0.0 {
                    value.log10()
                } else {
                    f64::NAN
                }
            }
            Self::SymmetricLog => value.signum() * (1.0 + value.abs()).log10(),
            Self::Time | Self::Category => value,
        }
    }

    /// Map a scaled value back into data space.
    pub fn inverse(self, value: f64) -> f64 {
        match self {
            Self::Linear | Self::Time | Self::Category => value,
            Self::Log10 => 10f64.powf(value),
            Self::SymmetricLog => value.signum() * (10f64.powf(value.abs()) - 1.0),
        }
    }
}

/// One tick: its position in scaled space, its label, and whether it is a major tick.
#[derive(Clone, Debug, PartialEq)]
pub struct Tick {
    /// Position in scaled space.
    pub value: f64,
    /// The formatted label (empty for unlabeled minors).
    pub label: String,
    /// Whether the tick gets a label and a major grid line.
    pub major: bool,
}

/// Overrides for tick placement, from the plot axis configuration.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TickRules<'a> {
    /// Fixed major step (decades on log axes).
    pub step: Option<f64>,
    /// Minor ticks between majors.
    pub minor: Minor,
    /// Decimals of the labels; from the step when `None`.
    pub decimals: Option<u8>,
    /// Category labels.
    pub categories: Option<&'a [String]>,
}

/// "Nice" ticks (1, 2, 5 × 10ⁿ) in `[min, max]` (scaled space), about `pixels / spacing`
/// of them, with labels formatted to the step's precision, plus minor ticks.
pub fn ticks<'a>(scale: Scale, min: f64, max: f64, pixels: f32, spacing: f32, rules: TickRules<'a>) -> Vec<Tick> {
    if max <= min || !min.is_finite() || !max.is_finite() || !(max - min).is_finite() {
        return Vec::new();
    }
    let target = f64::from((pixels / spacing).max(2.0));
    match scale {
        Scale::Linear => linear_ticks(min, max, target, pixels, rules),
        Scale::Log10 => log_ticks(min, max, target, rules),
        Scale::SymmetricLog => symmetric_log_ticks(min, max, target, pixels, rules),
        Scale::Time => time_ticks(min, max, target, rules),
        Scale::Category => category_ticks(min, max, rules),
    }
}

/// The nice step for a span split into about `target` intervals.
pub fn nice_step(span: f64, target: f64) -> f64 {
    if !span.is_finite() || span <= 0.0 || !target.is_finite() {
        return 1.0;
    }
    let raw = (span / target.max(1.0)).max(f64::MIN_POSITIVE);
    let magnitude = 10f64.powf(raw.log10().floor()).max(f64::MIN_POSITIVE);
    let residual = raw / magnitude;
    let nice = if residual <= 1.0 {
        1.0
    } else if residual <= 2.0 {
        2.0
    } else if residual <= 5.0 {
        5.0
    } else {
        10.0
    };
    let step = nice * magnitude;
    if step.is_finite() && step > 0.0 { step } else { raw }
}

fn symmetric_log_ticks(min: f64, max: f64, target: f64, pixels: f32, rules: TickRules<'_>) -> Vec<Tick> {
    let decimals = rules.decimals.unwrap_or(3) as usize;
    let mut ticks = linear_ticks(min, max, target, pixels, rules);
    for tick in &mut ticks {
        let value = Scale::SymmetricLog.inverse(tick.value);
        tick.label = format_number(value, decimals);
    }
    ticks
}

fn time_ticks(min: f64, max: f64, target: f64, rules: TickRules<'_>) -> Vec<Tick> {
    let span = max - min;
    let step = rules
        .step
        .filter(|step| *step > 0.0 && span / *step <= 500.0)
        .unwrap_or_else(|| nice_time_step(span, target));
    let first = (min / step).ceil() as i64;
    let last = (max / step).floor() as i64;
    let Some(count) = last.checked_sub(first) else {
        return Vec::new();
    };
    if count > 1000 {
        return Vec::new();
    }
    let mut ticks = Vec::new();
    for index in first..=last {
        let value = index as f64 * step;
        ticks.push(Tick {
            value,
            label: format_timestamp(value, span),
            major: true,
        });
    }
    ticks
}

fn nice_time_step(span: f64, target: f64) -> f64 {
    const STEPS: [f64; 19] = [
        1.0,
        2.0,
        5.0,
        10.0,
        15.0,
        30.0,
        60.0,
        300.0,
        900.0,
        1800.0,
        3600.0,
        10_800.0,
        21_600.0,
        43_200.0,
        86_400.0,
        172_800.0,
        604_800.0,
        2_592_000.0,
        31_536_000.0,
    ];
    let ideal = span / target.max(1.0);
    STEPS
        .iter()
        .copied()
        .find(|step| *step >= ideal)
        .unwrap_or(31_536_000.0)
}

fn format_timestamp(seconds: f64, span: f64) -> String {
    let Some(time) = jiff::Timestamp::from_second(seconds as i64).ok() else {
        return format_number(seconds, 0);
    };
    let format = if span >= 2.0 * 86_400.0 {
        "%Y-%m-%d"
    } else if span >= 86_400.0 {
        "%m-%d %H:%M"
    } else if span >= 3_600.0 {
        "%H:%M"
    } else {
        "%H:%M:%S"
    };
    time.strftime(format).to_string()
}

fn format_number(value: f64, decimals: usize) -> String {
    if decimals == 0 {
        format!("{value:.0}")
    } else {
        format!("{value:.decimals$}")
    }
}

fn category_ticks(min: f64, max: f64, rules: TickRules<'_>) -> Vec<Tick> {
    let first = min.floor().max(0.0) as usize;
    let last = max.ceil().max(0.0) as usize;
    if last.saturating_sub(first) > 500 {
        return Vec::new();
    }
    (first..=last)
        .map(|index| Tick {
            value: index as f64,
            label: rules
                .categories
                .and_then(|categories| categories.get(index))
                .cloned()
                .unwrap_or_else(|| index.to_string()),
            major: true,
        })
        .collect()
}

fn linear_ticks(min: f64, max: f64, target: f64, pixels: f32, rules: TickRules<'_>) -> Vec<Tick> {
    let auto = nice_step(max - min, target);
    // A fixed step that would draw thousands of ticks falls back to the automatic one.
    let step = rules.step.filter(|step| (max - min) / step <= 500.0).unwrap_or(auto);
    if !step.is_finite() || step <= 0.0 {
        return Vec::new();
    }
    let decimals = rules
        .decimals
        .map_or_else(|| (-step.log10().floor()).max(0.0) as usize, usize::from)
        .min(15);
    let first = (min / step).ceil() as i64;
    let last = (max / step).floor() as i64;
    let Some(count) = last.checked_sub(first) else {
        return Vec::new();
    };
    if count > 1000 {
        return Vec::new();
    }
    let mut ticks: Vec<Tick> = (first..=last)
        .map(|index| {
            let value = index as f64 * step;
            Tick {
                value,
                label: format_value(value, decimals, step),
                major: true,
            }
        })
        .collect();
    let per_major = (step / (max - min)) as f32 * pixels;
    let divisions = match rules.minor {
        Minor::Off => 0,
        Minor::Divisions(divisions) => u32::from(divisions),
        Minor::Auto => {
            // 4 subdivisions for 2-steps, 5 otherwise; fewer when they would crowd.
            let digit = (step / 10f64.powf(step.log10().floor())).round();
            let preferred = if digit == 2.0 { 4 } else { 5 };
            [preferred, 2]
                .into_iter()
                .find(|divisions| per_major / *divisions as f32 >= 8.0)
                .unwrap_or(0)
        }
    };
    if divisions > 1
        && count
            .checked_add(2)
            .and_then(|count| count.checked_mul(i64::from(divisions)))
            .is_some_and(|count| count <= 4000)
    {
        for index in first.saturating_sub(1)..=last {
            for part in 1..divisions {
                let value = (index as f64 + f64::from(part) / f64::from(divisions)) * step;
                if (min..=max).contains(&value) {
                    ticks.push(Tick {
                        value,
                        label: String::new(),
                        major: false,
                    });
                }
            }
        }
    }
    ticks
}

fn log_ticks(min: f64, max: f64, target: f64, rules: TickRules) -> Vec<Tick> {
    // Decades are majors (every n-th labeled when crowded; the others keep their grid
    // line); 2…9 are minors when there is room for them.
    let first = min.floor() as i64;
    let last = max.ceil() as i64;
    let Some(count) = last.checked_sub(first) else {
        return Vec::new();
    };
    if count > 300 {
        return Vec::new();
    }
    let decades = count.max(1) as f64;
    let every = rules.step.map_or_else(
        || (decades / target).ceil().max(1.0) as i64,
        |step| step.round().max(1.0) as i64,
    );
    let minors = match rules.minor {
        Minor::Off => false,
        Minor::Divisions(_) => true,
        Minor::Auto => decades * 3.0 <= target,
    };
    // One notation for the whole axis: plain numbers only when every label is short.
    let plain = min.ceil() >= -3.0 && max.floor() <= 4.0;
    let mut ticks = Vec::new();
    for exponent in first..=last {
        let value = exponent as f64;
        if (min..=max).contains(&value) {
            let labeled = exponent.rem_euclid(every) == 0;
            ticks.push(Tick {
                value,
                label: if labeled {
                    format_power(exponent, plain)
                } else {
                    String::new()
                },
                major: labeled,
            });
        }
        if minors {
            for factor in 2..=9 {
                let value = exponent as f64 + f64::from(factor).log10();
                if (min..=max).contains(&value) {
                    ticks.push(Tick {
                        value,
                        label: String::new(),
                        major: false,
                    });
                }
            }
        }
    }
    ticks
}

fn format_power(exponent: i64, plain: bool) -> String {
    if !plain {
        return format!("1e{exponent}");
    }
    if exponent < 0 {
        format!("{:.*}", exponent.unsigned_abs() as usize, 10f64.powi(exponent as i32))
    } else {
        10i64.pow(exponent as u32).to_string()
    }
}

/// A value at the precision of `step`, switching to scientific notation for very large
/// or very small magnitudes. `-0` prints as `0`.
pub fn format_value(value: f64, decimals: usize, step: f64) -> String {
    let decimals = decimals.min(15);
    if value.abs() < step * 1e-9 {
        // Same precision as its neighbors: "0.0" next to "0.2", never "-0".
        return format!("{:.decimals$}", 0.0);
    }
    let magnitude = value.abs();
    if magnitude >= 1e6 || (magnitude < 1e-4 && magnitude > 0.0) {
        let digits = (step.abs().log10().floor() - magnitude.log10().floor()).abs().min(6.0) as usize;
        return format!("{value:.digits$e}");
    }
    format!("{value:.decimals$}")
}

/// A readable value for tooltips: about 4 significant digits.
pub fn format_readout(value: f64) -> String {
    if !value.is_finite() {
        return value.to_string();
    }
    let magnitude = value.abs();
    if magnitude != 0.0 && !(1e-3..1e6).contains(&magnitude) {
        return format!("{value:.3e}");
    }
    let decimals = if magnitude == 0.0 {
        0
    } else {
        (3 - magnitude.log10().floor() as i32).clamp(0, 6) as usize
    };
    let text = format!("{value:.decimals$}");
    if text.contains('.') {
        text.trim_end_matches('0').trim_end_matches('.').to_owned()
    } else {
        text
    }
}

#[cfg(test)]
mod tests;