lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! The native marker capabilities also govern hand-authored recipes.

use crate::kind::Capability;
use crate::{recipe::codec::invalid, spec::PlotKind, Result};
use toml_edit::Item;
use toml_edit::TableLike;

fn require_fields(
    fields: &dyn TableLike,
    kind: PlotKind,
    path: &str,
    admitted: bool,
    names: &[&str],
) -> Result<()> {
    if !admitted {
        if let Some(name) = names.iter().find(|name| fields.contains_key(name)) {
            return Err(invalid(format!(
                "{path}.{name}: unsupported for {}",
                kind.name()
            )));
        }
    }
    Ok(())
}

// TOML reaches the native description without going through generic marker
// bounds. Admit the same owner-level fields before resolving any data.
pub(super) fn validate_family(fields: &dyn TableLike, kind: PlotKind, path: &str) -> Result<()> {
    for (admitted, names) in permissions(kind) {
        require_fields(fields, kind, path, admitted, names)?;
    }
    validate_axis_and_text_owners(fields, kind, path)
}

fn permissions(kind: PlotKind) -> Vec<(bool, &'static [&'static str])> {
    use Capability as Cap;
    let mut permissions = [
        (Cap::SourceRows, &["source_rows"][..]),
        (Cap::Hue, &["hue"]),
        (Cap::Group, &["group"]),
        (Cap::Series, &["series"]),
        (
            Cap::ContinuousColor,
            &[
                "color_label",
                "color_label_format",
                "continuous_color_scale",
            ],
        ),
        (
            Cap::HeatmapOptions,
            &[
                "heatmap_null_row_annotations",
                "highlight_cells",
                "heatmap_layout",
                "heatmap_annotations",
                "x_order",
                "y_order",
            ],
        ),
        (
            Cap::CoefficientOptions,
            &["estimate_labels", "coefficient_reference_line"],
        ),
        (
            Cap::SignificanceStyle,
            &["significance_mark_style", "significance"],
        ),
        (Cap::Guides, &["guides"]),
        (Cap::CategoryOrder, &["category_order"]),
        (Cap::SignedBars, &["color_by_sign"]),
        (Cap::ZeroLine, &["zero_line"]),
        (Cap::EstimateStatus, &["estimate_status"]),
        (Cap::Markers, &["markers_visible"]),
        (Cap::CategoricalScale, &["categorical_color_scale"]),
        (Cap::TextAnnotation, &["panel_text_annotations"]),
        (Cap::PointOutline, &["point_outline_visible"]),
        (Cap::Legend, &["legend", "legend_composition"]),
        (Cap::PointAlpha, &["point_alpha"]),
        (Cap::LineAlpha, &["line_alpha"]),
        (Cap::FillAlpha, &["fill_alpha"]),
        (Cap::RawOverlay, &["raw_overlay"]),
        (Cap::Facet, &["facet"]),
    ]
    .into_iter()
    .map(|(capability, names)| (capability.admits(kind), names))
    .collect::<Vec<_>>();
    permissions.extend([
        (
            matches!(kind, PlotKind::Bar | PlotKind::HorizontalBar),
            &["bar_spacing", "bar_point_layers"][..],
        ),
        (kind == PlotKind::Forest, &["axis_scale"]),
        (
            kind == PlotKind::Histogram,
            &["histogram_bins", "histogram_stat", "histogram_composite"],
        ),
        (kind == PlotKind::Qq, &["qq_line"]),
        (kind == PlotKind::Raincloud, &["raincloud_hue_label"]),
        (kind == PlotKind::Line, &["band", "point_layers"]),
        (kind == PlotKind::Regression, &["regression_band"]),
        (kind == PlotKind::LinePath, &["line_path_style"]),
        (
            kind == PlotKind::Interaction,
            &["interaction_connectors", "interaction_styles"],
        ),
        (
            kind == PlotKind::Waterfall,
            &["waterfall_labels", "total_format"],
        ),
    ]);
    permissions
}
pub(super) fn permits(kind: PlotKind, name: &str) -> bool {
    permissions(kind)
        .into_iter()
        .all(|(allowed, fields)| allowed || !fields.contains(&name))
}

fn axis_permissions(kind: PlotKind, index: usize) -> [(bool, &'static [&'static str]); 2] {
    use Capability as Cap;
    let numeric = [Cap::NumericX, Cap::NumericY][index].admits(kind);
    let categorical = [Cap::CategoricalX, Cap::CategoricalY][index].admits(kind);
    [
        (numeric, &["window", "ticks", "generation", "format"]),
        (categorical, &["category_labels"]),
    ]
}

pub(super) fn axis_permits(kind: PlotKind, index: usize, name: &str) -> bool {
    axis_permissions(kind, index)
        .iter()
        .all(|(allowed, fields)| *allowed || !fields.contains(&name))
}

fn text_permissions(kind: PlotKind) -> Vec<(bool, &'static [&'static str])> {
    use Capability as Cap;
    let mut permissions = [
        (Cap::XAxisText, &["x_tick"][..]),
        (Cap::YAxisText, &["y_tick"]),
        (Cap::Facet, &["facet_row", "facet_column"]),
        (Cap::Legend, &["guide_title", "guide_entry", "guide_number"]),
        (Cap::HeatmapOptions, &["value", "null_row"]),
        (Cap::EstimateDetailText, &["estimate"]),
        (Cap::SignificanceStyle, &["significance"]),
    ]
    .into_iter()
    .map(|(cap, fields)| (cap.admits(kind), fields))
    .collect::<Vec<_>>();
    permissions.extend([
        (
            kind == PlotKind::Matrix,
            &["matrix_row", "matrix_column"][..],
        ),
        (kind == PlotKind::Waterfall, &["total"]),
    ]);
    permissions
}

pub(super) fn forbidden_text_fields(kind: PlotKind) -> Vec<&'static str> {
    text_permissions(kind)
        .into_iter()
        .filter(|(allowed, _)| !*allowed)
        .flat_map(|(_, fields)| fields.iter().copied())
        .collect()
}

fn validate_axis_and_text_owners(fields: &dyn TableLike, kind: PlotKind, path: &str) -> Result<()> {
    if let Some(axes) = fields.get("axes").and_then(Item::as_table_like) {
        for (index, name) in ["x", "y"].into_iter().enumerate() {
            if let Some(axis) = axes.get(name).and_then(Item::as_table_like) {
                let path = format!("{path}.axes.{name}");
                for (allowed, fields) in axis_permissions(kind, index) {
                    require_fields(axis, kind, &path, allowed, fields)?;
                }
            }
        }
    }
    if let Some(roles) = fields.get("text_layouts").and_then(Item::as_table_like) {
        let path = format!("{path}.text_layouts");
        for (allowed, fields) in text_permissions(kind) {
            require_fields(roles, kind, &path, allowed, fields)?;
        }
    }
    Ok(())
}