Skip to main content

plotine_core/
scale.rs

1//! Continuous scales mapping data values into a normalized [0, 1] domain.
2
3use crate::error::{PlotError, Result};
4
5/// Mapping from data space to unit interval (and back).
6pub trait Scale: Clone {
7    fn domain(&self) -> (f64, f64);
8    fn normalize(&self, value: f64) -> f64;
9    fn denormalize(&self, unit: f64) -> f64;
10}
11
12/// Which continuous scale an axis uses.
13///
14/// Prefer setting the scale on axes **before** adding artists so auto-limits use
15/// the correct padding. Log domains must be strictly positive; use
16/// [`ScaleType::Symlog`] when data crosses zero.
17#[derive(Debug, Clone, Copy, PartialEq, Default)]
18#[non_exhaustive]
19pub enum ScaleType {
20    /// Identity mapping over `[min, max]` (default).
21    #[default]
22    Linear,
23    /// Base-10 logarithmic scale. Domain must be `> 0`.
24    Log,
25    /// Linear near zero within `±linthresh`, logarithmic outside.
26    Symlog {
27        /// Half-width of the linear region around zero (must be `> 0`).
28        linthresh: f64,
29    },
30}
31
32/// Type-erased scale used by the transform / tick pipeline.
33#[derive(Debug, Clone, Copy, PartialEq)]
34pub enum ScaleKind {
35    Linear(LinearScale),
36    Log(LogScale),
37    Symlog(SymlogScale),
38}
39
40impl ScaleKind {
41    pub fn build(scale_type: ScaleType, min: f64, max: f64) -> Result<Self> {
42        match scale_type {
43            ScaleType::Linear => Ok(Self::Linear(LinearScale::from_values(min, max)?)),
44            ScaleType::Log => Ok(Self::Log(LogScale::from_values(min, max)?)),
45            ScaleType::Symlog { linthresh } => {
46                Ok(Self::Symlog(SymlogScale::from_values(min, max, linthresh)?))
47            }
48        }
49    }
50
51    pub fn domain(self) -> (f64, f64) {
52        match self {
53            Self::Linear(s) => s.domain(),
54            Self::Log(s) => s.domain(),
55            Self::Symlog(s) => s.domain(),
56        }
57    }
58
59    pub fn normalize(self, value: f64) -> f64 {
60        match self {
61            Self::Linear(s) => s.normalize(value),
62            Self::Log(s) => s.normalize(value),
63            Self::Symlog(s) => s.normalize(value),
64        }
65    }
66
67    /// Inverse of [`normalize`](Self::normalize): unit interval → data value.
68    pub fn denormalize(self, unit: f64) -> f64 {
69        match self {
70            Self::Linear(s) => s.denormalize(unit),
71            Self::Log(s) => s.denormalize(unit),
72            Self::Symlog(s) => s.denormalize(unit),
73        }
74    }
75}
76
77/// Linear scale over a closed interval `[min, max]`.
78#[derive(Debug, Clone, Copy, PartialEq)]
79pub struct LinearScale {
80    min: f64,
81    max: f64,
82}
83
84impl LinearScale {
85    pub fn new(min: f64, max: f64) -> Result<Self> {
86        if !min.is_finite() || !max.is_finite() {
87            return Err(PlotError::InvalidRange {
88                min,
89                max,
90                message: "bounds must be finite",
91                suggestion: "replace NaN/Inf with finite data-derived limits",
92            });
93        }
94        if min >= max {
95            return Err(PlotError::invalid_range(min, max));
96        }
97        Ok(Self { min, max })
98    }
99
100    pub fn from_values(min: f64, max: f64) -> Result<Self> {
101        if (max - min).abs() < f64::EPSILON {
102            let pad = if min.abs() < 1.0 {
103                0.5
104            } else {
105                min.abs() * 0.05
106            };
107            return Self::new(min - pad, max + pad);
108        }
109        Self::new(min, max)
110    }
111
112    pub fn min(self) -> f64 {
113        self.min
114    }
115
116    pub fn max(self) -> f64 {
117        self.max
118    }
119
120    pub fn span(self) -> f64 {
121        self.max - self.min
122    }
123}
124
125impl Scale for LinearScale {
126    fn domain(&self) -> (f64, f64) {
127        (self.min, self.max)
128    }
129
130    fn normalize(&self, value: f64) -> f64 {
131        (value - self.min) / self.span()
132    }
133
134    fn denormalize(&self, unit: f64) -> f64 {
135        self.min + unit * self.span()
136    }
137}
138
139/// Logarithmic scale (base 10). Domain must be strictly positive.
140#[derive(Debug, Clone, Copy, PartialEq)]
141pub struct LogScale {
142    min: f64,
143    max: f64,
144}
145
146impl LogScale {
147    pub fn new(min: f64, max: f64) -> Result<Self> {
148        if !min.is_finite() || !max.is_finite() {
149            return Err(PlotError::InvalidRange {
150                min,
151                max,
152                message: "bounds must be finite",
153                suggestion: "replace NaN/Inf with finite positive limits",
154            });
155        }
156        if min <= 0.0 {
157            return Err(PlotError::log_non_positive(min));
158        }
159        if max <= 0.0 {
160            return Err(PlotError::log_non_positive(max));
161        }
162        if min >= max {
163            return Err(PlotError::invalid_range(min, max));
164        }
165        Ok(Self { min, max })
166    }
167
168    pub fn from_values(min: f64, max: f64) -> Result<Self> {
169        let min = if min <= 0.0 { f64::NAN } else { min };
170        let max = if max <= 0.0 { f64::NAN } else { max };
171        if !min.is_finite() {
172            return Err(PlotError::log_non_positive(0.0));
173        }
174        if !max.is_finite() {
175            return Err(PlotError::log_non_positive(0.0));
176        }
177        if (max - min).abs() < f64::EPSILON * min.abs().max(1.0) {
178            return Self::new(min / 10.0_f64.sqrt(), max * 10.0_f64.sqrt());
179        }
180        Self::new(min, max)
181    }
182
183    pub fn min(self) -> f64 {
184        self.min
185    }
186
187    pub fn max(self) -> f64 {
188        self.max
189    }
190}
191
192impl Scale for LogScale {
193    fn domain(&self) -> (f64, f64) {
194        (self.min, self.max)
195    }
196
197    fn normalize(&self, value: f64) -> f64 {
198        if value <= 0.0 {
199            return f64::NAN;
200        }
201        let a = self.min.log10();
202        let b = self.max.log10();
203        (value.log10() - a) / (b - a)
204    }
205
206    fn denormalize(&self, unit: f64) -> f64 {
207        let a = self.min.log10();
208        let b = self.max.log10();
209        10f64.powf(a + unit * (b - a))
210    }
211}
212
213/// Symlog scale: linear in `[-linthresh, linthresh]`, log outside.
214#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct SymlogScale {
216    min: f64,
217    max: f64,
218    linthresh: f64,
219}
220
221impl SymlogScale {
222    pub fn new(min: f64, max: f64, linthresh: f64) -> Result<Self> {
223        if !min.is_finite() || !max.is_finite() || !linthresh.is_finite() {
224            return Err(PlotError::InvalidRange {
225                min,
226                max,
227                message: "bounds and linthresh must be finite",
228                suggestion: "provide finite symlog parameters",
229            });
230        }
231        if linthresh <= 0.0 {
232            return Err(PlotError::InvalidRange {
233                min: linthresh,
234                max: linthresh,
235                message: "linthresh must be positive",
236                suggestion: "pass Symlog { linthresh: 1.0 } or another positive threshold",
237            });
238        }
239        if min >= max {
240            return Err(PlotError::invalid_range(min, max));
241        }
242        Ok(Self {
243            min,
244            max,
245            linthresh,
246        })
247    }
248
249    pub fn from_values(min: f64, max: f64, linthresh: f64) -> Result<Self> {
250        let linthresh = if linthresh > 0.0 { linthresh } else { 1.0 };
251        if (max - min).abs() < f64::EPSILON {
252            let pad = linthresh.max(0.5);
253            return Self::new(min - pad, max + pad, linthresh);
254        }
255        Self::new(min, max, linthresh)
256    }
257
258    fn forward(self, value: f64) -> f64 {
259        let lt = self.linthresh;
260        if value.abs() <= lt {
261            value
262        } else {
263            value.signum() * (lt + (value.abs() / lt).ln())
264        }
265    }
266
267    pub fn min(self) -> f64 {
268        self.min
269    }
270
271    pub fn max(self) -> f64 {
272        self.max
273    }
274
275    pub fn linthresh(self) -> f64 {
276        self.linthresh
277    }
278}
279
280impl Scale for SymlogScale {
281    fn domain(&self) -> (f64, f64) {
282        (self.min, self.max)
283    }
284
285    fn normalize(&self, value: f64) -> f64 {
286        let a = self.forward(self.min);
287        let b = self.forward(self.max);
288        let v = self.forward(value);
289        (v - a) / (b - a)
290    }
291
292    fn denormalize(&self, unit: f64) -> f64 {
293        let a = self.forward(self.min);
294        let b = self.forward(self.max);
295        let t = a + unit * (b - a);
296        let lt = self.linthresh;
297        if t.abs() <= lt {
298            t
299        } else {
300            t.signum() * lt * (t.abs() - lt).exp()
301        }
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn rejects_inverted_domain() {
311        assert!(LinearScale::new(1.0, 0.0).is_err());
312    }
313
314    #[test]
315    fn normalizes_endpoints() {
316        let s = LinearScale::new(0.0, 10.0).unwrap();
317        assert!((s.normalize(0.0) - 0.0).abs() < 1e-12);
318        assert!((s.normalize(10.0) - 1.0).abs() < 1e-12);
319        assert!((s.normalize(5.0) - 0.5).abs() < 1e-12);
320    }
321
322    #[test]
323    fn log_rejects_non_positive() {
324        assert!(matches!(
325            LogScale::new(-1.0, 10.0),
326            Err(PlotError::LogScaleNonPositive { .. })
327        ));
328    }
329
330    #[test]
331    fn log_midpoint() {
332        let s = LogScale::new(1.0, 100.0).unwrap();
333        assert!((s.normalize(10.0) - 0.5).abs() < 1e-12);
334    }
335
336    #[test]
337    fn symlog_passes_through_zero() {
338        let s = SymlogScale::new(-100.0, 100.0, 1.0).unwrap();
339        assert!(s.normalize(0.0).is_finite());
340        assert!((s.normalize(0.0) - 0.5).abs() < 1e-9);
341    }
342
343    #[test]
344    fn scale_kind_denormalize_roundtrip() {
345        for st in [
346            ScaleType::Linear,
347            ScaleType::Log,
348            ScaleType::Symlog { linthresh: 1.0 },
349        ] {
350            let (min, max) = match st {
351                ScaleType::Log => (1.0, 100.0),
352                _ => (-10.0, 10.0),
353            };
354            let s = ScaleKind::build(st, min, max).unwrap();
355            for u in [0.0, 0.25, 0.5, 0.75, 1.0] {
356                let v = s.denormalize(u);
357                let u2 = s.normalize(v);
358                assert!(
359                    (u - u2).abs() < 1e-9,
360                    "roundtrip failed for {st:?} at u={u}: got {u2}"
361                );
362            }
363        }
364    }
365}