Skip to main content

plotters_ternary/coord/
validation.rs

1use std::fmt;
2
3use super::Component;
4
5/// The explicit sum policy applied before a composition is used geometrically.
6#[derive(Clone, Copy, Debug, PartialEq)]
7pub enum Normalization {
8    /// Accept only compositions whose components sum to one within tolerance.
9    RequireUnitSum,
10    /// Scale a finite, non-negative composition to unit sum.
11    Normalize,
12    /// Accept only compositions whose components sum to the specified positive value.
13    RequireSum(f64),
14}
15
16/// Absolute and relative tolerances used by validation and triangle boundaries.
17///
18/// Both values must be finite and strictly positive. Values within the absolute
19/// tolerance of zero are treated as floating-point boundary noise where the
20/// documented operation permits boundary clean-up.
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct Tolerance {
23    /// Absolute tolerance, used near zero.
24    pub absolute: f64,
25    /// Relative tolerance, scaled by the compared magnitudes.
26    pub relative: f64,
27}
28
29impl Tolerance {
30    /// Construct a tolerance after checking that both terms are usable.
31    pub fn new(absolute: f64, relative: f64) -> Result<Self, Error> {
32        let tolerance = Self { absolute, relative };
33        tolerance.validate()?;
34        Ok(tolerance)
35    }
36
37    /// Validate a tolerance value, including one built with public fields.
38    pub fn validate(self) -> Result<(), Error> {
39        if !self.absolute.is_finite()
40            || !self.relative.is_finite()
41            || self.absolute <= 0.0
42            || self.relative <= 0.0
43        {
44            return Err(Error::InvalidTolerance {
45                absolute: self.absolute,
46                relative: self.relative,
47            });
48        }
49        Ok(())
50    }
51
52    /// Return whether two finite values are equal within this tolerance.
53    pub fn is_close(self, left: f64, right: f64) -> bool {
54        (left - right).abs() <= self.absolute + self.relative * left.abs().max(right.abs())
55    }
56
57    pub(crate) fn is_near_zero(self, value: f64) -> bool {
58        value.abs() <= self.absolute
59    }
60}
61
62impl Default for Tolerance {
63    fn default() -> Self {
64        Self {
65            absolute: 1.0e-12,
66            relative: 1.0e-12,
67        }
68    }
69}
70
71/// Errors reported by composition validation and geometric projection.
72#[derive(Clone, Debug, PartialEq)]
73#[non_exhaustive]
74pub enum Error {
75    /// A tolerance has a non-finite or non-positive term.
76    InvalidTolerance { absolute: f64, relative: f64 },
77    /// A composition component is NaN or infinite.
78    NonFiniteComponent { component: Component, value: f64 },
79    /// A composition component is negative by more than the absolute tolerance.
80    NegativeComponent {
81        component: Component,
82        value: f64,
83        tolerance: f64,
84    },
85    /// A composition sum is non-finite, zero, or too close to zero.
86    InvalidSum { sum: f64, minimum: f64 },
87    /// A custom required sum is non-finite or too close to zero.
88    InvalidRequiredSum { required_sum: f64, minimum: f64 },
89    /// A composition does not have the sum required by its policy.
90    RequiredSumMismatch {
91        expected: f64,
92        actual: f64,
93        tolerance: Tolerance,
94    },
95    /// A vertex order repeats one or more components.
96    InvalidVertexOrder {
97        left: Component,
98        right: Component,
99        apex: Component,
100    },
101    /// A Cartesian coordinate is NaN or infinite.
102    NonFiniteCartesian { x: f64, y: f64 },
103    /// A Cartesian point is materially outside the complete ternary triangle.
104    CartesianOutsideTriangle {
105        x: f64,
106        y: f64,
107        tolerance: Tolerance,
108    },
109    /// One or more logical viewport bounds are NaN or infinite.
110    NonFiniteViewportBounds {
111        x_min: f64,
112        x_max: f64,
113        y_min: f64,
114        y_max: f64,
115    },
116    /// A viewport range is reversed, zero, near-zero, or otherwise unusable.
117    InvalidViewport {
118        x_min: f64,
119        x_max: f64,
120        y_min: f64,
121        y_max: f64,
122        minimum_span: f64,
123    },
124    /// An allocated pixel rectangle has a zero width or height.
125    InvalidPixelRect {
126        x: i32,
127        y: i32,
128        width: u32,
129        height: u32,
130    },
131    /// A floating-point pixel coordinate is NaN or infinite.
132    NonFinitePixelCoordinate { x: f64, y: f64 },
133    /// At least one endpoint of a Cartesian segment is NaN or infinite.
134    NonFiniteSegment {
135        start_x: f64,
136        start_y: f64,
137        end_x: f64,
138        end_y: f64,
139    },
140    /// A component-isoline value is materially outside the unit interval.
141    InvalidIsolineValue { value: f64, tolerance: Tolerance },
142}
143
144impl fmt::Display for Error {
145    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146        match self {
147            Self::InvalidTolerance { absolute, relative } => write!(
148                formatter,
149                "invalid tolerance: absolute={absolute:?}, relative={relative:?}; both must be finite and positive"
150            ),
151            Self::NonFiniteComponent { component, value } => {
152                write!(
153                    formatter,
154                    "component {component:?} is not finite: {value:?}"
155                )
156            }
157            Self::NegativeComponent {
158                component,
159                value,
160                tolerance,
161            } => write!(
162                formatter,
163                "component {component:?} is negative beyond tolerance {tolerance:?}: {value:?}"
164            ),
165            Self::InvalidSum { sum, minimum } => write!(
166                formatter,
167                "composition sum must be finite and greater than {minimum:?}: {sum:?}"
168            ),
169            Self::InvalidRequiredSum {
170                required_sum,
171                minimum,
172            } => write!(
173                formatter,
174                "required sum must be finite and greater than {minimum:?}: {required_sum:?}"
175            ),
176            Self::RequiredSumMismatch {
177                expected,
178                actual,
179                tolerance,
180            } => write!(
181                formatter,
182                "composition sum {actual:?} does not match required sum {expected:?} within {tolerance:?}"
183            ),
184            Self::InvalidVertexOrder { left, right, apex } => write!(
185                formatter,
186                "vertex order must contain A, B, and C exactly once; received {left:?}, {right:?}, {apex:?}"
187            ),
188            Self::NonFiniteCartesian { x, y } => {
189                write!(
190                    formatter,
191                    "Cartesian coordinate is not finite: ({x:?}, {y:?})"
192                )
193            }
194            Self::CartesianOutsideTriangle { x, y, tolerance } => write!(
195                formatter,
196                "Cartesian point ({x:?}, {y:?}) is outside the ternary triangle within {tolerance:?}"
197            ),
198            Self::NonFiniteViewportBounds {
199                x_min,
200                x_max,
201                y_min,
202                y_max,
203            } => write!(
204                formatter,
205                "viewport bounds must be finite: x={x_min:?}..{x_max:?}, y={y_min:?}..{y_max:?}"
206            ),
207            Self::InvalidViewport {
208                x_min,
209                x_max,
210                y_min,
211                y_max,
212                minimum_span,
213            } => write!(
214                formatter,
215                "viewport ranges must be ordered and wider than {minimum_span:?}: x={x_min:?}..{x_max:?}, y={y_min:?}..{y_max:?}"
216            ),
217            Self::InvalidPixelRect {
218                x,
219                y,
220                width,
221                height,
222            } => write!(
223                formatter,
224                "pixel rectangle at ({x}, {y}) must have non-zero dimensions: {width}x{height}"
225            ),
226            Self::NonFinitePixelCoordinate { x, y } => {
227                write!(formatter, "pixel coordinate is not finite: ({x:?}, {y:?})")
228            }
229            Self::NonFiniteSegment {
230                start_x,
231                start_y,
232                end_x,
233                end_y,
234            } => write!(
235                formatter,
236                "segment endpoints must be finite: ({start_x:?}, {start_y:?}) to ({end_x:?}, {end_y:?})"
237            ),
238            Self::InvalidIsolineValue { value, tolerance } => write!(
239                formatter,
240                "component-isoline value {value:?} is outside [0, 1] within {tolerance:?}"
241            ),
242        }
243    }
244}
245
246impl std::error::Error for Error {}
247
248pub(crate) fn validate_components(
249    mut components: [f64; 3],
250    normalization: Normalization,
251    tolerance: Tolerance,
252) -> Result<[f64; 3], Error> {
253    tolerance.validate()?;
254
255    if let Normalization::RequireSum(required_sum) = normalization
256        && (!required_sum.is_finite() || required_sum <= tolerance.absolute)
257    {
258        return Err(Error::InvalidRequiredSum {
259            required_sum,
260            minimum: tolerance.absolute,
261        });
262    }
263
264    for (component, value) in Component::ALL.into_iter().zip(&mut components) {
265        if !value.is_finite() {
266            return Err(Error::NonFiniteComponent {
267                component,
268                value: *value,
269            });
270        }
271        if *value < -tolerance.absolute {
272            return Err(Error::NegativeComponent {
273                component,
274                value: *value,
275                tolerance: tolerance.absolute,
276            });
277        }
278        if *value < 0.0 {
279            *value = 0.0;
280        }
281    }
282
283    let sum: f64 = components.into_iter().sum();
284    if !sum.is_finite() || sum <= tolerance.absolute {
285        return Err(Error::InvalidSum {
286            sum,
287            minimum: tolerance.absolute,
288        });
289    }
290
291    match normalization {
292        Normalization::Normalize => Ok(components.map(|component| component / sum)),
293        Normalization::RequireUnitSum => {
294            require_sum(sum, 1.0, tolerance)?;
295            Ok(components)
296        }
297        Normalization::RequireSum(required_sum) => {
298            require_sum(sum, required_sum, tolerance)?;
299            Ok(components)
300        }
301    }
302}
303
304fn require_sum(actual: f64, expected: f64, tolerance: Tolerance) -> Result<(), Error> {
305    if tolerance.is_close(actual, expected) {
306        Ok(())
307    } else {
308        Err(Error::RequiredSumMismatch {
309            expected,
310            actual,
311            tolerance,
312        })
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    #[test]
321    fn close_values_use_absolute_and_relative_terms() {
322        let tolerance = Tolerance::new(1.0e-6, 1.0e-6).unwrap();
323        assert!(tolerance.is_close(1.0, 1.0 + 1.5e-6));
324        assert!(!tolerance.is_close(1.0, 1.0 + 3.0e-6));
325    }
326}