lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Numeric presentation and generated tick requests, independent of scientific windows.

use std::sync::Arc;
use toml_edit::{InlineTable, Item, TableLike};

use crate::{
    coordinates::TickGeneration,
    kind::Capability,
    recipe::codec::{invalid, table},
    spec::HeatmapAnnotations,
    NumericFormat, Result,
};

use crate::recipe::schema::{self as grammar, Schema};

use super::{PlotDescription, StyleEdit};

fn capture_format(
    fields: &mut InlineTable,
    key: &str,
    format: Option<&NumericFormat>,
    retain_unit_reference: bool,
) -> Result<()> {
    if let Some(format) = format {
        fields.insert(
            key,
            format
                .style_recipe_value(retain_unit_reference)
                .map_err(|error| error.with_prefix(key))?,
        );
    }
    Ok(())
}

fn numeric_axis(source: &PlotDescription, index: usize) -> bool {
    [Capability::NumericX, Capability::NumericY][index].admits(source.kind())
        && source
            .automatic_axis_category_values(source.kind(), index == 0)
            .is_none()
}

pub(super) fn capture(source: &PlotDescription, fields: &mut InlineTable) -> Result<()> {
    let payload = &source.payload;
    let mut axis_fields = InlineTable::new();
    for (index, key) in ["x", "y"].into_iter().enumerate() {
        if !numeric_axis(source, index) {
            continue;
        }
        let axis = &payload.axes[index];
        let mut value = InlineTable::new();
        // Exact ticks are the actual authored coordinates and labels, and
        // suppress both the generator and numeric formatter for this axis.
        if axis.exact_ticks.is_none() {
            if !axis.generation.is_automatic() {
                value.insert(
                    "generation",
                    axis.generation
                        .recipe_value()
                        .map_err(|error| error.with_prefix(&format!("axes.{key}.generation")))?,
                );
            }
            capture_format(&mut value, "format", axis.format.as_deref(), false)?;
        }
        axis_fields.insert(key, value.into());
    }
    if !axis_fields.is_empty() {
        fields.insert("axes", axis_fields.into());
    }
    for (key, format, reference) in [
        (
            "color_label_format",
            payload.color_label_format.as_deref(),
            true,
        ),
        ("estimate_labels", payload.estimate_labels.as_ref(), false),
        ("total_format", payload.total_format.as_deref(), false),
    ] {
        capture_format(fields, key, format, reference)?;
    }
    if let HeatmapAnnotations::Values(format) = &payload.heatmap_annotations {
        capture_format(fields, "heatmap_annotations", Some(format), false)?;
    }
    Ok(())
}

fn read_format(fields: &dyn TableLike, key: &str) -> Result<Option<NumericFormat>> {
    fields
        .get(key)
        .map(NumericFormat::from_style_value)
        .transpose()
        .map_err(|error| error.with_prefix(key))
}

const STYLE_AXIS_FIELDS: &[grammar::Field] = &[
    grammar::custom("generation", false, TickGeneration::schema),
    grammar::custom("format", false, NumericFormat::style_schema),
];
pub(super) fn schema(ctx: &mut Schema, kind: crate::spec::PlotKind) -> serde_json::Value {
    grammar::object(
        [("x", Capability::NumericX), ("y", Capability::NumericY)]
            .into_iter()
            .filter(|(_, cap)| cap.admits(kind))
            .map(|(name, _)| (name, grammar::record(ctx, STYLE_AXIS_FIELDS))),
        &[],
    )
}

#[derive(Default)]
struct AxisStyle {
    present: bool,
    generation: TickGeneration,
    format: Option<NumericFormat>,
}

fn read_axes(item: Option<&Item>) -> Result<[AxisStyle; 2]> {
    let mut axes = [AxisStyle::default(), AxisStyle::default()];
    if let Some(item) = item {
        let fields = table(item, &["x", "y"])?;
        for (axis, key) in axes.iter_mut().zip(["x", "y"]) {
            let Some(item) = fields.get(key) else {
                continue;
            };
            let fields = grammar::record_fields(item, STYLE_AXIS_FIELDS)?;
            axis.present = true;
            axis.format = read_format(fields, "format")?;
            if let Some(item) = fields.get("generation") {
                axis.generation = TickGeneration::from_recipe_value(item)
                    .map_err(|error| error.with_prefix(&format!("axes.{key}.generation")))?;
            }
        }
    }
    Ok(axes)
}

fn apply_format(
    style: Option<NumericFormat>,
    target: Option<&NumericFormat>,
    key: &str,
) -> Result<Option<NumericFormat>> {
    NumericFormat::apply_recipe_style(style, target).map_err(|error| error.with_prefix(key))
}

fn apply_axes(source: &mut PlotDescription, styles: [AxisStyle; 2]) -> Result<()> {
    for (index, style) in styles.into_iter().enumerate() {
        let key = ["x", "y"][index];
        if !numeric_axis(source, index) && style.present {
            return Err(invalid(format!(
                "axes.{key}: target has no compatible numeric axis"
            )));
        }
        let axis = &mut source.payload_mut().axes[index];
        axis.format = apply_format(
            style.format,
            axis.format.as_deref(),
            &format!("axes.{key}.format"),
        )?
        .map(Arc::new);
        axis.generation = style.generation;
        axis.validate(key)?;
    }
    Ok(())
}

pub(super) fn read(fields: &dyn TableLike, kind: crate::spec::PlotKind) -> Result<StyleEdit> {
    let axes = read_axes(fields.get("axes"))?;
    for (index, axis) in axes.iter().enumerate() {
        if axis.present && ![Capability::NumericX, Capability::NumericY][index].admits(kind) {
            return Err(invalid("style refers to an unsupported numeric axis"));
        }
    }
    let color = read_format(fields, "color_label_format")?;
    let estimates = read_format(fields, "estimate_labels")?;
    let totals = read_format(fields, "total_format")?;
    let cells = if fields.get("heatmap_annotations").and_then(Item::as_str) == Some("hidden") {
        None
    } else {
        read_format(fields, "heatmap_annotations")?
    };
    Ok(Box::new(move |description| {
        apply_axes(description, axes)?;
        let payload = description.payload_mut();
        payload.color_label_format = apply_format(
            color,
            payload.color_label_format.as_deref(),
            "color_label_format",
        )?
        .map(Arc::new);
        payload.estimate_labels = apply_format(
            estimates,
            payload.estimate_labels.as_ref(),
            "estimate_labels",
        )?;
        payload.total_format =
            apply_format(totals, payload.total_format.as_deref(), "total_format")?.map(Arc::new);
        let cell_target = match &payload.heatmap_annotations {
            HeatmapAnnotations::Values(format) => Some(format),
            HeatmapAnnotations::Hidden => None,
        };
        payload.heatmap_annotations = apply_format(cells, cell_target, "heatmap_annotations")?
            .map_or(HeatmapAnnotations::Hidden, HeatmapAnnotations::Values);
        Ok(())
    }))
}

pub(super) fn project(
    source: &dyn TableLike,
    kind: crate::spec::PlotKind,
    target: &mut InlineTable,
) -> Result<()> {
    let categorical_x = source
        .get("input")
        .and_then(|item| item.get("xy"))
        .and_then(|item| item.get("x_type"))
        .and_then(Item::as_str)
        == Some("category");
    let mut axis_fields = InlineTable::new();
    for (index, key) in ["x", "y"].into_iter().enumerate() {
        if ![Capability::NumericX, Capability::NumericY][index].admits(kind)
            || (index == 0 && categorical_x)
        {
            continue;
        }
        let mut style = InlineTable::new();
        if let Some(axis) = source
            .get("axes")
            .and_then(|item| item.get(key))
            .and_then(Item::as_table_like)
        {
            if !axis.contains_key("ticks") {
                crate::recipe::style::copy_fields(axis, &mut style, &["generation"])?;
                let format = axis
                    .get("format")
                    .map(NumericFormat::from_recipe_value)
                    .transpose()?;
                capture_format(&mut style, "format", format.as_ref(), false)?;
            }
        }
        axis_fields.insert(key, style.into());
    }
    if !axis_fields.is_empty() {
        target.insert("axes", axis_fields.into());
    }
    for (key, reference_unit) in [
        ("color_label_format", true),
        ("estimate_labels", false),
        ("total_format", false),
        ("heatmap_annotations", false),
    ] {
        if let Some(item) = source
            .get(key)
            .filter(|item| item.as_str() != Some("hidden"))
        {
            let format = NumericFormat::from_recipe_value(item)?;
            capture_format(target, key, Some(&format), reference_unit)?;
        }
    }
    Ok(())
}