use std::sync::Arc;
use super::{Attached, FacetCell, Pairwise, Significance, SignificanceMark, SignificanceTarget};
use crate::{
data::{KeyValues, RawKey},
layout::FacetBinding,
CategoryValues, Error, NumericValues, Result,
};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceTargetInput {
Column(KeyValues),
CategorySeries(KeyValues, KeyValues),
Fixed(SignificanceTarget),
Values(Arc<[SignificanceTarget]>),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceMarkInput {
PValues(NumericValues),
Categories {
values: CategoryValues,
mapping: Arc<[(String, SignificanceMark)]>,
},
Fixed(SignificanceMark),
Values(Arc<[SignificanceMark]>),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceFacetInput {
Unfaceted,
Fixed(FacetCell),
Values(Arc<[FacetCell]>),
Split(FacetBinding),
}
#[derive(Debug, Clone, PartialEq)]
pub struct SignificanceBinding {
targets: Targets,
marks: SignificanceMarkInput,
facets: SignificanceFacetInput,
}
#[derive(Debug, Clone, PartialEq)]
#[expect(
clippy::large_enum_variant,
reason = "one owning batch has one or two original endpoint declarations"
)]
enum Targets {
Attached(SignificanceTargetInput),
Pairwise(SignificanceTargetInput, SignificanceTargetInput),
}
impl SignificanceBinding {
pub fn get_attached(&self) -> Option<&SignificanceTargetInput> {
match &self.targets {
Targets::Attached(target) => Some(target),
Targets::Pairwise(..) => None,
}
}
pub fn get_pairwise(&self) -> Option<(&SignificanceTargetInput, &SignificanceTargetInput)> {
match &self.targets {
Targets::Pairwise(left, right) => Some((left, right)),
Targets::Attached(_) => None,
}
}
pub fn marks(&self) -> &SignificanceMarkInput {
&self.marks
}
pub fn facets(&self) -> &SignificanceFacetInput {
&self.facets
}
}
#[derive(Debug, Clone, PartialEq)]
#[doc(hidden)]
pub struct SignificanceOrigin {
pub(crate) binding: Arc<SignificanceBinding>,
pub(crate) row: usize,
pub(crate) facet_overridden: bool,
}
struct Sequence<T> {
values: Vec<T>,
scalar: bool,
}
impl<T: Clone> Sequence<T> {
fn fixed(value: &T) -> Self {
Self {
values: vec![value.clone()],
scalar: true,
}
}
fn many(values: Vec<T>) -> Self {
Self {
values,
scalar: false,
}
}
fn shape(&self) -> (usize, bool) {
(self.values.len(), self.scalar)
}
fn at(&self, row: usize) -> T {
self.values[if self.scalar { 0 } else { row }].clone()
}
}
fn length(role: &str, expected: usize, actual: usize) -> Result<()> {
if expected == actual {
Ok(())
} else {
Err(Error::Data(
format!("{role}: expected {expected} result slots, got {actual}").into(),
))
}
}
fn categories(values: &CategoryValues, role: &str) -> Result<Vec<String>> {
crate::data::source::collect_source(values.iter().enumerate().map(|(slot, value)| {
let value = value.ok_or_else(|| {
Error::Data(format!("{role}: missing category at slot {slot}").into())
})?;
crate::data::source::copy_source_string(value)
}))
}
impl SignificanceTargetInput {
fn decode(&self) -> Result<Sequence<SignificanceTarget>> {
Ok(match self {
Self::Column(values) => Sequence::many(
raw_keys(values, "significance target")?
.into_iter()
.map(SignificanceTarget::category)
.collect(),
),
Self::CategorySeries(category, series) => {
let category = raw_keys(category, "significance category")?;
let series = raw_keys(series, "significance series")?;
length("significance series", category.len(), series.len())?;
Sequence::many(
category
.into_iter()
.zip(series)
.map(|(category, series)| {
SignificanceTarget::category_series(category, series)
})
.collect(),
)
}
Self::Fixed(target) => Sequence::fixed(target),
Self::Values(values) => Sequence::many(values.to_vec()),
})
}
}
impl SignificanceMarkInput {
fn original(self) -> Result<Self> {
match self {
Self::Categories { values, mapping } => {
let KeyValues::Strings(values) = values.key_values() else {
return Err(Error::Data(
"significance mark mapping requires string category keys".into(),
));
};
Ok(Self::Categories { values, mapping })
}
input => Ok(input),
}
}
fn decode(&self) -> Result<Sequence<SignificanceMark>> {
Ok(match self {
Self::PValues(values) => Sequence::many(crate::data::source::collect_source(
values.iter().enumerate().map(|(slot, value)| {
value.map(SignificanceMark::PValue).ok_or_else(|| {
Error::Data(
format!("significance p-values: missing value at slot {slot}").into(),
)
})
}),
)?),
Self::Categories { values, mapping } => {
let values = categories(values, "significance marks")?;
Sequence::many(crate::data::source::collect_source(values.iter().map(
|value| {
let mut matches = mapping.iter().filter(|(key, _)| key == value);
let mark = matches
.next()
.ok_or_else(|| {
Error::Data(
format!("significance marks: unmapped key {value:?}").into(),
)
})?
.1;
if matches.next().is_some() {
return Err(Error::Data(
format!("significance marks: duplicate map key {value:?}").into(),
));
}
Ok(mark)
},
))?)
}
Self::Fixed(mark) => Sequence::fixed(mark),
Self::Values(values) => Sequence::many(values.to_vec()),
})
}
}
fn raw_keys(values: &KeyValues, role: &str) -> Result<Vec<RawKey>> {
crate::data::source::collect_source((0..values.len()).map(|slot| {
let key = match values {
KeyValues::Strings(values) => values.get(slot).flatten().map(RawKey::from),
KeyValues::Raw(values) => values.get(slot).flatten().cloned(),
};
key.ok_or_else(|| Error::Data(format!("{role}: missing category at slot {slot}").into()))
}))
}
impl SignificanceFacetInput {
fn decode(&self) -> Result<Option<Sequence<FacetCell>>> {
Ok(Some(match self {
Self::Unfaceted => return Ok(None),
Self::Fixed(facet) => Sequence::fixed(facet),
Self::Values(facets) => Sequence::many(facets.to_vec()),
Self::Split(FacetBinding::Wrap(values)) => Sequence::many(
raw_keys(values, "significance facet")?
.into_iter()
.map(FacetCell::single)
.collect(),
),
Self::Split(FacetBinding::Grid { row, column }) => {
let row = raw_keys(row, "significance facet row")?;
let column = raw_keys(column, "significance facet column")?;
length("significance facet column", row.len(), column.len())?;
Sequence::many(
row.into_iter()
.zip(column)
.map(|(row, column)| FacetCell::grid(row, column))
.collect(),
)
}
}))
}
}
fn count(parts: &[(usize, bool)], facets: Option<&Sequence<FacetCell>>) -> Result<usize> {
let mut shapes = parts.to_vec();
shapes.extend(facets.map(Sequence::shape));
let count = shapes
.iter()
.find(|(_, scalar)| !scalar)
.map_or(1, |(length, _)| *length);
for (length_value, scalar) in shapes {
if !scalar {
length("significance", count, length_value)?;
}
}
Ok(count)
}
pub fn significance_attached(
target: SignificanceTargetInput,
marks: SignificanceMarkInput,
facets: SignificanceFacetInput,
) -> Result<Vec<Significance<Attached>>> {
let decoded_facets = facets.decode()?;
let decoded_target = target.decode()?;
let marks = marks.original()?;
let decoded_marks = marks.decode()?;
let count = count(
&[decoded_target.shape(), decoded_marks.shape()],
decoded_facets.as_ref(),
)?;
let binding = Arc::new(SignificanceBinding {
targets: Targets::Attached(target),
marks,
facets,
});
crate::data::source::collect_source((0..count).map(|row| {
let mut value = Significance::at(decoded_target.at(row), decoded_marks.at(row));
if let Some(facets) = &decoded_facets {
value = value.facet(facets.at(row));
}
Ok(value.with_origin(binding.clone(), row))
}))
}
pub fn significance_pairwise(
left: SignificanceTargetInput,
right: SignificanceTargetInput,
marks: SignificanceMarkInput,
facets: SignificanceFacetInput,
) -> Result<Vec<Significance<Pairwise>>> {
let decoded_facets = facets.decode()?;
let decoded_left = left.decode()?;
let decoded_right = right.decode()?;
let marks = marks.original()?;
let decoded_marks = marks.decode()?;
let count = count(
&[
decoded_left.shape(),
decoded_right.shape(),
decoded_marks.shape(),
],
decoded_facets.as_ref(),
)?;
let binding = Arc::new(SignificanceBinding {
targets: Targets::Pairwise(left, right),
marks,
facets,
});
crate::data::source::collect_source((0..count).map(|row| {
let mut value = Significance::between(
decoded_left.at(row),
decoded_right.at(row),
decoded_marks.at(row),
);
if let Some(facets) = &decoded_facets {
value = value.facet(facets.at(row));
}
Ok(value.with_origin(binding.clone(), row))
}))
}