use crisol_core::color::Rgba;
use crate::axis::Scale;
use crate::transform::YAxis;
pub const PLOT_SPEC_VERSION: u32 = 1;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default, rename_all = "snake_case"))]
#[derive(Clone, Debug, PartialEq)]
pub struct PlotSpec {
pub version: u32,
pub title: Option<String>,
pub x_label: Option<String>,
pub y_label: Option<String>,
pub width: u32,
pub height: u32,
pub x_scale: Scale,
pub y_scale: Scale,
pub x_range: Option<[f64; 2]>,
pub y_range: Option<[f64; 2]>,
pub series: Vec<SeriesSpec>,
pub legend: bool,
pub grid: bool,
pub theme: Option<PlotTheme>,
}
impl Default for PlotSpec {
fn default() -> Self {
Self {
version: PLOT_SPEC_VERSION,
title: None,
x_label: None,
y_label: None,
width: 900,
height: 600,
x_scale: Scale::Linear,
y_scale: Scale::Linear,
x_range: None,
y_range: None,
series: Vec::new(),
legend: true,
grid: true,
theme: None,
}
}
}
impl PlotSpec {
pub fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
..Self::default()
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn x_label(mut self, label: impl Into<String>) -> Self {
self.x_label = Some(label.into());
self
}
pub fn y_label(mut self, label: impl Into<String>) -> Self {
self.y_label = Some(label.into());
self
}
pub fn scale(mut self, x: Scale, y: Scale) -> Self {
self.x_scale = x;
self.y_scale = y;
self
}
pub fn range(mut self, x: [f64; 2], y: [f64; 2]) -> Self {
self.x_range = Some(x);
self.y_range = Some(y);
self
}
pub fn series(mut self, series: SeriesSpec) -> Self {
self.series.push(series);
self
}
pub fn preset(mut self, preset: PagePreset, dpi: u32) -> Self {
let (width, height) = preset.pixels(dpi);
self.width = width;
self.height = height;
self
}
pub fn theme(mut self, theme: PlotTheme) -> Self {
self.theme = Some(theme);
self
}
pub fn validate(&self) -> Result<(), SpecError> {
if self.version > PLOT_SPEC_VERSION {
return Err(SpecError::Version(self.version));
}
if self.width == 0 || self.height == 0 {
return Err(SpecError::Size);
}
const MAX_SIDE: u32 = 16_384;
const MAX_PIXELS: u64 = 64_000_000;
if self.width > MAX_SIDE
|| self.height > MAX_SIDE
|| u64::from(self.width) * u64::from(self.height) > MAX_PIXELS
{
return Err(SpecError::TooLarge {
width: self.width,
height: self.height,
});
}
for range in [self.x_range, self.y_range].into_iter().flatten() {
if !range[0].is_finite() || !range[1].is_finite() || range[1] <= range[0] {
return Err(SpecError::Range(range));
}
}
for series in &self.series {
if series.points.is_empty() {
return Err(SpecError::EmptySeries(series.name.clone()));
}
if !series.points.iter().flatten().all(|value| value.is_finite()) {
return Err(SpecError::NonFinite(series.name.clone()));
}
}
Ok(())
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PagePreset {
#[default]
SingleColumn,
DoubleColumn,
Letter,
}
impl PagePreset {
pub const fn inches(self) -> (f32, f32) {
match self {
Self::SingleColumn => (3.5, 2.5),
Self::DoubleColumn => (7.16, 4.5),
Self::Letter => (8.5, 11.0),
}
}
pub fn pixels(self, dpi: u32) -> (u32, u32) {
let (width, height) = self.inches();
(
(width * dpi as f32).round() as u32,
(height * dpi as f32).round() as u32,
)
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default, rename_all = "snake_case"))]
#[derive(Clone, Debug, PartialEq)]
pub struct SeriesSpec {
pub name: String,
pub kind: SeriesKind,
pub points: Vec<[f64; 2]>,
pub color: Option<Rgba>,
pub width: f32,
pub marker: Option<MarkerSpec>,
pub fill_opacity: f32,
pub y_axis: YAxis,
pub legend: bool,
pub baseline: f64,
pub bar_width: Option<f64>,
}
impl Default for SeriesSpec {
fn default() -> Self {
Self {
name: String::new(),
kind: SeriesKind::Line,
points: Vec::new(),
color: None,
width: 1.5,
marker: None,
fill_opacity: 0.2,
y_axis: YAxis::Left,
legend: true,
baseline: 0.0,
bar_width: None,
}
}
}
impl SeriesSpec {
pub fn line(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
Self {
name: name.into(),
points,
..Self::default()
}
}
pub fn scatter(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
Self {
name: name.into(),
kind: SeriesKind::Scatter,
marker: Some(MarkerSpec::Circle),
points,
..Self::default()
}
}
pub fn area(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
Self {
name: name.into(),
kind: SeriesKind::Area,
points,
..Self::default()
}
}
pub fn step(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
Self {
name: name.into(),
kind: SeriesKind::Step,
points,
..Self::default()
}
}
pub fn bars(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
Self {
name: name.into(),
kind: SeriesKind::Bars,
points,
..Self::default()
}
}
pub fn color(mut self, color: Rgba) -> Self {
self.color = Some(color);
self
}
pub fn width(mut self, width: f32) -> Self {
self.width = width;
self
}
pub fn marker(mut self, marker: MarkerSpec) -> Self {
self.marker = Some(marker);
self
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SeriesKind {
#[default]
Line,
Scatter,
Area,
Step,
Bars,
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarkerSpec {
#[default]
Circle,
Square,
Diamond,
Triangle,
Cross,
Plus,
Ring,
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
#[derive(Clone, Debug, PartialEq)]
pub struct PlotTheme {
pub background: Rgba,
pub plot_background: Rgba,
pub text: Rgba,
pub axis: Rgba,
pub grid: Rgba,
pub palette: Vec<Rgba>,
}
impl Default for PlotTheme {
fn default() -> Self {
Self {
background: Rgba::WHITE,
plot_background: Rgba::WHITE,
text: Rgba::from_rgb(0x1f, 0x23, 0x28),
axis: Rgba::from_rgb(0x6a, 0x73, 0x7d),
grid: Rgba::from_rgb(0xe1, 0xe4, 0xe8),
palette: vec![
Rgba::from_rgb(0x1f, 0x77, 0xb4),
Rgba::from_rgb(0xff, 0x7f, 0x0e),
Rgba::from_rgb(0x2c, 0xa0, 0x2c),
Rgba::from_rgb(0xd6, 0x27, 0x28),
Rgba::from_rgb(0x94, 0x67, 0xbd),
Rgba::from_rgb(0x8c, 0x56, 0x4b),
],
}
}
}
impl PlotTheme {
pub fn series_color(&self, index: usize) -> Rgba {
if self.palette.is_empty() {
Rgba::BLACK
} else {
self.palette[index % self.palette.len()]
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SpecError {
Version(u32),
Size,
TooLarge {
width: u32,
height: u32,
},
Range([f64; 2]),
EmptySeries(String),
NonFinite(String),
}
impl std::fmt::Display for SpecError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Version(version) => write!(
formatter,
"plot spec version {version} is newer than {PLOT_SPEC_VERSION}"
),
Self::Size => write!(formatter, "plot width and height must be positive"),
Self::TooLarge { width, height } => write!(
formatter,
"plot {width}×{height} exceeds the 16384 px side or 64M-pixel budget"
),
Self::Range(range) => write!(formatter, "invalid range {range:?}"),
Self::EmptySeries(name) => write!(formatter, "series `{name}` has no points"),
Self::NonFinite(name) => write!(formatter, "series `{name}` has a non-finite point"),
}
}
}
impl std::error::Error for SpecError {}
#[cfg(test)]
mod tests;