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
//! Complete axis chrome and exact role-local spacing construction.

use crate::layout::kernel::{FeedbackRound, SpatialRounding};
use crate::{Error, Result};

use super::spacing::ExactLength;
use super::{LocalMetric, RelativeSpacing, StrokeTheme};

pub(crate) fn stroke_style(stroke: &StrokeTheme) -> Result<crate::render::backend::LineStyle> {
    stroke.validate()?;
    let width = crate::layout::kernel::LayoutScalar::from_css_pixels(
        f64::from(stroke.get_width()),
        SpatialRounding::NearestEven,
    )?;
    if width.quanta() == 0 {
        return Err(Error::Render("axis stroke collapses in CSS quanta".into()));
    }
    Ok(stroke.backend_style())
}

/// Nonempty set of physical coordinate-frame sides.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FrameSides {
    bits: u8,
}

macro_rules! side_field {
    ($field:ident, $get:ident, $bit:literal) => {
        #[doc = concat!("Inspect whether the physical `", stringify!($field), "` side is present.")]
        pub fn $get(&self) -> bool {
            self.bits & $bit != 0
        }
        #[doc = concat!("Replace only the `", stringify!($field), "` side; at least one side must remain.")]
        pub fn $field(mut self, value: bool) -> Result<Self> {
            self.bits = if value {
                self.bits | $bit
            } else {
                self.bits & !$bit
            };
            self.validate()?;
            Ok(self)
        }
    };
}

impl FrameSides {
    #[expect(
        clippy::fn_params_excessive_bools,
        reason = "the complete constructor explicitly names the four independent frame sides"
    )]
    /// Construct a present frame's physical side set; at least one must be true.
    pub fn new(top: bool, right: bool, bottom: bool, left: bool) -> Result<Self> {
        let value = Self {
            bits: u8::from(top)
                | (u8::from(right) << 1)
                | (u8::from(bottom) << 2)
                | (u8::from(left) << 3),
        };
        value.validate()?;
        Ok(value)
    }

    fn validate(&self) -> Result<()> {
        if self.bits != 0 && self.bits & !15 == 0 {
            Ok(())
        } else {
            Err(Error::Data(
                "a present frame requires at least one side".into(),
            ))
        }
    }

    side_field!(top, get_top, 1);
    side_field!(right, get_right, 2);
    side_field!(bottom, get_bottom, 4);
    side_field!(left, get_left, 8);

    /// Existing standard drawing order: bottom, right, top, left.
    pub(crate) fn drawing_order(&self) -> [bool; 4] {
        [
            self.get_bottom(),
            self.get_right(),
            self.get_top(),
            self.get_left(),
        ]
    }
}

/// Complete frame sides and independent stroke appearance.
#[derive(Clone, Debug, PartialEq)]
pub struct FrameTheme {
    pub(crate) sides: FrameSides,
    pub(crate) stroke: StrokeTheme,
}

impl FrameTheme {
    /// Construct a nonempty side set and complete stroke.
    pub fn new(sides: FrameSides, stroke: StrokeTheme) -> Result<Self> {
        let value = Self { sides, stroke };
        value.validate()?;
        Ok(value)
    }
    fn validate(&self) -> Result<()> {
        self.sides.validate()?;
        self.stroke.validate()
    }
    /// Borrow the physical side set.
    pub fn get_sides(&self) -> &FrameSides {
        &self.sides
    }
    /// Borrow the complete frame stroke.
    pub fn get_stroke(&self) -> &StrokeTheme {
        &self.stroke
    }
    /// Replace only the nonempty physical side set.
    pub fn sides(self, sides: FrameSides) -> Result<Self> {
        Self::new(sides, self.stroke)
    }
    /// Replace only the complete frame stroke.
    pub fn stroke(self, stroke: StrokeTheme) -> Result<Self> {
        Self::new(self.sides, stroke)
    }
}

/// Complete tick stroke and positive integral CSS length.
#[derive(Clone, Debug, PartialEq)]
pub struct TickTheme {
    pub(crate) stroke: StrokeTheme,
    pub(crate) length: u32,
}

impl TickTheme {
    /// Construct the tick stroke and positive CSS length.
    pub fn new(stroke: StrokeTheme, length: u32) -> Result<Self> {
        let value = Self { stroke, length };
        value.validate()?;
        Ok(value)
    }
    fn validate(&self) -> Result<()> {
        self.stroke.validate()?;
        if self.length == 0 {
            return Err(Error::Data(
                "tick length must be positive CSS pixels".into(),
            ));
        }
        Ok(())
    }
    /// Borrow the complete tick stroke.
    pub fn get_stroke(&self) -> &StrokeTheme {
        &self.stroke
    }
    /// Inspect the positive tick length in CSS pixels.
    pub fn get_length(&self) -> u32 {
        self.length
    }
    /// Replace only the complete tick stroke.
    pub fn stroke(self, stroke: StrokeTheme) -> Result<Self> {
        Self::new(stroke, self.length)
    }
    /// Replace only the positive CSS tick length.
    pub fn length(self, length: u32) -> Result<Self> {
        Self::new(self.stroke, length)
    }
}

macro_rules! axis_spacing {
    ($($field:ident => $get:ident : $metric:literal),+ $(,)?) => {
        #[derive(Clone, Debug, PartialEq, Eq)]
        /// Exact independent axis gaps, resolved from tick-label or axis-title em.
        pub struct AxisSpacing { $(pub(crate) $field: RelativeSpacing),+ }

        impl AxisSpacing {
            /// Construct all six nonnegative local spacing relationships.
            pub fn new($($field: RelativeSpacing),+) -> Result<Self> { Ok(Self { $($field),+ }) }
            $(
                #[doc = concat!("Borrow the exact `", stringify!($field), "` relationship.")]
                pub fn $get(&self) -> &RelativeSpacing { &self.$field }
                #[doc = concat!("Replace only the `", stringify!($field), "` relationship.")]
                pub fn $field(mut self, value: RelativeSpacing) -> Result<Self> {
                    self.$field = value;
                    self.revalidated()
                }
            )+
            fn revalidated(self) -> Result<Self> { Self::new($(self.$field),+) }
            pub(crate) fn relationships(&self) -> [&RelativeSpacing; 6] { [$(&self.$field),+] }
            pub(crate) fn lengths(&self, tick: f64, title: f64) -> Result<AxisLengths> {
                let metrics = [LocalMetric::css_pixels(tick)?, LocalMetric::css_pixels(title)?];
                Ok(AxisLengths { $($field: self.$get().product(metrics[$metric])),+ })
            }
        }

        /// Post-selection exact products; never a second stored appearance value.
        #[derive(Debug)]
        pub(crate) struct AxisLengths { $(pub(crate) $field: ExactLength),+ }
    };
}

axis_spacing! {
    x_tick_label_gap => get_x_tick_label_gap: 0,
    y_tick_label_gap => get_y_tick_label_gap: 0,
    x_title_tick_label_gap => get_x_title_tick_label_gap: 1,
    x_title_without_tick_labels_gap => get_x_title_without_tick_labels_gap: 1,
    y_title_tick_label_gap => get_y_title_tick_label_gap: 1,
    y_title_edge_padding => get_y_title_edge_padding: 1,
}

/// Complete coordinate/cell frame, tick, grid and local spacing appearance.
#[derive(Clone, Debug, PartialEq)]
pub struct AxisTheme {
    pub(crate) frame: Option<FrameTheme>,
    pub(crate) cell_frame: Option<FrameTheme>,
    pub(crate) ticks: Option<TickTheme>,
    pub(crate) grid: Option<StrokeTheme>,
    pub(crate) spacing: AxisSpacing,
}

/// Borrowed chrome selected for a coordinate-axis consumer, not another theme.
pub(crate) struct AxisChrome<'a> {
    pub(crate) frame: Option<&'a FrameTheme>,
    pub(crate) grid: Option<&'a StrokeTheme>,
    ticks: Option<&'a TickTheme>,
}

impl AxisChrome<'_> {
    pub(crate) fn outward(
        &self,
        side: crate::layout::AxisSide,
        present_ticks: bool,
    ) -> Result<ExactLength> {
        let frame = self.frame.filter(|frame| match side {
            crate::layout::AxisSide::Bottom => frame.get_sides().get_bottom(),
            crate::layout::AxisSide::Left => frame.get_sides().get_left(),
        });
        let mut length = ExactLength::pixels(
            frame.map_or(0.0, |frame| f64::from(frame.get_stroke().get_width()) / 2.0),
        )?;
        if let Some(ticks) = self.ticks.filter(|_| present_ticks) {
            length = length
                .add_pixels(f64::from(ticks.get_length()))?
                .add_pixels(f64::from(ticks.get_stroke().get_width()) / 2.0)?;
        }
        Ok(length)
    }
}

impl AxisTheme {
    /// Construct complete axis chrome, using None for absent frame/ticks/grid.
    pub fn new(
        frame: Option<FrameTheme>,
        cell_frame: Option<FrameTheme>,
        ticks: Option<TickTheme>,
        grid: Option<StrokeTheme>,
        spacing: AxisSpacing,
    ) -> Result<Self> {
        let value = Self {
            frame,
            cell_frame,
            ticks,
            grid,
            spacing,
        };
        value.validate()?;
        Ok(value)
    }
    pub(crate) fn validate(&self) -> Result<()> {
        if let Some(value) = self.get_frame() {
            value.validate()?;
        }
        if let Some(value) = self.get_cell_frame() {
            value.validate()?;
        }
        if let Some(value) = self.get_ticks() {
            value.validate()?;
        }
        if let Some(value) = self.get_grid() {
            value.validate()?;
        }
        Ok(())
    }
    /// Borrow the optional ordinary coordinate frame.
    pub fn get_frame(&self) -> Option<&FrameTheme> {
        self.frame.as_ref()
    }
    /// Borrow the independent optional variable-grid cell frame.
    pub fn get_cell_frame(&self) -> Option<&FrameTheme> {
        self.cell_frame.as_ref()
    }
    /// Borrow the optional tick appearance.
    pub fn get_ticks(&self) -> Option<&TickTheme> {
        self.ticks.as_ref()
    }
    /// Borrow the optional grid stroke.
    pub fn get_grid(&self) -> Option<&StrokeTheme> {
        self.grid.as_ref()
    }
    /// Borrow all independent exact axis relationships.
    pub fn get_spacing(&self) -> &AxisSpacing {
        &self.spacing
    }
    pub(crate) fn coordinate_chrome(&self) -> AxisChrome<'_> {
        AxisChrome {
            frame: self.get_frame(),
            grid: self.get_grid(),
            ticks: self.get_ticks(),
        }
    }
    /// Cell outlines belong to the native grid; common cell axes paint only ticks
    /// and text. Natural sizing and Matrix planning share this same selection.
    pub(crate) fn cell_axis_chrome(&self) -> AxisChrome<'_> {
        AxisChrome {
            frame: None,
            grid: None,
            ticks: self.get_ticks(),
        }
    }
    /// Replace only the optional coordinate frame.
    pub fn frame(self, frame: Option<FrameTheme>) -> Result<Self> {
        Self::new(frame, self.cell_frame, self.ticks, self.grid, self.spacing)
    }
    /// Replace only the optional variable-grid cell frame.
    pub fn cell_frame(self, cell_frame: Option<FrameTheme>) -> Result<Self> {
        Self::new(self.frame, cell_frame, self.ticks, self.grid, self.spacing)
    }
    /// Replace only the optional tick appearance.
    pub fn ticks(self, ticks: Option<TickTheme>) -> Result<Self> {
        Self::new(self.frame, self.cell_frame, ticks, self.grid, self.spacing)
    }
    /// Replace only the optional grid stroke.
    pub fn grid(self, grid: Option<StrokeTheme>) -> Result<Self> {
        Self::new(self.frame, self.cell_frame, self.ticks, grid, self.spacing)
    }
    /// Replace only the complete local axis relationships.
    pub fn spacing(self, spacing: AxisSpacing) -> Result<Self> {
        Self::new(self.frame, self.cell_frame, self.ticks, self.grid, spacing)
    }

    pub(crate) fn same_validated(&self, other: &Self) -> Result<bool> {
        self.validate()?;
        other.validate()?;

        if self.frame != other.frame
            || self.cell_frame != other.cell_frame
            || self.ticks != other.ticks
            || self.grid != other.grid
        {
            return Ok(false);
        }
        for (left, right) in self
            .get_spacing()
            .relationships()
            .into_iter()
            .zip(other.get_spacing().relationships())
        {
            if !left.same(right) {
                return Ok(false);
            }
        }
        Ok(true)
    }

    pub(crate) fn observe_feedback(&self, round: &mut FeedbackRound) -> Result<()> {
        for stroke in [
            self.get_frame().map(FrameTheme::get_stroke),
            self.get_cell_frame().map(FrameTheme::get_stroke),
            self.get_ticks().map(TickTheme::get_stroke),
            self.get_grid(),
        ] {
            round.observe_count(usize::from(stroke.is_some()))?;
            if let Some(stroke) = stroke {
                round.observe_number(f64::from(stroke.get_width()))?;
                round.observe_count(stroke.get_pattern() as usize)?;
                for channel in [
                    stroke.get_color().red(),
                    stroke.get_color().green(),
                    stroke.get_color().blue(),
                ] {
                    round.observe_count(usize::from(channel))?;
                }
                round.observe_number(stroke.get_color().get_alpha())?;
            }
        }
        for frame in [self.get_frame(), self.get_cell_frame()]
            .into_iter()
            .flatten()
        {
            for side in frame.get_sides().drawing_order() {
                round.observe_count(usize::from(side))?;
            }
        }
        if let Some(ticks) = self.get_ticks() {
            round.observe_count(ticks.get_length() as usize)?;
        }
        for spacing in self.get_spacing().relationships() {
            spacing.observe_feedback(round)?;
        }
        Ok(())
    }
}

impl AxisLengths {
    pub(crate) fn before(value: &ExactLength, anchor: f64) -> Result<f64> {
        Self::pixels(value.before(anchor)?)
    }
    pub(crate) fn hard(value: &ExactLength) -> Result<f64> {
        Self::pixels(value.round(SpatialRounding::Ceil)?)
    }

    #[expect(
        clippy::cast_precision_loss,
        reason = "the checked quanta bound guarantees exact integer conversion"
    )]
    fn pixels(value: crate::layout::kernel::LayoutScalar) -> Result<f64> {
        if value.quanta().unsigned_abs() > (1_u64 << 53) {
            return Err(Error::Render(
                "axis length cannot retain exact CSS quanta".into(),
            ));
        }
        Ok(value.quanta() as f64 / 1024.0)
    }
}