lichtung-plot 0.3.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Typed supplemental geometry for numeric charts.

use crate::Error;

use crate::style::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, elements::GuideStyle, style::LinePattern};
/// let guide = GuideStyle::new(Color::rgba(20, 80, 140, 128.0 / 255.0)?, 1.5, LinePattern::Solid)?
///     .pattern(LinePattern::Dashed)?;
/// assert_eq!(guide.get_color().get_alpha(), 128.0 / 255.0);
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// Exact paint is typed; RGB tuples are not style inputs:
/// ```compile_fail
/// use lichtung_plot::{elements::GuideStyle, style::LinePattern};
/// let _ = GuideStyle::new((20, 80, 140), 1.5, LinePattern::Solid);
/// ```
#[derive(Debug, Clone, Copy, 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> {
        validate_guide_width(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 validate_guide_width(width: f32) -> Result<(), Error> {
    if !width.is_finite() || width <= 0.0 {
        return Err(Error::Data(
            format!("guide width must be finite and strictly positive; got {width}").into(),
        ));
    }
    Ok(())
}

/// The scientific geometry of a supplemental reference line.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum GuideGeometry {
    /// A horizontal line across the resolved panel range.
    Horizontal {
        /// Authored numeric y coordinate.
        y: f64,
    },
    /// A vertical line across the resolved panel range.
    Vertical {
        /// Authored numeric x coordinate.
        x: f64,
    },
    /// A finite segment in scientific coordinates.
    Segment {
        /// First endpoint.
        start: (f64, f64),
        /// Second endpoint.
        end: (f64, f64),
    },
}

/// An authored numeric guide, independent of its owner's effective theme.
///
/// Geometry never expands the scientific window. Finite off-window portions
/// are clipped; omitted visual fields resolve at preparation against the
/// effective theme's estimate-reference stroke.
#[derive(Debug, Clone, PartialEq)]
pub struct GuideSpec {
    geometry: GuideGeometry,
    color: Option<Color>,
    width: Option<f32>,
    pattern: Option<LinePattern>,
}

impl GuideSpec {
    const fn new(geometry: GuideGeometry) -> Self {
        Self {
            geometry,
            color: None,
            width: None,
            pattern: None,
        }
    }

    /// Construct a horizontal guide with theme styling.
    #[must_use]
    pub const fn horizontal(y: f64) -> Self {
        Self::new(GuideGeometry::Horizontal { y })
    }

    /// Construct a vertical guide with theme styling.
    #[must_use]
    pub const fn vertical(x: f64) -> Self {
        Self::new(GuideGeometry::Vertical { x })
    }

    /// Construct a finite scientific segment with theme styling.
    #[must_use]
    pub const fn segment(x_start: f64, y_start: f64, x_end: f64, y_end: f64) -> Self {
        Self::new(GuideGeometry::Segment {
            start: (x_start, y_start),
            end: (x_end, y_end),
        })
    }

    /// Borrow the original scientific geometry.
    pub const fn geometry(&self) -> &GuideGeometry {
        &self.geometry
    }

    /// Supply all three exact visual overrides.
    #[must_use]
    pub fn style(self, style: GuideStyle) -> Self {
        Self {
            geometry: self.geometry,
            color: Some(style.color),
            width: Some(style.width),
            pattern: Some(style.pattern),
        }
    }

    /// Override only the complete reference paint.
    #[must_use]
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Override only the positive finite CSS stroke width.
    pub fn width(mut self, width: f32) -> Result<Self, Error> {
        validate_guide_width(width)?;
        self.width = Some(width);
        Ok(self)
    }

    /// Override only the line pattern.
    #[must_use]
    pub fn pattern(mut self, pattern: LinePattern) -> Self {
        self.pattern = Some(pattern);
        self
    }

    /// The explicitly supplied paint, if any.
    pub const fn get_color(&self) -> Option<Color> {
        self.color
    }

    /// The explicitly supplied width, if any.
    pub const fn get_width(&self) -> Option<f32> {
        self.width
    }

    /// The explicitly supplied pattern, if any.
    pub const fn get_pattern(&self) -> Option<LinePattern> {
        self.pattern
    }

    pub(crate) fn replace_visual(
        &mut self,
        color: Option<Color>,
        width: Option<f32>,
        pattern: Option<LinePattern>,
    ) {
        self.color = color;
        self.width = width;
        self.pattern = pattern;
    }

    pub(crate) fn line_style(&self, theme: &crate::Theme) -> crate::render::backend::LineStyle {
        let defaults = theme
            .marks
            .get_strokes()
            .get_references()
            .get_estimate_reference();
        crate::render::backend::LineStyle {
            color: self.color.unwrap_or(defaults.get_color()),
            width: self.width.unwrap_or(defaults.get_width()),
            pattern: self.pattern.unwrap_or(defaults.get_pattern()),
        }
    }
}

/// 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, Text, Theme, elements::PointLayer, text::TextAlignment};
/// 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(0.5)?.color(Color::rgb(20, 80, 140)).radius(5)?.legend_label(label);
/// assert_eq!(layer.get_alpha(), Some(0.5));
/// assert_eq!(layer.get_color(), Some(Color::rgb(20, 80, 140)));
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// There is one explicit alpha setter; no second opacity alias:
/// ```compile_fail
/// use lichtung_plot::{NumericValues, elements::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) identity: crate::data::InstanceId,
    pub(crate) label_layout: Option<crate::text::TextLayout>,
    x: NumericValues,
    y: NumericValues,
    labels: Option<CategoryValues>,
    legend_label: crate::Text,
    color: Option<Color>,
    radius: Option<u32>,
    alpha: Option<f64>,
}

/// 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.
///
/// Each explicit Color owns its complete paint, including zero opacity:
/// ```
/// use lichtung_plot::{CategoryValues, Color, NumericValues, elements::BarPointLayer};
/// let layer = BarPointLayer::new(
///     CategoryValues::new("category", ["A"])?,
///     NumericValues::new("value", [2.0]),
/// ).color(Color::rgba(20, 80, 140, 0.0)?).radius(4)?;
/// assert_eq!(layer.get_color().unwrap().get_alpha(), 0.0);
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct BarPointLayer {
    pub(crate) identity: crate::data::InstanceId,
    category: CategoryValues,
    series: Option<CategoryValues>,
    value: NumericValues,
    color: Option<Color>,
    radius: Option<u32>,
}

impl BarPointLayer {
    /// Construct independent observations at their native category slots.
    /// Omitted paint and radius are resolved from the effective plot theme.
    #[must_use]
    pub fn new(category: CategoryValues, value: NumericValues) -> Self {
        Self {
            identity: crate::data::InstanceId::new(),
            category,
            series: None,
            value,
            color: None,
            radius: None,
        }
    }

    /// Bind positioned series independently of the main plot's source.
    #[must_use]
    pub fn series(mut self, series: CategoryValues) -> Self {
        self.series = Some(series);
        self
    }

    /// Supply a complete fixed point paint, with its original opacity.
    #[must_use]
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Supply a fixed positive CSS point radius.
    pub fn radius(mut self, radius: u32) -> Result<Self, Error> {
        validate_point_radius("bar-point-layer", radius)?;
        self.radius = Some(radius);
        Ok(self)
    }

    /// 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
    }

    /// The explicit complete paint, or None for theme paint.
    #[must_use]
    pub const fn get_color(&self) -> Option<Color> {
        self.color
    }

    /// The explicit radius, or None for the theme radius.
    #[must_use]
    pub const fn get_radius(&self) -> Option<u32> {
        self.radius
    }

    pub(crate) fn replace_visual(&mut self, color: Option<Color>, radius: Option<u32>) {
        self.color = color;
        self.radius = radius;
    }

    pub(crate) fn point_style(&self, theme: &crate::Theme) -> crate::render::backend::PointStyle {
        let defaults = theme.marks.get_points().get_supplemental();
        let color = self.color.unwrap_or_else(|| {
            crate::theme::color_from_rgb(theme.marks.get_neutral_paints().get_path().as_rgb())
                .with_alpha(defaults.get_fill_alpha())
        });
        crate::render::backend::PointStyle {
            color,
            radius: self.radius.unwrap_or(defaults.get_radius()),
            outline: None,
            shape: crate::style::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::text::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 0.8). Nonempty,
    /// aligned, finite values are validated during chart preflight.
    #[must_use]
    pub fn new(x: NumericValues, y: NumericValues) -> Self {
        Self {
            identity: crate::data::InstanceId::new(),
            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.
    pub fn alpha(mut self, alpha: f64) -> Result<Self, Error> {
        self.alpha = Some(crate::alpha::validated_alpha(alpha)?);
        Ok(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<f64> {
        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 replace_visual(
        &mut self,
        color: Option<Color>,
        radius: Option<u32>,
        alpha: Option<f64>,
        legend: crate::Text,
        layout: Option<crate::text::TextLayout>,
    ) {
        self.color = color;
        self.radius = radius;
        self.alpha = alpha;
        self.legend_label.apply_appearance(legend);
        self.label_layout = layout;
    }

    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).with_alpha(defaults.get_fill_alpha())
        });
        crate::render::backend::PointStyle {
            color: self.alpha.map_or(color, |alpha| color.with_alpha(alpha)),
            radius: self.radius.unwrap_or(defaults.get_radius()),
            outline: None,
            shape: crate::style::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.with_alpha(alpha)))
    }
}

pub(crate) 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").into(),
        ));
    }
    Ok(())
}