use std::marker::PhantomData;
use std::rc::Rc;
use crate::error::{binding, length, BindingResult};
use crate::{
kind, AdapterError, ArraySource, CategoryInput, CategoryValues, FacetScales, FacetSpec, Labels,
Plot, PlotKind, SourceRowsInput,
};
mod alpha;
mod constructors;
mod forwarding;
mod geometry;
mod grid;
#[cfg(test)]
mod metadata_tests;
#[cfg(test)]
mod projection_tests;
mod status;
mod wide;
pub(crate) type Context<'source> = Option<Rc<dyn ArraySource + 'source>>;
pub(crate) fn context<'source>(
source: impl ArraySource + 'source,
) -> BindingResult<Context<'source>> {
source.validate()?;
Ok(Some(Rc::new(source)))
}
#[derive(Clone)]
pub struct BindingMetadata<K: kind::Marker> {
len: Option<usize>,
geometry_points: Option<usize>,
labels: Labels,
facet: Option<FacetSpec>,
grid: Option<grid::Grid>,
expansion: Option<wide::Expansion>,
matrix_keys: Option<Vec<String>>,
marker: PhantomData<K>,
}
#[derive(Clone)]
pub struct PlotAdapter<'source, K: kind::Marker> {
plot: Plot<K>,
pub(crate) source: Context<'source>,
bindings: BindingMetadata<K>,
}
macro_rules! families {
($($family:ident),+) => {$ (
#[doc = concat!("ndarray frontend for native ", stringify!($family), ".")]
pub type $family<'source> = PlotAdapter<'source, kind::$family>;
)+};
}
families!(
Scatter,
Histogram,
Density,
Qq,
PointInterval,
Line,
Trajectory,
LinePath,
Interaction,
Coefficient,
Forest,
Dumbbell,
Heatmap,
Bar,
HorizontalBar,
StackedBar,
StackedHorizontalBar,
Boxplot,
Violin,
Raincloud,
Regression,
Marginal,
Matrix,
Beeswarm,
Waterfall
);
impl<'source, K: kind::Marker> PlotAdapter<'source, K> {
fn bound(plot: Plot<K>, source: Context<'source>, len: Option<usize>) -> Self {
Self {
plot,
source,
bindings: BindingMetadata {
len,
geometry_points: None,
labels: Labels::default(),
facet: None,
grid: None,
expansion: None,
matrix_keys: None,
marker: PhantomData,
},
}
}
pub fn into_parts(self) -> (Plot<K>, BindingMetadata<K>) {
(self.plot, self.bindings)
}
fn aligned(&self, role: &'static str, name: &str, actual: usize) -> BindingResult<()> {
if let Some(expected) = self.bindings.len {
length(role, name, expected, actual)?;
}
Ok(())
}
fn row_copies(&self) -> usize {
self.bindings.expansion.as_ref().map_or_else(
|| self.bindings.grid.as_ref().map_or(1, grid::Grid::columns),
|wide| wide.keys.len(),
)
}
fn alpha_len(&self) -> Option<usize> {
self.bindings.geometry_points.or(self.bindings.len)
}
fn category_rows(
&self,
values: impl CategoryInput,
role: &'static str,
) -> BindingResult<CategoryValues> {
let values =
values.bind_category_repeated(self.source.as_deref(), role, self.row_copies())?;
self.aligned(role, values.name(), values.len())?;
Ok(values)
}
pub fn kind(&self) -> PlotKind {
self.plot.kind()
}
#[must_use]
pub fn labels(mut self, labels: Labels) -> Self {
self.bindings.labels = labels.clone();
self.plot = self.plot.labels(labels);
self
}
pub fn source_rows(
mut self,
values: impl SourceRowsInput,
) -> std::result::Result<Self, AdapterError>
where
K: kind::SourceRows,
{
self.cell_shape(&values, "source rows")?;
let values = values.bind_source_rows_repeated(
self.source.as_deref(),
"source rows",
self.row_copies(),
)?;
self.aligned("source rows", "source rows", values.len())?;
self.plot = self.plot.source_rows(values);
Ok(self)
}
#[must_use]
pub fn facet(mut self, facet: FacetSpec) -> Self
where
K: kind::Facet,
{
self.bindings.facet = Some(facet.clone());
self.plot = self.plot.facet(facet);
self
}
pub fn facet_row(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
where
K: kind::Facet,
{
let values = self.category_rows(values, "facet row")?;
Ok(self.facet(FacetSpec::row(values)))
}
pub fn facet_column(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
where
K: kind::Facet,
{
let values = self.category_rows(values, "facet column")?;
Ok(self.facet(FacetSpec::column(values)))
}
pub fn facet_grid(
self,
row: impl CategoryInput,
column: impl CategoryInput,
) -> std::result::Result<Self, AdapterError>
where
K: kind::Facet,
{
let row = self.category_rows(row, "facet row")?;
let column = self.category_rows(column, "facet column")?;
Ok(self.facet(FacetSpec::grid(row, column)?))
}
pub fn facet_wrap(
self,
values: impl CategoryInput,
columns: usize,
) -> std::result::Result<Self, AdapterError>
where
K: kind::Facet,
{
let values = self.category_rows(values, "facet wrap")?;
Ok(self.facet(FacetSpec::wrap(values, columns)?))
}
pub fn facet_scales(self, scales: FacetScales) -> std::result::Result<Self, AdapterError>
where
K: kind::Facet,
{
let facet = self
.bindings
.facet
.clone()
.ok_or_else(|| binding("facet scales", "select a facet first"))?;
Ok(self.facet(facet.scales(scales)))
}
}
impl<K: kind::Marker> PlotAdapter<'static, K> {
#[must_use]
pub fn from_parts(plot: Plot<K>, metadata: BindingMetadata<K>) -> Self {
Self {
plot,
source: None,
bindings: metadata,
}
}
pub fn from_parts_with_data<'source>(
plot: Plot<K>,
metadata: BindingMetadata<K>,
source: impl ArraySource + 'source,
) -> std::result::Result<PlotAdapter<'source, K>, AdapterError> {
Ok(PlotAdapter {
plot,
source: context(source)?,
bindings: metadata,
})
}
}
macro_rules! category_binding {
($name:ident,$cap:ident) => {
impl<K:kind::$cap> PlotAdapter<'_,K> {
#[doc = concat!("Bind row-scoped native ",stringify!($name)," from a column or categorical vector.")]
pub fn $name(mut self,values:impl CategoryInput) -> std::result::Result<Self,AdapterError> {
let values=self.category_rows(values,stringify!($name))?; self.plot=self.plot.$name(values); Ok(self)
}
}
};
}
category_binding!(hue, Hue);
category_binding!(group, Group);
category_binding!(series, Series);
impl<K: kind::ExactFamily> PlotAdapter<'_, K> {
pub fn erase(self) -> Plot<kind::Any> {
self.plot.erase()
}
}
impl<K: kind::Marker> From<PlotAdapter<'_, K>> for Plot<K> {
fn from(adapter: PlotAdapter<'_, K>) -> Self {
adapter.plot
}
}