use toml_edit::{InlineTable, Item, Value};
use crate::{
layout::{AuthoredAxisSpec, RawWindow, RootRequest, RootSize, SizeUnit},
recipe::{
capture::Capture,
codec::{choice, field, invalid, Codec},
collection::CategoryRequest,
declaration::{BindingRequirement, BindingValueType, Group},
figure::plot_kind,
plot_input::{self, BuildInput},
resolve::Resolver,
RecipeFigure,
},
spec::{
AxisScale, BarSpacing, CategoryOrder, HeatmapAnnotations, HeatmapLayout, HistogramBins,
HistogramStat, LegendComposition, LegendPolicy, LegendPosition, LinePathStyle, PlotKind,
QqLine, RawOverlay, RegressionBand, ValueSort,
},
NumericFormat, Result, Text, Theme,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::{Plot, PlotDescription};
mod admission;
mod extras;
mod opacity;
mod significance;
pub(crate) mod style;
choice!(AxisScale {Linear=>"linear",Log10=>"log10"});
choice!(BarSpacing {Comfort=>"comfort",Compact=>"compact"});
choice!(RegressionBand {PointwiseMean95=>"pointwise_mean95",Hidden=>"hidden"});
choice!(QqLine {Quartiles=>"quartiles",Identity=>"identity",Hidden=>"hidden"});
choice!(LinePathStyle {Neutral=>"neutral",Hue=>"hue"});
choice!(RawOverlay {Hidden=>"hidden",Points=>"points",Jittered=>"jittered"});
choice!(LegendComposition {Combined=>"combined",Separate=>"separate"});
choice!(ValueSort {Ascending=>"ascending",Descending=>"descending"});
choice!(SizeUnit {Inch=>"in",Centimeter=>"cm",Millimeter=>"mm",Point=>"pt"});
choice!(LegendPosition {
Auto=>"auto",InsideTopLeft=>"inside_top_left",InsideTop=>"inside_top",InsideTopRight=>"inside_top_right",
InsideRightTop=>"inside_right_top",InsideRight=>"inside_right",InsideRightBottom=>"inside_right_bottom",
InsideBottomLeft=>"inside_bottom_left",InsideBottom=>"inside_bottom",InsideBottomRight=>"inside_bottom_right",
InsideLeftTop=>"inside_left_top",InsideLeft=>"inside_left",InsideLeftBottom=>"inside_left_bottom",
OutsideRightTop=>"outside_right_top",OutsideRight=>"outside_right",OutsideRightBottom=>"outside_right_bottom",
OutsideTopLeft=>"outside_top_left",OutsideTop=>"outside_top",OutsideTopRight=>"outside_top_right",
OutsideBottomLeft=>"outside_bottom_left",OutsideBottom=>"outside_bottom",OutsideBottomRight=>"outside_bottom_right",
OutsideLeftTop=>"outside_left_top",OutsideLeft=>"outside_left",OutsideLeftBottom=>"outside_left_bottom"
});
impl Codec for LegendPolicy {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
grammar::choices(&["automatic", "hidden"]),
ctx.reference::<LegendPosition>(),
])
}
fn encode(&self) -> Value {
match self {
Self::Automatic => Value::from("automatic"),
Self::Hidden => Value::from("hidden"),
Self::Visible(position) => position.encode(),
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
match item.as_str() {
Some("automatic") => Ok(Self::Automatic),
Some("hidden") => Ok(Self::Hidden),
_ => LegendPosition::decode(item, None).map(Self::Visible),
}
}
}
impl Codec for CategoryOrder {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
grammar::literal("observed"),
ctx.reference::<Vec<String>>(),
ctx.reference::<ValueSort>(),
])
}
fn encode(&self) -> Value {
match self {
Self::Observed => Value::from("observed"),
Self::Explicit(values) => values.encode(),
Self::Value(sort) => sort.encode(),
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("observed") {
Ok(Self::Observed)
} else if item.is_array() {
Vec::<String>::decode(item, None).map(Self::Explicit)
} else {
ValueSort::decode(item, None).map(Self::Value)
}
}
}
const BINS_FIELDS: &[grammar::Field] = &[
grammar::optional::<usize>("count"),
grammar::optional::<f64>("width"),
];
impl Codec for HistogramBins {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
grammar::literal("auto"),
grammar::with(
grammar::record(ctx, BINS_FIELDS),
grammar::exclusive(&["count", "width"]),
),
])
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
match self {
Self::Auto => return Value::from("auto"),
Self::Count(value) => {
fields.insert("count", crate::data::ExactInteger::from(*value).encode())
}
Self::Width(value) => fields.insert("width", value.encode()),
};
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("auto") {
return Ok(Self::Auto);
}
let fields = grammar::record_fields(item, BINS_FIELDS)?;
if fields.len() != 1 {
return Err(invalid("bins require one count or width"));
}
if let Some(count) = fields.get("count") {
Ok(Self::Count(
crate::data::ExactInteger::decode(count, None)?
.to_usize()
.ok_or_else(|| invalid("invalid bin count"))?,
))
} else {
field(fields, "width", None).map(Self::Width)
}
}
}
const HEATMAP_LAYOUT_FIELDS: &[grammar::Field] = &[
grammar::custom("kind", true, |_| {
grammar::choices(&["lower_triangle", "upper_triangle"])
}),
grammar::optional::<bool>("diagonal"),
];
impl Codec for HeatmapLayout {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
grammar::literal("cartesian"),
grammar::record(ctx, HEATMAP_LAYOUT_FIELDS),
])
}
fn encode(&self) -> Value {
let (kind, diagonal) = match *self {
Self::Cartesian => return Value::from("cartesian"),
Self::LowerTriangle { diagonal } => ("lower_triangle", diagonal),
Self::UpperTriangle { diagonal } => ("upper_triangle", diagonal),
};
let mut fields = InlineTable::new();
fields.insert("kind", Value::from(kind));
fields.insert("diagonal", diagonal.encode());
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("cartesian") {
return Ok(Self::Cartesian);
}
let fields = grammar::record_fields(item, HEATMAP_LAYOUT_FIELDS)?;
let diagonal = field(fields, "diagonal", Some(true))?;
match field::<String>(fields, "kind", None)?.as_str() {
"lower_triangle" => Ok(Self::LowerTriangle { diagonal }),
"upper_triangle" => Ok(Self::UpperTriangle { diagonal }),
_ => Err(invalid("unknown heatmap layout")),
}
}
}
const ROOT_SIZE_FIELDS: &[grammar::Field] = &[
grammar::optional::<Option<f64>>("width"),
grammar::optional::<Option<f64>>("height"),
grammar::optional::<Option<u32>>("max_width"),
grammar::optional::<Option<SizeUnit>>("unit"),
];
impl Codec for RootRequest {
fn schema(ctx: &mut Schema) -> serde_json::Value {
{
let shape = grammar::record(ctx, ROOT_SIZE_FIELDS);
let fields = ["width", "height", "max_width", "unit"];
let modes = [
&["width"][..],
&["height"],
&["width", "height"],
&["width", "height", "unit"],
&["max_width"],
];
let allowed = grammar::one_of(
modes
.into_iter()
.map(|mode| grammar::exact_values(&fields, mode)),
);
grammar::one_of([grammar::literal("natural"), grammar::with(shape, allowed)])
}
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
match *self {
Self::Natural => return Value::from("natural"),
Self::ExactWidth(width) => {
fields.insert("width", f64::from_bits(width).encode());
}
Self::MaxWidth(width) => {
fields.insert("max_width", width.encode());
}
Self::ExactHeight(height) => {
fields.insert("height", f64::from_bits(height).encode());
}
Self::ExactSize(size) => {
if let Some(physical) = size.physical_size() {
fields.insert("width", physical.width().encode());
fields.insert("height", physical.height().encode());
fields.insert("unit", physical.unit().encode());
} else {
let (width, height) = size.dimensions().unwrap_or((0.0, 0.0));
fields.insert("width", width.encode());
fields.insert("height", height.encode());
}
}
}
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("natural") {
return Ok(Self::Natural);
}
let fields = grammar::record_fields(item, ROOT_SIZE_FIELDS)?;
let width: Option<f64> = field(fields, "width", Some(None))?;
let height: Option<f64> = field(fields, "height", Some(None))?;
let maximum: Option<u32> = field(fields, "max_width", Some(None))?;
let unit: Option<SizeUnit> = field(fields, "unit", Some(None))?;
let valid = |value: f64| value > 0.0 && value <= f64::from(u32::MAX);
if width.is_some_and(|value| !valid(value))
|| height.is_some_and(|value| !valid(value))
|| maximum == Some(0)
{
return Err(invalid(
"root dimensions must be positive and representable",
));
}
match (width, height, maximum, unit) {
(Some(width), Some(height), None, Some(unit)) => {
RootSize::with_unit(width, height, unit).map(Self::ExactSize)
}
(Some(width), Some(height), None, None) => Ok(Self::size(width, height)),
(Some(width), None, None, None) => Ok(Self::width(width)),
(None, Some(height), None, None) => Ok(Self::height(height)),
(None, None, Some(width), None) => Ok(Self::MaxWidth(width)),
_ => Err(invalid("incompatible root size fields")),
}
}
}
fn authored<T: Codec + PartialEq>(fields: &mut InlineTable, name: &str, value: &T, default: &T) {
if value != default {
fields.insert(name, value.encode());
}
}
const CONFIG_FIELDS: &[grammar::Field] = &[
grammar::custom("scope", false, |_| grammar::literal("full")),
grammar::custom("kind", true, |_| {
grammar::choices(
&crate::recipe::figure::FAMILIES
.iter()
.map(|(_, name)| *name)
.collect::<Vec<_>>(),
)
}),
grammar::custom("input", true, |_| grammar::primitive("object")),
grammar::optional::<String>("binding"),
grammar::optional::<Theme>("theme"),
grammar::optional::<Theme>("default_theme"),
grammar::optional::<RootRequest>("size"),
grammar::optional::<Text>("title"),
grammar::optional::<Text>("subtitle"),
grammar::optional::<Text>("caption"),
grammar::optional::<Text>("x_label"),
grammar::optional::<Text>("y_label"),
grammar::optional::<Text>("color_label"),
grammar::optional::<Text>("raincloud_hue_label"),
grammar::role("source_rows", false),
grammar::custom("hue", false, CategoryRequest::schema),
grammar::custom("series", false, CategoryRequest::schema),
grammar::custom("group", false, CategoryRequest::schema),
grammar::role("highlight_cells", false),
grammar::optional::<BarSpacing>("bar_spacing"),
grammar::optional::<HistogramBins>("histogram_bins"),
grammar::optional::<Option<HistogramStat>>("histogram_stat"),
grammar::optional::<QqLine>("qq_line"),
grammar::optional::<RawOverlay>("raw_overlay"),
grammar::optional::<RegressionBand>("regression_band"),
grammar::optional::<LinePathStyle>("line_path_style"),
grammar::optional::<bool>("interaction_connectors"),
grammar::optional::<bool>("point_outline_visible"),
grammar::optional::<LegendPolicy>("legend"),
grammar::optional::<LegendComposition>("legend_composition"),
grammar::optional::<HeatmapLayout>("heatmap_layout"),
grammar::optional::<CategoryOrder>("category_order"),
grammar::optional::<CategoryOrder>("x_order"),
grammar::optional::<CategoryOrder>("y_order"),
grammar::optional::<bool>("color_by_sign"),
grammar::optional::<bool>("zero_line"),
grammar::optional::<bool>("markers_visible"),
grammar::optional::<Option<f64>>("coefficient_reference_line"),
grammar::optional::<AxisScale>("axis_scale"),
grammar::custom("labels", false, labels_schema),
grammar::custom("band", false, |ctx| grammar::group(ctx, BAND_FIELDS)),
grammar::custom("axes", false, axes_schema),
grammar::optional::<crate::text::roles::TextRoles>("text_layouts"),
grammar::optional::<Vec<crate::spec::PlotTextAnnotation>>("panel_text_annotations"),
grammar::optional::<Vec<crate::spec::HeatmapNullRowAnnotation>>("heatmap_null_row_annotations"),
grammar::optional::<Option<crate::spec::WaterfallLabels>>("waterfall_labels"),
grammar::custom("color_label_format", false, NumericFormat::schema),
grammar::custom("estimate_labels", false, NumericFormat::schema),
grammar::custom("total_format", false, NumericFormat::schema),
grammar::custom("heatmap_annotations", false, |ctx| {
grammar::any_of([grammar::literal("hidden"), NumericFormat::schema(ctx)])
}),
grammar::optional::<Option<crate::scales::CategoricalColorScale>>("categorical_color_scale"),
grammar::optional::<Option<crate::scales::ContinuousColorScale>>("continuous_color_scale"),
grammar::optional::<Option<crate::elements::SignificanceMarkStyle>>("significance_mark_style"),
grammar::optional::<Option<Vec<crate::plots::InteractionStyle>>>("interaction_styles"),
grammar::optional::<Vec<crate::elements::GuideSpec>>("guides"),
grammar::custom("facet", false, extras::facet_schema),
grammar::custom("histogram_composite", false, extras::histogram_schema),
grammar::custom("point_layers", false, extras::point_layers_schema),
grammar::custom("bar_point_layers", false, extras::bar_points_schema),
grammar::custom("estimate_status", false, extras::status_schema),
grammar::custom("point_alpha", false, opacity::schema),
grammar::custom("line_alpha", false, opacity::schema),
grammar::custom("fill_alpha", false, opacity::schema),
grammar::custom("significance", false, |_| grammar::primitive("array")),
];
type ConfigurePlot = Box<dyn FnOnce(&mut PlotDescription, &mut Resolver<'_>) -> Result<()>>;
pub(crate) struct Blueprint {
kind: PlotKind,
input: BuildInput,
configure: ConfigurePlot,
}
impl Blueprint {
#[expect(
clippy::too_many_lines,
reason = "validate the complete authored plot field set before installing it"
)]
pub(crate) fn read(
item: &Item,
path: &str,
fallback: Option<&str>,
requirements: &mut Vec<BindingRequirement>,
) -> Result<Self> {
let group = Group::new(
item,
&grammar::names(CONFIG_FIELDS),
path,
format!("{path}.rows"),
fallback,
requirements,
)?;
let fields = group.fields;
if field::<String>(fields, "scope", Some("full".to_owned()))? != "full" {
return Err(invalid("Plot construction requires full scope"));
}
let binding = group.binding().map(str::to_owned);
let kind = plot_kind(&field::<String>(fields, "kind", None)?)?;
admission::validate_family(fields, kind, path)?;
let root = fields
.get("input")
.ok_or_else(|| invalid("plot.input is required"))?;
let mode = plot_input::collection_mode(root, kind);
let rectangular = mode.is_some();
let domain = format!("{path}.{}", if rectangular { "cells" } else { "rows" });
let input = plot_input::read(root, kind, path, binding.as_deref(), requirements)?;
let group = Group::new(
item,
&grammar::names(CONFIG_FIELDS),
path,
&domain,
fallback,
requirements,
)?;
let mut group = if rectangular {
group
.rectangular(path)
.with_generated_columns(mode != Some(plot_input::CollectionMode::Grid))
} else {
group
};
let rows = group.optional("source_rows", BindingValueType::RecordId)?;
let mut hue = CategoryRequest::optional(&mut group, "hue")?;
let mut series = CategoryRequest::optional(&mut group, "series")?;
let mut groups = CategoryRequest::optional(&mut group, "group")?;
let highlight = group.optional("highlight_cells", BindingValueType::Boolean)?;
if matches!(
mode,
Some(plot_input::CollectionMode::Wide | plot_input::CollectionMode::Indexed)
) {
let generated = || CategoryRequest::Generated;
match kind {
PlotKind::Scatter => {
hue.get_or_insert_with(generated);
}
PlotKind::Line => {
hue.get_or_insert_with(generated);
groups.get_or_insert_with(generated);
}
PlotKind::Boxplot | PlotKind::Violin | PlotKind::Raincloud => {
series.get_or_insert_with(generated);
}
_ => {}
}
}
let mut prose = Vec::new();
for name in [
"title",
"subtitle",
"caption",
"x_label",
"y_label",
"color_label",
"raincloud_hue_label",
] {
prose.push(
fields
.get(name)
.map(|value| Text::decode(value, None))
.transpose()?
.unwrap_or(Text::UNSET),
);
}
let [title, subtitle, caption, x_label, y_label, color_label, raincloud_hue_label]: [Text;
7] = prose.try_into().expect("seven text roles");
let theme = fields
.get("theme")
.map(|item| Theme::decode(item, None))
.transpose()?
.map(std::sync::Arc::new);
let default_theme = fields
.get("default_theme")
.map(|item| Theme::decode(item, None))
.transpose()?
.map(std::sync::Arc::new);
let root_size = field(fields, "size", Some(RootRequest::Natural))?;
let raw_overlay = field(fields, "raw_overlay", Some(RawOverlay::default()))?;
let regression_band = field(fields, "regression_band", Some(RegressionBand::default()))?;
let line_path_style = field(fields, "line_path_style", Some(LinePathStyle::default()))?;
let interaction_connectors = fields
.get("interaction_connectors")
.map(|value| bool::decode(value, None))
.transpose()?;
let legend_composition = field(
fields,
"legend_composition",
Some(LegendComposition::default()),
)?;
let bar_spacing = field(fields, "bar_spacing", Some(BarSpacing::default()))?;
let histogram_bins = field(fields, "histogram_bins", Some(HistogramBins::default()))?;
let histogram_stat = field(fields, "histogram_stat", Some(None::<HistogramStat>))?;
let qq_line = field(fields, "qq_line", Some(QqLine::default()))?;
let point_outline_visible = field(fields, "point_outline_visible", Some(true))?;
let legend_policy = field(fields, "legend", Some(LegendPolicy::Automatic))?;
let heatmap_layout = field(fields, "heatmap_layout", Some(HeatmapLayout::default()))?;
let category_order = field(fields, "category_order", Some(CategoryOrder::default()))?;
let x_order = field(fields, "x_order", Some(CategoryOrder::default()))?;
let y_order = field(fields, "y_order", Some(CategoryOrder::default()))?;
let color_by_sign = field(fields, "color_by_sign", Some(false))?;
let zero_line = field(fields, "zero_line", Some(false))?;
let markers_visible = field(fields, "markers_visible", Some(true))?;
let coefficient_reference_line = field(fields, "coefficient_reference_line", Some(None))?;
let axis_scale = field(fields, "axis_scale", Some(AxisScale::Linear))?;
let (labels, grid_rows) = if let Some(item) = fields.get("labels") {
read_labels(
item,
path,
binding.as_deref().or(fallback),
mode == Some(plot_input::CollectionMode::Grid),
requirements,
)?
} else {
Default::default()
};
let axes = fields
.get("axes")
.map(read_axes)
.transpose()?
.unwrap_or_default();
let band = if let Some(band) = fields.get("band") {
let group = Group::new(
band,
&grammar::names(BAND_FIELDS),
format!("{path}.band"),
&domain,
fallback,
requirements,
)?;
let mut group = if rectangular {
group.rectangular(path)
} else {
group
};
Some((
group.required("lower", BindingValueType::Numeric)?,
group.required("upper", BindingValueType::Numeric)?,
))
} else {
None
};
let text_layouts = field(
fields,
"text_layouts",
Some(crate::text::roles::TextRoles::default()),
)?;
let panel_text_annotations = field(fields, "panel_text_annotations", Some(Vec::new()))?;
let heatmap_null_row_annotations =
field(fields, "heatmap_null_row_annotations", Some(Vec::new()))?;
let waterfall_labels = field(fields, "waterfall_labels", Some(None))?;
let color_label_format =
read_format(fields, "color_label_format")?.map(std::sync::Arc::new);
let estimate_labels = read_format(fields, "estimate_labels")?;
let total_format = read_format(fields, "total_format")?.map(std::sync::Arc::new);
let heatmap_annotations = match fields.get("heatmap_annotations") {
None => HeatmapAnnotations::Hidden,
Some(value) if value.as_str() == Some("hidden") => HeatmapAnnotations::Hidden,
Some(value) => HeatmapAnnotations::Values(
NumericFormat::from_recipe_value(value)
.map_err(|error| error.with_prefix("heatmap_annotations"))?,
),
};
let additional = extras::read(
kind,
mode,
fields,
path,
binding.as_deref().or(fallback),
fallback,
requirements,
)?;
let configure = Box::new(
move |description: &mut PlotDescription, resolver: &mut Resolver<'_>| {
description.title = title;
description.subtitle = subtitle;
description.root_size = root_size;
description.raw_overlay = raw_overlay;
description.regression_band = regression_band;
description.line_path_style = line_path_style;
description.interaction_connectors = interaction_connectors;
description.legend_composition = legend_composition;
let payload = description.payload_mut();
payload.caption = caption;
payload.x_label = x_label;
payload.y_label = y_label;
payload.color_label = color_label;
payload.raincloud_hue_label = raincloud_hue_label;
payload.theme = theme;
payload.default_theme = default_theme;
payload.source_rows = rows.map(|value| value.source_rows(resolver)).transpose()?;
payload.hue = hue.map(|value| value.category(resolver)).transpose()?;
payload.series = series.map(|value| value.category(resolver)).transpose()?;
payload.group = groups.map(|value| value.category(resolver)).transpose()?;
payload.highlight_cells =
highlight.map(|value| value.boolean(resolver)).transpose()?;
payload.bar_spacing = bar_spacing;
payload.histogram_bins = histogram_bins;
payload.histogram_stat = histogram_stat;
payload.qq_line = qq_line;
payload.point_outline_visible = point_outline_visible;
payload.legend_policy = legend_policy;
payload.heatmap_layout = heatmap_layout;
payload.category_orders = super::CategoryOrders {
primary: category_order,
x: x_order,
y: y_order,
};
payload.color_by_sign = color_by_sign;
payload.zero_line = zero_line;
payload.markers_visible = markers_visible;
payload.coefficient_reference_line = coefficient_reference_line;
payload.axis_scale = axis_scale;
payload.labels = labels;
if let Some(rows) = grid_rows {
let (values, displays) = resolver
.grid_row_labels(&rows.reference)
.map_err(|err| rows.context(err))?;
payload.labels =
std::mem::take(&mut payload.labels).restore_grid_rows(values, displays)?;
}
if mode == Some(plot_input::CollectionMode::Grid) {
let crate::input::PlotInput::Heatmap { fill, .. } = payload.input.as_ref()
else {
unreachable!("validated grid mode")
};
payload
.labels
.validate_grid_labels(fill.get_source().selected_shape())?;
}
payload.text_layouts = text_layouts;
payload.panel_text_annotations = panel_text_annotations;
payload.heatmap_null_row_annotations = heatmap_null_row_annotations;
payload.waterfall_labels = waterfall_labels;
payload.color_label_format = color_label_format;
payload.estimate_labels = estimate_labels;
payload.total_format = total_format;
payload.heatmap_annotations = heatmap_annotations;
payload.axes = axes;
payload.line_band = band
.map(|(lower, upper)| {
Ok::<_, crate::Error>(crate::spec::Bounds::new(
lower.numeric(resolver)?,
upper.numeric(resolver)?,
))
})
.transpose()?;
additional(description, resolver)
},
);
Ok(Self {
kind,
input,
configure,
})
}
pub(crate) fn build(self, resolver: &mut Resolver<'_>) -> Result<RecipeFigure> {
self.build_description(resolver)
.map(RecipeFigure::from_description)
}
pub(crate) fn build_description(self, resolver: &mut Resolver<'_>) -> Result<PlotDescription> {
resolver.begin_plot();
let mut description = PlotDescription::new((self.input)(resolver)?, self.kind);
(self.configure)(&mut description, resolver)?;
let payload = description.payload_mut();
payload.labels = std::mem::take(&mut payload.labels)
.with_captured_aliases_from(&resolver.take_captured_labels());
description.validate_configuration(self.kind)?;
Ok(description)
}
}
const BAND_FIELDS: &[grammar::Field] =
&[grammar::role("lower", true), grammar::role("upper", true)];
const LABEL_KEY_ALIAS: &[grammar::Field] = &[
grammar::mandatory::<crate::data::RawKey>("key"),
grammar::mandatory::<String>("source_label"),
grammar::mandatory::<String>("label"),
];
const LABEL_POSITION_ALIAS: &[grammar::Field] = &[
grammar::custom("axis", true, |_| grammar::choices(&["x", "y"])),
grammar::mandatory::<usize>("position"),
grammar::mandatory::<String>("label"),
];
const LABEL_FIELDS: &[grammar::Field] = &[
grammar::custom("mode", false, |_| grammar::choices(&["humanized", "raw"])),
grammar::custom("aliases", false, |ctx| {
grammar::dictionary(ctx.reference::<String>())
}),
grammar::custom("key_aliases", false, |ctx| {
grammar::array(grammar::record(ctx, LABEL_KEY_ALIAS))
}),
grammar::custom("positions", false, |ctx| {
grammar::array(grammar::record(ctx, LABEL_POSITION_ALIAS))
}),
grammar::role("row_labels", false),
grammar::optional::<Vec<String>>("x_labels"),
grammar::optional::<Vec<String>>("y_labels"),
];
const EXACT_TICK_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<f64>("position"),
grammar::mandatory::<String>("label"),
];
const AXIS_FIELDS: &[grammar::Field] = &[
grammar::custom("window", false, |ctx| grammar::pair(ctx.reference::<f64>())),
grammar::custom("ticks", false, |ctx| {
grammar::array(grammar::record(ctx, EXACT_TICK_FIELDS))
}),
grammar::custom(
"generation",
false,
crate::coordinates::TickGeneration::schema,
),
grammar::custom("format", false, NumericFormat::schema),
grammar::optional::<crate::coordinates::CategoryLabelSelection>("category_labels"),
];
const AXES_FIELDS: &[grammar::Field] = &[
grammar::custom("x", false, |ctx| grammar::record(ctx, AXIS_FIELDS)),
grammar::custom("y", false, |ctx| grammar::record(ctx, AXIS_FIELDS)),
];
pub(crate) fn labels_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("Labels", |ctx| {
grammar::with(
grammar::group(ctx, LABEL_FIELDS),
grammar::at_most_one(&["row_labels", "y_labels"]),
)
})
}
fn axes_schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, AXES_FIELDS)
}
fn admitted_axes_schema(ctx: &mut Schema, kind: PlotKind) -> serde_json::Value {
grammar::object(
["x", "y"].into_iter().enumerate().map(|(index, name)| {
let fields = AXIS_FIELDS
.iter()
.copied()
.filter(|field| admission::axis_permits(kind, index, field.name))
.collect::<Vec<_>>();
(name, grammar::record(ctx, &fields))
}),
&[],
)
}
pub(super) fn text_layouts_schema(ctx: &mut Schema, kind: PlotKind) -> serde_json::Value {
let shape = ctx.reference::<crate::text::roles::TextRoles>();
let forbidden = admission::forbidden_text_fields(kind);
if forbidden.is_empty() {
return shape;
}
grammar::with(
shape,
serde_json::json!({"not":{"anyOf":forbidden.iter().map(|field|grammar::required(&[field])).collect::<Vec<_>>()}}),
)
}
const GRID_LABEL_FIELDS: &[&str] = &["positions", "row_labels", "x_labels", "y_labels"];
pub(crate) fn non_grid_labels_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("NonGridLabels", |ctx| {
let fields = LABEL_FIELDS
.iter()
.copied()
.filter(|field| !GRID_LABEL_FIELDS.contains(&field.name))
.collect::<Vec<_>>();
grammar::group(ctx, &fields)
})
}
pub(super) fn native_properties(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, CONFIG_FIELDS)
}
fn family_schema(ctx: &mut Schema, kind: PlotKind, name: &str) -> serde_json::Value {
let forbidden = CONFIG_FIELDS
.iter()
.filter(|field| !admission::permits(kind, field.name))
.map(|field| field.name)
.collect::<Vec<_>>();
let mut properties = serde_json::json!({
"kind":grammar::literal(name),
"input":plot_input::schema(ctx,kind),
"axes":admitted_axes_schema(ctx,kind),
"text_layouts":text_layouts_schema(ctx,kind),
});
if admission::permits(kind, "significance") {
properties["significance"] = significance::schema(ctx, kind);
}
let mut shape = grammar::with(
serde_json::json!({"properties":properties}),
grammar::forbidden(&forbidden),
);
if kind == PlotKind::Heatmap {
shape = grammar::with(
shape,
serde_json::json!({
"if":{"properties":{"input":{"not":{"required":["grid"]}}}},
"then":{"properties":{"labels":non_grid_labels_schema(ctx)}}
}),
);
} else {
shape["properties"]["labels"] = non_grid_labels_schema(ctx);
}
shape
}
pub(crate) fn schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("Plot", |ctx| {
let base = native_properties(ctx);
let families = grammar::one_of(
crate::recipe::figure::FAMILIES
.iter()
.map(|(kind, name)| family_schema(ctx, *kind, name)),
);
grammar::with(base, families)
})
}
pub(crate) fn read_labels(
item: &Item,
path: &str,
fallback: Option<&str>,
grid: bool,
requirements: &mut Vec<BindingRequirement>,
) -> Result<(crate::formatting::Labels, Option<BindingRequirement>)> {
let group = Group::new(
item,
&grammar::names(LABEL_FIELDS),
format!("{path}.labels"),
format!("{path}.rows"),
fallback,
requirements,
)?;
let fields = group.fields;
if !grid && GRID_LABEL_FIELDS.iter().any(|key| fields.contains_key(key)) {
return Err(invalid("grid labels require a rectangular Heatmap input"));
}
let mode: String = field(fields, "mode", Some("humanized".to_owned()))?;
let mut labels = match mode.as_str() {
"raw" => crate::formatting::Labels::raw(),
"humanized" => crate::formatting::Labels::humanized(),
_ => return Err(invalid("unknown label mode")),
};
if let Some(aliases) = fields.get("aliases") {
let aliases = aliases
.as_table_like()
.ok_or_else(|| invalid("label aliases must be a table"))?;
for (key, value) in aliases.iter() {
labels = labels.alias(key, String::decode(value, None)?);
}
}
if let Some(values) = fields.get("key_aliases") {
let mut seen = std::collections::HashSet::new();
for item in crate::recipe::codec::array_items(values)? {
let fields = grammar::record_fields(item, LABEL_KEY_ALIAS)?;
let key: crate::data::RawKey = field(fields, "key", None)?;
crate::recipe::capture::portable_key(&key)?;
let name: String = field(fields, "source_label", None)?;
let label = field(fields, "label", None)?;
if !seen.insert((key.clone(), name.clone())) {
return Err(invalid("duplicate original key label alias"));
}
labels = labels.key_alias(key, name, label);
}
}
if fields.contains_key("y_labels") && fields.contains_key("row_labels") {
return Err(invalid(
"literal and bound grid row labels are mutually exclusive",
));
}
for (axis, key) in [(1, "x_labels"), (0, "y_labels")] {
if let Some(values) = fields.get(key) {
labels = labels.grid_axis_labels(axis, Vec::<String>::decode(values, None)?);
}
}
if let Some(values) = fields.get("positions") {
let mut seen = std::collections::HashSet::new();
for item in crate::recipe::codec::array_items(values)? {
let fields = grammar::record_fields(item, LABEL_POSITION_ALIAS)?;
let axis = match field::<String>(fields, "axis", None)?.as_str() {
"x" => 1,
"y" => 0,
_ => return Err(invalid("grid label axis must be x or y")),
};
let index = field(fields, "position", None)?;
if !seen.insert((axis, index)) {
return Err(invalid("duplicate grid label position"));
}
labels = labels.position_alias(axis, index, field(fields, "label", None)?);
}
}
let mut group = group;
let rows = group.optional("row_labels", BindingValueType::Category)?;
Ok((labels, rows))
}
pub(crate) fn encode_labels(
labels: &crate::formatting::Labels,
context: &mut Capture,
path: &str,
) -> Result<Value> {
let mut fields = InlineTable::new();
fields.insert(
"mode",
Value::from(if labels.is_humanized() {
"humanized"
} else {
"raw"
}),
);
let mut aliases = InlineTable::new();
let mut keys: std::collections::HashMap<(crate::data::RawKey, String), String> = labels
.authored_key_aliases()
.map(|(key, name, label)| ((key.clone(), name.to_owned()), label.to_owned()))
.collect();
let mut positions = labels
.authored_positions()
.map(|(key, label)| (key, label.to_owned()))
.collect::<std::collections::BTreeMap<_, _>>();
for (token, label) in labels.authored_aliases().into_iter().flatten() {
if let Some(position) = labels.captured_position(token) {
positions.insert(position, label.to_owned());
} else if let Some((key, name)) = labels.captured_identity(token) {
keys.insert((key.clone(), name.to_owned()), label.to_owned());
} else {
aliases.insert(token, label.into());
}
}
if !aliases.is_empty() {
fields.insert("aliases", aliases.into());
}
if !keys.is_empty() {
let mut ordered = keys
.into_iter()
.map(|((key, name), label)| {
let mut fields = InlineTable::new();
fields.insert("key", crate::recipe::capture::portable_key(&key)?);
fields.insert("source_label", name.encode());
fields.insert("label", label.encode());
Ok((crate::data::key_bytes(&key)?, name, Value::from(fields)))
})
.collect::<Result<Vec<_>>>()?;
ordered.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
let items: toml_edit::Array = ordered.into_iter().map(|(_, _, value)| value).collect();
fields.insert("key_aliases", items.into());
}
for (axis, key) in [(1, "x_labels"), (0, "y_labels")] {
if let Some(values) = labels.grid_axis_values(axis) {
fields.insert(key, values.to_vec().encode());
}
}
if !positions.is_empty() {
let items: toml_edit::Array = positions
.into_iter()
.map(|((axis, index), label)| {
let mut entry = InlineTable::new();
entry.insert("axis", Value::from(if axis == 1 { "x" } else { "y" }));
entry.insert("position", index.encode());
entry.insert("label", label.encode());
Value::from(entry)
})
.collect();
fields.insert("positions", items.into());
}
if let Some(values) = labels.grid_row_values() {
fields.insert(
"row_labels",
context.category(values, "row_labels", &format!("{path}.labels.row_labels"))?,
);
}
Ok(fields.into())
}
fn read_format(fields: &dyn toml_edit::TableLike, name: &str) -> Result<Option<NumericFormat>> {
fields
.get(name)
.map(NumericFormat::from_recipe_value)
.transpose()
.map_err(|error| error.with_prefix(name))
}
fn read_axes(item: &Item) -> Result<[AuthoredAxisSpec; 2]> {
let fields = grammar::record_fields(item, AXES_FIELDS)?;
let mut axes = [AuthoredAxisSpec::default(), AuthoredAxisSpec::default()];
for (axis, key) in axes.iter_mut().zip(["x", "y"]) {
let Some(item) = fields.get(key) else {
continue;
};
let fields = grammar::record_fields(item, AXIS_FIELDS)?;
if let Some(window) = fields.get("window") {
let values = Vec::<f64>::decode(window, None)?;
let [lower, upper] = values.as_slice() else {
return Err(invalid("axis window requires two endpoints"));
};
axis.window = Some(RawWindow::from_pair((*lower, *upper)));
}
if let Some(ticks) = fields.get("ticks") {
let ticks = ticks
.as_array()
.ok_or_else(|| invalid("exact ticks must be an array"))?;
let mut values = Vec::new();
for tick in ticks {
let item = Item::Value(tick.clone());
let fields = grammar::record_fields(&item, EXACT_TICK_FIELDS)?;
values.push(crate::coordinates::AxisTick::new(
field(fields, "position", None)?,
field::<String>(fields, "label", None)?,
));
}
axis.exact_ticks = Some(values);
}
if let Some(generation) = fields.get("generation") {
axis.generation = crate::coordinates::TickGeneration::from_recipe_value(generation)
.map_err(|error| error.with_prefix(&format!("axes.{key}.generation")))?;
}
axis.format = read_format(fields, "format")?.map(std::sync::Arc::new);
axis.category_labels = field(
fields,
"category_labels",
Some(crate::coordinates::CategoryLabelSelection::all()),
)?;
axis.validate(key)?;
}
Ok(axes)
}
fn encode_axes(axes: &[AuthoredAxisSpec; 2]) -> Result<Value> {
let mut fields = InlineTable::new();
for (axis, key) in axes.iter().zip(["x", "y"]) {
let mut value = InlineTable::new();
if let Some(window) = axis.window {
value.insert("window", vec![window.lower, window.upper].encode());
}
if let Some(ticks) = &axis.exact_ticks {
let values: toml_edit::Array = ticks
.iter()
.map(|tick| {
let mut fields = InlineTable::new();
fields.insert("position", tick.position.encode());
fields.insert("label", tick.label.encode());
Value::from(fields)
})
.collect();
value.insert("ticks", Value::from(values));
}
if !axis.generation.is_automatic() {
value.insert(
"generation",
axis.generation
.recipe_value()
.map_err(|error| error.with_prefix(&format!("axes.{key}.generation")))?,
);
}
if let Some(format) = &axis.format {
value.insert(
"format",
format
.recipe_value()
.map_err(|error| error.with_prefix(&format!("axes.{key}.format")))?,
);
}
if !axis.category_labels.is_all() {
value.insert("category_labels", axis.category_labels.encode());
}
if !value.is_empty() {
fields.insert(key, value.into());
}
}
Ok(fields.into())
}
impl PlotDescription {
#[expect(
clippy::too_many_lines,
reason = "explicit portable fields of one native plot owner"
)]
pub(crate) fn capture_recipe(&self, context: &mut Capture, path: &str) -> Result<Value> {
context.begin_plot();
let payload = &self.payload;
let mut fields = InlineTable::new();
fields.insert("kind", Value::from(self.kind.name()));
fields.insert("input", plot_input::capture(&payload.input, context, path)?);
authored(&mut fields, "size", &self.root_size, &RootRequest::Natural);
for (name, text) in [
("title", &self.title),
("subtitle", &self.subtitle),
("caption", &payload.caption),
("x_label", &payload.x_label),
("y_label", &payload.y_label),
("color_label", &payload.color_label),
("raincloud_hue_label", &payload.raincloud_hue_label),
] {
if *text != Text::UNSET {
fields.insert(name, text.encode());
}
}
if let Some(theme) = &payload.theme {
fields.insert("theme", theme.encode());
}
if let Some(theme) = &payload.default_theme {
fields.insert("default_theme", theme.encode());
}
if let Some(rows) = &payload.source_rows {
fields.insert(
"source_rows",
context.rows(rows, "source_rows", &format!("{path}.source_rows"))?,
);
}
for (role, value) in [
("hue", &payload.hue),
("series", &payload.series),
("group", &payload.group),
] {
if let Some(value) = value {
fields.insert(
role,
context.category(value, role, &format!("{path}.{role}"))?,
);
}
}
if let Some(value) = &payload.highlight_cells {
fields.insert(
"highlight_cells",
context.boolean(value, "highlight_cells", &format!("{path}.highlight_cells"))?,
);
}
if let Some(bounds) = &payload.line_band {
let mut band = InlineTable::new();
band.insert(
"lower",
context.numeric(bounds.lower(), "lower", &format!("{path}.band.lower"))?,
);
band.insert(
"upper",
context.numeric(bounds.upper(), "upper", &format!("{path}.band.upper"))?,
);
fields.insert("band", band.into());
}
authored(
&mut fields,
"raw_overlay",
&self.raw_overlay,
&RawOverlay::default(),
);
authored(
&mut fields,
"regression_band",
&self.regression_band,
&RegressionBand::default(),
);
authored(
&mut fields,
"line_path_style",
&self.line_path_style,
&LinePathStyle::default(),
);
authored(
&mut fields,
"legend_composition",
&self.legend_composition,
&LegendComposition::default(),
);
if let Some(value) = self.interaction_connectors {
fields.insert("interaction_connectors", value.encode());
}
authored(
&mut fields,
"bar_spacing",
&payload.bar_spacing,
&BarSpacing::default(),
);
authored(
&mut fields,
"histogram_bins",
&payload.histogram_bins,
&HistogramBins::default(),
);
if let Some(value) = payload.histogram_stat {
fields.insert("histogram_stat", value.encode());
}
authored(&mut fields, "qq_line", &payload.qq_line, &QqLine::default());
authored(
&mut fields,
"point_outline_visible",
&payload.point_outline_visible,
&true,
);
authored(
&mut fields,
"legend",
&payload.legend_policy,
&LegendPolicy::Automatic,
);
authored(
&mut fields,
"heatmap_layout",
&payload.heatmap_layout,
&HeatmapLayout::default(),
);
authored(
&mut fields,
"category_order",
&payload.category_orders.primary,
&CategoryOrder::default(),
);
authored(
&mut fields,
"x_order",
&payload.category_orders.x,
&CategoryOrder::default(),
);
authored(
&mut fields,
"y_order",
&payload.category_orders.y,
&CategoryOrder::default(),
);
authored(&mut fields, "color_by_sign", &payload.color_by_sign, &false);
authored(&mut fields, "zero_line", &payload.zero_line, &false);
authored(
&mut fields,
"markers_visible",
&payload.markers_visible,
&true,
);
if let Some(value) = payload.coefficient_reference_line {
fields.insert("coefficient_reference_line", value.encode());
}
authored(
&mut fields,
"axis_scale",
&payload.axis_scale,
&AxisScale::Linear,
);
if payload.labels != crate::formatting::Labels::default() {
fields.insert("labels", encode_labels(&payload.labels, context, path)?);
}
authored(
&mut fields,
"text_layouts",
&payload.text_layouts,
&crate::text::roles::TextRoles::default(),
);
if !payload.panel_text_annotations.is_empty() {
fields.insert(
"panel_text_annotations",
payload.panel_text_annotations.encode(),
);
}
if !payload.heatmap_null_row_annotations.is_empty() {
fields.insert(
"heatmap_null_row_annotations",
payload.heatmap_null_row_annotations.encode(),
);
}
if let Some(value) = &payload.waterfall_labels {
fields.insert("waterfall_labels", value.encode());
}
for (name, value) in [
("color_label_format", payload.color_label_format.as_deref()),
("estimate_labels", payload.estimate_labels.as_ref()),
("total_format", payload.total_format.as_deref()),
] {
if let Some(value) = value {
fields.insert(
name,
value
.recipe_value()
.map_err(|error| error.with_prefix(name))?,
);
}
}
if let HeatmapAnnotations::Values(format) = &payload.heatmap_annotations {
fields.insert(
"heatmap_annotations",
format
.recipe_value()
.map_err(|error| error.with_prefix("heatmap_annotations"))?,
);
}
extras::capture(self, context, path, &mut fields)?;
let axes = encode_axes(&payload.axes)?;
if axes
.as_inline_table()
.is_some_and(|fields| !fields.is_empty())
{
fields.insert("axes", axes);
}
Ok(fields.into())
}
}
impl<K: crate::kind::Marker> Plot<K> {
pub(crate) fn from_recipe_description(description: PlotDescription) -> Self {
Self {
description,
marker: std::marker::PhantomData,
}
}
}