lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! The four semantic total-eligibility sets, resolved before fonts. Feedback
//! selects an already prepared result or recorded precision refusal.

use super::PreparedWaterfall;
use crate::numeric::set::{FormattedSet, NumericPresentation};
use crate::orchestrator::registration::DisplayExtent;
use crate::{Error, Result};

#[derive(Debug)]
pub(super) struct PreparedTotals {
    pub(super) totals: [(f64, Option<crate::Text>); 2],
    pub(super) numeric: std::sync::Arc<NumericPresentation>,
}

#[derive(Debug)]
pub(super) enum TotalVariant {
    Ready(PreparedTotals),
    Collision,
}

impl PreparedWaterfall {
    pub(crate) fn total_explanation(
        &self,
        projection: &crate::layout::Projection,
    ) -> Result<Option<&crate::Text>> {
        Ok(self
            .selected_totals(projection)?
            .numeric
            .set
            .explanation
            .as_ref())
    }

    pub(crate) fn total_explanations(&self) -> impl Iterator<Item = &crate::Text> {
        self.total_variants
            .iter()
            .flatten()
            .filter_map(|variant| match variant {
                TotalVariant::Ready(prepared) => prepared.numeric.set.explanation.as_ref(),
                TotalVariant::Collision => None,
            })
    }
    #[expect(
        clippy::needless_pass_by_value,
        reason = "one preparation pass consumes its short-lived numeric, axis and format inputs"
    )]
    pub(crate) fn prepare_totals(
        &mut self,
        input: super::WaterfallTotalsPrepare<'_>,
        can_expand: bool,
    ) -> Result<()> {
        let axes = input.axes;
        let x = axes[0].extent()?.pair();
        let y = axes[1].extent()?.pair();
        let projection = crate::layout::Projection::new(x, y, (0.0, 1.0, 0.0, 1.0));
        let initial = self.eligibility(&projection)?;
        let row_position = self.source_y()?;
        let y_visible = row_position >= y.0 && row_position <= y.1;
        for mask in 0..4_u8 {
            if mask != initial && !(can_expand && y_visible && (mask | initial) == mask) {
                continue;
            }
            if self.total_variants[usize::from(mask)].is_none() {
                self.total_variants[usize::from(mask)] = Some(self.prepare_variant(mask, &input)?);
            }
        }
        self.selected_totals(&projection)?;
        Ok(())
    }

    fn source_y(&self) -> Result<f64> {
        Ok(f64::from(u32::try_from(self.spans.len()).map_err(
            |_| Error::Render("Waterfall category count exceeds spatial range".into()),
        )?))
    }

    fn eligibility(&self, projection: &crate::layout::Projection) -> Result<u8> {
        let row_position = self.source_y()?;
        Ok(self
            .total_candidates
            .iter()
            .enumerate()
            .fold(0, |mask, (index, (value, _))| {
                mask | if projection.contains_data(*value, row_position) {
                    1 << index
                } else {
                    0
                }
            }))
    }

    pub(super) fn selected_totals(
        &self,
        projection: &crate::layout::Projection,
    ) -> Result<&PreparedTotals> {
        match self.total_variants[usize::from(self.eligibility(projection)?)].as_ref() {
            Some(TotalVariant::Ready(prepared)) => Ok(prepared),
            Some(TotalVariant::Collision) => Err(Error::Data(
                "Waterfall total labels are not unique at configured precision".into(),
            )),
            None => Err(Error::Render(
                "Waterfall total eligibility was not prepared before fonts".into(),
            )),
        }
    }

    fn prepare_variant(
        &self,
        mask: u8,
        input: &super::WaterfallTotalsPrepare<'_>,
    ) -> Result<TotalVariant> {
        let axes = input.axes;
        let mut members = [0.0; 2];
        let mut count = 0;
        for (index, (value, _)) in self.total_candidates.iter().enumerate() {
            if mask & (1 << index) != 0 {
                members[count] = *value;
                count += 1;
            }
        }
        let members = &members[..count];
        let set = if let Some(format) = input.format {
            let values = crate::numeric::source::collect_values(
                count,
                self.total_candidates
                    .iter()
                    .enumerate()
                    .filter(|(index, _)| mask & (1 << index) != 0)
                    .map(|(index, (value, _))| {
                        Ok(crate::numeric::context::ContextValue {
                            operand: crate::numeric::operand::Operand::number(*value, false),
                            identity: if index == 0 {
                                crate::numeric::context::Identity::Base
                            } else {
                                crate::numeric::context::Identity::Terminal
                            },
                        })
                    }),
            )?;
            let range = axes[0].extent()?.pair();
            let domain = crate::numeric::context::DomainInfo::axis(
                range,
                crate::coordinates::AxisScale::Linear,
                axes[0].provenance(),
                Some(range),
            );
            let mut info = input.numeric.context(
                crate::formatting::NumericRole::WaterfallTotals,
                crate::formatting::NumericPurpose::ActualSet,
                values,
                Some(domain),
            )?;
            let [x, y] = axes.map(|axis| axis.extent().map(DisplayExtent::pair));
            info.window = Some([x?, y?].map(|(a, b)| (a.to_bits(), b.to_bits())));
            let Some(set) = format.materialize(input.numeric.operation, info, false)? else {
                return Ok(TotalVariant::Collision);
            };
            set
        } else {
            FormattedSet {
                members: crate::data::source::collect_source(
                    members
                        .iter()
                        .map(|value| Ok(crate::numeric::operand::Operand::number(*value, false))),
                )?,
                labels: crate::data::source::collect_source(members.iter().map(|value| {
                    crate::numeric::profiles::BuiltinProfile::WaterfallTotal.format(*value)
                }))?,
                precision: 3,
                ..FormattedSet::default()
            }
        };
        let mut labels = set.labels.iter();
        let mut totals = self
            .total_candidates
            .each_ref()
            .map(|(value, _)| (*value, None));
        for (index, ((_, name), (_, source))) in
            self.total_candidates.iter().zip(&mut totals).enumerate()
        {
            if mask & (1 << index) == 0 {
                continue;
            }
            let number = labels
                .next()
                .ok_or_else(|| Error::Render("Waterfall numeric occurrence missing".into()))?;
            let mut label = String::new();
            let length = name
                .as_str()
                .len()
                .checked_add(1)
                .and_then(|length| length.checked_add(number.len()))
                .ok_or_else(|| Error::Render("Waterfall total source length overflow".into()))?;
            crate::data::source::reserve_source_string(&mut label, length)?;
            label.push_str(name.as_str());
            label.push(' ');
            label.push_str(number);
            *source = Some(name.try_copy_with_source(label)?);
        }
        Ok(TotalVariant::Ready(PreparedTotals {
            totals,
            numeric: crate::data::source::source_arc(NumericPresentation {
                format: input.format.cloned(),
                set,
            })?,
        }))
    }

    /// Every actual successful source reachable under admitted window feedback.
    pub(crate) fn total_font_sources<'a>(
        &'a self,
        layout: Option<&'a crate::text::TextLayout>,
    ) -> impl Iterator<Item = &'a crate::Text> {
        self.total_variants
            .iter()
            .flatten()
            .filter_map(|variant| match variant {
                TotalVariant::Ready(prepared) => Some(prepared),
                TotalVariant::Collision => None,
            })
            .flat_map(move |prepared| {
                prepared
                    .totals
                    .iter()
                    .enumerate()
                    .filter_map(move |(index, (_, source))| {
                        let text = source.as_ref()?;
                        let mut eligible = [0; 2];
                        let mut count = 0;
                        for (index, (_, source)) in prepared.totals.iter().enumerate() {
                            if source.is_some() {
                                eligible[count] = index;
                                count += 1;
                            }
                        }
                        let request = text.get_layout().or(layout);
                        request
                            .and_then(|request| request.instructions().visibility.as_ref())
                            .is_none_or(|policy| policy.includes(index, &eligible[..count]))
                            .then_some(text)
                    })
            })
            .chain(self.total_explanations())
    }
}