lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Actual independent diagonal density domains, keyed by the original variables.

use crate::{
    builder::PlotDescription,
    data::{ComponentPathPart, DataRole, GroupKey, PlotData, SourceMembers},
    elements::ElementRef,
    layout::{PanelPath, PanelStep},
    operation::OperationOptions,
    plots::{
        density::result::{DensityDisplay, DensityValues},
        DensityResult,
    },
    Result,
};

impl super::PreparedMatrixAxes {
    pub(crate) fn scientific_results(
        &self,
        chart: &PlotDescription,
        owner: &ElementRef,
        column: usize,
    ) -> Result<Vec<DensityResult>> {
        diagonal_results(
            chart,
            owner,
            &self.groups,
            column,
            column,
            &self.diagonals[column],
        )
    }
}

fn diagonal_results(
    chart: &PlotDescription,
    owner: &ElementRef,
    groups: &[super::HueGroup],
    column: usize,
    sample_column: usize,
    density: &super::MatrixDensity,
) -> Result<Vec<DensityResult>> {
    let variables = chart.matrix_variables().expect("actual matrix variables");
    let variable = variables.get_at(column).expect("actual diagonal variable");
    let originals = chart.primary_layer_data(&owner.declaration());
    let inputs = crate::data::select_value(&originals, DataRole::Variables.into())?;
    let [domain] = inputs.info().domains() else {
        return Err(crate::Error::Render(
            "matrix variables have no observation domain".into(),
        ));
    };
    let path = [
        ComponentPathPart::Field("variables".into()),
        ComponentPathPart::Key(variable.key.clone()),
        ComponentPathPart::Field("values".into()),
    ];
    let component = domain
        .components()
        .iter()
        .find(|component| component.path() == path)
        .expect("actual variable source");
    crate::data::source::collect_source(groups.iter().zip(&density.curves).map(|(group, curve)| {
        let members = SourceMembers::from_component_slots(
            domain,
            component,
            group.alphas.iter().map(|alpha| alpha.slot),
        )?;
        let display = crate::data::source::collect_source(curve.weighted_values().map(Ok))?;
        DensityResult::from_curve(
            DensityValues {
                name: variable.values.name(),
                grid: &density.positions,
                densities: &curve.values,
                bandwidth: group.bandwidths[sample_column],
                denominator: group.alphas.len(),
                display: Some(DensityDisplay {
                    values: &display,
                    divisor: None,
                    weight: Some(curve.weight),
                    common_count: Some(density.count),
                }),
            },
            chart,
            owner,
            &group.identity,
            &members,
        )
    }))
}

fn column_index(chart: &PlotDescription, panel: &PanelPath) -> Result<usize> {
    let [PanelStep::Matrix(x, y)] = panel.steps() else {
        return Err(crate::Error::Data(
            "select an actual Matrix diagonal variable".into(),
        ));
    };
    if x != y {
        return Err(crate::Error::Data(
            "an off-diagonal Matrix scatter region has no density result".into(),
        ));
    }
    let variables = chart.matrix_variables().expect("actual matrix variables");
    variables.get(x)?;
    Ok(variables
        .variables()
        .iter()
        .position(|variable| &variable.key == x)
        .expect("validated variable"))
}

fn prepare_result(
    chart: &PlotDescription,
    data: PlotData<'_, '_>,
    owner: &ElementRef,
    column: usize,
    selected: Option<&GroupKey>,
) -> Result<Vec<DensityResult>> {
    let variables = chart.matrix_variables().expect("actual matrix variables");
    let name = variables
        .get_at(column)
        .expect("actual diagonal variable")
        .values
        .raw_name();
    let (groups, _) = super::build_groups(chart, &[name], data, None)?;
    let range =
        super::matrix_support_range(&groups, 0, name, chart.group_name(), chart.hue_name())?;
    let count = groups.iter().map(|group| group.alphas.len()).sum();
    let groups = if let Some(selected) = selected {
        let mut retained = Vec::new();
        for group in groups {
            if crate::data::group_key::CollectiveKeys::new(chart, &group.identity)?
                .key()
                .as_ref()
                == Some(selected)
            {
                crate::data::source::reserve_source(&mut retained, 1)?;
                retained.push(group);
            }
        }
        retained
    } else {
        groups
    };
    if groups.is_empty() {
        return Ok(Vec::new());
    }
    let (density, _) = super::prepare_density(chart, &groups, 0, name, range, count)?;
    diagonal_results(chart, owner, &groups, column, 0, &density)
}

impl crate::Plot<crate::kind::Matrix> {
    /// Prepare the actual selected diagonal density without fonts or layout.
    pub fn stat_result_in(&self, panel: &PanelPath) -> Result<DensityResult> {
        self.stat_result_in_with_operation(panel, &OperationOptions::default())
    }

    /// Prepare the diagonal density with explicit per-call operation limits.
    pub fn stat_result_in_with_operation(
        &self,
        panel: &PanelPath,
        options: &OperationOptions,
    ) -> Result<DensityResult> {
        self.stat_result_selected(panel, None, options)
    }

    /// Prepare the selected diagonal for an explicit original group.
    pub fn stat_result_group(&self, panel: &PanelPath, group: &GroupKey) -> Result<DensityResult> {
        self.stat_result_group_with_operation(panel, group, &OperationOptions::default())
    }

    /// Prepare the selected diagonal group with explicit operation limits.
    pub fn stat_result_group_with_operation(
        &self,
        panel: &PanelPath,
        group: &GroupKey,
        options: &OperationOptions,
    ) -> Result<DensityResult> {
        self.stat_result_selected(panel, Some(group), options)
    }

    fn stat_result_selected(
        &self,
        panel: &PanelPath,
        group: Option<&GroupKey>,
        options: &OperationOptions,
    ) -> Result<DensityResult> {
        let chart = self.description();
        let column = column_index(chart, panel)?;
        crate::orchestrator::science::with_scope(chart, panel, options, |data, owner| {
            DensityResult::select(prepare_result(chart, data, owner, column, group)?, group)
        })
    }
}

#[cfg(test)]
#[test]
fn independent_diagonal_estimates_only_the_requested_group_with_common_normalization() {
    use crate::stats::distribution::KDE_CALLS;
    use crate::stats::DensityField;
    use crate::{CategoryValues, NumericValues, Plot};

    let plot = Plot::matrix(vec![
        NumericValues::new("x", [0., 1., 2., 10., 12.]),
        NumericValues::new("y", [1., 3., 4., 5., 6.]),
    ])
    .group(CategoryValues::new("group", ["A", "A", "A", "B", "B"]).unwrap());
    let panel = PanelPath::root().matrix("x", "x");
    let group = GroupKey::single("B");
    KDE_CALLS.with(|count| count.set(0));
    let selected = plot.stat_result_group(&panel, &group).unwrap();
    assert_eq!(KDE_CALLS.with(std::cell::Cell::get), 1);
    let run = plot.render_with_results().unwrap();
    assert_eq!(KDE_CALLS.with(std::cell::Cell::get), 5);
    let result = run
        .results()
        .iter()
        .find(|entry| entry.panel() == &panel && entry.group() == Some(&group))
        .unwrap();
    let crate::stats::ScientificResult::Density(result) = result.value() else {
        panic!("actual diagonal")
    };
    let crate::data::DataPayload::Numeric(selected_values) =
        selected.fields().values(DensityField::Density).unwrap()
    else {
        panic!("numeric density")
    };
    let crate::data::DataPayload::Numeric(actual_values) =
        result.fields().values(DensityField::Density).unwrap()
    else {
        panic!("numeric density")
    };
    assert_eq!(selected_values, actual_values);
    assert_eq!(selected.common_norm_count(), result.common_norm_count());
}