lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
use std::path::Path;

use crate::{
    kind,
    operation::OperationOptions,
    output::{Format, PngOptions},
    plots::PlotKind,
    Error, Plot, Result, Theme,
};

macro_rules! families {
    ($($family:ident => $name:literal),+ $(,)?) => {
        pub(crate) const FAMILIES: &[(PlotKind,&str)] = &[$((PlotKind::$family,$name),)+];
        /// A rebuilt, editable native figure retains its exact family.
        #[derive(Clone)]
        #[non_exhaustive]
        #[expect(clippy::large_enum_variant,reason="the exact native Canvas branch owns its editable value directly")]
        pub enum RecipeFigure {
            $(#[doc=concat!("A native ",$name," plot.")] $family(Plot<kind::$family>),)+
            /// A rebuilt editable Canvas grid.
            Canvas(crate::Canvas),
            /// An independent complete theme declaration.
            Theme(Box<Theme>),
        }

        impl RecipeFigure {
            pub(crate) fn from_description(description:crate::builder::PlotDescription) -> Self {
                match description.kind() {
                    $(PlotKind::$family=>Self::$family(Plot::from_recipe_description(description)),)+
                }
            }

            /// Inspect the actual plot family, if this declaration is a plot.
            pub const fn kind(&self)->Option<PlotKind> {
                match self {
                    $(Self::$family(_)=>Some(PlotKind::$family),)+
                    Self::Canvas(_)|Self::Theme(_)=>None,
                }
            }

            pub(crate) fn check_science(&self)->Result<()> {
                match self {
                    $(Self::$family(plot)=>check_plot(plot.description()),)+
                    Self::Canvas(canvas)=>canvas.check_recipe_science(),
                    Self::Theme(_)=>Ok(()),
                }
            }

            /// Validate the complete rebuilt figure.
            pub fn preflight(&self)->Result<()> {
                self.preflight_with_operation(&OperationOptions::default())
            }

            /// Perform this operation using the caller's cancellation options.
            pub fn preflight_with_operation(&self,options:&OperationOptions)->Result<()> {
                match self {
                    $(Self::$family(plot)=>plot.preflight_with_operation(options),)+
                    Self::Canvas(canvas)=>canvas.preflight_with_operation(options),
                    Self::Theme(_)=>Ok(()),
                }
            }

            /// Read the accepted native layout.
            pub fn layout_report(&self)->Result<crate::layout::LayoutReport> {
                self.layout_report_with_operation(&OperationOptions::default())
            }

            /// Perform this operation using the caller's cancellation options.
            pub fn layout_report_with_operation(&self,options:&OperationOptions)->Result<crate::layout::LayoutReport> {
                match self {
                    $(Self::$family(plot)=>plot.layout_report_with_operation(options),)+
                    Self::Canvas(canvas)=>canvas.layout_report_with_operation(options),
                    Self::Theme(_)=>Err(no_figure()),
                }
            }

            /// Freeze the figure with its same-operation scientific results.
            pub fn render_with_results(&self)->Result<crate::stats::RenderWithResults> {
                self.render_with_results_with_operation(&OperationOptions::default())
            }

            /// Perform this operation using the caller's cancellation options.
            pub fn render_with_results_with_operation(&self,options:&OperationOptions)->Result<crate::stats::RenderWithResults> {
                match self {
                    $(Self::$family(plot)=>plot.render_with_results_with_operation(options),)+
                    Self::Canvas(canvas)=>canvas.render_with_results_with_operation(options),
                    Self::Theme(_)=>Err(no_figure()),
                }
            }

            /// Extract the current editable declaration.
            pub fn get_recipe(&self)->Result<super::Recipe> {
                self.get_recipe_with_operation(&OperationOptions::default())
            }

            /// Perform this operation using the caller's cancellation options.
            pub fn get_recipe_with_operation(&self,options:&OperationOptions)->Result<super::Recipe> {
                match self {
                    $(Self::$family(plot)=>plot.get_recipe_with_operation(options),)+
                    Self::Canvas(canvas)=>canvas.get_recipe_with_operation(options),
                    Self::Theme(theme)=>theme.get_recipe_with_operation(options),
                }
            }

            /// Freeze the rebuilt figure in a native Output.
            pub fn render(&self)->Result<crate::Output> {
                self.render_with_operation(&OperationOptions::default())
            }

            /// Prepare and freeze under one cancellable operation.
            pub fn render_with_operation(&self,options:&OperationOptions)->Result<crate::Output> {
                crate::operation::run(options,||self.freeze())
            }

            pub(crate) fn freeze(&self)->Result<crate::Output> {
                match self {
                    $(Self::$family(plot)=>plot.freeze(),)+
                    Self::Canvas(canvas)=>canvas.freeze(),
                    Self::Theme(_)=>Err(no_figure()),
                }
            }

            /// Publish outlined SVG.
            pub fn svg(&self,path:impl AsRef<Path>)->Result<crate::Output> {
                self.svg_with_operation(path,&OperationOptions::default())
            }
            /// Publish with the caller's cancellation options.
            pub fn svg_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
                self.save_with_operation(path,Format::svg(),options)
            }

            /// Publish SVG retaining selectable text.
            pub fn svg_preserve_text(&self,path:impl AsRef<Path>)->Result<crate::Output> {
                self.svg_preserve_text_with_operation(path,&OperationOptions::default())
            }
            /// Publish with the caller's cancellation options.
            pub fn svg_preserve_text_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
                self.save_with_operation(path,Format::svg().preserve_text(true),options)
            }

            /// Publish the default balanced PNG.
            pub fn png(&self,path:impl AsRef<Path>)->Result<crate::Output> {
                self.png_with_operation(path,&OperationOptions::default())
            }
            /// Publish with the caller's cancellation options.
            pub fn png_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
                self.save_with_operation(path,Format::png(),options)
            }

            /// Publish a source-sized PNG.
            pub fn png_preview(&self,path:impl AsRef<Path>)->Result<crate::Output> {
                self.png_preview_with_operation(path,&OperationOptions::default())
            }
            /// Publish with the caller's cancellation options.
            pub fn png_preview_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
                self.save_with_operation(path,PngOptions { sizing:crate::output::PngSizing::Source,compression:crate::output::PngCompression::Balanced },options)
            }

            /// Publish a PNG with explicit device options.
            pub fn png_with_options(&self,path:impl AsRef<Path>,options:PngOptions)->Result<crate::Output> {
                self.png_with_options_with_operation(path,options,&OperationOptions::default())
            }
            /// Publish a PNG with explicit sampling and operation options.
            pub fn png_with_options_with_operation(&self,path:impl AsRef<Path>,options:PngOptions,operation:&OperationOptions)->Result<crate::Output> {
                self.save_with_operation(path,options,operation)
            }

            /// Write the current native declaration and return that same Recipe.
            pub fn recipe(&self,path:impl AsRef<Path>)->Result<super::Recipe> {
                self.recipe_with_operation(path,&OperationOptions::default())
            }
            /// Extract and write the declaration under one operation.
            pub fn recipe_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<super::Recipe> {
                match self {
                    $(Self::$family(plot)=>plot.recipe_with_operation(path,options),)+
                    Self::Canvas(canvas)=>canvas.recipe_with_operation(path,options),
                    Self::Theme(theme)=>theme.recipe_with_operation(path,options),
                }
            }
        }

        impl TryFrom<&RecipeFigure> for crate::composition::CompositionSource {
            type Error=Error;
            fn try_from(figure:&RecipeFigure)->Result<Self>{
                match figure{
                    $(RecipeFigure::$family(plot)=>Ok(plot.into()),)+
                    RecipeFigure::Canvas(canvas)=>Ok(canvas.into()),
                    RecipeFigure::Theme(_)=>Err(no_figure()),
                }
            }
        }

        pub(crate) fn plot_kind(name:&str)->Result<PlotKind> {
            match name {
                $($name=>Ok(PlotKind::$family),)+
                _=>Err(Error::Data(format!("unknown plot kind {name:?}").into())),
            }
        }
    }
}

fn no_figure() -> Error {
    Error::Data("independent theme has no drawable figure".into())
}

pub(crate) fn check_plot(source: &crate::builder::PlotDescription) -> Result<()> {
    crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
    source.validate_configuration(source.kind())?;
    let appearance = source.resolve_theme()?;
    let operation = crate::font::canonical::OperationContext::new();
    let (registry, _) = crate::plots::shared_x::prepare_plot(source, &operation, &appearance)?;
    crate::layout::interior::guide::validate_categorical_scale(
        source,
        &registry.panels,
        &appearance,
        None,
    )
}

families! {
    Scatter=>"scatter", Histogram=>"histogram", Density=>"density", Qq=>"qq",
    PointInterval=>"point_interval", Line=>"line", Trajectory=>"trajectory", LinePath=>"line_path",
    Interaction=>"interaction", Coefficient=>"coefficient", Forest=>"forest", Dumbbell=>"dumbbell",
    Heatmap=>"heatmap", Bar=>"bar", HorizontalBar=>"horizontal_bar", StackedBar=>"stacked_bar",
    StackedHorizontalBar=>"stacked_horizontal_bar", Boxplot=>"boxplot", Violin=>"violin", Raincloud=>"raincloud",
    Regression=>"regression", Marginal=>"marginal", Matrix=>"matrix", Beeswarm=>"beeswarm", Waterfall=>"waterfall",
}