Skip to main content

plotters_ternary/series/
contour.rs

1use plotters::style::{BLACK, Color, RGBAColor, ShapeStyle};
2
3use crate::{contour::ContourSet, series::SeriesError};
4
5/// Maps contour levels to Plotters-native line styles.
6pub enum ContourStylePolicy<'a> {
7    /// Use one style for every contour level.
8    Uniform(ShapeStyle),
9    /// Apply styles in level order, cycling when there are more levels than styles.
10    Ordered(Vec<ShapeStyle>),
11    /// Select a style directly from the scalar level value.
12    ByLevel(Box<dyn Fn(f64) -> ShapeStyle + 'a>),
13    /// Map the normalized level range to an RGBA colour and fixed stroke width.
14    Continuous {
15        minimum: f64,
16        maximum: f64,
17        stroke_width: u32,
18        map: Box<dyn Fn(f64) -> RGBAColor + 'a>,
19    },
20}
21
22impl Default for ContourStylePolicy<'_> {
23    fn default() -> Self {
24        Self::Uniform(BLACK.stroke_width(2))
25    }
26}
27
28impl<'a> ContourStylePolicy<'a> {
29    /// Construct a uniform style policy.
30    pub fn uniform<S: Into<ShapeStyle>>(style: S) -> Self {
31        Self::Uniform(style.into())
32    }
33
34    /// Construct a cycling ordered palette.
35    pub fn ordered<I, S>(styles: I) -> Result<Self, SeriesError>
36    where
37        I: IntoIterator<Item = S>,
38        S: Into<ShapeStyle>,
39    {
40        let styles = styles.into_iter().map(Into::into).collect::<Vec<_>>();
41        if styles.is_empty() {
42            return Err(SeriesError::EmptyContourStyleCollection);
43        }
44        Ok(Self::Ordered(styles))
45    }
46
47    /// Construct a callback-driven style policy.
48    pub fn by_level<F>(provider: F) -> Self
49    where
50        F: Fn(f64) -> ShapeStyle + 'a,
51    {
52        Self::ByLevel(Box::new(provider))
53    }
54
55    /// Construct a continuous colour-map policy.
56    ///
57    /// The callback receives a normalized value in `[0, 1]`.
58    pub fn continuous<F>(
59        minimum: f64,
60        maximum: f64,
61        stroke_width: u32,
62        map: F,
63    ) -> Result<Self, SeriesError>
64    where
65        F: Fn(f64) -> RGBAColor + 'a,
66    {
67        if !minimum.is_finite() || !maximum.is_finite() || maximum <= minimum || stroke_width == 0 {
68            return Err(SeriesError::InvalidContourColorRange {
69                minimum,
70                maximum,
71                stroke_width,
72            });
73        }
74        Ok(Self::Continuous {
75            minimum,
76            maximum,
77            stroke_width,
78            map: Box::new(map),
79        })
80    }
81
82    /// Resolve the style for one level index and value.
83    pub fn style_for(&self, index: usize, level: f64) -> Result<ShapeStyle, SeriesError> {
84        let style = match self {
85            Self::Uniform(style) => *style,
86            Self::Ordered(styles) => {
87                if styles.is_empty() {
88                    return Err(SeriesError::EmptyContourStyleCollection);
89                }
90                styles[index % styles.len()]
91            }
92            Self::ByLevel(provider) => provider(level),
93            Self::Continuous {
94                minimum,
95                maximum,
96                stroke_width,
97                map,
98            } => {
99                if !minimum.is_finite()
100                    || !maximum.is_finite()
101                    || maximum <= minimum
102                    || *stroke_width == 0
103                {
104                    return Err(SeriesError::InvalidContourColorRange {
105                        minimum: *minimum,
106                        maximum: *maximum,
107                        stroke_width: *stroke_width,
108                    });
109                }
110                let normalized = ((level - minimum) / (maximum - minimum)).clamp(0.0, 1.0);
111                map(normalized).stroke_width(*stroke_width)
112            }
113        };
114        Ok(style)
115    }
116}
117
118/// Selects which scalar levels create native Plotters legend entries.
119#[derive(Clone, Debug, Default, PartialEq)]
120#[non_exhaustive]
121pub enum ContourLegendPolicy {
122    /// Register no automatic per-level legend entries.
123    #[default]
124    None,
125    /// Register every level.
126    EveryLevel,
127    /// Register the listed scalar levels, matched with a small relative tolerance.
128    Selected(Vec<f64>),
129    /// Register every `n`th level in sorted contour order.
130    EveryNth(usize),
131}
132
133impl ContourLegendPolicy {
134    pub(crate) fn selected(&self, index: usize, level: f64) -> Result<bool, SeriesError> {
135        match self {
136            Self::None => Ok(false),
137            Self::EveryLevel => Ok(true),
138            Self::Selected(values) => Ok(values.iter().any(|candidate| {
139                let scale = candidate.abs().max(level.abs()).max(1.0);
140                (candidate - level).abs() <= 1.0e-12 * scale
141            })),
142            Self::EveryNth(0) => Err(SeriesError::InvalidContourLegendStride { stride: 0 }),
143            Self::EveryNth(stride) => Ok(index.is_multiple_of(*stride)),
144        }
145    }
146}
147
148pub(crate) type LevelFormatter<'a> = Box<dyn Fn(f64) -> String + 'a>;
149
150pub(crate) struct ContourSeriesParts<'a> {
151    pub contours: &'a ContourSet,
152    pub styles: ContourStylePolicy<'a>,
153    pub legend: ContourLegendPolicy,
154    pub formatter: LevelFormatter<'a>,
155}
156
157/// Plotters adapter for a precomputed [`ContourSet`].
158///
159/// The input set is immutable final numerical geometry. This adapter only
160/// projects paths, clips them for display, selects styles, and registers native
161/// Plotters series annotations.
162pub struct TernaryContourSeries<'a> {
163    contours: &'a ContourSet,
164    styles: ContourStylePolicy<'a>,
165    legend: ContourLegendPolicy,
166    formatter: LevelFormatter<'a>,
167}
168
169impl<'a> TernaryContourSeries<'a> {
170    /// Create a contour series with a black two-pixel default stroke.
171    pub fn new(contours: &'a ContourSet) -> Self {
172        Self {
173            contours,
174            styles: ContourStylePolicy::default(),
175            legend: ContourLegendPolicy::None,
176            formatter: Box::new(|level| format!("{level}")),
177        }
178    }
179
180    /// Use one Plotters-native stroke style for every level.
181    pub fn style<S: Into<ShapeStyle>>(mut self, style: S) -> Self {
182        self.styles = ContourStylePolicy::uniform(style);
183        self
184    }
185
186    /// Select an owned style from each scalar level at draw time.
187    pub fn style_for_level<F>(mut self, provider: F) -> Self
188    where
189        F: Fn(f64) -> ShapeStyle + 'a,
190    {
191        self.styles = ContourStylePolicy::by_level(provider);
192        self
193    }
194
195    /// Alias for [`Self::style_for_level`] with level-oriented naming.
196    pub fn style_by_level<F>(self, provider: F) -> Self
197    where
198        F: Fn(f64) -> ShapeStyle + 'a,
199    {
200        self.style_for_level(provider)
201    }
202
203    /// Use an explicit style policy.
204    pub fn style_policy(mut self, policy: ContourStylePolicy<'a>) -> Self {
205        self.styles = policy;
206        self
207    }
208
209    /// Apply a cycling ordered style collection in contour-level order.
210    pub fn ordered_styles<I, S>(mut self, styles: I) -> Result<Self, SeriesError>
211    where
212        I: IntoIterator<Item = S>,
213        S: Into<ShapeStyle>,
214    {
215        self.styles = ContourStylePolicy::ordered(styles)?;
216        Ok(self)
217    }
218
219    /// Apply a continuous normalized colour map over a scalar range.
220    pub fn color_map<F>(
221        mut self,
222        minimum: f64,
223        maximum: f64,
224        stroke_width: u32,
225        map: F,
226    ) -> Result<Self, SeriesError>
227    where
228        F: Fn(f64) -> RGBAColor + 'a,
229    {
230        self.styles = ContourStylePolicy::continuous(minimum, maximum, stroke_width, map)?;
231        Ok(self)
232    }
233
234    /// Select automatic native Plotters legend entries.
235    pub fn legend_policy(mut self, policy: ContourLegendPolicy) -> Self {
236        self.legend = policy;
237        self
238    }
239
240    /// Format automatic legend labels from scalar values.
241    pub fn level_formatter<F, S>(mut self, formatter: F) -> Self
242    where
243        F: Fn(f64) -> S + 'a,
244        S: Into<String>,
245    {
246        self.formatter = Box::new(move |level| formatter(level).into());
247        self
248    }
249
250    pub(crate) fn into_parts(self) -> ContourSeriesParts<'a> {
251        ContourSeriesParts {
252            contours: self.contours,
253            styles: self.styles,
254            legend: self.legend,
255            formatter: self.formatter,
256        }
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use plotters::style::{BLUE, Color, RED, RGBColor};
263
264    use super::*;
265
266    #[test]
267    fn style_selection_uses_exact_levels_ordered_palettes_and_continuous_maps() {
268        let callback = ContourStylePolicy::by_level(|level| {
269            if level == 2.5 {
270                RED.stroke_width(4)
271            } else {
272                BLUE.stroke_width(1)
273            }
274        });
275        assert_eq!(callback.style_for(9, 2.5).unwrap(), RED.stroke_width(4));
276
277        let ordered =
278            ContourStylePolicy::ordered([RED.stroke_width(1), BLUE.stroke_width(2)]).unwrap();
279        assert_eq!(ordered.style_for(0, 10.0).unwrap(), RED.stroke_width(1));
280        assert_eq!(ordered.style_for(3, 40.0).unwrap(), BLUE.stroke_width(2));
281
282        let continuous = ContourStylePolicy::continuous(0.0, 100.0, 3, |t| {
283            RGBColor((255.0 * t).round() as u8, 0, 0).to_rgba()
284        })
285        .unwrap();
286        assert_eq!(
287            continuous.style_for(0, 50.0).unwrap(),
288            RGBColor(128, 0, 0).stroke_width(3)
289        );
290
291        assert!(
292            ContourStylePolicy::Ordered(Vec::new())
293                .style_for(0, 0.0)
294                .is_err()
295        );
296        let invalid_continuous = ContourStylePolicy::Continuous {
297            minimum: 1.0,
298            maximum: 1.0,
299            stroke_width: 2,
300            map: Box::new(|_| RED.to_rgba()),
301        };
302        assert!(invalid_continuous.style_for(0, 1.0).is_err());
303    }
304
305    #[test]
306    fn legend_policies_select_deterministic_level_rows() {
307        assert!(!ContourLegendPolicy::None.selected(0, 1.0).unwrap());
308        assert!(ContourLegendPolicy::EveryLevel.selected(4, 1.0).unwrap());
309        assert!(
310            ContourLegendPolicy::Selected(vec![2.0])
311                .selected(9, 2.0 + 1.0e-13)
312                .unwrap()
313        );
314        assert!(ContourLegendPolicy::EveryNth(3).selected(6, 9.0).unwrap());
315        assert!(!ContourLegendPolicy::EveryNth(3).selected(5, 9.0).unwrap());
316        assert!(ContourLegendPolicy::EveryNth(0).selected(0, 0.0).is_err());
317    }
318}