lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Scientific values of an actual Gaussian density curve.

use std::sync::Arc;

use crate::{
    data::{
        DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload, DataRole, ExactInteger,
        GroupKey, MemberAddress, SourceMembers,
    },
    elements::ElementRef,
    errors::{Diagnostic, DiagnosticKind, DiagnosticReference, ErrorContext, OperationPhase},
    stats::{results::numeric_column, DensityField, Kernel, StatResult},
    Error, Result,
};

/// The actual evaluated density of one scientific group.
#[derive(Debug, Clone)]
pub struct DensityResult(Arc<DensityData>);

#[derive(Debug)]
struct DensityData {
    fields: StatResult,
    bandwidth: Option<f64>,
    denominator: Option<ExactInteger>,
    support: (f64, f64),
    display: Option<DensityDisplayData>,
}

#[derive(Debug)]
struct DensityDisplayData {
    values: crate::NumericValues,
    divisor: Option<f64>,
    weight: Option<f64>,
    common_count: Option<ExactInteger>,
    domain: DataDomainInfo,
}

impl DensityResult {
    /// The same actual evaluation fields consumed by scientific readback.
    pub fn fields(&self) -> &StatResult {
        &self.0.fields
    }
    /// Bandwidth used to evaluate the curve, absent for supplied values.
    pub fn bandwidth(&self) -> Option<f64> {
        self.0.bandwidth
    }
    /// Actual normalizing observation count, when known.
    pub fn denominator(&self) -> Option<&ExactInteger> {
        self.0.denominator.as_ref()
    }
    /// The actual Gaussian kernel.
    pub const fn kernel(&self) -> Kernel {
        Kernel::Gaussian
    }
    /// The first and last evaluated coordinates, independent of clipping.
    pub fn support(&self) -> (f64, f64) {
        self.0.support
    }
    /// Actual display density operands before projection or theme sizing.
    /// Closure at zero and common-normalization weighting leave the raw density unchanged.
    pub fn get_display_density(&self) -> Option<&crate::NumericValues> {
        self.0.display.as_ref().map(|display| &display.values)
    }
    /// Actual shared maximum used as the marginal strip divisor, if applicable.
    pub fn display_divisor(&self) -> Option<f64> {
        self.0.display.as_ref().and_then(|display| display.divisor)
    }
    /// Actual group fraction used by Matrix common normalization, if applicable.
    pub fn group_weight(&self) -> Option<f64> {
        self.0.display.as_ref().and_then(|display| display.weight)
    }
    /// Exact total observation count used by common normalization, if applicable.
    pub fn common_norm_count(&self) -> Option<&ExactInteger> {
        self.0
            .display
            .as_ref()
            .and_then(|display| display.common_count.as_ref())
    }
    /// Actual independent scientific result domains.
    pub fn domains(&self) -> &[DataDomainInfo] {
        self.0.display.as_ref().map_or_else(
            || self.0.fields.domains(),
            |display| std::slice::from_ref(&display.domain),
        )
    }
    /// Original members of an evaluation node.
    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
        self.0.fields.result_domains().members(&address.into())
    }
    /// Original members in the actual result domain.
    pub fn members_in(
        &self,
        domain: &DataDomainRef,
        address: impl Into<MemberAddress>,
    ) -> Result<Option<SourceMembers>> {
        self.0.fields.members_in(domain, address)
    }

    pub(crate) fn from_curve(
        values: DensityValues<'_>,
        chart: &crate::builder::PlotDescription,
        owner: &ElementRef,
        identity: &crate::data::CollectivePair,
        members: &SourceMembers,
    ) -> Result<Self> {
        let keys = crate::data::group_key::CollectiveKeys::new(chart, identity)?;
        let group = keys.key();
        let x = numeric_column(values.name, values.grid.iter().copied())?;
        let density = numeric_column("density", values.densities.iter().copied())?;
        let mut columns = vec![
            (DensityField::X.into(), DataPayload::Numeric(x)),
            (DensityField::Density.into(), DataPayload::Numeric(density)),
        ];
        for (field, key) in [
            (DensityField::Group, keys.group.as_ref()),
            (DensityField::Hue, keys.hue.as_ref()),
        ] {
            if let Some((name, key)) = key {
                crate::data::source::reserve_source(&mut columns, 1)?;
                columns.push((
                    field.into(),
                    crate::data::group_key::key_column(
                        name,
                        std::iter::repeat_n(key.clone(), values.grid.len()),
                    )?,
                ));
            }
        }
        let relations = crate::data::source::collect_source(
            (0..values.grid.len()).map(|_| Ok(Some(members.clone()))),
        )?;
        let fields = StatResult::single_domain(owner, group.as_ref(), columns, relations)?;
        let display = values
            .display
            .map(|display| {
                let values = numeric_column("display_density", display.values.iter().copied())?;
                let domain =
                    fields.domains()[0]
                        .clone()
                        .with_component(DataComponentInfo::scientific(
                            "get_display_density",
                            &DataPayload::Numeric(values.clone()),
                        )?)?;
                Ok::<_, Error>(DensityDisplayData {
                    values,
                    divisor: display.divisor,
                    weight: display.weight,
                    common_count: display.common_count.map(ExactInteger::from),
                    domain,
                })
            })
            .transpose()?;
        Ok(Self(crate::data::source::source_arc(DensityData {
            fields,
            display,
            bandwidth: Some(values.bandwidth),
            denominator: Some(values.denominator.into()),
            support: (
                *values.grid.first().expect("actual evaluated nodes"),
                *values.grid.last().expect("actual evaluated nodes"),
            ),
        })?))
    }

    pub(crate) fn select(results: Vec<Self>, group: Option<&GroupKey>) -> Result<Self> {
        let matches = crate::data::source::collect_source(
            results
                .into_iter()
                .filter(|result| {
                    group.is_none() || result.domains()[0].reference().group_key() == group
                })
                .map(Ok),
        )?;
        match matches.as_slice() {
            [result] => Ok(result.clone()),
            [] => Err(Error::Data(
                Diagnostic::new(
                    DiagnosticKind::UnknownKey {
                        key: group.map(|group| crate::data::RawKey::Tuple(group.keys().to_vec())),
                    },
                    "density has no result for the selected group",
                )
                .with_context(ErrorContext::new().with_operation(OperationPhase::Prepare)),
            )),
            _ => Err(Error::Data(
                Diagnostic::new(
                    DiagnosticKind::Ambiguous {
                        candidates: matches
                            .iter()
                            .map(|result| {
                                DiagnosticReference::Domain(result.domains()[0].reference().clone())
                            })
                            .collect(),
                    },
                    "density has several scientific groups; select an actual group",
                )
                .with_context(ErrorContext::new().with_operation(OperationPhase::Prepare)),
            )),
        }
    }
}

#[derive(Clone, Copy)]
pub(crate) struct DensityValues<'a> {
    pub(crate) name: &'a str,
    pub(crate) grid: &'a [f64],
    pub(crate) densities: &'a [f64],
    pub(crate) bandwidth: f64,
    pub(crate) denominator: usize,
    pub(crate) display: Option<DensityDisplay<'a>>,
}

#[derive(Clone, Copy)]
pub(crate) struct DensityDisplay<'a> {
    pub(crate) values: &'a [f64],
    pub(crate) divisor: Option<f64>,
    pub(crate) weight: Option<f64>,
    pub(crate) common_count: Option<usize>,
}

impl super::PreparedDensity {
    pub(crate) fn scientific_results(
        &self,
        chart: &crate::builder::PlotDescription,
        owner: &ElementRef,
    ) -> Result<Vec<DensityResult>> {
        let originals = chart.primary_layer_data(&owner.declaration());
        let samples = crate::data::select_value(&originals, DataRole::Value.into())?;
        let name = samples.info().name().unwrap_or("value");
        crate::data::source::collect_source(self.curves.iter().map(|curve| {
            let capture = curve.capture.as_ref().expect("actual result capture");
            let members = SourceMembers::from_slots(&[&samples], capture.slots.iter().copied())?;
            DensityResult::from_curve(
                DensityValues {
                    name,
                    grid: &curve.grid,
                    densities: &curve.densities,
                    bandwidth: capture.bandwidth,
                    denominator: capture.slots.len(),
                    display: None,
                },
                chart,
                owner,
                &curve.identity,
                &members,
            )
        }))
    }
}

impl crate::Plot<crate::kind::Density> {
    /// Prepare the unique density group without fonts or layout.
    pub fn stat_result(&self) -> Result<DensityResult> {
        self.stat_result_with_operation(&crate::operation::OperationOptions::default())
    }
    /// Prepare with explicit per-call resource options.
    pub fn stat_result_with_operation(
        &self,
        options: &crate::operation::OperationOptions,
    ) -> Result<DensityResult> {
        self.stat_result_in_with_operation(&crate::layout::PanelPath::root(), options)
    }
    /// Prepare the unique group of an actual selected panel.
    pub fn stat_result_in(&self, panel: &crate::layout::PanelPath) -> Result<DensityResult> {
        self.stat_result_in_with_operation(panel, &crate::operation::OperationOptions::default())
    }
    /// Prepare the selected panel with operation options.
    pub fn stat_result_in_with_operation(
        &self,
        panel: &crate::layout::PanelPath,
        options: &crate::operation::OperationOptions,
    ) -> Result<DensityResult> {
        self.stat_result_selected(panel, None, options)
    }
    /// Prepare an explicit original group of the selected panel.
    pub fn stat_result_group(
        &self,
        panel: &crate::layout::PanelPath,
        group: &GroupKey,
    ) -> Result<DensityResult> {
        self.stat_result_group_with_operation(
            panel,
            group,
            &crate::operation::OperationOptions::default(),
        )
    }
    /// Prepare an explicit original group with per-call options.
    pub fn stat_result_group_with_operation(
        &self,
        panel: &crate::layout::PanelPath,
        group: &GroupKey,
        options: &crate::operation::OperationOptions,
    ) -> Result<DensityResult> {
        self.stat_result_selected(panel, Some(group), options)
    }

    fn stat_result_selected(
        &self,
        panel: &crate::layout::PanelPath,
        group: Option<&GroupKey>,
        options: &crate::operation::OperationOptions,
    ) -> Result<DensityResult> {
        let chart = self.description();
        crate::orchestrator::science::with_scope(chart, panel, options, |data, layer| {
            let parent = (!data.is_full_plot())
                .then(|| crate::data::observed_source_collectives(chart, "density facet channels"))
                .transpose()?;
            let prepared = super::PreparedDensity::new_selected(
                chart,
                data,
                parent.as_ref().map(|parent| parent.identities.as_slice()),
                group,
            )?;
            DensityResult::select(prepared.scientific_results(chart, layer)?, group)
        })
    }
}