lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
use lichtung_plot::{data::Bounds, plots::BarInput, CategoryValues, NumericValues, Plot};

struct IntervalData {
    category: CategoryValues,
    value: NumericValues,
    lower: NumericValues,
    upper: NumericValues,
}

fn identity_interval_plot(data: &IntervalData, horizontal: bool) -> Plot {
    if horizontal {
        Plot::horizontal_bar(
            data.category.clone(),
            BarInput::estimates_with_error_bars(
                data.value.clone(),
                Bounds::new(data.lower.clone(), data.upper.clone()),
            ),
        )
        .erase()
    } else {
        Plot::bar(
            data.category.clone(),
            BarInput::estimates_with_error_bars(
                data.value.clone(),
                Bounds::new(data.lower.clone(), data.upper.clone()),
            ),
        )
        .erase()
    }
}

#[test]
fn identity_bar_rejects_invalid_endpoint_order_during_preflight() {
    let data = IntervalData {
        category: CategoryValues::new("category", ["a"]).unwrap(),
        value: NumericValues::new("value", [2.0]),
        lower: NumericValues::new("lower", [3.0]),
        upper: NumericValues::new("upper", [4.0]),
    };
    let error = identity_interval_plot(&data, false)
        .preflight()
        .unwrap_err();

    assert!(error.to_string().contains("lower <= value <= upper"));
}

fn rendered_axes<K: lichtung_plot::kind::Marker>(plot: &Plot<K>) -> String {
    let directory = tempfile::tempdir().unwrap();
    let path = directory.path().join("axes.svg");
    plot.svg_preserve_text(&path).unwrap();
    std::fs::read_to_string(path).unwrap()
}

fn tick_corner_gaps(svg: &str) -> [[f64; 2]; 2] {
    let panel = super::parse_first_clip_rect(svg);
    let bottom = panel.y + panel.height;
    let document = roxmltree::Document::parse(svg).unwrap();
    let axes = document
        .descendants()
        .find(|node| node.attribute("id") == Some("axes"))
        .unwrap();
    let mut gaps = [[f64::INFINITY; 2]; 2];
    for line in axes.children().filter(|node| node.has_tag_name("polyline")) {
        let points = line.attribute("points").unwrap();
        let (start, end) = points.split_once(' ').unwrap();
        let point = |text: &str| {
            let (x, y) = text.split_once(',').unwrap();
            (x.parse::<f64>().unwrap(), y.parse::<f64>().unwrap())
        };
        let (x0, y0) = point(start);
        let (x1, y1) = point(end);
        if x0.total_cmp(&x1).is_eq() && y0 >= bottom && y1 > y0 {
            gaps[0][0] = gaps[0][0].min(x0 - panel.x);
            gaps[0][1] = gaps[0][1].min(panel.x + panel.width - x0);
        }
        if y0.total_cmp(&y1).is_eq() && x0 <= panel.x && x1 < x0 {
            gaps[1][0] = gaps[1][0].min(bottom - y0);
            gaps[1][1] = gaps[1][1].min(y0 - panel.y);
        }
    }
    assert!(gaps.iter().flatten().all(|gap| gap.is_finite()), "{gaps:?}");
    gaps
}

#[test]
fn ordinary_automatic_tick_positions_leave_room_at_the_axis_corner() {
    use lichtung_plot::coordinates::TickGeneration;

    let plot = Plot::scatter(
        NumericValues::new("x", [0., 6., 12., 19.]),
        NumericValues::new("y", [-1.8, 20., 40., 70.5]),
    )
    .size(840, 560)
    .x_tick_generation(TickGeneration::target(5).unwrap())
    .y_tick_generation(TickGeneration::target(5).unwrap());
    let automatic = tick_corner_gaps(&rendered_axes(&plot));
    assert!(automatic.iter().all(|gap| gap[0] > 2.0), "{automatic:?}");
    let explicit = tick_corner_gaps(&rendered_axes(&plot.x_limits(0., 20.).y_limits(0., 80.)));
    assert_eq!(explicit.map(|gap| gap[0].to_bits()), [0.0_f64.to_bits(); 2]);
}

#[test]
fn default_ticks_avoid_both_frame_corners_without_changing_the_display_domain() {
    use lichtung_plot::coordinates::{TickGeneration, TickSpace};

    let values = [0., 2.5, 5., 7.5, 10.];
    let plot = Plot::scatter(
        NumericValues::new("x", values),
        NumericValues::new("y", values),
    )
    .size(2400, 1500);
    let svg = rendered_axes(&plot);
    let gaps = tick_corner_gaps(&svg);
    assert!(gaps.iter().flatten().all(|gap| *gap >= 5.8), "{gaps:?}");

    // Verify the marks still use the original automatic [-0.5, 10.5] window.
    let panel = super::parse_first_clip_rect(&svg);
    let marks = super::support::parse_circles(&svg);
    assert_eq!(marks.len(), values.len());
    for (value, (x, y)) in values.into_iter().zip(marks) {
        let fraction = (value + 0.5) / 11.0;
        assert!((x - (panel.x + fraction * panel.width)).abs() < 0.002);
        assert!((y - (panel.y + (1.0 - fraction) * panel.height)).abs() < 0.002);
    }

    // Explicit endpoint-including sources still draw every requested tick.
    let explicit = rendered_axes(
        &plot
            .x_tick_generation(TickGeneration::exact_count(2, TickSpace::Data))
            .y_tick_generation(TickGeneration::exact_count(2, TickSpace::Data)),
    );
    let gaps = tick_corner_gaps(&explicit);
    assert!(
        gaps.iter().flatten().all(|gap| gap.abs() < 0.001),
        "{gaps:?}"
    );

    let histogram = Plot::histogram(lichtung_plot::plots::HistogramInput::samples(
        NumericValues::new("x", values),
    ))
    .size(800, 600);
    let gaps = tick_corner_gaps(&rendered_axes(&histogram));
    // The real baseline may acquire a small ink reserve, but its zero tick is
    // retained even when it lies inside the ordinary automatic corner gap.
    assert!(gaps[1][0] < 5.8, "anchored zero tick: {gaps:?}");
}

#[test]
fn generated_vertical_labels_keep_the_fitted_numeric_request() {
    use lichtung_plot::NumericFormat;

    let directory = tempfile::tempdir().unwrap();
    let path = directory.path().join("formatted.svg");
    Plot::scatter(
        NumericValues::new("x", [1.0, 2.0]),
        NumericValues::new("y", [0.125, 0.875]),
    )
    .size(600, 480)
    .y_tick_format(NumericFormat::default().value_function(|context| {
        let label = context.format_builtin()?;
        Ok(if context.index() == 0 {
            format!("start: {label}")
        } else {
            label
        })
    }))
    .svg_preserve_text(&path)
    .unwrap();
    let svg = std::fs::read_to_string(path).unwrap();
    let labels = super::parse_text_elements(&svg);
    assert!(labels.iter().any(|label| {
        label
            .content
            .strip_prefix("start: ")
            .is_some_and(|value| value.parse::<f64>().is_ok())
    }));
}

#[test]
fn svg_keeps_full_alpha_and_png_samples_it_at_the_device_boundary() {
    use lichtung_plot::{guides::LegendPolicy, theme::SurfaceTheme, Color, Theme};

    let transparent = Color::rgba(0, 0, 0, 0.0).unwrap();
    let theme = Theme::publication()
        .customize()
        .surfaces(SurfaceTheme::new(transparent, transparent).unwrap())
        .build()
        .unwrap();
    let plot = Plot::scatter(
        NumericValues::new("x", [0.73, 1.73, 1.23, 1.23]),
        NumericValues::new("y", [0.83, 1.83, 1.33, 1.33]),
    )
    .point_alpha(lichtung_plot::scales::AlphaEncoding::observations(
        lichtung_plot::scales::AlphaValues::new(
            "alpha",
            [
                f64::from_bits(0.5_f64.to_bits() - 1),
                128.0 / 255.0,
                0.5,
                0.5,
            ],
        )
        .unwrap(),
    ))
    .unwrap()
    .hide_point_outline()
    .legend(LegendPolicy::Hidden)
    .x_limits(0.0, 2.0)
    .y_limits(0.0, 2.0)
    .size(800, 600)
    .theme(theme);
    let directory = tempfile::tempdir().unwrap();
    let svg_path = directory.path().join("alpha.svg");
    let png_path = directory.path().join("alpha.png");
    let output = plot.render().unwrap();
    output.svg_preserve_text(&svg_path).unwrap();
    output.png_preview(&png_path).unwrap();
    let svg = std::fs::read_to_string(svg_path).unwrap();
    assert_eq!(svg.matches("fill-opacity=\"0.5\"").count(), 2);
    assert_eq!(
        svg.matches("fill-opacity=\"0.49999999999999994\"").count(),
        1
    );
    assert_eq!(
        svg.matches("fill-opacity=\"0.5019607843137255\"").count(),
        1
    );
    let png = resvg::tiny_skia::Pixmap::decode_png(&std::fs::read(png_path).unwrap()).unwrap();
    let points = super::support::parse_circles(&svg);
    assert_eq!(points.len(), 4);
    assert_eq!(points[2], points[3]);
    for (index, (x, y)) in points.into_iter().enumerate() {
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "the actual point centers lie within the positive raster viewport"
        )]
        let pixel = png.pixel(x.floor() as u32, y.floor() as u32).unwrap();
        assert_eq!(pixel.alpha(), [127, 128, 191, 191][index]);
    }
}