lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Field and mode tables for the actual input constructors and their schema.

use serde_json::{json, Value};

use crate::{
    data::GeneratedColumns,
    recipe::{
        codec::invalid,
        schema::{self as grammar, Example, Field, Schema},
    },
    spec::{ErrorBar, HistogramStat, PlotKind},
    Color, Result,
};

use grammar::{custom, mandatory, optional, role as scoped_role};

const fn numeric(name: &'static str, needed: bool) -> Field {
    custom(
        name,
        needed,
        crate::recipe::resolve::DataReference::vector_schema,
    )
    .example(Example::Column("numeric values"))
}

const fn category(name: &'static str, needed: bool) -> Field {
    custom(
        name,
        needed,
        crate::recipe::resolve::DataReference::vector_schema,
    )
    .example(Example::Column("categorical values"))
}

const fn collection(name: &'static str) -> Field {
    custom(
        name,
        true,
        crate::recipe::resolve::DataReference::collection_schema,
    )
    .example(Example::Variables)
}

#[derive(Clone, Copy)]
pub(in crate::recipe) struct Mode {
    pub(in crate::recipe) name: &'static str,
    pub(in crate::recipe) fields: &'static [Field],
    pub(in crate::recipe) grouped: bool,
}

const fn group(name: &'static str, fields: &'static [Field]) -> Mode {
    Mode {
        name,
        fields,
        grouped: true,
    }
}

const fn geometry(fields: &'static [Field]) -> Mode {
    Mode {
        name: "geometry",
        fields,
        grouped: false,
    }
}

const XY: &[Field] = &[numeric("x", true), numeric("y", true)];
const SAMPLES: &[Field] = &[numeric("values", true)];
const DISTRIBUTION: &[Field] = &[category("category", true), numeric("value", true)];
const CELLS: &[Field] = &[
    category("x", true),
    category("y", true),
    numeric("fill", true),
];
const STACKED: &[Field] = &[
    category("category", true),
    numeric("value", true),
    category("series", true),
];
const LINE: &[Field] = &[
    numeric("x", true),
    numeric("y", true),
    custom("x_type", false, |_| {
        grammar::choices(&["numeric", "category"])
    })
    .example(Example::Literal(r#""category""#)),
];
const TRAJECTORY: &[Field] = &[
    numeric("x", true),
    numeric("y", true),
    custom("x_type", false, |_| {
        grammar::choices(&["numeric", "category"])
    })
    .example(Example::Literal(r#""category""#)),
    category("group", true),
];
const LINE_PATH: &[Field] = &[
    numeric("x", true),
    numeric("y", true),
    category("group", false),
];
const POINT_INTERVAL: &[Field] = &[
    category("category", true),
    numeric("estimate", true),
    numeric("lower", true),
    numeric("upper", true),
];
const COEFFICIENT_ESTIMATES: &[Field] = &[category("term", true), numeric("estimate", true)];
const COEFFICIENT_INTERVALS: &[Field] = &[
    category("term", true),
    numeric("estimate", true),
    numeric("lower", true),
    numeric("upper", true),
];
const FOREST: &[Field] = &[
    category("term", true),
    numeric("estimate", true),
    numeric("lower", true),
    numeric("upper", true),
    optional::<f64>("reference").example(Example::Literal("0.0")),
];
const INTERACTION: &[Field] = &[
    category("condition", true),
    numeric("estimate", true),
    numeric("lower", true),
    numeric("upper", true),
    category("group", true),
];
const DUMBBELL: &[Field] = &[
    category("category", true),
    numeric("left", true),
    numeric("right", true),
    mandatory::<String>("left_label").example(Example::Literal(r#""Before""#)),
    mandatory::<Color>("left_color").example(Example::Literal(r##""#426B9E""##)),
    mandatory::<String>("right_label").example(Example::Literal(r#""After""#)),
    mandatory::<Color>("right_color").example(Example::Literal(r##""#A14D35""##)),
];
const BAR_SAMPLES: &[Field] = &[
    category("category", true),
    numeric("value", true),
    optional::<ErrorBar>("error_bar").example(Example::Literal(
        r#"{kind="confidence_interval",algorithm="bootstrap",resamples=1000,seed=0}"#,
    )),
    category("units", false),
];
const BAR_ESTIMATES: &[Field] = &[
    category("category", true),
    numeric("value", true),
    numeric("lower", false),
    numeric("upper", false),
];
const RAINCLOUD_SAMPLES: &[Field] = &[category("category", true), numeric("values", true)];
const MATRIX: &[Field] = &[collection("variables")];
const BEESWARM: &[Field] = &[
    category("category", true),
    numeric("value", true),
    numeric("color", false),
    optional::<Option<Color>>("fixed_color").example(Example::Literal(r##""#426B9E""##)),
];
const WATERFALL: &[Field] = &[
    category("labels", true),
    numeric("deltas", true),
    optional::<f64>("base").example(Example::Literal("0.0")),
];
const GRID: &[Field] = &[custom(
    "fill",
    true,
    crate::recipe::resolve::DataReference::collection_schema,
)
.example(Example::Grid)];
const WIDE_XY: &[Field] = &[
    scoped_role("x", true).example(Example::Column("one numeric value per source row")),
    collection("y"),
    optional::<GeneratedColumns>("column_identity"),
];
const INDEXED: &[Field] = &[
    collection("y"),
    optional::<GeneratedColumns>("column_identity"),
];
const WIDE_DISTRIBUTION: &[Field] = &[
    scoped_role("category", true).example(Example::Column("one category per source row")),
    collection("value"),
    optional::<GeneratedColumns>("column_identity"),
];
const COLUMNS: &[Field] = &[
    collection("value"),
    optional::<GeneratedColumns>("column_identity"),
];
const WIDE_RAINCLOUD: &[Field] = &[
    scoped_role("category", true).example(Example::Column("one category per source row")),
    collection("values"),
    optional::<GeneratedColumns>("column_identity"),
];
const RAINCLOUD_COLUMNS: &[Field] = &[
    collection("values"),
    optional::<GeneratedColumns>("column_identity"),
];

pub(super) const HISTOGRAM_BINS: &[Field] = &[
    numeric("lower", true),
    numeric("upper", true),
    numeric("height", true),
    optional::<HistogramStat>("stat").example(Example::Literal(r#""count""#)),
];
pub(super) const HISTOGRAM_KDE: &[Field] = &[numeric("x", true), numeric("density", true)];
pub(super) const HISTOGRAM_RUG: &[Field] = &[
    numeric("x", true),
    numeric("baseline", true),
    numeric("top", true),
];
pub(super) const HISTOGRAM_GEOMETRY: &[Field] = &[
    custom("bins", true, |ctx| grammar::group(ctx, HISTOGRAM_BINS))
        .example(Example::Group(HISTOGRAM_BINS)),
    custom("kde", false, |ctx| grammar::group(ctx, HISTOGRAM_KDE))
        .example(Example::Group(HISTOGRAM_KDE)),
    custom("rug", false, |ctx| grammar::group(ctx, HISTOGRAM_RUG))
        .example(Example::Group(HISTOGRAM_RUG)),
    optional::<Option<String>>("value_dimension").example(Example::Literal(r#""value""#)),
    optional::<Option<String>>("height_dimension").example(Example::Literal(r#""height""#)),
];

pub(super) const RAINCLOUD_SUMMARY: &[Field] = &[
    category("category", true),
    category("hue", false),
    numeric("q1", true),
    numeric("median", true),
    numeric("q3", true),
];
pub(super) const RAINCLOUD_DENSITY: &[Field] = &[
    category("category", true),
    category("hue", false),
    numeric("y", true),
    numeric("normalized_width", true),
];
pub(super) const RAINCLOUD_POINTS: &[Field] = &[
    category("category", true),
    category("hue", false),
    numeric("y", true),
    numeric("normalized_strip", true),
];
pub(super) const RAINCLOUD_GEOMETRY: &[Field] = &[
    custom("summary", true, |ctx| {
        grammar::group(ctx, RAINCLOUD_SUMMARY)
    })
    .example(Example::Group(RAINCLOUD_SUMMARY)),
    custom("density", true, |ctx| {
        grammar::group(ctx, RAINCLOUD_DENSITY)
    })
    .example(Example::Group(RAINCLOUD_DENSITY)),
    custom("points", true, |ctx| grammar::group(ctx, RAINCLOUD_POINTS))
        .example(Example::Group(RAINCLOUD_POINTS)),
    mandatory::<String>("category_dimension").example(Example::Literal(r#""category""#)),
    mandatory::<String>("value_dimension").example(Example::Literal(r#""value""#)),
    optional::<Option<String>>("hue_dimension").example(Example::Literal(r#""group""#)),
];

pub(in crate::recipe) fn modes(kind: PlotKind) -> Vec<Mode> {
    use PlotKind as K;
    match kind {
        K::Scatter => vec![
            group("xy", XY),
            group("wide", WIDE_XY),
            group("indexed", INDEXED),
        ],
        K::Regression | K::Marginal => vec![group("xy", XY)],
        K::Density | K::Qq => vec![group("samples", SAMPLES)],
        K::Histogram => vec![group("samples", SAMPLES), geometry(HISTOGRAM_GEOMETRY)],
        K::Boxplot | K::Violin => vec![
            group("samples", DISTRIBUTION),
            group("wide", WIDE_DISTRIBUTION),
            group("columns", COLUMNS),
        ],
        K::Heatmap => vec![group("cells", CELLS), group("grid", GRID)],
        K::StackedBar | K::StackedHorizontalBar => vec![group("estimates", STACKED)],
        K::Line => vec![
            group("xy", LINE),
            group("wide", WIDE_XY),
            group("indexed", INDEXED),
        ],
        K::Trajectory => vec![group("xy", TRAJECTORY)],
        K::LinePath => vec![group("xy", LINE_PATH)],
        K::PointInterval => vec![group("intervals", POINT_INTERVAL)],
        K::Coefficient => vec![
            group("estimates", COEFFICIENT_ESTIMATES),
            group("intervals", COEFFICIENT_INTERVALS),
        ],
        K::Forest => vec![group("intervals", FOREST)],
        K::Interaction => vec![group("intervals", INTERACTION)],
        K::Dumbbell => vec![group("endpoints", DUMBBELL)],
        K::Bar | K::HorizontalBar => vec![
            group("samples", BAR_SAMPLES),
            group("estimates", BAR_ESTIMATES),
        ],
        K::Raincloud => vec![
            group("samples", RAINCLOUD_SAMPLES),
            geometry(RAINCLOUD_GEOMETRY),
            group("wide", WIDE_RAINCLOUD),
            group("columns", RAINCLOUD_COLUMNS),
        ],
        K::Matrix => vec![group("columns", MATRIX)],
        K::Beeswarm => vec![group("samples", BEESWARM)],
        K::Waterfall => vec![group("deltas", WATERFALL)],
    }
}

pub(in crate::recipe) fn select(kind: PlotKind, name: &str) -> Result<Mode> {
    modes(kind)
        .into_iter()
        .find(|mode| mode.name == name)
        .ok_or_else(|| invalid(format!("{} has no input mode {name:?}", kind.name())))
}

pub(crate) fn schema(ctx: &mut Schema, kind: PlotKind) -> Value {
    grammar::one_of(modes(kind).into_iter().map(|mode|{
        let mut shape=if mode.grouped {
            grammar::group(ctx,mode.fields)
        } else {
            grammar::record(ctx,mode.fields)
        };
        if shape["properties"].get("lower").is_some() && shape["properties"].get("upper").is_some(){
            shape=grammar::dependent_pair(shape,"lower","upper");
        }
        if kind==PlotKind::Beeswarm {
            shape=grammar::with(shape,json!({"not":{"required":["color","fixed_color"],"properties":{"fixed_color":{"not":{"const":false}}}}}));
        }
        grammar::object([(mode.name,shape)],&[mode.name])
    }))
}