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)
}
fn continuous_coordinates(domain: (f64, f64), logarithmic: bool) -> Result<(f64, f64)> {
Ok(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
})
}
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 = continuous_coordinates(domain, logarithmic)?;
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 original = source.key_values();
let values = original
.get_strings()
.ok_or_else(|| Error::Data("categorical alpha requires actual string categories".into()))?;
for (index, value) in values.iter().enumerate() {
crate::operation::check()?;
if value.is_none() {
return Err(Error::Data(
format!(
"alpha source {:?} is missing at index {index}",
source.name()
)
.into(),
));
}
}
let entries = collect_source(values.levels().iter().map(|category| {
Ok((
RawKey::String(copy_source_string(category)?),
validated_alpha(f(category))?,
))
}))?;
AlphaValues::from_declared_categories(source, entries)
}
fn validate_continuous_entries(domain: (f64, f64), entries: &[(f64, f64)]) -> Result<()> {
for &(coordinate, alpha) in entries {
crate::operation::check()?;
if !coordinate.is_finite() || coordinate < domain.0 || coordinate > domain.1 {
return Err(Error::Data(
"alpha evaluated coordinate lies outside its domain".into(),
));
}
validated_alpha(alpha)?;
}
if entries.windows(2).any(|pair| pair[0].0 >= pair[1].0) {
return Err(Error::Data(
"alpha evaluated coordinates must be unique and ascending".into(),
));
}
for coordinate in representatives(domain)? {
if entries
.binary_search_by(|(value, _)| {
f64::from_bits(numeric_key(*value)).total_cmp(&coordinate)
})
.is_err()
{
return Err(Error::Data(
format!("alpha mapping has no declared value for {coordinate}").into(),
));
}
}
Ok(())
}
fn category_indices(entries: &[(RawKey, f64)]) -> Result<std::collections::HashMap<&str, usize>> {
let mut indices = std::collections::HashMap::new();
indices.try_reserve(entries.len()).map_err(|error| {
Error::Render(format!("alpha category index reservation: {error}").into())
})?;
for (index, (key, alpha)) in entries.iter().enumerate() {
let RawKey::String(key) = key else {
return Err(Error::Data(
"categorical alpha mapping requires string keys".into(),
));
};
validated_alpha(*alpha)?;
if indices.insert(key.as_str(), index).is_some() {
return Err(Error::Data("duplicate categorical alpha key".into()));
}
}
Ok(indices)
}
impl AlphaValues {
pub(crate) fn from_declared_continuous(
source: &NumericValues,
raw_domain: (f64, f64),
entries: &[(f64, f64)],
) -> Result<Self> {
let domain = domain(raw_domain)?;
let members = numeric_members(source, false)?;
let name = copy_source_string(source.raw_name())?;
validate_continuous_entries(domain, entries)?;
let table =
collect_source(entries.iter().map(|&(coordinate, alpha)| {
Ok((numeric_key(coordinate), validated_alpha(alpha)?))
}))?;
let representatives = representatives(domain)?;
for &member in &members {
crate::operation::check()?;
let key = clamped_key(member, domain);
if table
.binary_search_by(|(value, _)| {
f64::from_bits(*value).total_cmp(&f64::from_bits(key))
})
.is_err()
{
return Err(Error::Data(
format!(
"alpha mapping has no declared value for {}",
f64::from_bits(key)
)
.into(),
));
}
}
let examples = guide_presentation(&representatives, None)?;
finish_continuous(
source,
name,
&members,
domain,
|table| {
Ok(AlphaMapping::Continuous {
domain: [raw_domain.0, raw_domain.1],
evaluated: table
.into_iter()
.map(|(key, alpha)| (f64::from_bits(key), alpha))
.collect(),
})
},
examples,
table,
)
}
pub(crate) fn from_declared_categories(
source: &CategoryValues,
mut entries: Vec<(RawKey, f64)>,
) -> Result<Self> {
let name = copy_source_string(source.name())?;
let original = source.key_values();
let values = original.get_strings().ok_or_else(|| {
Error::Data("categorical alpha requires actual string categories".into())
})?;
let indices = category_indices(&entries)?;
let members = collect_source(values.iter().enumerate().map(|(index, key)| {
let key = key.ok_or_else(|| {
Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
})?;
indices.get(key).copied().ok_or_else(|| {
Error::Data(format!("alpha mapping has no declared value for {key:?}").into())
})
}))?;
drop(indices);
for (_, alpha) in &mut entries {
*alpha = validated_alpha(*alpha)?;
}
let values = collect_source(members.iter().map(|&index| Ok(entries[index].1)))?;
Self::from_parts(
name,
values,
AlphaMembers::Categorical(original, members),
AlphaDeclaration {
mapping: AlphaMapping::Categorical(entries),
examples: Vec::new(),
labels: Vec::new(),
},
)
}
}
fn validate_thresholds(boundaries: &[f64], alphas: &[f64]) -> Result<()> {
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(),
));
}
if boundaries.len().checked_add(1) != Some(alphas.len()) {
return Err(Error::Data(
"alpha thresholds require one more coefficient than boundaries".into(),
));
}
for &alpha in alphas {
crate::operation::check()?;
validated_alpha(alpha)?;
}
Ok(())
}
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)?;
let alphas = collect_source(alphas.into_iter().map(validated_alpha))?;
validate_thresholds(&boundaries, &alphas)?;
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,
},
)
}
impl AlphaMapping {
pub(crate) fn validate_declaration(&self) -> Result<()> {
match self {
Self::Undeclared => Ok(()),
Self::Linear {
domain: [a, b],
range,
}
| Self::Log10 {
domain: [a, b],
range,
} => {
let domain = domain((*a, *b))?;
continuous_coordinates(domain, matches!(self, Self::Log10 { .. }))?;
validated_alpha(range[0])?;
validated_alpha(range[1])?;
Ok(())
}
Self::Continuous {
domain: [a, b],
evaluated,
} => validate_continuous_entries(domain((*a, *b))?, evaluated),
Self::Categorical(entries) => category_indices(entries).map(|_| ()),
Self::Threshold { boundaries, alphas } => validate_thresholds(boundaries, alphas),
}
}
}