lichtung-plot 0.1.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Typed supplemental geometry for numeric charts.

use crate::Error;

use crate::LinePattern;
use crate::{CategoryValues, Color, NumericValues};

/// Closed visual style for a numeric guide line.
///
/// The pattern is selected through [`LinePattern`]; arbitrary backend dash
/// strings are not accepted.
///
/// ```
/// use lichtung_plot::{Color, GuideStyle, LinePattern};
/// let guide = GuideStyle::new(Color::rgba(20, 80, 140, 128), 1.5, LinePattern::Solid)?
///     .pattern(LinePattern::Dashed)?;
/// assert_eq!(guide.get_color().get_alpha(), 128);
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// Exact paint is typed; RGB tuples are not style inputs:
/// ```compile_fail
/// use lichtung_plot::{GuideStyle, LinePattern};
/// let _ = GuideStyle::new((20, 80, 140), 1.5, LinePattern::Solid);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct GuideStyle {
    color: Color,
    width: f32,
    pattern: LinePattern,
}

impl GuideStyle {
    /// Construct a guide style with a complete RGBA paint, positive width, and
    /// closed line pattern.
    ///
    /// # Errors
    ///
    /// Returns an error when `width` is not finite and strictly positive.
    pub fn new(color: Color, width: f32, pattern: LinePattern) -> Result<Self, Error> {
        if !width.is_finite() || width <= 0.0 {
            return Err(Error::Data(format!(
                "guide width must be finite and strictly positive; got {width}"
            )));
        }
        Ok(Self {
            color,
            width,
            pattern,
        })
    }

    /// Inspect the complete exact guide paint.
    pub const fn get_color(&self) -> Color {
        self.color
    }

    /// Inspect the positive guide width in CSS pixels.
    pub const fn get_width(&self) -> f32 {
        self.width
    }

    /// Inspect the closed guide pattern.
    pub const fn get_pattern(&self) -> LinePattern {
        self.pattern
    }

    /// Replace the complete exact guide paint.
    pub fn color(self, color: Color) -> Result<Self, Error> {
        Self::new(color, self.width, self.pattern)
    }

    /// Replace the positive guide width in CSS pixels.
    pub fn width(self, width: f32) -> Result<Self, Error> {
        Self::new(self.color, width, self.pattern)
    }

    /// Replace the closed guide pattern.
    pub fn pattern(self, pattern: LinePattern) -> Result<Self, Error> {
        Self::new(self.color, self.width, pattern)
    }

    pub(crate) fn line_style(&self) -> crate::render::backend::LineStyle {
        crate::render::backend::LineStyle {
            color: self.color,
            width: self.width,
            pattern: self.pattern.stroke_pattern(),
        }
    }
}

/// Supplemental numeric guide geometry.
///
/// Horizontal and vertical guides span the resolved panel range. A segment is
/// finite and may be diagonal. Every coordinate must lie in the corresponding
/// resolved numeric axis range.
#[derive(Debug, Clone, PartialEq)]
pub enum GuideSpec {
    /// A horizontal guide spanning the numeric x range.
    Horizontal {
        /// Numeric y position.
        y: f64,
        /// Guide visual style.
        style: GuideStyle,
    },
    /// A vertical guide spanning the numeric y range.
    Vertical {
        /// Numeric x position.
        x: f64,
        /// Guide visual style.
        style: GuideStyle,
    },
    /// A finite segment between two numeric data-space endpoints.
    Segment {
        /// First `(x, y)` endpoint.
        start: (f64, f64),
        /// Second `(x, y)` endpoint.
        end: (f64, f64),
        /// Guide visual style.
        style: GuideStyle,
    },
}

impl GuideSpec {
    /// Construct a horizontal guide.
    #[must_use]
    pub const fn horizontal(y: f64, style: GuideStyle) -> Self {
        Self::Horizontal { y, style }
    }

    /// Construct a vertical guide.
    #[must_use]
    pub const fn vertical(x: f64, style: GuideStyle) -> Self {
        Self::Vertical { x, style }
    }

    /// Construct a finite segment, including a diagonal guide when both
    /// coordinates differ between endpoints.
    #[must_use]
    pub const fn segment(
        x_start: f64,
        y_start: f64,
        x_end: f64,
        y_end: f64,
        style: GuideStyle,
    ) -> Self {
        Self::Segment {
            start: (x_start, y_start),
            end: (x_end, y_end),
            style,
        }
    }
}

/// A strict supplemental point layer owned independently from the primary line.
///
/// The aligned x/y values are arbitrary caller-selected coordinates. Optional
/// labels annotate individual points, while an optional legend label identifies
/// the complete layer once.
///
/// ```
/// use lichtung_plot::{Color, NumericValues, PointLayer, Text, TextAlignment, Theme};
/// let label = Text::new("Selected coordinates").style(
///     Theme::publication().typography().get_guides().get_legend_label().clone()
/// ).alignment(TextAlignment::End);
/// let layer = PointLayer::new(
///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
/// ).alpha(128).color(Color::rgb(20, 80, 140)).radius(5)?.legend_label(label);
/// assert_eq!(layer.get_alpha(), Some(128));
/// assert_eq!(layer.get_color(), Some(Color::rgb(20, 80, 140)));
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// Alpha instructions are exact bytes rather than floating opacity:
/// ```compile_fail
/// use lichtung_plot::{NumericValues, PointLayer};
/// let _ = PointLayer::new(
///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
/// ).opacity(0.5);
/// ```
#[derive(Debug, Clone)]
pub struct PointLayer {
    pub(crate) label_layout: Option<crate::TextLayout>,
    x: NumericValues,
    y: NumericValues,
    labels: Option<CategoryValues>,
    legend_label: crate::Text,
    color: Option<Color>,
    radius: Option<u32>,
    alpha: Option<u8>,
}

/// A complete strict point layer positioned at prepared ordinary-bar centers.
///
/// Category and optional series values resolve against the bar cells. Every row
/// creates exactly one point and the layer creates no legend.
///
/// The constructor's Color owns the complete paint, with no opacity argument:
/// ```
/// use lichtung_plot::{BarPointLayer, CategoryValues, Color, NumericValues};
/// let layer = BarPointLayer::new(
///     CategoryValues::new("category", ["A"])?, None,
///     NumericValues::new("value", [2.0]), Color::rgba(20, 80, 140, 0), 4,
/// )?;
/// assert_eq!(layer.color().get_alpha(), 0);
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// ```compile_fail
/// use lichtung_plot::{BarPointLayer, CategoryValues, Color, NumericValues};
/// let _ = BarPointLayer::new(
///     CategoryValues::new("category", ["A"]).unwrap(), None,
///     NumericValues::new("value", [2.0]), Color::rgb(20, 80, 140), 4, 0.5,
/// );
/// ```
#[derive(Debug, Clone)]
pub struct BarPointLayer {
    category: CategoryValues,
    series: Option<CategoryValues>,
    value: NumericValues,
    color: Color,
    radius: u32,
}

impl BarPointLayer {
    /// Construct an owned bar point layer with optional positioned series.
    ///
    /// Pass `None` for a single-series bar and `Some(column)` for a chart whose
    /// ordinary bars use an explicit positioned series.
    pub fn new(
        category: CategoryValues,
        series: Option<CategoryValues>,
        value: NumericValues,
        color: Color,
        radius: u32,
    ) -> Result<Self, Error> {
        validate_point_radius("bar-point-layer", radius)?;
        Ok(Self {
            category,
            series,
            value,
            color,
            radius,
        })
    }

    /// Categories resolved against prepared bar categories.
    #[must_use]
    pub const fn category_values(&self) -> &CategoryValues {
        &self.category
    }

    /// Optional series values resolved against prepared bar series.
    #[must_use]
    pub const fn series_values(&self) -> Option<&CategoryValues> {
        self.series.as_ref()
    }

    /// Strict finite numeric point values.
    #[must_use]
    pub const fn values(&self) -> &NumericValues {
        &self.value
    }

    /// Complete exact point paint, including alpha.
    #[must_use]
    pub const fn color(&self) -> Color {
        self.color
    }

    /// Fixed positive point radius.
    #[must_use]
    pub const fn radius(&self) -> u32 {
        self.radius
    }

    pub(crate) fn point_style(&self) -> crate::render::backend::PointStyle {
        crate::render::backend::PointStyle {
            color: self.color,
            radius: self.radius,
            outline: None,
            shape: crate::PointShape::Circle,
        }
    }
}

impl PointLayer {
    /// Replace the complete layout default for this layer's column-backed labels.
    #[must_use]
    pub fn label_text_layout(mut self, layout: crate::TextLayout) -> Self {
        self.label_layout = Some(layout);
        self
    }
    /// Construct an owned point layer with owner-theme styling.
    ///
    /// The x/y values may describe raw observations or any other supplemental
    /// coordinates and need not align with the primary line input. They default
    /// to the next theme-coordinated color and the theme's supplemental radius
    /// and alpha (built-ins use radius 4 and alpha 204). Nonempty,
    /// aligned, finite values are validated during chart preflight.
    #[must_use]
    pub fn new(x: NumericValues, y: NumericValues) -> Self {
        Self {
            x,
            label_layout: None,
            y,
            labels: None,
            legend_label: crate::Text::UNSET,
            color: None,
            radius: None,
            alpha: None,
        }
    }

    /// Replace the automatic mark paint and label paint with complete RGBA.
    /// An independent explicit alpha instruction takes precedence over this alpha.
    #[must_use]
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Override the default point radius.
    ///
    /// # Errors
    ///
    /// Returns an error when `radius` is zero.
    pub fn radius(mut self, radius: u32) -> Result<Self, Error> {
        validate_point_radius("point-layer", radius)?;
        self.radius = Some(radius);
        Ok(self)
    }

    /// Replace mark and label alpha, including transparent and opaque endpoints.
    ///
    /// This replaces alpha after resolving color, regardless of edit order.
    /// Without an exact color, label RGB stays owned by its theme text role.
    #[must_use]
    pub const fn alpha(mut self, alpha: u8) -> Self {
        self.alpha = Some(alpha);
        self
    }

    /// Inspect the optional caller paint instruction, before theme resolution.
    pub const fn get_color(&self) -> Option<Color> {
        self.color
    }

    /// Inspect the optional caller alpha instruction, before theme resolution.
    pub const fn get_alpha(&self) -> Option<u8> {
        self.alpha
    }

    /// Inspect the optional caller radius instruction, before theme resolution.
    pub const fn get_radius(&self) -> Option<u32> {
        self.radius
    }

    /// Attach one caller-owned annotation label to every point.
    ///
    /// Point labels do not create legend entries. They must align one-to-one
    /// with the layer's x/y coordinates.
    #[must_use]
    pub fn labels(mut self, labels: CategoryValues) -> Self {
        self.labels = Some(labels);
        self
    }

    /// Give the complete layer one legend identity.
    ///
    /// This creates at most one legend entry and does not label individual
    /// points. Identity uses the retained source; style and layout remain display
    /// instructions. Plain replacement retains prior Text instructions. Duplicate
    /// identities require equal complete displayed Text and mark keys.
    #[must_use]
    pub fn legend_label(mut self, label: impl Into<crate::Text>) -> Self {
        self.legend_label
            .replace_from(label.into())
            .expect("public Text always has a source");
        self
    }

    /// Remove only the local legend-label appearance, retaining its identity/layout.
    #[must_use]
    pub fn clear_legend_label_style(mut self) -> Self {
        self.legend_label.edit_clear_style();
        self
    }

    /// Remove only the local legend-label layout, retaining its identity/appearance.
    #[must_use]
    pub fn clear_legend_label_layout(mut self) -> Self {
        self.legend_label.edit_clear_layout();
        self
    }

    pub(crate) const fn x_values(&self) -> &NumericValues {
        &self.x
    }

    pub(crate) const fn y_values(&self) -> &NumericValues {
        &self.y
    }

    pub(crate) const fn label_values(&self) -> Option<&CategoryValues> {
        self.labels.as_ref()
    }

    pub(crate) const fn legend_content(&self) -> Option<&crate::Text> {
        self.legend_label.provided()
    }

    pub(crate) fn point_style(
        &self,
        automatic_color: (u8, u8, u8),
        defaults: &crate::theme::mark::SupplementalPointTheme,
    ) -> crate::render::backend::PointStyle {
        let color = self.color.unwrap_or_else(|| {
            crate::theme::color_from_rgb(automatic_color).alpha(defaults.get_fill_alpha())
        });
        crate::render::backend::PointStyle {
            color: self.alpha.map_or(color, |alpha| color.alpha(alpha)),
            radius: self.radius.unwrap_or(defaults.get_radius()),
            outline: None,
            shape: crate::PointShape::Circle,
        }
    }

    pub(crate) fn label_appearance(
        &self,
        role: &crate::theme::TextTheme,
    ) -> Result<crate::theme::TextTheme, Error> {
        let paint = self.color.unwrap_or(role.get_color());
        role.try_copy()?
            .color(self.alpha.map_or(paint, |alpha| paint.alpha(alpha)))
    }
}

fn validate_point_radius(role: &str, radius: u32) -> Result<(), Error> {
    if radius == 0 {
        return Err(Error::Data(format!(
            "{role} radius must be greater than zero"
        )));
    }
    Ok(())
}