lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Truthful explanation operands from the owned declaration and actual consumers.

use super::{collect_input, AlphaMapping, AlphaMembers, AlphaValues, ResolvedAlpha};
use crate::data::source::{collect_source, reserve_source};
use crate::data::{
    category::{shared_text, RawField},
    KeyValues, RawKey,
};
use crate::{Error, Result};

/// Exact original sample or category, or the original half-open threshold interval.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AlphaExampleKey {
    Sample(RawKey),
    Category(RawKey),
    Interval {
        lower: Option<RawKey>,
        upper: Option<RawKey>,
    },
}

pub(crate) struct AlphaExample<'a> {
    pub(crate) ordinal: usize,
    pub(crate) key: AlphaExampleKey,
    pub(crate) label: &'a str,
    pub(crate) alpha: f64,
}

impl AlphaValues {
    pub(crate) fn same_declaration(&self, other: &Self) -> bool {
        self.original_field() == other.original_field() && self.declaration == other.declaration
    }

    fn original_field(&self) -> RawKey {
        if let Some(key) = self
            .get_numeric_source()
            .and_then(crate::NumericValues::field_key)
        {
            key.clone()
        } else if let Some(KeyValues::Strings(values)) = self.get_category_source() {
            values.original_field()
        } else {
            RawKey::from(self.raw_name())
        }
    }

    pub(crate) fn guide_field(&self) -> Result<RawField> {
        Ok(RawField::from_key(
            shared_text(self.raw_name())?,
            self.original_field(),
        ))
    }

    pub(crate) fn guide_examples(
        &self,
        consumed: impl IntoIterator<Item = ResolvedAlpha>,
    ) -> Result<Vec<AlphaExample<'_>>> {
        let mut members = Vec::new();
        let count = match self.get_mapping() {
            AlphaMapping::Undeclared => return Ok(Vec::new()),
            AlphaMapping::Linear { .. }
            | AlphaMapping::Log10 { .. }
            | AlphaMapping::Continuous { .. } => self.declaration.labels.len(),
            AlphaMapping::Categorical(table) => table.len(),
            AlphaMapping::Threshold { alphas, .. } => alphas.len(),
        };
        reserve_source(&mut members, count)?;
        members.resize(count, false);
        let mut present = false;
        for member in consumed {
            let index = member
                .index
                .ok_or_else(|| Error::Render("fixed alpha has no declaration member".into()))?;
            if self.get(index) != Some(member.alpha) {
                return Err(Error::Render(
                    "retained alpha member differs from its complete input".into(),
                ));
            }
            present = true;
            let ordinal = match &self.data.members {
                AlphaMembers::Categorical(_, values) | AlphaMembers::Threshold(_, values) => {
                    Some(values[index])
                }
                AlphaMembers::Numeric(_) | AlphaMembers::Undeclared(_) => None,
            };
            if let Some(ordinal) = ordinal {
                *members.get_mut(ordinal).ok_or_else(|| {
                    Error::Render("alpha declaration member is outside its table".into())
                })? = true;
            }
        }
        if !present {
            return Ok(Vec::new());
        }
        match self.get_mapping() {
            AlphaMapping::Undeclared => unreachable!("undeclared alpha returned above"),
            AlphaMapping::Linear { .. }
            | AlphaMapping::Log10 { .. }
            | AlphaMapping::Continuous { .. } => collect_source(
                self.declaration
                    .labels
                    .iter()
                    .zip(self.examples())
                    .enumerate()
                    .map(|(ordinal, (label, &(raw, alpha)))| {
                        Ok(AlphaExample {
                            ordinal,
                            key: AlphaExampleKey::Sample(RawKey::Float(raw)),
                            label,
                            alpha,
                        })
                    }),
            ),
            AlphaMapping::Categorical(table) => collect_input(
                table
                    .iter()
                    .enumerate()
                    .filter(|(ordinal, _)| members[*ordinal])
                    .map(|(ordinal, (key, alpha))| {
                        let RawKey::String(label) = key else {
                            unreachable!("current categorical alpha maps actual strings")
                        };
                        AlphaExample {
                            ordinal,
                            key: AlphaExampleKey::Category(key.clone()),
                            label,
                            alpha: *alpha,
                        }
                    }),
            ),
            AlphaMapping::Threshold { boundaries, alphas } => collect_input(
                self.declaration
                    .labels
                    .iter()
                    .zip(alphas)
                    .enumerate()
                    .filter(|(ordinal, _)| members[*ordinal])
                    .map(|(ordinal, (label, &alpha))| AlphaExample {
                        ordinal,
                        key: AlphaExampleKey::Interval {
                            lower: ordinal
                                .checked_sub(1)
                                .and_then(|index| boundaries.get(index))
                                .copied()
                                .map(RawKey::Float),
                            upper: boundaries.get(ordinal).copied().map(RawKey::Float),
                        },
                        label,
                        alpha,
                    }),
            ),
        }
    }
}