lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Caller-computed columnar geometry accepted by distribution renderers.

use crate::{CategoryValues, Error, NumericValues};

mod histogram;
mod raincloud;
mod stats;

pub(crate) use histogram::{validate_kde, validate_rug_count};
pub use histogram::{HistogramBinsData, HistogramGeometry, HistogramRugData};
pub(crate) use raincloud::validate_raincloud_counts;

/// Complete supplied raincloud geometry in three independently aligned domains.
///
/// Summary row order determines group order. Density and point rows name their
/// summary group by raw category/hue strings and retain their relative order.
#[derive(Debug, Clone)]
pub struct RaincloudGeometry {
    pub(crate) data: std::sync::Arc<RaincloudData>,
    result: Option<std::sync::Arc<stats::RaincloudScience>>,
}

#[derive(Debug, Clone)]
pub(crate) struct RaincloudData {
    /// Scientific category dimension, also used for the inferred x-axis title.
    pub(crate) category_dimension: String,
    /// Scientific value dimension, also used for the inferred y-axis title.
    pub(crate) value_dimension: String,
    /// Scientific hue dimension; present together with all three hue columns.
    pub(crate) hue_dimension: Option<String>,
    /// One category per summary row.
    pub(crate) category: CategoryValues,
    /// One hue per summary row when hue is present.
    pub(crate) hue: Option<CategoryValues>,
    /// First quartiles aligned with summary categories.
    pub(crate) q1: NumericValues,
    /// Medians aligned with summary categories.
    pub(crate) median: NumericValues,
    /// Third quartiles aligned with summary categories.
    pub(crate) q3: NumericValues,
    /// Category keys for density rows.
    pub(crate) density_category: CategoryValues,
    /// Hue keys for density rows when hue is present.
    pub(crate) density_hue: Option<CategoryValues>,
    /// Density support coordinates, strictly increasing within each group.
    pub(crate) density_y: NumericValues,
    /// Density widths in the inclusive range `[0, 1]`.
    pub(crate) normalized_width: NumericValues,
    /// Category keys for raw-point rows.
    pub(crate) point_category: CategoryValues,
    /// Hue keys for raw-point rows when hue is present.
    pub(crate) point_hue: Option<CategoryValues>,
    /// Raw-point data-space coordinates.
    pub(crate) point_y: NumericValues,
    /// Raw-point strip coordinates in the inclusive range `[0, 1]`.
    pub(crate) normalized_strip: NumericValues,
}

impl PartialEq for RaincloudGeometry {
    fn eq(&self, other: &Self) -> bool {
        self.data.category_dimension == other.data.category_dimension
            && self.data.value_dimension == other.data.value_dimension
            && self.data.hue_dimension == other.data.hue_dimension
            && [
                (&self.data.category, &other.data.category),
                (&self.data.density_category, &other.data.density_category),
                (&self.data.point_category, &other.data.point_category),
            ]
            .into_iter()
            .all(|(left, right)| category_equal(left, right))
            && [
                (&self.data.hue, &other.data.hue),
                (&self.data.density_hue, &other.data.density_hue),
                (&self.data.point_hue, &other.data.point_hue),
            ]
            .into_iter()
            .all(|(left, right)| match (left, right) {
                (Some(left), Some(right)) => category_equal(left, right),
                (None, None) => true,
                _ => false,
            })
            && [
                (&self.data.q1, &other.data.q1),
                (&self.data.median, &other.data.median),
                (&self.data.q3, &other.data.q3),
                (&self.data.density_y, &other.data.density_y),
                (&self.data.normalized_width, &other.data.normalized_width),
                (&self.data.point_y, &other.data.point_y),
                (&self.data.normalized_strip, &other.data.normalized_strip),
            ]
            .into_iter()
            .all(|(left, right)| numeric_equal(left, right))
    }
}

pub(crate) fn numeric_equal(left: &NumericValues, right: &NumericValues) -> bool {
    left.name() == right.name()
        && left.len() == right.len()
        && (0..left.len()).all(|row| left.get(row) == right.get(row))
}

fn category_equal(left: &CategoryValues, right: &CategoryValues) -> bool {
    if left.original_name() != right.original_name() || left.len() != right.len() {
        return false;
    }
    let left = left.key_values();
    let right = right.key_values();
    (0..left.len()).all(|row| left.key_at(row) == right.key_at(row))
}

fn dimension(value: &str, role: &str) -> Result<(), Error> {
    if value.trim().is_empty() {
        Err(Error::Data(format!("{role} must be nonempty").into()))
    } else {
        Ok(())
    }
}

fn aligned(domain: &str, expected: usize, columns: &[(&str, usize)]) -> Result<(), Error> {
    for &(name, actual) in columns {
        if actual != expected {
            use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
            return Err(Error::Data(
                Diagnostic::new(
                    DiagnosticKind::ShapeMismatch {
                        expected: vec![expected],
                        actual: vec![actual],
                    },
                    format!("{domain} column {name:?} has {actual} rows; expected {expected}"),
                )
                .with_context(ErrorContext::new().with_operation(OperationPhase::Bind)),
            ));
        }
    }
    Ok(())
}

pub(crate) fn finite(values: &NumericValues, row: usize, role: &str) -> Result<f64, Error> {
    let value = values.get(row).flatten();
    value.filter(|value| value.is_finite()).ok_or_else(|| {
        use crate::{
            data::{MemberAddress, RawKey},
            errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
        };
        let binding = values
            .field_key()
            .cloned()
            .unwrap_or_else(|| RawKey::from(values.name()));
        Error::Data(
            Diagnostic::new(
                DiagnosticKind::InvalidValue {
                    value: value.map(RawKey::Float),
                    constraint: "present finite numeric value".to_owned(),
                },
                format!(
                    "{role} column {:?} requires a present finite value at row {row}",
                    values.name()
                ),
            )
            .with_context(
                ErrorContext::new()
                    .with_operation(OperationPhase::Prepare)
                    .with_binding(binding)
                    .with_member(MemberAddress::Slot(row)),
            ),
        )
    })
}

pub(crate) fn category_value<'a>(
    values: &'a CategoryValues,
    row: usize,
    role: &str,
) -> Result<&'a str, Error> {
    let value = values.get(row).flatten().ok_or_else(|| {
        Error::Data(
            format!(
                "{role} column {:?} has a missing key at row {row}",
                values.original_name()
            )
            .into(),
        )
    })?;
    dimension(value, role)?;
    Ok(value)
}

#[cfg(test)]
mod validation_tests;