Skip to main content

plotters_ternary/coord/
point.rs

1use super::validation::validate_components;
2use super::{Error, Normalization, Tolerance};
3
4/// One of the three semantic components of a ternary composition.
5#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
6#[repr(usize)]
7pub enum Component {
8    /// The first semantic component.
9    A = 0,
10    /// The second semantic component.
11    B = 1,
12    /// The third semantic component.
13    C = 2,
14}
15
16impl Component {
17    /// Components in stable semantic A/B/C order.
18    pub const ALL: [Self; 3] = [Self::A, Self::B, Self::C];
19
20    /// Return this component's stable index in an A/B/C array.
21    pub const fn index(self) -> usize {
22        self as usize
23    }
24
25    /// Return the two components other than this one, in A/B/C order.
26    pub const fn others(self) -> [Self; 2] {
27        match self {
28            Self::A => [Self::B, Self::C],
29            Self::B => [Self::A, Self::C],
30            Self::C => [Self::A, Self::B],
31        }
32    }
33}
34
35/// A ternary composition in semantic A/B/C order.
36///
37/// [`TernaryPoint::new`] performs no validation or normalisation. Call
38/// [`TernaryPoint::validate`] before projecting a user-provided point.
39#[derive(Clone, Copy, Debug, PartialEq)]
40pub struct TernaryPoint {
41    a: f64,
42    b: f64,
43    c: f64,
44}
45
46impl TernaryPoint {
47    /// Construct an unvalidated composition without normalising it.
48    ///
49    /// ```
50    /// use plotters_ternary::{Normalization, TernaryPoint, Tolerance};
51    ///
52    /// let raw = TernaryPoint::new(0.2, 0.3, 0.5);
53    /// let point = raw.validate(Normalization::RequireUnitSum, Tolerance::default())?;
54    /// assert_eq!(point.component(plotters_ternary::Component::C), 0.5);
55    /// # Ok::<(), plotters_ternary::Error>(())
56    /// ```
57    pub const fn new(a: f64, b: f64, c: f64) -> Self {
58        Self { a, b, c }
59    }
60
61    /// Return a component value selected by its semantic name.
62    pub const fn component(self, component: Component) -> f64 {
63        match component {
64            Component::A => self.a,
65            Component::B => self.b,
66            Component::C => self.c,
67        }
68    }
69
70    /// Return the unvalidated arithmetic sum of the three components.
71    pub const fn sum(self) -> f64 {
72        self.a + self.b + self.c
73    }
74
75    /// Return the components in stable A/B/C order.
76    pub const fn as_array(self) -> [f64; 3] {
77        [self.a, self.b, self.c]
78    }
79
80    /// Validate this composition under an explicit sum policy.
81    ///
82    /// Tiny finite negatives in `[-tolerance.absolute, 0.0)` become exactly
83    /// zero before the sum is evaluated. Larger negatives, non-finite values,
84    /// and near-zero sums fail. `Normalization::Normalize` then scales the
85    /// cleaned values to unit sum.
86    ///
87    /// ```
88    /// use plotters_ternary::{Normalization, TernaryPoint, Tolerance};
89    ///
90    /// let point = TernaryPoint::new(2.0, 3.0, 5.0)
91    ///     .validate(Normalization::Normalize, Tolerance::default())?;
92    /// assert!((point.sum() - 1.0).abs() < 1.0e-12);
93    /// # Ok::<(), plotters_ternary::Error>(())
94    /// ```
95    pub fn validate(
96        self,
97        normalization: Normalization,
98        tolerance: Tolerance,
99    ) -> Result<Self, Error> {
100        let [a, b, c] = validate_components(self.as_array(), normalization, tolerance)?;
101        Ok(Self::new(a, b, c))
102    }
103}
104
105impl From<[f64; 3]> for TernaryPoint {
106    fn from([a, b, c]: [f64; 3]) -> Self {
107        Self::new(a, b, c)
108    }
109}
110
111impl From<TernaryPoint> for [f64; 3] {
112    fn from(point: TernaryPoint) -> Self {
113        point.as_array()
114    }
115}
116
117impl From<(f64, f64, f64)> for TernaryPoint {
118    fn from((a, b, c): (f64, f64, f64)) -> Self {
119        Self::new(a, b, c)
120    }
121}
122
123impl From<TernaryPoint> for (f64, f64, f64) {
124    fn from(point: TernaryPoint) -> Self {
125        (point.a, point.b, point.c)
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    const TOLERANCE: Tolerance = Tolerance {
134        absolute: 1.0e-9,
135        relative: 1.0e-9,
136    };
137
138    #[test]
139    fn construction_component_access_and_conversions_preserve_abc_order() {
140        let point = TernaryPoint::new(0.2, 0.3, 0.5);
141        assert_eq!(point.component(Component::A), 0.2);
142        assert_eq!(point.component(Component::B), 0.3);
143        assert_eq!(point.component(Component::C), 0.5);
144        assert_eq!(point.sum(), 1.0);
145        assert_eq!(point.as_array(), [0.2, 0.3, 0.5]);
146        assert_eq!(TernaryPoint::from([0.2, 0.3, 0.5]), point);
147        assert_eq!(<[f64; 3]>::from(point), [0.2, 0.3, 0.5]);
148        assert_eq!(TernaryPoint::from((0.2, 0.3, 0.5)), point);
149        assert_eq!(<(f64, f64, f64)>::from(point), (0.2, 0.3, 0.5));
150        assert_eq!(Component::B.index(), 1);
151        assert_eq!(Component::C.others(), [Component::A, Component::B]);
152    }
153
154    #[test]
155    fn validation_supports_all_sum_policies() {
156        let unit = TernaryPoint::new(0.2, 0.3, 0.5)
157            .validate(Normalization::RequireUnitSum, TOLERANCE)
158            .unwrap();
159        assert_eq!(unit, TernaryPoint::new(0.2, 0.3, 0.5));
160
161        assert!(matches!(
162            TernaryPoint::new(2.0, 3.0, 5.0).validate(Normalization::RequireUnitSum, TOLERANCE),
163            Err(Error::RequiredSumMismatch { .. })
164        ));
165
166        let normalised = TernaryPoint::new(2.0, 3.0, 5.0)
167            .validate(Normalization::Normalize, TOLERANCE)
168            .unwrap();
169        assert!((normalised.sum() - 1.0).abs() < 1.0e-12);
170        assert_eq!(normalised, TernaryPoint::new(0.2, 0.3, 0.5));
171
172        let custom = TernaryPoint::new(2.0, 3.0, 5.0)
173            .validate(Normalization::RequireSum(10.0), TOLERANCE)
174            .unwrap();
175        assert_eq!(custom, TernaryPoint::new(2.0, 3.0, 5.0));
176        assert!(matches!(
177            TernaryPoint::new(2.0, 3.0, 5.0).validate(Normalization::RequireSum(9.0), TOLERANCE),
178            Err(Error::RequiredSumMismatch { .. })
179        ));
180        assert!(matches!(
181            TernaryPoint::new(0.0, 0.0, 0.0).validate(Normalization::RequireSum(0.0), TOLERANCE),
182            Err(Error::InvalidRequiredSum { .. })
183        ));
184    }
185
186    #[test]
187    fn invalid_sums_and_negative_values_are_rejected_or_cleaned_deterministically() {
188        for point in [
189            TernaryPoint::new(0.0, 0.0, 0.0),
190            TernaryPoint::new(1.0e-12, 0.0, 0.0),
191        ] {
192            assert!(matches!(
193                point.validate(Normalization::Normalize, TOLERANCE),
194                Err(Error::InvalidSum { .. })
195            ));
196        }
197
198        assert!(matches!(
199            TernaryPoint::new(-2.0e-9, 0.5, 0.5).validate(Normalization::RequireUnitSum, TOLERANCE),
200            Err(Error::NegativeComponent {
201                component: Component::A,
202                ..
203            })
204        ));
205
206        let cleaned = TernaryPoint::new(-5.0e-10, 0.5, 0.5)
207            .validate(Normalization::RequireUnitSum, TOLERANCE)
208            .unwrap();
209        assert_eq!(cleaned, TernaryPoint::new(0.0, 0.5, 0.5));
210    }
211
212    #[test]
213    fn non_finite_components_and_invalid_tolerance_are_rejected() {
214        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
215            assert!(matches!(
216                TernaryPoint::new(value, 0.5, 0.5)
217                    .validate(Normalization::RequireUnitSum, TOLERANCE),
218                Err(Error::NonFiniteComponent {
219                    component: Component::A,
220                    ..
221                })
222            ));
223        }
224
225        assert!(matches!(
226            TernaryPoint::new(0.2, 0.3, 0.5).validate(
227                Normalization::RequireUnitSum,
228                Tolerance {
229                    absolute: 0.0,
230                    relative: 1.0e-9,
231                },
232            ),
233            Err(Error::InvalidTolerance { .. })
234        ));
235        assert!(matches!(
236            Tolerance::new(1.0e-9, f64::NAN),
237            Err(Error::InvalidTolerance { .. })
238        ));
239    }
240}