lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
use super::{Plot, PlotDescription};
use crate::alpha::{
    AlphaEncoding, AlphaInputs, AlphaTarget, AlphaUnitKind, PreparedAlpha, ResolvedAlpha,
};
use crate::{data::RawKey, CategoryValues};

pub(crate) struct ScopedAlpha {
    prepared: PreparedAlpha,
    facets: Vec<(RawKey, RawKey)>,
}

fn raw_unit(values: &CategoryValues, level: &str) -> crate::Result<(RawKey, RawKey)> {
    let key = values.key_for_level(level).ok_or_else(|| {
        crate::Error::Render("actual alpha unit has no original category key".into())
    })?;
    Ok((values.original_field(), key))
}

impl ScopedAlpha {
    pub(crate) fn bin(&self, bounds: (f64, f64)) -> crate::Result<Option<ResolvedAlpha>> {
        self.prepared.bin(bounds, &self.facets)
    }

    pub(crate) fn keyed(&self, unit: &[(RawKey, RawKey)]) -> crate::Result<Option<ResolvedAlpha>> {
        if self.prepared.selector_fields().is_empty() {
            return self.prepared.keyed(&[]);
        }
        let count = unit
            .len()
            .checked_add(self.facets.len())
            .ok_or_else(|| crate::Error::Data("alpha actual unit key count overflow".into()))?;
        let mut keys = Vec::new();
        crate::data::source::reserve_source(&mut keys, count)?;
        keys.extend_from_slice(unit);
        keys.extend_from_slice(&self.facets);
        self.prepared.keyed(&keys)
    }

    pub(crate) fn collective(
        &self,
        chart: &PlotDescription,
        identity: &crate::data::CollectivePair,
    ) -> crate::Result<Option<ResolvedAlpha>> {
        if self.prepared.selector_fields().is_empty() {
            return self.prepared.keyed(&[]);
        }
        let group = chart
            .legend_group_values()
            .zip(identity.group.as_deref())
            .map(|(values, level)| raw_unit(values, level))
            .transpose()?;
        let hue = chart
            .legend_hue_values()
            .zip(identity.hue.as_deref())
            .map(|(values, level)| raw_unit(values, level))
            .transpose()?;
        match (group, hue) {
            (Some(group), Some(hue)) => self.keyed(&[group, hue]),
            (Some(group), None) => self.keyed(&[group]),
            (None, Some(hue)) => self.keyed(&[hue]),
            (None, None) => self.keyed(&[]),
        }
    }

    pub(crate) fn aggregate(
        &self,
        category: (&CategoryValues, &str),
        series: Option<(&CategoryValues, &str)>,
    ) -> crate::Result<Option<ResolvedAlpha>> {
        if self.prepared.selector_fields().is_empty() {
            return self.prepared.keyed(&[]);
        }
        let category = raw_unit(category.0, category.1)?;
        if let Some(series) = series {
            self.keyed(&[category, raw_unit(series.0, series.1)?])
        } else {
            self.keyed(&[category])
        }
    }
}

impl<K: crate::kind::Marker> Plot<K> {
    /// Replace point-fill alpha using original observations or explicit Single.
    ///
    /// Outlines and supplemental layers remain independently owned. Repeated
    /// calls replace the complete target; [`AlphaEncoding::theme`] resets it.
    /// Resolve normal RGB/role/exact paint first, then replace alpha, never multiply.
    /// Declared mappings add a common-guide section; fixed or undeclared coefficients do not.
    ///
    /// ```
    /// use lichtung_plot::{NumericValues, Plot, scales::{AlphaEncoding, AlphaValues}};
    /// let plot = Plot::scatter(NumericValues::new("x", [0.0, 1.0]),
    ///     NumericValues::new("y", [1.0, 0.0]))
    ///     .point_alpha(AlphaEncoding::observations(AlphaValues::linear(
    ///         NumericValues::new("confidence", [0.2, 0.8]), (0.0, 1.0), (0.0, 1.0),
    ///     )?))?;
    /// # let _ = plot;
    /// # Ok::<(), lichtung_plot::Error>(())
    /// ```
    ///
    /// ```compile_fail
    /// use lichtung_plot::{Plot, scales::AlphaEncoding};
    /// fn erased(plot: Plot) { let _ = plot.point_alpha(AlphaEncoding::theme()); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Density>) { let _ = plot.point_alpha(AlphaEncoding::theme()); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Heatmap>, alpha: AlphaEncoding) { let _ = plot.point_alpha(alpha); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Bar>, alpha: AlphaEncoding) { let _ = plot.point_alpha(alpha); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Waterfall>, alpha: AlphaEncoding) { let _ = plot.point_alpha(alpha); }
    /// ```
    pub fn point_alpha(
        self,
        alpha: impl TryInto<AlphaEncoding, Error: Into<crate::Error>>,
    ) -> crate::Result<Self>
    where
        K: crate::kind::PointAlpha,
    {
        Ok(self.with_alpha(AlphaTarget::Point, alpha.try_into().map_err(Into::into)?))
    }

    /// Replace admitted scientific-stroke alpha using explicit actual-unit values.
    ///
    /// Qq/Regression/optional Histogram curves use Single; estimates and Dumbbell
    /// use original records; paths/Density/Interaction use actual series; categorical
    /// summaries use category/positioned-series aggregates. Unlisted references,
    /// points, fills, outlines and supplemental layers retain their own paints.
    /// Absent optional components still validate binding kind/schema before fonts.
    ///
    /// ```compile_fail
    /// use lichtung_plot::{Plot, scales::AlphaEncoding};
    /// fn erased(plot: Plot) { let _ = plot.line_alpha(AlphaEncoding::theme()); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Scatter>) { let _ = plot.line_alpha(AlphaEncoding::theme()); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::StackedBar>, alpha: AlphaEncoding) { let _ = plot.line_alpha(alpha); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Marginal>, alpha: AlphaEncoding) { let _ = plot.line_alpha(alpha); }
    /// ```
    pub fn line_alpha(
        self,
        alpha: impl TryInto<AlphaEncoding, Error: Into<crate::Error>>,
    ) -> crate::Result<Self>
    where
        K: crate::kind::LineAlpha,
    {
        Ok(self.with_alpha(AlphaTarget::Line, alpha.try_into().map_err(Into::into)?))
    }

    /// Replace admitted scientific area/body/cell fill alpha, independently of outlines.
    ///
    /// Histogram uses exact bins; Heatmap/Waterfall use original records; Line and
    /// Density/native densities use actual series; categorical bodies use actual
    /// aggregates; Regression bands use Single. Zero preserves scientific members.
    /// Normal RGB/role/exact paint resolves before alpha replacement. Repeated calls
    /// replace only this complete target; [`AlphaEncoding::theme`] resets it.
    ///
    /// ```compile_fail
    /// use lichtung_plot::{Plot, scales::AlphaEncoding};
    /// fn erased(plot: Plot) { let _ = plot.fill_alpha(AlphaEncoding::theme()); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Trajectory>) { let _ = plot.fill_alpha(AlphaEncoding::theme()); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Scatter>, alpha: AlphaEncoding) { let _ = plot.fill_alpha(alpha); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Interaction>, alpha: AlphaEncoding) { let _ = plot.fill_alpha(alpha); }
    /// ```
    /// ```compile_fail
    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
    /// fn unsupported(plot: Plot<kind::Beeswarm>, alpha: AlphaEncoding) { let _ = plot.fill_alpha(alpha); }
    /// ```
    pub fn fill_alpha(
        self,
        alpha: impl TryInto<AlphaEncoding, Error: Into<crate::Error>>,
    ) -> crate::Result<Self>
    where
        K: crate::kind::FillAlpha,
    {
        Ok(self.with_alpha(AlphaTarget::Fill, alpha.try_into().map_err(Into::into)?))
    }

    pub(crate) fn with_alpha(mut self, target: AlphaTarget, encoding: AlphaEncoding) -> Self {
        self.description.payload_mut().alpha.set(target, encoding);
        let role = match target {
            AlphaTarget::Point => crate::data::DataRole::PointAlpha,
            AlphaTarget::Line => crate::data::DataRole::LineAlpha,
            AlphaTarget::Fill => crate::data::DataRole::FillAlpha,
        };
        self.description.renew_role(role);
        self.description
            .renew_domain(crate::data::DomainSlot::Alpha(role));
        self
    }

    /// Inspect the authored point-fill encoding. An absent target has Theme
    /// as its default declaration and no bound values.
    #[must_use]
    pub fn get_point_alpha(&self) -> &AlphaEncoding {
        self.description.alpha_inputs().get(AlphaTarget::Point)
    }

    /// Inspect the authored scientific-stroke encoding.
    #[must_use]
    pub fn get_line_alpha(&self) -> &AlphaEncoding {
        self.description.alpha_inputs().get(AlphaTarget::Line)
    }

    /// Inspect the authored area/body/cell fill encoding.
    #[must_use]
    pub fn get_fill_alpha(&self) -> &AlphaEncoding {
        self.description.alpha_inputs().get(AlphaTarget::Fill)
    }
}

impl PlotDescription {
    pub(crate) fn alpha_inputs(&self) -> &AlphaInputs {
        &self.payload.alpha
    }

    pub(crate) fn prepare_alpha(
        &self,
        target: AlphaTarget,
        unit: AlphaUnitKind,
        required_fields: &[RawKey],
    ) -> Result<PreparedAlpha, crate::Error> {
        let mut facets = Vec::new();
        if let Some(facet) = &self.payload.facet {
            crate::data::source::reserve_source(&mut facets, 3)?;
            facets.extend(facet.values().map(CategoryValues::original_field));
        }
        let original_len = if let Some(geometry) = self.raincloud_geometry_input() {
            geometry.data.point_y.len()
        } else {
            self.row_count()
        };
        self.payload
            .alpha
            .get(target)
            .prepare(unit, original_len, required_fields, &facets)
    }

    pub(crate) fn prepare_scoped_alpha(
        &self,
        target: AlphaTarget,
        unit: AlphaUnitKind,
        required_fields: &[RawKey],
        facet: Option<crate::orchestrator::registration::FacetSelector<'_, '_>>,
    ) -> crate::Result<ScopedAlpha> {
        let prepared = self.prepare_alpha(target, unit, required_fields)?;
        let mut facets = Vec::new();
        if let Some(facet) = facet {
            for (_, values, raw) in facet.fields() {
                if !prepared
                    .selector_fields()
                    .contains(&values.original_field())
                {
                    continue;
                }
                crate::data::source::reserve_source(&mut facets, 1)?;
                facets.push(raw_unit(values, raw)?);
            }
        }
        Ok(ScopedAlpha { prepared, facets })
    }

    pub(crate) fn prepare_collective_alpha(
        &self,
        target: AlphaTarget,
        unit: AlphaUnitKind,
        include_hue: bool,
        facet: Option<crate::orchestrator::registration::FacetSelector<'_, '_>>,
    ) -> crate::Result<ScopedAlpha> {
        let mut fields = Vec::new();
        crate::data::source::reserve_source(&mut fields, 2)?;
        fields.extend(
            self.legend_group_values()
                .map(CategoryValues::original_field),
        );
        if include_hue {
            fields.extend(self.legend_hue_values().map(CategoryValues::original_field));
        }
        self.prepare_scoped_alpha(target, unit, &fields, facet)
    }
}