lichtung-plot 0.2.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"));
}

#[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 directory = tempfile::tempdir().unwrap();
    let first_tick_gaps = |plot: Plot| {
        let path = directory.path().join("axes.svg");
        plot.svg_preserve_text(&path).unwrap();
        let svg = std::fs::read_to_string(path).unwrap();
        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];
        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] = gaps[0].min(x0 - panel.x);
            }
            if y0.total_cmp(&y1).is_eq() && x0 <= panel.x && x1 < x0 {
                gaps[1] = gaps[1].min(bottom - y0);
            }
        }
        assert!(gaps.iter().all(|gap| gap.is_finite()), "{gaps:?}");
        gaps
    };
    let automatic = first_tick_gaps(plot.clone().erase());
    assert!(automatic.iter().all(|gap| *gap > 2.0), "{automatic:?}");
    let explicit = first_tick_gaps(plot.x_limits(0., 20.).y_limits(0., 80.).erase());
    assert_eq!(explicit.map(f64::to_bits), [0.0_f64.to_bits(); 2]);
}

#[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]);
    }
}