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
use super::*;
use lichtung_plot::{
    composition::{
        compose, ComposeOptions, Composite, ImageAsset, ImageRendering, ObjectFit, Placement,
    },
    layout::{Anchor, BoxTarget, GridCellState, PaintRole, PlacePoint, RectRef, ReservedSlot},
    scales::AccentPalette,
};
use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};

fn image(width: u32, height: u32, pixel: [u8; 4]) -> ImageAsset {
    ImageAsset::from_png_bytes(&super::assets::rgba_png(
        width,
        height,
        &pixel.repeat(width as usize * height as usize),
    ))
    .unwrap()
}

fn pixels(output: &lichtung_plot::Output, directory: &std::path::Path) -> (u32, Vec<u8>) {
    super::assets::rgba_preview(output, directory)
}

use super::assets::sample;

#[test]
fn flat_composition_keeps_the_first_origin_and_previous_viewport_clips() {
    let base = image(100, 60, [255, 255, 255, 255]);
    let red = image(20, 10, [255, 0, 0, 255]);
    let green = image(8, 8, [0, 255, 0, 255]);
    let expand = ComposeOptions {
        expand_canvas: true,
    };
    // The first annotation is partly clipped by the original output.
    let first = compose(&base, [Placement::at(&red, (-10., 0.)).unwrap()]).unwrap();
    let second = first
        .compose_with_options(
            [Placement::boxed(&red, (-20., -10., 20., 10.)).unwrap()],
            expand,
        )
        .unwrap();
    assert_eq!((second.width(), second.height()), (120., 70.));
    assert_eq!(second.base_origin_in_output(), (20., 10.));
    let a = second
        .compose([Placement::at(&green, (0., 0.)).unwrap()])
        .unwrap();
    let b = compose(second.output(), [Placement::at(&green, (0., 0.)).unwrap()]).unwrap();
    assert_eq!(a.base_origin_in_output(), (20., 10.));
    assert_eq!(b.base_origin_in_output(), (20., 10.));
    let folder = tempfile::tempdir().unwrap();
    let result = pixels(a.output(), folder.path());
    assert_eq!(result, pixels(b.output(), folder.path()));
    assert_eq!(sample(&result, 5., 5.), [255, 0, 0, 255]);
    assert_eq!(sample(&result, 15., 15.), [0, 0, 0, 0]); // old red stays clipped
    assert_eq!(sample(&result, 21., 11.), [0, 255, 0, 255]);
    assert_eq!(sample(&result, 40., 25.), [255; 4]);
    let path = folder.path().join("default.png");
    a.png(&path).unwrap();
    let dimensions = |path: &std::path::Path| {
        let file = std::fs::File::open(path).unwrap();
        let reader = png::Decoder::new(std::io::BufReader::new(file))
            .read_info()
            .unwrap();
        (reader.info().size(), reader.info().pixel_dims)
    };
    assert_eq!(dimensions(&path).0, (120, 70));
    assert!(dimensions(&path).1.is_none());
    a.output().png(&path).unwrap();
    assert_eq!(dimensions(&path).0, (375, 219));
    assert!(dimensions(&path).1.is_some());
    assert!(a.output().layout_report().is_err());
    assert!(a
        .compose([Placement::in_slot(&red, 0, 0).unwrap()])
        .is_err());
}

#[test]
fn expansion_uses_actual_png_alpha_and_clipped_support() {
    let base = image(40, 30, [255; 4]);
    let mut data = [0u8; 16 * 4];
    data[60..64].copy_from_slice(&[200, 40, 10, 128]);
    let partial = ImageAsset::from_png_bytes(&super::assets::rgba_png(4, 4, &data)).unwrap();
    let empty = image(100, 100, [255, 0, 0, 0]);
    let expand = ComposeOptions {
        expand_canvas: true,
    };
    let result = Composite::with_options(
        &base,
        [
            Placement::at(&partial, (-4., -4.))
                .unwrap()
                .image_rendering(ImageRendering::CrispEdges),
            Placement::at(&empty, (-100., -100.)).unwrap(),
        ],
        expand,
    )
    .unwrap();
    assert_eq!(result.base_origin_in_output(), (1., 1.));
    assert_eq!((result.width(), result.height()), (41., 31.));
    let folder = tempfile::tempdir().unwrap();
    let raster = pixels(result.output(), folder.path());
    assert_eq!(sample(&raster, 0., 0.), [200, 40, 10, 128]);
    let smooth = base
        .compose_with_options([Placement::at(&partial, (-4., -4.)).unwrap()], expand)
        .unwrap();
    assert_eq!(smooth.base_origin_in_output(), (1.5, 1.5));
    let cropped = base
        .compose_with_options(
            [Placement::boxed(&partial, (-20., -20., 1., 1.))
                .unwrap()
                .fit(ObjectFit::None)
                .position(lichtung_plot::composition::ObjectPosition::top_left())
                .image_rendering(ImageRendering::CrispEdges)],
            expand,
        )
        .unwrap();
    assert_eq!(cropped.base_origin_in_output(), (0., 0.));
    assert_eq!((cropped.width(), cropped.height()), (40., 30.));
}

#[test]
fn actual_native_boundary_orders_insertions_without_inheriting_the_scientific_clip() {
    let calls = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&calls);
    let theme = Theme::publication();
    let marks = theme
        .marks()
        .clone()
        .accents(AccentPalette::new([OpaqueColor::rgb(255, 0, 0)]).unwrap())
        .unwrap();
    let plot = Plot::scatter(
        NumericValues::new("x", [0.5, 1., 1.5]),
        NumericValues::new("y", [0.5, 1., 1.5]),
    )
    .x_limits(0., 2.)
    .y_limits(0., 2.)
    .size(600, 420)
    .point_alpha(1.)
    .unwrap()
    .theme(theme.customize().marks(marks).build().unwrap())
    .x_tick_format(
        lichtung_plot::NumericFormat::default().value_function(move |context| {
            counter.fetch_add(1, Ordering::Relaxed);
            context.format_builtin()
        }),
    );
    let base = plot.render().unwrap();
    let prepared = calls.load(Ordering::Relaxed);
    assert!(prepared > 0);
    let report = base.layout_report().unwrap();
    let area = report
        .rect(&RectRef::plot_area(lichtung_plot::layout::PanelPath::root()))
        .unwrap();
    let center = (
        area.left() + area.width() / 2.,
        area.top() + area.height() / 2.,
    );
    let gap = report
        .boundaries()
        .iter()
        .find(|gap| {
            gap.ahead()
                .is_some_and(|batch| matches!(batch.role(), PaintRole::Primary | PaintRole::Body))
        })
        .unwrap()
        .clone();
    let green = image(1, 1, [0, 255, 0, 255]);
    let blue = image(1, 1, [0, 0, 255, 255]);
    let behind = base
        .compose([
            Placement::boxed(&green, area)
                .unwrap()
                .fit(ObjectFit::Fill)
                .at_boundary(gap.clone()),
            Placement::at(&blue, (0., 0.))
                .unwrap()
                .size(10., 10.)
                .at_boundary(gap.clone()),
        ])
        .unwrap();
    let top = base
        .compose([Placement::boxed(&green, area).unwrap().fit(ObjectFit::Fill)])
        .unwrap();
    let folder = tempfile::tempdir().unwrap();
    let prior = pixels(&base, folder.path());
    assert_eq!(
        pixels(base.compose([]).unwrap().output(), folder.path()),
        prior
    );
    let under = pixels(behind.output(), folder.path());
    let above = pixels(top.output(), folder.path());
    assert_eq!(
        sample(&under, center.0, center.1),
        sample(&prior, center.0, center.1)
    );
    assert_ne!(sample(&prior, center.0, center.1), [0, 255, 0, 255]);
    assert_eq!(sample(&above, center.0, center.1), [0, 255, 0, 255]);
    assert_eq!(sample(&under, 2., 2.), [0, 0, 255, 255]);
    let expanded = behind
        .output()
        .compose_with_options(
            [Placement::at(&green, (-20., -10.))
                .unwrap()
                .size(20., 10.)
                .at_boundary(gap)],
            ComposeOptions {
                expand_canvas: true,
            },
        )
        .unwrap();
    assert_eq!(expanded.base_origin_in_output(), (20., 10.));
    assert_eq!(expanded.output().layout_report().unwrap(), report);
    let raster = pixels(expanded.output(), folder.path());
    assert_eq!(sample(&raster, 5., 5.), [0, 255, 0, 255]);
    assert_eq!(sample(&raster, 22., 12.), [0, 0, 255, 255]);
    let path = folder.path().join("text.svg");
    expanded.svg_preserve_text(&path).unwrap();
    assert_unique_svg_ids(&std::fs::read_to_string(path).unwrap());
    assert_eq!(calls.load(Ordering::Relaxed), prepared);
}

#[test]
fn borrowing_a_spanning_slot_retains_its_actual_allocation_and_occupancy() {
    let photo = image(10, 10, [23, 45, 67, 255]);
    let canvas = Canvas::grid(2, 2)
        .unwrap()
        .size(440, 320)
        .reserve(
            0,
            0,
            ReservedSlot::at_least(200., 180.)
                .unwrap()
                .span(2, 2)
                .unwrap(),
        )
        .unwrap();
    let base = canvas.render().unwrap();
    let rect = base
        .layout_report()
        .unwrap()
        .rect(&RectRef::slot(0, 0))
        .unwrap();
    assert!(canvas
        .clone()
        .panel_placement(Placement::in_slot(&photo, 1, 1).unwrap())
        .is_err());
    let page = canvas
        .panel_placement(
            Placement::in_slot(&photo, 0, 0)
                .unwrap()
                .fit(ObjectFit::Fill),
        )
        .unwrap();
    assert!(!page.slots()[0].is_filled());
    let out = page.render().unwrap();
    let report = out.layout_report().unwrap();
    assert_eq!(report, base.layout_report().unwrap());
    assert_eq!(report.grid_cells()[0].state(), GridCellState::Reserved);
    let folder = tempfile::tempdir().unwrap();
    let raster = pixels(&out, folder.path());
    assert_eq!(
        sample(&raster, rect.left() + 5., rect.top() + 5.),
        [23, 45, 67, 255]
    );
    let borrowed = base
        .compose([Placement::boxed(
            &photo,
            BoxTarget::corners(
                PlacePoint::on(RectRef::slot(0, 0), Anchor::TopLeft),
                PlacePoint::axes(
                    RectRef::slot(0, 0).x(1.).unwrap(),
                    RectRef::slot(0, 0).y(1.).unwrap(),
                )
                .unwrap(),
            ),
        )
        .unwrap()
        .fit(ObjectFit::Fill)])
        .unwrap();
    assert_eq!(pixels(borrowed.output(), folder.path()), raster);
}

#[test]
fn rectangular_svg_expands_only_actual_visible_rectangles_and_unknown_is_device_local() {
    let base = image(40, 30, [255; 4]);
    let asset = ImageAsset::from_svg_bytes(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect x="10" width="10" height="10" fill="red"/></svg>"#).unwrap();
    let expand = ComposeOptions {
        expand_canvas: true,
    };
    let out = base
        .compose_with_options([Placement::at(&asset, (-20., 0.)).unwrap()], expand)
        .unwrap();
    assert_eq!(out.base_origin_in_output(), (10., 0.));
    let circle = ImageAsset::from_svg_bytes(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><circle cx="10" cy="10" r="5"/></svg>"#).unwrap();
    let clipped = base
        .compose_with_options(
            [Placement::boxed(&circle, (-20., -20., 6., 6.))
                .unwrap()
                .fit(ObjectFit::None)
                .position(lichtung_plot::composition::ObjectPosition::top_left())],
            expand,
        )
        .unwrap();
    assert_eq!(clipped.base_origin_in_output(), (0., 0.));
    let full = base
        .compose_with_options([Placement::at(&circle, (-20., -20.)).unwrap()], expand)
        .unwrap();
    assert_eq!(full.base_origin_in_output(), (15., 15.));
    let unknown = ImageAsset::from_svg_bytes(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><defs><filter id="blur"><feGaussianBlur stdDeviation="2"/></filter></defs><circle cx="10" cy="5" r="4" filter="url(#blur)"/></svg>"#).unwrap();
    assert!(base
        .compose_with_options([Placement::at(&unknown, (-20., 0.)).unwrap()], expand)
        .is_err());
    let fixed = base
        .compose([Placement::at(&unknown, (-20., 0.)).unwrap()])
        .unwrap();
    let folder = tempfile::tempdir().unwrap();
    fixed.svg(folder.path().join("full.svg")).unwrap();
    // An unknown contribution already inside the extent doesn't require a
    // tight proof, even if a different item supplies the new extent.
    assert!(base
        .compose_with_options(
            [
                Placement::at(&unknown, (-20., 0.)).unwrap(),
                Placement::at(image(20, 10, [255, 0, 0, 255]), (-20., 0.)).unwrap(),
            ],
            expand
        )
        .is_ok());
    // The proof of the final union does not depend on whether the opaque
    // contribution was encountered before or after the unknown effect.
    let covered = base
        .compose_with_options(
            [
                Placement::at(&unknown, (-20., 0.)).unwrap(),
                Placement::at(image(20, 10, [255, 0, 0, 255]), (-20., 0.)).unwrap(),
            ],
            expand,
        )
        .unwrap();
    let nested = base
        .compose_with_options([Placement::at(&covered, (-60., 0.)).unwrap()], expand)
        .unwrap();
    assert_eq!(nested.base_origin_in_output(), (60., 0.));
}

#[test]
fn responsive_placement_uses_actual_fractional_constraints() {
    let base = image(900, 700, [255; 4]);
    let plot = Plot::scatter(
        NumericValues::new("x", [0., 1., 2.]),
        NumericValues::new("y", [1., 2., 1.]),
    )
    .size(800, 600);
    for placement in [
        Placement::boxed(&plot, (10., 20., 480.5, 340.25)).unwrap(),
        Placement::at(&plot, (10., 20.)).unwrap().width(480.5),
        Placement::at(&plot, (10., 20.)).unwrap().height(340.25),
    ] {
        let out = base.compose([placement]).unwrap();
        let folder = tempfile::tempdir().unwrap();
        let path = folder.path().join("content.svg");
        out.svg_preserve_text(&path).unwrap();
        let svg = std::fs::read_to_string(path).unwrap();
        let doc = roxmltree::Document::parse(&svg).unwrap();
        // The innermost native figure retains the exact allocated source
        // viewport, rather than scaling an old 800×600 figure into the frame.
        assert!(doc
            .descendants()
            .filter(|node| node.has_tag_name("svg"))
            .any(|node| node
                .attribute("viewBox")
                .is_some_and(|view| view.starts_with("0 0 ")
                    && (view.contains("480.5") || view.ends_with("340.25")))
                && node.attribute("preserveAspectRatio") == Some("none")));
        let _ = pixels(out.output(), folder.path());
    }
}

#[test]
fn borrowed_slot_inherits_actual_parent_but_final_placement_keeps_its_own_theme() {
    let theme = |color| {
        Theme::publication()
            .customize()
            .surfaces(lichtung_plot::theme::SurfaceTheme::new(color, color).unwrap())
            .build()
            .unwrap()
    };
    let parent = theme(lichtung_plot::Color::rgb(13, 67, 198));
    let child = theme(lichtung_plot::Color::rgb(203, 91, 24));
    let plot = child.with_context(|| {
        Plot::scatter(
            NumericValues::new("x", [0., 1.]),
            NumericValues::new("y", [1., 0.]),
        )
    });
    let canvas = Canvas::grid(1, 1)
        .unwrap()
        .theme(parent)
        .size(760, 540)
        .reserve(0, 0, (600., 400.))
        .unwrap();
    let item = Placement::in_slot(&plot, 0, 0).unwrap();
    let editable = canvas.clone().panel_placement(item.clone()).unwrap();
    let independent = canvas.compose([item]).unwrap();
    let folder = tempfile::tempdir().unwrap();
    let path = folder.path().join("editable.svg");
    editable.svg_preserve_text(&path).unwrap();
    let borrowed = std::fs::read_to_string(&path).unwrap();
    independent.svg_preserve_text(&path).unwrap();
    let independent = std::fs::read_to_string(&path).unwrap();
    assert!(borrowed.contains("#0D43C6") && !borrowed.contains("#CB5B18"));
    assert!(independent.contains("#0D43C6") && independent.contains("#CB5B18"));
    assert_eq!(plot.get_default_theme(), Some(&child));
    // A later edit cannot silently redirect a borrowed reservation to another
    // occupant; the old Canvas version and its frozen scene remain valid.
    let edited = editable.clone().set_panel(0, 0, &plot).unwrap();
    assert!(edited.preflight().is_err());
    editable.preflight().unwrap();
}

#[test]
fn extending_a_native_chain_preserves_physical_size_until_viewport_changes() {
    let base = Plot::scatter(
        NumericValues::new("x", [0., 1.]),
        NumericValues::new("y", [1., 0.]),
    )
    .size_with_unit(180., 120., lichtung_plot::layout::SizeUnit::Millimeter)
    .unwrap()
    .render()
    .unwrap();
    let badge = image(20, 10, [10, 200, 55, 255]);
    let first = base
        .compose([Placement::at(&badge, (10., 10.)).unwrap()])
        .unwrap();
    assert_eq!(first.output().physical_size(), base.physical_size());
    assert_eq!(
        (first.width(), first.height()),
        (base.width(), base.height())
    );
    let second = first
        .compose_with_options(
            [Placement::at(&badge, (-20., -10.)).unwrap()],
            ComposeOptions {
                expand_canvas: true,
            },
        )
        .unwrap();
    assert_eq!(second.base_origin_in_output(), (20., 10.));
    assert_eq!(
        (second.width(), second.height()),
        (base.width() + 20., base.height() + 10.)
    );
    assert!(second.output().physical_size().is_none());
    assert_eq!(
        second.layout_report().unwrap(),
        base.layout_report().unwrap()
    );
}