lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Construction is the only application-function boundary. All consumers retain
//! final coefficients, scientific membership, numeric text and complete mapping recipes.

use super::{
    collect_input, numeric_key, validated_alpha, AlphaDeclaration, AlphaMapping, AlphaMembers,
    AlphaValues,
};
use crate::data::source::{collect_source, copy_source_string, reserve_source, sort_source_by};
use crate::data::RawKey;
use crate::numeric::{mapping::normalized_fraction, set::guide_presentation};
use crate::{CategoryValues, Error, NumericValues, Result};

fn domain(domain: (f64, f64)) -> Result<(f64, f64)> {
    if !domain.0.is_finite() || !domain.1.is_finite() || domain.0 >= domain.1 {
        return Err(Error::Data(
            "alpha domain endpoints must be finite and strictly ascending".into(),
        ));
    }
    Ok((
        f64::from_bits(numeric_key(domain.0)),
        f64::from_bits(numeric_key(domain.1)),
    ))
}

fn numeric_members(source: &NumericValues, positive: bool) -> Result<Vec<u64>> {
    collect_source((0..source.len()).map(|index| {
        let value = source.get(index).flatten().ok_or_else(|| {
            Error::Data(
                format!(
                    "alpha source {:?} is missing at index {index}",
                    source.name()
                )
                .into(),
            )
        })?;
        if !value.is_finite() || (positive && value <= 0.0) {
            return Err(Error::Data(
                format!(
                    "alpha source {:?} at index {index} must be {}finite",
                    source.name(),
                    if positive {
                        "strictly positive and "
                    } else {
                        ""
                    },
                )
                .into(),
            ));
        }
        Ok(numeric_key(value))
    }))
}

fn representatives(domain: (f64, f64)) -> Result<Vec<f64>> {
    let midpoint = f64::midpoint(domain.0, domain.1);
    let mut values = collect_source(
        [
            domain.0,
            f64::midpoint(domain.0, midpoint),
            midpoint,
            f64::midpoint(midpoint, domain.1),
            domain.1,
        ]
        .into_iter()
        .map(|value| Ok(f64::from_bits(numeric_key(value)))),
    )?;
    values.dedup_by(|a, b| a.to_bits() == b.to_bits());
    Ok(values)
}

fn clamped_key(member: u64, domain: (f64, f64)) -> u64 {
    numeric_key(f64::from_bits(member).clamp(domain.0, domain.1))
}

fn evaluations(
    members: &[u64],
    representatives: &[f64],
    domain: (f64, f64),
    mut evaluate: impl FnMut(f64) -> Result<f64>,
) -> Result<Vec<(u64, f64)>> {
    let mut keys = collect_source(
        members
            .iter()
            .map(|&member| Ok(clamped_key(member, domain))),
    )?;
    reserve_source(&mut keys, representatives.len())?;
    keys.extend(representatives.iter().map(|&value| numeric_key(value)));
    sort_source_by(&mut keys, |a, b| {
        f64::from_bits(*a).total_cmp(&f64::from_bits(*b))
    })?;
    keys.dedup();
    collect_source(
        keys.iter()
            .map(|&key| Ok((key, evaluate(f64::from_bits(key))?))),
    )
}

fn evaluated(table: &[(u64, f64)], key: u64) -> f64 {
    let index = table
        .binary_search_by(|(value, _)| f64::from_bits(*value).total_cmp(&f64::from_bits(key)))
        .expect("validated materialized alpha coordinate");
    table[index].1
}

fn interpolate(fraction: f64, range: (f64, f64)) -> Result<f64> {
    let value = if fraction <= 0.0 || range.0.to_bits() == range.1.to_bits() {
        range.0
    } else if fraction >= 1.0 {
        range.1
    } else {
        (1.0 - fraction) * range.0 + fraction * range.1
    };
    validated_alpha(value)
}

pub(super) fn builtin(
    source: &NumericValues,
    raw_domain: (f64, f64),
    range: (f64, f64),
    logarithmic: bool,
) -> Result<AlphaValues> {
    let domain = domain(raw_domain)?;
    let range = (validated_alpha(range.0)?, validated_alpha(range.1)?);
    let name = copy_source_string(source.raw_name())?;
    let coordinates = if logarithmic {
        if domain.0 <= 0.0 {
            return Err(Error::Data(
                "log10 alpha domain must be strictly positive".into(),
            ));
        }
        let coordinates = (
            crate::numeric::log10(domain.0)?,
            crate::numeric::log10(domain.1)?,
        );
        if !coordinates.0.is_finite()
            || !coordinates.1.is_finite()
            || coordinates.0 >= coordinates.1
        {
            return Err(Error::Data(
                "log10 alpha domain coordinates must be finite and distinguishable".into(),
            ));
        }
        coordinates
    } else {
        domain
    };
    let members = numeric_members(source, logarithmic)?;
    let examples = guide_presentation(&representatives(domain)?, None)?;
    let example_values = collect_source(
        examples
            .members
            .iter()
            .map(crate::numeric::operand::Operand::binary64),
    )?;
    let table = evaluations(&members, &example_values, domain, |value| {
        let fraction = if value <= domain.0 {
            0.0
        } else if value >= domain.1 {
            1.0
        } else {
            let coordinate = if logarithmic {
                crate::numeric::log10(value)?
            } else {
                value
            };
            normalized_fraction(coordinates, coordinate)?
        };
        interpolate(fraction, range)
    })?;
    let rule = if logarithmic {
        AlphaMapping::Log10 {
            domain: [raw_domain.0, raw_domain.1],
            range: [range.0, range.1],
        }
    } else {
        AlphaMapping::Linear {
            domain: [raw_domain.0, raw_domain.1],
            range: [range.0, range.1],
        }
    };
    finish_continuous(
        source,
        name,
        &members,
        domain,
        |_| Ok(rule),
        examples,
        table,
    )
}

pub(super) fn continuous(
    source: &NumericValues,
    raw_domain: (f64, f64),
    mut f: impl FnMut(f64) -> f64,
) -> Result<AlphaValues> {
    let domain = domain(raw_domain)?;
    let name = copy_source_string(source.raw_name())?;
    let members = numeric_members(source, false)?;
    let representatives = representatives(domain)?;
    let examples = guide_presentation(&representatives, None)?;
    let table = evaluations(&members, &representatives, domain, |value| {
        validated_alpha(f(value))
    })?;
    finish_continuous(
        source,
        name,
        &members,
        domain,
        |table| {
            Ok(AlphaMapping::Continuous {
                domain: [raw_domain.0, raw_domain.1],
                evaluated: collect_source(
                    table
                        .into_iter()
                        .map(|(key, alpha)| Ok((f64::from_bits(key), alpha))),
                )?,
            })
        },
        examples,
        table,
    )
}

fn finish_continuous(
    source: &NumericValues,
    name: String,
    members: &[u64],
    domain: (f64, f64),
    rule: impl FnOnce(Vec<(u64, f64)>) -> Result<AlphaMapping>,
    examples: crate::numeric::set::FormattedSet,
    table: Vec<(u64, f64)>,
) -> Result<AlphaValues> {
    let values = collect_source(
        members
            .iter()
            .map(|&member| Ok(evaluated(&table, clamped_key(member, domain)))),
    )?;
    let samples = collect_source(examples.members.iter().map(|value| {
        let value = value.binary64()?;
        Ok((value, evaluated(&table, numeric_key(value))))
    }))?;
    AlphaValues::from_parts(
        name,
        values,
        AlphaMembers::Numeric(source.clone()),
        AlphaDeclaration {
            mapping: rule(table)?,
            examples: samples,
            labels: examples.labels,
        },
    )
}

pub(super) fn categorical(
    source: &CategoryValues,
    mut f: impl FnMut(&str) -> f64,
) -> Result<AlphaValues> {
    let name = copy_source_string(source.name())?;
    let original = source.key_values();
    let source = original
        .get_strings()
        .ok_or_else(|| Error::Data("categorical alpha requires actual string categories".into()))?;
    // Validate the complete source before invoking any application function.
    let raw = collect_source((0..source.len()).map(|index| {
        source.get(index).flatten().ok_or_else(|| {
            Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
        })
    }))?;
    let mut indices = std::collections::HashMap::new();
    indices
        .try_reserve(source.levels().len())
        .map_err(|error| {
            Error::Render(format!("alpha category index reservation: {error}").into())
        })?;
    for (index, category) in source.levels().iter().enumerate() {
        indices.insert(category.as_str(), index);
    }
    let members = collect_source(raw.iter().map(|category| Ok(indices[category])))?;
    let entries = collect_source(source.levels().iter().map(|category| {
        let retained = copy_source_string(category)?;
        Ok((RawKey::String(retained), validated_alpha(f(category))?))
    }))?;
    let values = collect_source(members.iter().map(|&index| Ok(entries[index].1)))?;
    AlphaValues::from_parts(
        name,
        values,
        AlphaMembers::Categorical(original, members),
        AlphaDeclaration {
            mapping: AlphaMapping::Categorical(entries),
            examples: Vec::new(),
            labels: Vec::new(),
        },
    )
}

pub(super) fn threshold(
    source: &NumericValues,
    boundaries: impl IntoIterator<Item = f64>,
    alphas: impl IntoIterator<Item = f64>,
) -> Result<AlphaValues> {
    let name = copy_source_string(source.raw_name())?;
    let boundaries = collect_input(boundaries)?;
    if boundaries.iter().any(|value| !value.is_finite())
        || boundaries.windows(2).any(|pair| pair[0] >= pair[1])
    {
        return Err(Error::Data(
            "alpha thresholds must be finite and strictly ascending".into(),
        ));
    }
    let alphas = collect_source(alphas.into_iter().map(validated_alpha))?;
    if boundaries.len().checked_add(1) != Some(alphas.len()) {
        return Err(Error::Data(
            "alpha thresholds require one more coefficient than boundaries".into(),
        ));
    }
    let source_members = numeric_members(source, false)?;
    let members = collect_source(
        source_members
            .iter()
            .map(|&key| Ok(boundaries.partition_point(|&bound| f64::from_bits(key) >= bound))),
    )?;
    let values = collect_source(members.iter().map(|&index| Ok(alphas[index])))?;
    let display_boundaries = collect_source(
        boundaries
            .iter()
            .map(|&value| Ok(f64::from_bits(numeric_key(value)))),
    )?;
    let display_boundaries = guide_presentation(&display_boundaries, None)?;
    let mut labels = Vec::new();
    reserve_source(&mut labels, alphas.len())?;
    if display_boundaries.labels.is_empty() {
        labels.push(copy_source_string("all values")?);
    } else {
        labels.push(format!("< {}", display_boundaries.labels[0]));
        for pair in display_boundaries.labels.windows(2) {
            labels.push(format!("[{}, {})", pair[0], pair[1]));
        }
        labels.push(format!(
            ">= {}",
            display_boundaries.labels.last().expect("nonempty bounds")
        ));
    }
    AlphaValues::from_parts(
        name,
        values,
        AlphaMembers::Threshold(source.clone(), members),
        AlphaDeclaration {
            mapping: AlphaMapping::Threshold { boundaries, alphas },
            examples: Vec::new(),
            labels,
        },
    )
}