lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! The actual native wide and generated-position input modes are recoverable
//! from their captured source rules, never from the number of flattened slots.

use toml_edit::{InlineTable, Item, Value};

use crate::{
    data::{AxisValues, BindingGeneration, GeneratedColumns},
    input::{PlotInput, RaincloudInput},
    recipe::{
        capture::{group_record, with_scope, Capture},
        codec::{field, invalid, Codec},
        declaration::{BindingRequirement, BindingValueType, Group},
        resolve::ValueScope,
    },
    spec::PlotKind,
    CategoryValues, NumericValues, Result,
};

use super::BuildInput;

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CollectionMode {
    Wide,
    Indexed,
    ColumnSamples,
    Grid,
}

pub(crate) fn mode(input: &Item, kind: PlotKind) -> Option<CollectionMode> {
    if kind == PlotKind::Heatmap && input.get("grid").is_some() {
        Some(CollectionMode::Grid)
    } else if input.get("wide").is_some() {
        Some(CollectionMode::Wide)
    } else if input.get("indexed").is_some() {
        Some(CollectionMode::Indexed)
    } else if matches!(
        kind,
        PlotKind::Boxplot | PlotKind::Violin | PlotKind::Raincloud
    ) && input.get("columns").is_some()
    {
        Some(CollectionMode::ColumnSamples)
    } else {
        None
    }
}

pub(super) fn read(
    item: &Item,
    kind: PlotKind,
    mode: &str,
    path: &str,
    fallback: Option<&str>,
    requirements: &mut Vec<BindingRequirement>,
    allowed: &[&str],
) -> Result<BuildInput> {
    if kind == PlotKind::Heatmap {
        let mut group = Group::new(
            item,
            allowed,
            format!("{path}.input.grid"),
            format!("{path}.cells"),
            fallback,
            requirements,
        )?
        .rectangular(path);
        let fill = group.required("fill", BindingValueType::NumericVariables)?;
        return Ok(Box::new(move |resolver| {
            let fill = fill.primary_rectangle(resolver, "Value", None)?;
            let (x, y) = resolver.grid_axes()?;
            Ok(PlotInput::Heatmap { x, y, fill })
        }));
    }
    let xy = matches!(kind, PlotKind::Line | PlotKind::Scatter);
    let values_role = if xy {
        "y"
    } else if kind == PlotKind::Raincloud {
        "values"
    } else {
        "value"
    };
    let has_first = mode == "wide";
    let mut group = Group::new(
        item,
        allowed,
        format!("{path}.input.{mode}"),
        format!("{path}.cells"),
        fallback,
        requirements,
    )?
    .rectangular(path);
    let identity = field(
        group.fields,
        "column_identity",
        Some(GeneratedColumns::default_columns()),
    )?;
    let values = group.required(values_role, BindingValueType::NumericVariables)?;
    if xy {
        let x = has_first
            .then(|| group.required_rows("x", BindingValueType::Numeric))
            .transpose()?;
        return Ok(Box::new(move |resolver| {
            let y = values.primary_rectangle(resolver, "y", Some(identity))?;
            let x = if let Some(x) = x {
                x.numeric(resolver)?
            } else {
                resolver.row_positions()?
            };
            Ok(if kind == PlotKind::Line {
                PlotInput::Line {
                    x: AxisValues::Numeric(x),
                    y,
                }
            } else {
                PlotInput::Scatter { x, y }
            })
        }));
    }
    let category = has_first
        .then(|| group.required_rows("category", BindingValueType::Category))
        .transpose()?;
    Ok(Box::new(move |resolver| {
        let value = values.primary_rectangle(resolver, "value", Some(identity))?;
        let category = if let Some(category) = category {
            category.category(resolver)?
        } else {
            resolver.generated_categories()?
        };
        Ok(match kind {
            PlotKind::Boxplot => PlotInput::Boxplot { category, value },
            PlotKind::Violin => PlotInput::Violin { category, value },
            PlotKind::Raincloud => PlotInput::Raincloud {
                input: RaincloudInput::samples(category, value),
            },
            _ => unreachable!("actual column distribution family"),
        })
    }))
}

fn actual_wide(values: &NumericValues) -> bool {
    values.get_source().generation() == Some(BindingGeneration::WideExpansion)
}

fn explicit_records(mut value: Value) -> Value {
    if !value
        .as_inline_table()
        .is_some_and(|fields| fields.contains_key("scope"))
    {
        value = with_scope(value, Some(ValueScope::Records));
    }
    value
}

fn insert_identity(fields: &mut InlineTable, values: &NumericValues) -> Result<()> {
    let identity = values
        .get_source()
        .column_generation()
        .ok_or_else(|| invalid("wide input lacks its actual generated-column identity policy"))?;
    fields.insert("column_identity", identity.encode());
    Ok(())
}

fn capture_xy(
    x: &NumericValues,
    y: &NumericValues,
    context: &mut Capture,
    path: &str,
) -> Result<Value> {
    let indexed = x.get_source().generation() == Some(BindingGeneration::RowPosition);
    let mode = if indexed { "indexed" } else { "wide" };
    let prefix = format!("{path}.input.{mode}");
    let mut fields = InlineTable::new();
    fields.insert(
        "y",
        context.primary_rectangle(y, "y", &format!("{prefix}.y"))?,
    );
    insert_identity(&mut fields, y)?;
    if indexed {
        let x_source = x.get_source();
        let y_source = y.get_source();
        if x_source.reference() != y_source.reference()
            || x_source.selector() != y_source.selector()
            || x_source.selected_shape() != y_source.selected_shape()
        {
            return Err(invalid(
                "generated row positions belong to another collection",
            ));
        }
        let [rows, columns] = y_source.selected_shape() else {
            return Err(invalid("indexed coordinates require a rectangle"));
        };
        let projection = x.vector_source();
        if rows.checked_mul(*columns) != Some(x.len())
            || !(projection.row_repetition() == Some(*columns)
                || (*columns == 1 && projection.is_identity()))
        {
            return Err(invalid(
                "indexed coordinates must retain the complete row projection",
            ));
        }
    } else {
        fields.insert(
            "x",
            explicit_records(context.numeric(x, "x", &format!("{prefix}.x"))?),
        );
    }
    Ok(group_record(mode, fields))
}

fn capture_distribution(
    category: &CategoryValues,
    values: &NumericValues,
    role: &str,
    context: &mut Capture,
    path: &str,
) -> Result<Value> {
    let generated = category.get_source().generation() == Some(BindingGeneration::ColumnNames);
    let mode = if generated { "columns" } else { "wide" };
    let prefix = format!("{path}.input.{mode}");
    let mut fields = InlineTable::new();
    fields.insert(
        role,
        context.primary_rectangle(values, role, &format!("{prefix}.{role}"))?,
    );
    insert_identity(&mut fields, values)?;
    if generated {
        // Verify that the constructor-owned category generation belongs to
        // this same declaration even though the mode already implies it.
        context.category(category, "category", &format!("{prefix}.category"))?;
    } else {
        fields.insert(
            "category",
            explicit_records(context.category(
                category,
                "category",
                &format!("{prefix}.category"),
            )?),
        );
    }
    Ok(group_record(mode, fields))
}

pub(super) fn capture(
    input: &PlotInput,
    context: &mut Capture,
    path: &str,
) -> Result<Option<Value>> {
    match input {
        PlotInput::Heatmap { x, y, fill }
            if x.get_source().generation() == Some(BindingGeneration::GridPosition)
                || y.get_source().generation() == Some(BindingGeneration::GridPosition) =>
        {
            let origin = fill.get_source();
            for (axis, values) in [(1, x), (0, y)] {
                let source = values.get_source();
                if source.generation() != Some(BindingGeneration::GridPosition)
                    || source.grid_axis() != Some(axis)
                    || source.reference() != origin.reference()
                    || source.selector() != origin.selector()
                    || source.selected_shape() != origin.selected_shape()
                {
                    return Err(invalid(
                        "grid axes must belong to the same actual rectangle",
                    ));
                }
            }
            let mut fields = InlineTable::new();
            fields.insert(
                "fill",
                context.primary_rectangle(fill, "fill", &format!("{path}.input.grid.fill"))?,
            );
            Ok(Some(group_record("grid", fields)))
        }
        PlotInput::Scatter { x, y }
        | PlotInput::Line {
            x: AxisValues::Numeric(x),
            y,
        } if actual_wide(y) => capture_xy(x, y, context, path).map(Some),
        PlotInput::Boxplot { category, value } | PlotInput::Violin { category, value }
            if actual_wide(value) =>
        {
            capture_distribution(category, value, "value", context, path).map(Some)
        }
        PlotInput::Raincloud { input } => {
            if let Some((category, values)) = input
                .samples_input()
                .filter(|(_, values)| actual_wide(values))
            {
                return capture_distribution(category, values, "values", context, path).map(Some);
            }
            Ok(None)
        }
        _ => Ok(None),
    }
}