lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Typed scientific fields/categories, literal domains and supplemental layers.
//! Display aliases never participate in raw identity or domain coordination.

use std::sync::Arc;

use crate::data::category::{shared_text, RawCategory, RawField};
use crate::{stats::RegressionBand, Error, Result};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RawLayerLabel(Arc<str>);

impl RawLayerLabel {
    pub(super) fn new(value: &str) -> Result<Self> {
        shared_text(value).map(Self)
    }

    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PrimaryTitleIdentity {
    Field(RawField),
    Pair { group: RawField, hue: RawField },
    Series,
    BarSign,
}

impl PrimaryTitleIdentity {
    pub(crate) fn resolved_text(&self, labels: &crate::formatting::Labels) -> Result<String> {
        match self {
            Self::Field(field) => labels.resolve(field.as_str()),
            Self::Pair { group, hue } => join(
                labels.resolve(group.as_str())?,
                " × ",
                &labels.resolve(hue.as_str())?,
            ),
            Self::Series => crate::data::source::copy_source_string("series"),
            Self::BarSign => crate::data::source::copy_source_string("Change"),
        }
    }
}

/// Original member identity is independent of its position in the declaration.
#[derive(Debug, Clone)]
pub(crate) struct AlphaGuideMember {
    pub(crate) key: crate::alpha::AlphaExampleKey,
    pub(crate) ordinal: u32,
}
impl PartialEq for AlphaGuideMember {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}
impl Eq for AlphaGuideMember {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum GuideEntryIdentity {
    Category {
        field: RawField,
        value: RawCategory,
    },
    Pair {
        group_field: RawField,
        group_value: RawCategory,
        hue_field: RawField,
        hue_value: RawCategory,
    },
    BarSign {
        decreasing: bool,
    },
    DumbbellEndpoint {
        label: Arc<str>,
    },
    RegressionObservation,
    RegressionFit {
        band: RegressionBand,
    },
    SupplementalLayer {
        label: RawLayerLabel,
    },
    AlphaMember(AlphaGuideMember),
}

impl GuideEntryIdentity {
    pub(crate) fn category(field: RawField, value: RawCategory) -> Self {
        Self::Category { field, value }
    }

    pub(crate) fn pair(
        group_field: RawField,
        group_value: RawCategory,
        hue_field: RawField,
        hue_value: RawCategory,
    ) -> Self {
        Self::Pair {
            group_field,
            group_value,
            hue_field,
            hue_value,
        }
    }

    pub(crate) const fn bar_sign(decreasing: bool) -> Self {
        Self::BarSign { decreasing }
    }

    pub(crate) fn endpoint(label: &str) -> Result<Self> {
        Ok(Self::DumbbellEndpoint {
            label: shared_text(label)?,
        })
    }

    pub(crate) fn supplemental(label: &str) -> Result<Self> {
        Ok(Self::SupplementalLayer {
            label: RawLayerLabel::new(label)?,
        })
    }

    pub(crate) fn primary_title(&self) -> Option<PrimaryTitleIdentity> {
        Some(match self {
            Self::Category { field, .. } => PrimaryTitleIdentity::Field(field.clone()),
            Self::Pair {
                group_field,
                hue_field,
                ..
            } => PrimaryTitleIdentity::Pair {
                group: group_field.clone(),
                hue: hue_field.clone(),
            },
            Self::BarSign { .. } => PrimaryTitleIdentity::BarSign,
            Self::DumbbellEndpoint { .. }
            | Self::RegressionObservation
            | Self::RegressionFit { .. } => PrimaryTitleIdentity::Series,
            Self::SupplementalLayer { .. } | Self::AlphaMember(_) => return None,
        })
    }

    pub(crate) fn resolved_label(
        &self,
        labels: &crate::formatting::Labels,
        layer_context: Option<super::source::LayerLabelContext>,
    ) -> Result<String> {
        let literal = crate::data::source::copy_source_string;
        match self {
            Self::Category { value, .. } => labels.resolve(value.as_str()),
            Self::Pair {
                group_value,
                hue_value,
                ..
            } => join(
                labels.resolve(group_value.as_str())?,
                ", ",
                &labels.resolve(hue_value.as_str())?,
            ),
            Self::BarSign { decreasing } => literal(if *decreasing {
                "Decreasing"
            } else {
                "Nondecreasing"
            }),
            Self::DumbbellEndpoint { label } => literal(label),
            Self::RegressionObservation => literal("Observations"),
            Self::RegressionFit { band } => literal(band.legend_label()),
            Self::SupplementalLayer { label } => match layer_context {
                Some(super::source::LayerLabelContext::Categorical) => {
                    labels.resolve(label.as_str())
                }
                Some(super::source::LayerLabelContext::LiteralSeries) => literal(label.as_str()),
                None => Err(Error::Render(
                    "supplemental guide requires its source label context".into(),
                )),
            },
            Self::AlphaMember(_) => Err(Error::Render(
                "alpha labels belong to their declared section".into(),
            )),
        }
    }
}

fn join(mut first: String, separator: &str, second: &str) -> Result<String> {
    let additional = separator
        .len()
        .checked_add(second.len())
        .ok_or_else(|| Error::Render("guide label length overflow".into()))?;
    crate::data::source::reserve_source_string(&mut first, additional)?;
    first.push_str(separator);
    first.push_str(second);
    Ok(first)
}

#[test]
fn categorical_guide_entries_preserve_original_fields_and_keys() {
    use super::discrete::{GuideSectionIdentity, PreparedGuide};
    use crate::data::{KeyValues, RawKey, RawKeyValues};
    use crate::Plot;
    let field = RawKey::Tuple(vec![RawKey::from("cohort"), RawKey::Integer(7.into())]);
    let first = RawKey::Integer(crate::data::ExactInteger::from(1_i64));
    let second = RawKey::from("1");
    let values = crate::CategoryValues::new("private_field", ["private_a", "private_b"])
        .unwrap()
        .with_field_key(field.clone(), "cohort")
        .with_key_values(KeyValues::Raw(
            RawKeyValues::new("cohort", [first.clone(), second.clone()]).unwrap(),
        ))
        .unwrap();
    let plot = Plot::scatter(
        crate::NumericValues::new("x", [1.0, 2.0]),
        crate::NumericValues::new("y", [3.0, 4.0]),
    )
    .hue(values)
    .labels(
        crate::formatting::Labels::raw()
            .alias("private_field", "cohort")
            .alias("private_a", "same")
            .alias("private_b", "same"),
    )
    .erase();
    let appearance = crate::Theme::publication().resolve().unwrap();
    let service = crate::text::TextService::default();
    let theme = crate::text::TextRequestContext::new(&appearance, &service);
    let descriptor =
        PreparedGuide::prepare_for_test(&plot, &theme, crate::guides::LegendComposition::Combined)
            .unwrap()
            .unwrap();
    let section = &descriptor.sections[0];
    let GuideSectionIdentity::Combined(PrimaryTitleIdentity::Field(actual)) = &section.identity
    else {
        panic!("actual single categorical field");
    };
    assert_eq!(actual.key(), &field);
    let keys = section
        .entries()
        .iter()
        .map(|entry| {
            assert_eq!(entry.display_label.as_str(), "same");
            let GuideEntryIdentity::Category {
                field: actual,
                value,
            } = &entry.identity
            else {
                panic!("actual categorical entry");
            };
            assert_eq!(actual.key(), &field);
            value.key().clone()
        })
        .collect::<Vec<_>>();
    assert_eq!(keys, [first, second]);
}