lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Commented templates of the actual declaration modes.

use std::fmt::Write;

use crate::{plots::PlotKind, Result};

use super::{
    codec::invalid,
    figure::FAMILIES,
    plot_input::modes::{modes, Mode},
    schema::{Example, Field},
    Recipe, RECIPE_VERSION,
};

const DOCUMENT_TASKS: &[&str] = &[
    "theme",
    "canvas",
    "canvas_layout",
    "canvas_style",
    "composition",
    "placement",
];

fn family(name: &str) -> Option<PlotKind> {
    FAMILIES
        .iter()
        .find_map(|(kind, declared)| (*declared == name).then_some(*kind))
}

fn input_mode(kind: PlotKind, requested: Option<&str>) -> Result<Mode> {
    let available = modes(kind);
    if let Some(requested) = requested {
        if let Some(mode) = available.iter().find(|mode| mode.name == requested) {
            return Ok(*mode);
        }
    } else if let [mode] = available.as_slice() {
        return Ok(*mode);
    }
    let choices = available
        .iter()
        .map(|mode| mode.name)
        .collect::<Vec<_>>()
        .join(", ");
    Err(invalid(match requested {
        Some(mode) => format!(
            "{} has no input mode {mode:?}; choose from {choices}",
            kind.name()
        ),
        None => format!(
            "{} requires an input mode; choose from {choices}",
            kind.name()
        ),
    }))
}

fn unknown_task(task: &str) -> crate::Error {
    let tasks = FAMILIES
        .iter()
        .map(|(_, name)| *name)
        .chain(DOCUMENT_TASKS.iter().copied())
        .collect::<Vec<_>>()
        .join(", ");
    invalid(format!(
        "unknown template task {task:?}; choose from {tasks}, or <plot kind>_style"
    ))
}

fn binding(text: &mut String, name: &str, prefix: &str) {
    writeln!(
        text,
        "\n{prefix}[bindings.{name}]\n{prefix}# Supply the local source, or replace the entire binding in memory.\n{prefix}# path = \"{name}.csv\""
    ).expect("write to String");
}

fn bindings(text: &mut String, mode: Mode) {
    if mode.grouped {
        binding(text, "data", "");
    } else {
        for field in mode.fields {
            if field.needed && matches!(field.example, Some(Example::Group(_))) {
                binding(text, field.name, "");
            }
        }
    }
}

fn scalar_fields(text: &mut String, fields: &[Field], prefix: &str) -> Result<()> {
    for field in fields {
        let name = field.name;
        match field.example {
            Some(Example::Column(description)) => {
                writeln!(
                    text,
                    "{prefix}# {} {description}; example: {name} = {name:?}.",
                    if field.needed { "Required" } else { "Optional" }
                )
                .expect("write to String");
                if field.needed && prefix.is_empty() {
                    writeln!(text, "{name} = {{ key = {{}} }}").expect("write to String");
                } else {
                    let optional = if field.needed { "" } else { "# " };
                    writeln!(text, "{prefix}{optional}{name} = {name:?}").expect("write to String");
                }
            }
            Some(Example::Variables) => {
                writeln!(text,"{prefix}# Select ordered numeric columns: {{ keys = [\"a\", \"b\"] }}, {{ indices = [0, 1] }}\n{prefix}# or discover the current numeric columns with {{ numeric_only = true }}.\n{prefix}{name} = {{ keys = [{{}}] }}")
                    .expect("write to String");
            }
            Some(Example::Grid) => {
                writeln!(text,"{prefix}# Supply a rectangular numeric array or table (e.g. a local NPY file).\n{prefix}{name} = {{}}")
                    .expect("write to String");
            }
            Some(Example::Literal(value)) => {
                if field.needed {
                    writeln!(text,"{prefix}# Required declaration; edit this example value.\n{prefix}{name} = {value}").expect("write to String");
                } else {
                    writeln!(text, "{prefix}# {name} = {value}").expect("write to String");
                }
            }
            None if field.needed => {
                return Err(invalid(format!(
                    "required template field {name:?} has no example"
                )));
            }
            Some(Example::Group(_)) | None => {}
        }
    }
    Ok(())
}

fn plot(text: &mut String, owner: &str, kind: PlotKind, mode: Mode) -> Result<()> {
    writeln!(
        text,
        "\n[{owner}]\nkind = {:?}\n# title = \"Title\"\n# theme = {{ preset = \"publication\" }}",
        kind.name()
    )
    .expect("write to String");
    let input = format!("{owner}.input.{}", mode.name);
    writeln!(text, "\n[{input}]").expect("write to String");
    if mode.grouped {
        text.push_str("binding = \"data\"\n");
    }
    scalar_fields(text, mode.fields, "")?;
    for field in mode.fields {
        if let Some(Example::Group(fields)) = field.example {
            let prefix = if field.needed { "" } else { "# " };
            if !field.needed {
                writeln!(text, "\n# Optional independently supplied {}:", field.name)
                    .expect("write to String");
                binding(text, field.name, prefix);
            }
            writeln!(
                text,
                "\n{prefix}[{input}.{}]\n{prefix}binding = {:?}",
                field.name, field.name
            )
            .expect("write to String");
            scalar_fields(text, fields, prefix)?;
        }
    }
    Ok(())
}

fn output(text: &mut String) {
    text.push_str("\n[output]\n# Select an action and its destination, or supply them at execution time.\n# action = \"image\"\n# image = \"figure.svg\"\n# layout = \"layout.json\"\n");
}

fn style(text: &mut String, kind: Option<PlotKind>) {
    text.push_str("\n# Apply this style to a compatible existing native owner.\n# Omitted visual requests use the native default appearance.\n");
    if let Some(kind) = kind {
        writeln!(text, "[plot]\nscope = \"style\"\nkind = {:?}", kind.name())
            .expect("write to String");
    } else {
        text.push_str("[canvas]\nscope = \"style\"\n");
    }
    text.push_str("theme = { preset = \"publication\" }\n");
}

fn document_task(text: &mut String, task: &str) -> Result<()> {
    match task {
        "theme" => text.push_str("\n[theme]\n# Select a preset and override its actual theme fields as needed.\npreset = \"publication\"\n"),
        "canvas" => {
            let mode = input_mode(PlotKind::Line,Some("xy"))?;
            bindings(text,mode);
            text.push_str("\n[canvas]\nrows = 1\ncolumns = 2\n\n[[canvas.panels]]\nname = \"overview\"\nrow = 0\ncolumn = 0\n");
            plot(text,"canvas.panels.plot",PlotKind::Line,mode)?;
            text.push_str("\n[[canvas.panels]]\nname = \"notes\"\nrow = 0\ncolumn = 1\ntext = { title = \"Notes\", body = \"Describe the figure here.\" }\n");
            output(text);
        }
        "canvas_layout" => text.push_str("\n[canvas]\nscope = \"layout\"\nrows = 1\ncolumns = 2\n# Fill the declared footprints through the Canvas API by name or anchor.\n\n[[canvas.panels]]\nname = \"overview\"\nrow = 0\ncolumn = 0\n\n[[canvas.panels]]\nname = \"detail\"\nrow = 0\ncolumn = 1\n"),
        "canvas_style" => style(text,None),
        "composition" | "placement" => {
            if task == "composition" {
                text.push_str("\n[base]\n# Existing local SVG or PNG to use as the base.\nasset = \"base.svg\"\n");
            }
            text.push_str("\n[[placements]]\n# Supply the local overlay; the box is left, top, width, height in CSS pixels.\nasset = \"overlay.svg\"\nbox = [40, 20, 180, 120]\nfit = \"contain\"\n# position = \"center\"\n");
            if task == "composition" {
                text.push_str("\n[composition]\nexpand_canvas = false\n");
                output(text);
            }
        }
        _ => return Err(unknown_task(task)),
    }
    Ok(())
}

impl Recipe {
    /// The current template tasks, including visual and document scopes.
    pub fn template_tasks() -> Vec<String> {
        FAMILIES
            .iter()
            .map(|(_, name)| (*name).to_owned())
            .chain(DOCUMENT_TASKS.iter().map(|name| (*name).to_owned()))
            .chain(FAMILIES.iter().map(|(_, name)| format!("{name}_style")))
            .collect()
    }

    /// Input modes of this task. An empty list indicates a document or visual
    /// task that does not take an input mode.
    pub fn template_modes(task: &str) -> Result<Vec<&'static str>> {
        if let Some(kind) = family(task) {
            Ok(modes(kind).iter().map(|mode| mode.name).collect())
        } else if DOCUMENT_TASKS.contains(&task)
            || task.strip_suffix("_style").and_then(family).is_some()
        {
            Ok(Vec::new())
        } else {
            Err(unknown_task(task))
        }
    }

    /// Generate commented TOML for a current native task. If the task has
    /// distinct input modes, choose one with [`Self::template_for`].
    pub fn template(task: &str) -> Result<String> {
        Self::template_inner(task, None)
    }

    /// Generate a template for the explicitly selected native input mode.
    pub fn template_for(task: &str, mode: &str) -> Result<String> {
        Self::template_inner(task, Some(mode))
    }

    fn template_inner(task: &str, requested: Option<&str>) -> Result<String> {
        let mut text = format!(
            "# Lichtung Plot native Recipe\n# Schema: specs/recipe-{RECIPE_VERSION}.schema.json\n# Complete the marked inputs before checking or executing.\nrecipe_version = {RECIPE_VERSION:?}\n"
        );
        if let Some(kind) = family(task) {
            let mode = input_mode(kind, requested)?;
            bindings(&mut text, mode);
            plot(&mut text, "plot", kind, mode)?;
            output(&mut text);
        } else {
            let style_kind = task.strip_suffix("_style").and_then(family);
            if style_kind.is_none() && !DOCUMENT_TASKS.contains(&task) {
                return Err(unknown_task(task));
            }
            if requested.is_some() {
                return Err(invalid(format!("template task {task:?} has no input mode")));
            }
            if let Some(kind) = style_kind {
                style(&mut text, Some(kind));
            } else {
                document_task(&mut text, task)?;
            }
        }
        // Templates are authored declarations too. Check their structure
        // through the native reader; never open a suggested file or asset.
        let document = text
            .parse::<toml_edit::DocumentMut>()
            .map_err(|error| invalid(format!("invalid template declaration: {error}")))?;
        Self::inventory(&document)?;
        Ok(text)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::recipe::RecipeFigure;

    #[test]
    fn every_actual_template_mode_is_readable_without_supplied_data() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("template.toml");
        for &(kind, name) in FAMILIES {
            let available = modes(kind);
            assert_eq!(Recipe::template(name).is_ok(), available.len() == 1);
            for mode in available {
                let template = Recipe::template_for(name, mode.name).unwrap();
                assert!(template.contains('#'));
                std::fs::write(&path, template).unwrap();
                let recipe = Recipe::read(&path).unwrap();
                assert!(!recipe.bindings().is_empty(), "{name} {}", mode.name);
                assert!(recipe.check().is_err(), "{name} {}", mode.name);
            }
            let style = Recipe::template(&format!("{name}_style")).unwrap();
            std::fs::write(&path, style).unwrap();
            Recipe::read(&path).unwrap().check().unwrap();
        }
        for &task in DOCUMENT_TASKS {
            let template = Recipe::template(task).unwrap();
            std::fs::write(&path, template).unwrap();
            Recipe::read(&path).unwrap();
            assert!(Recipe::template_for(task, "xy").is_err());
        }
        std::fs::write(&path, Recipe::template("canvas_layout").unwrap()).unwrap();
        let RecipeFigure::Canvas(canvas) = Recipe::read(&path).unwrap().build().unwrap() else {
            panic!("fillable Canvas");
        };
        assert_eq!(canvas.slots().len(), 2);
        assert!(Recipe::template("future_family").is_err());
        assert!(Recipe::template_for("line", "not_an_input").is_err());
    }
}