Skip to main content

lichtung_plot/spec/
estimate.rs

1//! Line, interaction, and estimate-family display policies.
2
3use crate::{style::LinePattern, Error, NumericValues};
4
5/// Explicit drawable lower and upper bounds.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct Bounds {
8    lower: NumericValues,
9    upper: NumericValues,
10}
11
12impl Bounds {
13    /// Construct aligned drawable bounds.
14    #[must_use]
15    pub fn new(lower: NumericValues, upper: NumericValues) -> Self {
16        Self { lower, upper }
17    }
18
19    /// Borrow the lower endpoints.
20    #[must_use]
21    pub const fn lower(&self) -> &NumericValues {
22        &self.lower
23    }
24
25    /// Borrow the upper endpoints.
26    #[must_use]
27    pub const fn upper(&self) -> &NumericValues {
28        &self.upper
29    }
30}
31
32/// Closed owned input for a model-coefficient plot.
33#[derive(Debug, Clone)]
34pub struct CoefficientInput {
35    values: NumericValues,
36    bounds: Option<Bounds>,
37}
38
39impl CoefficientInput {
40    /// Use one precomputed estimate per term without bounds.
41    #[must_use]
42    pub fn estimates(values: NumericValues) -> Self {
43        Self {
44            values,
45            bounds: None,
46        }
47    }
48
49    /// Use one precomputed estimate and explicit drawable bounds per term.
50    #[must_use]
51    pub fn estimates_with_intervals(values: NumericValues, bounds: Bounds) -> Self {
52        Self {
53            values,
54            bounds: Some(bounds),
55        }
56    }
57
58    pub(crate) const fn values(&self) -> &NumericValues {
59        &self.values
60    }
61
62    pub(crate) const fn bounds(&self) -> Option<&Bounds> {
63        self.bounds.as_ref()
64    }
65}
66
67/// Closed text weights used by renderer-owned emphasis.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub enum TextWeight {
70    /// Ordinary body and axis text.
71    #[default]
72    Normal,
73    /// Moderate emphasis.
74    Semibold,
75    /// Strong emphasis.
76    Bold,
77}
78
79impl TextWeight {
80    pub(crate) const fn svg_value(self) -> u16 {
81        match self {
82            Self::Normal => 400,
83            Self::Semibold => 600,
84            Self::Bold => 700,
85        }
86    }
87}
88
89/// Independent typography and clearance for exact significance marks.
90///
91/// An explicit default is 16 CSS pixels, Normal weight and an 8px gap. Omitting
92/// the style lets the owning theme supply those properties instead.
93/// ```
94/// use lichtung_plot::{elements::SignificanceMarkStyle, text::TextWeight};
95/// let style = SignificanceMarkStyle::default()
96///     .font_size(18.0)?.weight(TextWeight::Semibold)?.gap(9.0)?;
97/// assert_eq!(style.get_font_size(), 18.0);
98/// assert_eq!(style.get_weight(), TextWeight::Semibold);
99/// assert_eq!(style.get_gap(), 9.0);
100/// # Ok::<(), lichtung_plot::Error>(())
101/// ```
102///
103/// Private fields prevent bypassing complete construction validation:
104/// ```compile_fail
105/// use lichtung_plot::elements::SignificanceMarkStyle;
106/// let mut style = SignificanceMarkStyle::default();
107/// style.gap = f64::NAN;
108/// ```
109#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct SignificanceMarkStyle {
111    font_size: f64,
112    weight: TextWeight,
113    gap: f64,
114}
115
116impl SignificanceMarkStyle {
117    /// Built-in values for an explicitly constructed default exact style.
118    pub(crate) const DEFAULT: Self = Self {
119        font_size: 16.0,
120        weight: TextWeight::Normal,
121        gap: 8.0,
122    };
123
124    /// Construct a validated mark style.
125    pub fn new(font_size: f64, weight: TextWeight, gap: f64) -> Result<Self, Error> {
126        Self {
127            font_size,
128            weight,
129            gap,
130        }
131        .validate()
132    }
133
134    /// Replace the positive mark font size in CSS pixels.
135    pub fn font_size(mut self, font_size: f64) -> Result<Self, Error> {
136        self.font_size = font_size;
137        self.validate()
138    }
139
140    /// Replace the mark font weight.
141    pub fn weight(mut self, weight: TextWeight) -> Result<Self, Error> {
142        self.weight = weight;
143        self.validate()
144    }
145
146    /// Replace the finite nonnegative mark-to-data gap in CSS pixels.
147    pub fn gap(mut self, gap: f64) -> Result<Self, Error> {
148        self.gap = gap;
149        self.validate()
150    }
151
152    fn validate(mut self) -> Result<Self, Error> {
153        if !self.font_size.is_finite()
154            || self.font_size <= 0.0
155            || !self.gap.is_finite()
156            || self.gap < 0.0
157        {
158            return Err(Error::Data(
159                "significance mark style requires positive font size and finite nonnegative gap"
160                    .into(),
161            ));
162        }
163        if self.gap == 0.0 {
164            self.gap = 0.0;
165        }
166        Ok(self)
167    }
168
169    /// Inspect the exact positive font size in CSS pixels.
170    pub const fn get_font_size(&self) -> f64 {
171        self.font_size
172    }
173
174    /// Inspect the exact font weight.
175    pub const fn get_weight(&self) -> TextWeight {
176        self.weight
177    }
178
179    /// Inspect the exact finite nonnegative gap in CSS pixels.
180    pub const fn get_gap(&self) -> f64 {
181        self.gap
182    }
183}
184
185impl Default for SignificanceMarkStyle {
186    fn default() -> Self {
187        Self::DEFAULT
188    }
189}
190
191/// Confidence-band policy for a generated simple OLS regression plot.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
193pub enum RegressionBand {
194    /// Draw the classical pointwise mean-response Student-t 95% confidence band.
195    #[default]
196    PointwiseMean95,
197    /// Draw only the descriptive OLS fit and make no interval claim.
198    Hidden,
199}
200
201impl RegressionBand {
202    pub(crate) const fn legend_label(self) -> &'static str {
203        match self {
204            Self::PointwiseMean95 => "Pointwise 95% Student-t mean band",
205            Self::Hidden => "Descriptive OLS fit (no band)",
206        }
207    }
208}
209
210/// Reference-line policy for a normal Q-Q plot.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
212pub enum QqLine {
213    /// Draw the line through the theoretical and observed first and third quartiles.
214    #[default]
215    Quartiles,
216    /// Draw the identity line `y = x`.
217    Identity,
218    /// Draw no reference line.
219    Hidden,
220}
221
222/// Color and legend policy for source-ordered line paths.
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
224pub enum LinePathStyle {
225    /// Retain neutral connectors and the existing observation-point behavior.
226    #[default]
227    Neutral,
228    /// Color each complete path by its one categorical hue and emit line legend glyphs.
229    Hue,
230}
231
232/// Closed point shapes accepted by interaction styles.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
234#[non_exhaustive]
235pub enum PointShape {
236    /// Filled circular marker.
237    #[default]
238    Circle,
239    /// Filled upward-pointing triangular marker.
240    TriangleUp,
241}
242
243/// One exact point and connector style owned by an interaction group.
244///
245/// ```
246/// use lichtung_plot::{plots::InteractionStyle, style::{LinePattern, PointShape}};
247/// let style = InteractionStyle::new("Control")?
248///     .point_shape(PointShape::TriangleUp)?
249///     .line_pattern(LinePattern::Dashed)?;
250/// assert_eq!(style.group(), "Control");
251/// # Ok::<(), lichtung_plot::Error>(())
252/// ```
253///
254/// ```compile_fail
255/// use lichtung_plot::{plots::InteractionStyle, style::PointShape};
256/// let _ = InteractionStyle::new("Control").unwrap().shape(PointShape::TriangleUp);
257/// ```
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct InteractionStyle {
260    group: String,
261    shape: PointShape,
262    pattern: LinePattern,
263}
264
265impl InteractionStyle {
266    /// Construct a circle-and-solid style for one exact graphical group label.
267    ///
268    /// The raw selector must be nonempty, already trimmed and control-free.
269    /// Its bytes, including interior whitespace, are retained for exact lookup.
270    pub fn new(group: impl Into<String>) -> Result<Self, Error> {
271        Self {
272            group: group.into(),
273            shape: PointShape::default(),
274            pattern: LinePattern::default(),
275        }
276        .validate()
277    }
278
279    /// Select the point shape for this group.
280    pub fn point_shape(mut self, shape: PointShape) -> Result<Self, Error> {
281        self.shape = shape;
282        self.validate()
283    }
284
285    /// Select the connector pattern for this group.
286    pub fn line_pattern(mut self, pattern: LinePattern) -> Result<Self, Error> {
287        self.pattern = pattern;
288        self.validate()
289    }
290
291    fn validate(self) -> Result<Self, Error> {
292        if self.group.is_empty()
293            || self.group.trim() != self.group
294            || self.group.chars().any(char::is_control)
295        {
296            return Err(Error::Data(
297                "interaction style group must be nonempty, already trimmed, and contain no control characters".into(),
298            ));
299        }
300        Ok(self)
301    }
302
303    /// Exact graphical group label that owns this style.
304    #[must_use]
305    pub fn group(&self) -> &str {
306        &self.group
307    }
308
309    /// Configured point shape.
310    #[must_use]
311    pub const fn get_point_shape(&self) -> PointShape {
312        self.shape
313    }
314
315    /// Configured connector pattern.
316    #[must_use]
317    pub const fn get_line_pattern(&self) -> LinePattern {
318        self.pattern
319    }
320}
321
322/// Typed availability of one aligned estimate row.
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324pub enum EstimateStatus {
325    /// The row owns a complete finite estimate tuple.
326    Estimated,
327    /// The row owns no numeric estimate tuple and is displayed explicitly.
328    NotEstimable,
329}
330
331/// Numeric scale used by interval-estimate plot families.
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
333#[non_exhaustive]
334pub enum AxisScale {
335    /// Untransformed additive scale.
336    #[default]
337    Linear,
338    /// Base-10 logarithmic scale for strictly positive multiplicative estimates.
339    Log10,
340}