plotkit-core 0.1.1

Core types and logic for the plotkit plotting library
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
//! The top-level Figure container.
//!
//! A [`Figure`] owns one or more [`Axes`] (subplots) and orchestrates the
//! full rendering pipeline: filling the figure background, computing the
//! subplot grid layout, drawing the optional super-title, and delegating
//! per-axes rendering.

use crate::axes::Axes;
use crate::error::Result;
use crate::layout;
use crate::primitives::{Affine, HAlign, Paint, Path, Point, Rect, TextStyle, VAlign};
use crate::renderer::Renderer;
use crate::theme::Theme;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Default figure width in pixels.
const DEFAULT_WIDTH: u32 = 800;

/// Default figure height in pixels.
const DEFAULT_HEIGHT: u32 = 600;

/// Vertical space (in pixels) reserved for the suptitle when present.
const SUPTITLE_RESERVED_HEIGHT: f64 = 30.0;

/// Default outer margin (in pixels) around the subplot grid.
const DEFAULT_MARGIN: f64 = 20.0;

/// Default gap (in pixels) between subplot cells.
const DEFAULT_GAP: f64 = 15.0;

// ---------------------------------------------------------------------------
// Figure
// ---------------------------------------------------------------------------

/// A figure is the top-level container for one or more axes (subplots).
///
/// The figure owns all axes, holds the overall dimensions, an optional
/// super-title, and the visual theme. It implements the rendering pipeline
/// described in `ARCHITECTURE.md`:
///
/// 1. Fill figure background.
/// 2. Draw suptitle if set.
/// 3. Compute subplot layout rectangles.
/// 4. For each axes: delegate rendering with its allocated rectangle and theme.
///
/// # Ownership model (ADR-003)
///
/// `Figure` owns `Vec<Axes>` directly -- no `Rc`, no `RefCell`.
/// [`add_subplot`](Figure::add_subplot) returns `&mut Axes`, and the borrow
/// checker enforces single-axes mutation at compile time.
///
/// # Examples
///
/// ```no_run
/// use plotkit_core::figure::Figure;
///
/// let mut fig = Figure::new();
/// let ax = fig.add_subplot(1, 1, 1);
/// // ax.plot(...)?;
/// ```
#[derive(Debug)]
pub struct Figure {
    /// The subplot axes owned by this figure, stored in insertion order.
    axes: Vec<Axes>,
    /// Width of the output image in pixels.
    width: u32,
    /// Height of the output image in pixels.
    height: u32,
    /// Optional overall title displayed above all subplots.
    suptitle: Option<String>,
    /// The visual theme applied to the figure and inherited by axes.
    theme: Theme,
    /// Subplot grid dimensions `(nrows, ncols)`, set by `add_subplot`.
    subplot_grid: Option<(usize, usize)>,
}

impl Figure {
    /// Creates a new figure with default dimensions (800 x 600 pixels).
    pub fn new() -> Self {
        Self {
            axes: Vec::new(),
            width: DEFAULT_WIDTH,
            height: DEFAULT_HEIGHT,
            suptitle: None,
            theme: Theme::default(),
            subplot_grid: None,
        }
    }

    /// Creates a new figure with the specified dimensions in pixels.
    pub fn with_size(width: u32, height: u32) -> Self {
        Self {
            axes: Vec::new(),
            width,
            height,
            suptitle: None,
            theme: Theme::default(),
            subplot_grid: None,
        }
    }

    /// Returns the figure width in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Returns the figure height in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Adds a subplot and returns a mutable reference to it.
    ///
    /// Uses 1-based indexing in matplotlib style: `(nrows, ncols, index)`.
    /// The index counts across rows first (row-major), starting at 1.
    ///
    /// If a subplot already exists at the given `index`, the existing axes
    /// is returned without creating a duplicate. Otherwise a new [`Axes`]
    /// is created, appended to the figure's axes list, and returned.
    ///
    /// # Panics
    ///
    /// Panics if `nrows`, `ncols`, or `index` is zero, or if `index` exceeds
    /// `nrows * ncols`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use plotkit_core::figure::Figure;
    ///
    /// let mut fig = Figure::new();
    /// let ax = fig.add_subplot(2, 2, 1); // top-left of a 2x2 grid
    /// ```
    pub fn add_subplot(&mut self, nrows: usize, ncols: usize, index: usize) -> &mut Axes {
        assert!(nrows > 0, "nrows must be at least 1");
        assert!(ncols > 0, "ncols must be at least 1");
        assert!(index >= 1, "subplot index is 1-based; got 0");
        assert!(
            index <= nrows * ncols,
            "subplot index {index} exceeds grid size {nrows}x{ncols} = {}",
            nrows * ncols
        );

        // Store (or validate) the grid dimensions. If the grid was already set
        // with different dimensions, update to the latest request -- this
        // mirrors matplotlib's behaviour where later add_subplot calls can
        // redefine the grid.
        self.subplot_grid = Some((nrows, ncols));

        // Convert 1-based index to 0-based for internal storage.
        let zero_index = index - 1;

        // Ensure the internal axes vec is large enough. If the user skips
        // indices (e.g. add_subplot(2,2,3) without adding 1 and 2 first) we
        // pad with default Axes so that positional indexing is consistent.
        while self.axes.len() <= zero_index {
            self.axes.push(Axes::new());
        }

        &mut self.axes[zero_index]
    }

    /// Sets the overall figure title (super-title), displayed above all
    /// subplots.
    ///
    /// Returns `&mut Self` for builder-style chaining.
    pub fn suptitle(&mut self, title: &str) -> &mut Self {
        self.suptitle = Some(title.to_string());
        self
    }

    /// Sets the visual theme for the entire figure.
    ///
    /// The theme is inherited by all axes during rendering unless an
    /// individual axes has its own override.
    ///
    /// Returns `&mut Self` for builder-style chaining.
    pub fn set_theme(&mut self, theme: Theme) -> &mut Self {
        self.theme = theme;
        self
    }

    /// Returns a reference to the figure's theme.
    pub fn theme(&self) -> &Theme {
        &self.theme
    }

    /// Returns mutable access to the axes at `index` (0-based).
    ///
    /// Returns `None` if `index` is out of bounds.
    pub fn axes_mut(&mut self, index: usize) -> Option<&mut Axes> {
        self.axes.get_mut(index)
    }

    /// Returns a shared reference to the axes at `index` (0-based).
    ///
    /// Returns `None` if `index` is out of bounds.
    pub fn axes(&self, index: usize) -> Option<&Axes> {
        self.axes.get(index)
    }

    /// Returns the number of axes (subplots) in this figure.
    pub fn num_axes(&self) -> usize {
        self.axes.len()
    }

    // -----------------------------------------------------------------------
    // Rendering
    // -----------------------------------------------------------------------

    /// Renders the figure using the given renderer.
    ///
    /// This is the core rendering pipeline (per `ARCHITECTURE.md`):
    ///
    /// 1. Fill figure background with the theme's `figure_background` color.
    /// 2. Draw suptitle if one has been set.
    /// 3. Compute the subplot grid layout, producing one [`Rect`] per axes.
    /// 4. For each axes, delegate to [`Axes::render`] with its assigned
    ///    rectangle and the figure theme.
    pub fn render(&self, renderer: &mut impl Renderer) {
        let (w, h) = renderer.size();
        let fw = w as f64;
        let fh = h as f64;
        let theme = &self.theme;

        // ----- 1. Fill figure background -----------------------------------
        let bg_path = Path::rect(Rect::new(0.0, 0.0, fw, fh));
        renderer.fill_path(
            &bg_path,
            &Paint::new(theme.figure_background),
            Affine::IDENTITY,
        );

        // ----- 2. Draw suptitle if set -------------------------------------
        let top_offset = if let Some(ref title) = self.suptitle {
            let style = TextStyle {
                size: theme.title_size + 2.0, // suptitle slightly larger than axes title
                color: theme.text_color,
                weight: theme.title_weight,
                family: theme.font_family.clone(),
                halign: HAlign::Center,
                valign: VAlign::Top,
            };

            let text_pos = Point::new(fw / 2.0, DEFAULT_MARGIN * 0.5);
            renderer.draw_text(title, text_pos, &style, Affine::IDENTITY);

            SUPTITLE_RESERVED_HEIGHT
        } else {
            0.0
        };

        // ----- 3. Compute subplot layout -----------------------------------
        // Reduce the available height by the suptitle offset so that subplots
        // are laid out below the suptitle instead of overlapping it.
        let grid = self.subplot_grid.unwrap_or((1, 1));
        let rects = layout::compute_subplot_rects(
            fw,
            fh - top_offset,
            grid.0,
            grid.1,
            DEFAULT_MARGIN,
            DEFAULT_GAP,
        )
        .into_iter()
        .map(|mut r| {
            r.y += top_offset;
            r
        })
        .collect::<Vec<_>>();

        // ----- 4. Render each axes -----------------------------------------
        for (i, axes) in self.axes.iter().enumerate() {
            if let Some(rect) = rects.get(i) {
                axes.render(renderer, *rect, theme);
            }
        }
    }

    /// Renders the figure using the given renderer and returns the encoded
    /// output bytes (PNG, SVG, PDF, etc., depending on the renderer).
    ///
    /// This convenience method calls [`render`](Figure::render) and then
    /// [`Renderer::finalize`] to produce the final byte output.
    pub fn render_to<R: Renderer>(&self, mut renderer: R) -> Vec<u8> {
        self.render(&mut renderer);
        renderer.finalize()
    }

    /// Saves the figure to a file using the provided renderer.
    ///
    /// The renderer determines the output format. The encoded bytes are
    /// written to `path` atomically via [`std::fs::write`].
    pub fn save_with<R: Renderer>(&self, renderer: R, path: impl AsRef<std::path::Path>) -> Result<()> {
        let bytes = self.render_to(renderer);
        std::fs::write(path, bytes)?;
        Ok(())
    }
}

impl Default for Figure {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::Color;

    #[test]
    fn new_figure_has_default_dimensions() {
        let fig = Figure::new();
        assert_eq!(fig.width(), DEFAULT_WIDTH);
        assert_eq!(fig.height(), DEFAULT_HEIGHT);
    }

    #[test]
    fn with_size_sets_dimensions() {
        let fig = Figure::with_size(1024, 768);
        assert_eq!(fig.width(), 1024);
        assert_eq!(fig.height(), 768);
    }

    #[test]
    fn default_figure_has_no_axes() {
        let fig = Figure::new();
        assert_eq!(fig.num_axes(), 0);
    }

    #[test]
    fn add_subplot_creates_axes() {
        let mut fig = Figure::new();
        let _ax = fig.add_subplot(1, 1, 1);
        assert_eq!(fig.num_axes(), 1);
    }

    #[test]
    fn add_subplot_returns_same_axes_on_repeat() {
        let mut fig = Figure::new();
        fig.add_subplot(2, 2, 1);
        fig.add_subplot(2, 2, 1); // same index, should not duplicate
        assert_eq!(fig.num_axes(), 1);
    }

    #[test]
    fn add_subplot_pads_for_skipped_indices() {
        let mut fig = Figure::new();
        fig.add_subplot(2, 2, 3); // skip indices 1 and 2
        assert_eq!(fig.num_axes(), 3); // indices 0, 1, 2 all exist
    }

    #[test]
    #[should_panic(expected = "nrows must be at least 1")]
    fn add_subplot_panics_on_zero_rows() {
        let mut fig = Figure::new();
        fig.add_subplot(0, 1, 1);
    }

    #[test]
    #[should_panic(expected = "ncols must be at least 1")]
    fn add_subplot_panics_on_zero_cols() {
        let mut fig = Figure::new();
        fig.add_subplot(1, 0, 1);
    }

    #[test]
    #[should_panic(expected = "subplot index is 1-based")]
    fn add_subplot_panics_on_zero_index() {
        let mut fig = Figure::new();
        fig.add_subplot(1, 1, 0);
    }

    #[test]
    #[should_panic(expected = "subplot index 5 exceeds grid size")]
    fn add_subplot_panics_on_index_out_of_range() {
        let mut fig = Figure::new();
        fig.add_subplot(2, 2, 5);
    }

    #[test]
    fn suptitle_sets_title() {
        let mut fig = Figure::new();
        fig.suptitle("My Figure");
        assert_eq!(fig.suptitle, Some("My Figure".to_string()));
    }

    #[test]
    fn suptitle_returns_self_for_chaining() {
        let mut fig = Figure::new();
        fig.suptitle("Title 1").suptitle("Title 2");
        assert_eq!(fig.suptitle, Some("Title 2".to_string()));
    }

    #[test]
    fn set_theme_updates_theme() {
        let mut fig = Figure::new();
        let dark = Theme::dark();
        fig.set_theme(dark);
        assert_eq!(fig.theme().figure_background, Color::rgb(0x1C, 0x1C, 0x1C));
    }

    #[test]
    fn theme_returns_reference() {
        let fig = Figure::new();
        assert_eq!(fig.theme().figure_background, Color::WHITE);
    }

    #[test]
    fn axes_mut_returns_none_for_out_of_bounds() {
        let mut fig = Figure::new();
        assert!(fig.axes_mut(0).is_none());
    }

    #[test]
    fn axes_mut_returns_some_for_valid_index() {
        let mut fig = Figure::new();
        fig.add_subplot(1, 1, 1);
        assert!(fig.axes_mut(0).is_some());
    }

    #[test]
    fn axes_returns_shared_reference() {
        let mut fig = Figure::new();
        fig.add_subplot(1, 1, 1);
        assert!(fig.axes(0).is_some());
        assert!(fig.axes(1).is_none());
    }

    #[test]
    fn default_impl_matches_new() {
        let from_new = Figure::new();
        let from_default = Figure::default();
        assert_eq!(from_new.width(), from_default.width());
        assert_eq!(from_new.height(), from_default.height());
        assert_eq!(from_new.num_axes(), from_default.num_axes());
    }

    #[test]
    fn multiple_subplots_in_grid() {
        let mut fig = Figure::new();
        fig.add_subplot(2, 3, 1);
        fig.add_subplot(2, 3, 4);
        fig.add_subplot(2, 3, 6);
        assert_eq!(fig.num_axes(), 6); // padded to fill up to index 6
        assert_eq!(fig.subplot_grid, Some((2, 3)));
    }
}