use std::sync::Arc;
use super::{collect_input, numeric_key, validated_alpha, AlphaValues};
use crate::data::source::{collect_source, sort_source_by, source_arc};
use crate::{
data::{Bounds, KeyColumns, KeyValues, NamedKeyValues, RawKey, RawKeyValues},
CategoryValues, Error, Result,
};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AlphaEncoding {
binding: Binding,
}
#[derive(Debug, Clone, Default, PartialEq)]
enum Binding {
#[default]
Theme,
Fixed(f64),
Observations(AlphaValues),
Single(AlphaValues),
Keyed(Arc<SelectorTable>, AlphaValues),
Bins(Arc<BinTable>, AlphaValues),
}
impl Eq for Binding {}
#[derive(Debug)]
struct SelectorTable {
columns: KeyColumns,
member_keys: Option<RawKeyValues>,
fields: Vec<RawKey>,
rows: Vec<Vec<Vec<u8>>>,
order: Vec<usize>,
}
#[derive(Debug, PartialEq, Eq)]
struct BinTable {
facets: SelectorTable,
original_bounds: Bounds,
member_keys: RawKeyValues,
bounds: Vec<[u64; 2]>,
order: Vec<usize>,
}
impl PartialEq for SelectorTable {
fn eq(&self, other: &Self) -> bool {
self.fields == other.fields
&& self.rows == other.rows
&& self.order == other.order
&& self.columns.len() == other.columns.len()
&& self.columns.columns().iter().all(|column| {
other
.columns
.get(&column.key)
.is_ok_and(|values| *values == column.values)
})
}
}
impl Eq for SelectorTable {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AlphaUnitKind {
Observation,
Series,
Aggregate,
Bin,
Single,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedAlpha {
encoding: AlphaEncoding,
unit: AlphaUnitKind,
original_len: usize,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ResolvedAlpha {
pub(crate) index: Option<usize>,
pub(crate) alpha: f64,
}
impl Eq for ResolvedAlpha {}
impl TryFrom<f64> for AlphaEncoding {
type Error = Error;
fn try_from(value: f64) -> Result<Self> {
Self::fixed(value)
}
}
impl AlphaEncoding {
#[must_use]
pub const fn theme() -> Self {
Self {
binding: Binding::Theme,
}
}
pub fn fixed(alpha: f64) -> Result<Self> {
Ok(Self {
binding: Binding::Fixed(validated_alpha(alpha)?),
})
}
#[must_use]
pub const fn get_fixed(&self) -> Option<f64> {
match self.binding {
Binding::Fixed(alpha) => Some(alpha),
_ => None,
}
}
#[must_use]
pub fn observations(values: AlphaValues) -> Self {
Self {
binding: Binding::Observations(values),
}
}
pub fn single(values: AlphaValues) -> Result<Self> {
if values.len() != 1 {
return Err(Error::Data(
"single alpha requires exactly one value".into(),
));
}
Ok(Self {
binding: Binding::Single(values),
})
}
pub fn keyed(
keys: impl IntoIterator<Item = CategoryValues>,
values: AlphaValues,
) -> Result<Self> {
let mut table = SelectorTable::new(keys, values.len())?;
if table.fields.is_empty() {
return Err(Error::Data(
"keyed alpha requires at least one selector field".into(),
));
}
if table
.order
.windows(2)
.any(|pair| table.rows[pair[0]] == table.rows[pair[1]])
{
return Err(Error::Data(
"keyed alpha contains duplicate selector tuples".into(),
));
}
table.member_keys = Some(RawKeyValues::new(
"alpha keys",
(0..values.len()).map(|slot| {
let keys = table
.columns
.row_keys(slot)
.expect("validated actual selector row");
if let [key] = keys.as_slice() {
key.clone()
} else {
RawKey::Tuple(keys)
}
}),
)?);
Ok(Self {
binding: Binding::Keyed(source_arc(table)?, values),
})
}
pub fn bins(
bounds: Bounds,
facets: impl IntoIterator<Item = CategoryValues>,
values: AlphaValues,
) -> Result<Self> {
if bounds.lower().len() != values.len() || bounds.upper().len() != values.len() {
return Err(Error::Data(
"alpha bin bounds must align with the alpha values".into(),
));
}
let facets = SelectorTable::new(facets, values.len())?;
let original_bounds = bounds;
let bounds = collect_source((0..values.len()).map(|index| {
let low = original_bounds.lower().get(index).flatten();
let high = original_bounds.upper().get(index).flatten();
match (low, high) {
(Some(low), Some(high)) if low.is_finite() && high.is_finite() && low < high => {
Ok([numeric_key(low), numeric_key(high)])
}
_ => Err(Error::Data(
format!(
"alpha bin at index {index} requires finite nonmissing lower < upper bounds"
)
.into(),
)),
}
}))?;
let mut order = collect_source((0..values.len()).map(Ok))?;
sort_source_by(&mut order, |a, b| {
facets.rows[*a]
.cmp(&facets.rows[*b])
.then(bounds[*a].cmp(&bounds[*b]))
})?;
if order.windows(2).any(|pair| {
facets.rows[pair[0]] == facets.rows[pair[1]] && bounds[pair[0]] == bounds[pair[1]]
}) {
return Err(Error::Data(
"alpha bins contain duplicate exact interval/facet keys".into(),
));
}
let member_keys = RawKeyValues::new(
"alpha bins",
(0..values.len()).map(|slot| {
let mut key = vec![
RawKey::Float(
original_bounds
.lower()
.get(slot)
.flatten()
.expect("validated lower bound"),
),
RawKey::Float(
original_bounds
.upper()
.get(slot)
.flatten()
.expect("validated upper bound"),
),
];
key.extend(
facets
.columns
.row_keys(slot)
.expect("validated actual selector row"),
);
RawKey::Tuple(key)
}),
)?;
Ok(Self {
binding: Binding::Bins(
source_arc(BinTable {
facets,
original_bounds,
member_keys,
bounds,
order,
})?,
values,
),
})
}
pub(crate) fn member_keys(&self) -> Option<&RawKeyValues> {
match &self.binding {
Binding::Keyed(table, _) => table.member_keys.as_ref(),
Binding::Bins(table, _) => Some(&table.member_keys),
_ => None,
}
}
#[must_use]
pub const fn is_theme(&self) -> bool {
matches!(self.binding, Binding::Theme)
}
#[must_use]
pub const fn values(&self) -> Option<&AlphaValues> {
match &self.binding {
Binding::Theme | Binding::Fixed(_) => None,
Binding::Observations(values)
| Binding::Single(values)
| Binding::Keyed(_, values)
| Binding::Bins(_, values) => Some(values),
}
}
#[must_use]
pub const fn get_observations(&self) -> Option<&AlphaValues> {
match &self.binding {
Binding::Observations(values) => Some(values),
_ => None,
}
}
#[must_use]
pub const fn get_single(&self) -> Option<&AlphaValues> {
match &self.binding {
Binding::Single(values) => Some(values),
_ => None,
}
}
#[must_use]
pub fn get_keyed(&self) -> Option<(&KeyColumns, &AlphaValues)> {
match &self.binding {
Binding::Keyed(table, values) => Some((&table.columns, values)),
_ => None,
}
}
#[must_use]
pub fn get_bins(&self) -> Option<(&Bounds, &KeyColumns, &AlphaValues)> {
match &self.binding {
Binding::Bins(table, values) => {
Some((&table.original_bounds, &table.facets.columns, values))
}
_ => None,
}
}
pub(crate) fn prepare(
&self,
unit: AlphaUnitKind,
original_len: usize,
required_fields: &[RawKey],
facet_fields: &[RawKey],
) -> Result<PreparedAlpha> {
match &self.binding {
Binding::Theme | Binding::Fixed(_) | Binding::Single(_) => {}
Binding::Observations(values) if unit == AlphaUnitKind::Observation => {
if values.len() != original_len {
use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
return Err(Error::Data(Diagnostic::new(DiagnosticKind::ShapeMismatch {
expected: vec![original_len], actual: vec![values.len()],
}, format!("observation alpha {:?} has length {}, expected all {original_len} original input slots", values.name(), values.len()))
.with_context(ErrorContext::new().with_operation(OperationPhase::Prepare))));
}
}
Binding::Keyed(table, _)
if matches!(unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) =>
{
table.validate_schema(required_fields, facet_fields)?;
}
Binding::Bins(table, _) if unit == AlphaUnitKind::Bin => {
table.facets.validate_schema(&[], facet_fields)?;
}
_ => {
return Err(Error::Data(
format!("alpha binding does not support {unit:?} units").into(),
))
}
}
Ok(PreparedAlpha {
encoding: self.clone(),
unit,
original_len,
})
}
}
impl SelectorTable {
fn new(keys: impl IntoIterator<Item = CategoryValues>, len: usize) -> Result<Self> {
let keys = collect_input(keys)?;
let columns = collect_source(keys.iter().map(|column| {
let source = column.get_source();
let source_field = source
.selected_keys()
.filter(|keys| keys.len() == 1 && source.generation().is_none())
.and_then(|_| source.field(0));
let values = match column.key_values() {
KeyValues::Strings(values) => {
KeyValues::Strings(if let Some((key, name)) = source_field {
values.with_field_name(&name).with_field_key(key, name)
} else {
values
})
}
KeyValues::Raw(values) => KeyValues::Raw(if let Some((_, name)) = source_field {
values.with_name(&name)
} else {
values
}),
};
Ok(NamedKeyValues {
key: column.original_field(),
values,
})
}))?;
let mut keys = collect_source(keys.into_iter().map(|column| {
let field = column.original_field();
Ok((crate::data::key_bytes(&field)?, field, column))
}))?;
sort_source_by(&mut keys, |a, b| a.0.cmp(&b.0))?;
let fields = collect_source(keys.iter().map(|(_, field, column)| {
if column.len() != len {
return Err(Error::Data(
format!(
"alpha selector {:?} has length {}, expected {len}",
column.name(),
column.len()
)
.into(),
));
}
Ok(field.clone())
}))?;
if fields.windows(2).any(|pair| pair[0] == pair[1]) {
return Err(Error::Data(
"alpha selector field names must be unique".into(),
));
}
let rows = collect_source((0..len).map(|index| {
collect_source(keys.iter().map(|(_, _, column)| {
let raw = column.key_at(index).ok_or_else(|| {
Error::Data(
format!(
"alpha selector {:?} is missing at index {index}",
column.name()
)
.into(),
)
})?;
crate::data::key_bytes(&raw)
}))
}))?;
let mut order = collect_source((0..len).map(Ok))?;
sort_source_by(&mut order, |a, b| rows[*a].cmp(&rows[*b]))?;
Ok(Self {
columns: KeyColumns::new(columns)?,
member_keys: None,
fields,
rows,
order,
})
}
fn validate_schema(&self, required: &[RawKey], facets: &[RawKey]) -> Result<()> {
for field in &self.fields {
if !required.contains(field) && !facets.contains(field) {
return Err(Error::Data(
format!("alpha selector {field:?} is not an actual unit or owning facet field")
.into(),
));
}
}
for field in required {
if !self.fields.iter().any(|name| name == field) {
return Err(Error::Data(
format!("alpha binding is missing required unit field {field:?}").into(),
));
}
}
Ok(())
}
fn tuple(&self, keys: &[(RawKey, RawKey)]) -> Result<Vec<Vec<u8>>> {
for (index, (field, value)) in keys.iter().enumerate() {
if keys[..index]
.iter()
.any(|(other, raw)| other == field && raw != value)
{
return Err(Error::Data(
format!("actual alpha unit has conflicting raw values for field {field:?}")
.into(),
));
}
}
collect_source(self.fields.iter().map(|field| {
keys.iter()
.find(|(name, _)| name == field)
.ok_or_else(|| {
Error::Data(
format!("actual alpha unit has no value for selector field {field:?}")
.into(),
)
})
.and_then(|(_, raw)| crate::data::key_bytes(raw))
}))
}
fn compare_row(&self, index: usize, tuple: &[Vec<u8>]) -> std::cmp::Ordering {
self.rows[index].as_slice().cmp(tuple)
}
}
impl PreparedAlpha {
pub(crate) fn selector_fields(&self) -> &[RawKey] {
match &self.encoding.binding {
Binding::Keyed(table, _) => &table.fields,
Binding::Bins(table, _) => &table.facets.fields,
Binding::Theme | Binding::Fixed(_) | Binding::Observations(_) | Binding::Single(_) => {
&[]
}
}
}
fn resolved(&self, index: usize) -> Result<Option<ResolvedAlpha>> {
if let Some(alpha) = self.encoding.get_fixed() {
return Ok(Some(ResolvedAlpha { index: None, alpha }));
}
self.encoding
.values()
.map(|values| {
values
.get(index)
.map(|alpha| ResolvedAlpha {
index: Some(index),
alpha,
})
.ok_or_else(|| {
Error::Data(
format!(
"alpha source {:?} has no original slot {index}",
values.name()
)
.into(),
)
})
})
.transpose()
}
fn constant(&self) -> Option<Result<Option<ResolvedAlpha>>> {
match &self.encoding.binding {
Binding::Theme => Some(Ok(None)),
Binding::Fixed(_) | Binding::Single(_) => Some(self.resolved(0)),
_ => None,
}
}
pub(crate) fn observation(
&self,
index: usize,
source_row: usize,
) -> Result<Option<ResolvedAlpha>> {
if self.unit != AlphaUnitKind::Observation {
return Err(Error::Data(
"alpha source requires an observation unit".into(),
));
}
if index >= self.original_len {
return Err(Error::Data(format!(
"alpha original slot {index} is outside length {} at diagnostic source row {source_row}",
self.original_len,
).into()));
}
self.constant()
.unwrap_or_else(|| self.resolved(index))
.map_err(|error| {
Error::Data(format!("{error} at diagnostic source row {source_row}").into())
})
}
pub(crate) fn single(&self) -> Result<Option<ResolvedAlpha>> {
if self.unit != AlphaUnitKind::Single {
return Err(Error::Data("alpha source requires a single unit".into()));
}
self.resolved(0)
}
pub(crate) fn keyed(&self, keys: &[(RawKey, RawKey)]) -> Result<Option<ResolvedAlpha>> {
if !matches!(self.unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) {
return Err(Error::Data(
"alpha source requires a series or aggregate unit".into(),
));
}
if let Some(value) = self.constant() {
return value;
}
let Binding::Keyed(table, _) = &self.encoding.binding else {
unreachable!("prepared keyed binding")
};
let tuple = table.tuple(keys)?;
let position = table
.order
.binary_search_by(|&index| table.compare_row(index, &tuple))
.map_err(|_| {
Error::Data(
format!("alpha binding has no value for actual raw unit {keys:?}").into(),
)
})?;
self.resolved(table.order[position])
}
pub(crate) fn bin(
&self,
bounds: (f64, f64),
facets: &[(RawKey, RawKey)],
) -> Result<Option<ResolvedAlpha>> {
if self.unit != AlphaUnitKind::Bin {
return Err(Error::Data("alpha source requires a bin unit".into()));
}
if !bounds.0.is_finite() || !bounds.1.is_finite() || bounds.0 >= bounds.1 {
return Err(Error::Data(
"actual alpha bin must have finite lower < upper bounds".into(),
));
}
if let Some(value) = self.constant() {
return value;
}
let Binding::Bins(table, _) = &self.encoding.binding else {
unreachable!("prepared bin binding")
};
let tuple = table.facets.tuple(facets)?;
let key = [numeric_key(bounds.0), numeric_key(bounds.1)];
let position = table
.order
.binary_search_by(|&index| {
table
.facets
.compare_row(index, &tuple)
.then(table.bounds[index].cmp(&key))
})
.map_err(|_| {
Error::Data(
format!(
"alpha binding has no value for exact actual bin {bounds:?} in {facets:?}"
)
.into(),
)
})?;
self.resolved(table.order[position])
}
}
#[cfg(test)]
mod tests;