use super::{binding::SignificanceOrigin, SignificanceBinding, SignificanceFacetInput};
use std::{marker::PhantomData, sync::Arc};
use crate::{data::RawKey, Error};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SignificanceMark {
PValue(f64),
NotSignificant,
OneStar,
TwoStars,
ThreeStars,
FourStars,
}
impl SignificanceMark {
pub(crate) fn glyph(self) -> Result<&'static str, Error> {
match self {
Self::PValue(value) if !value.is_finite() || !(0.0..=1.0).contains(&value) => {
Err(Error::Data(
format!("significance p-value must be finite and in [0, 1]; got {value}")
.into(),
))
}
Self::PValue(value) if value >= 0.05 => Ok("ns"),
Self::PValue(value) if value < 0.0001 => Ok("****"),
Self::PValue(value) if value < 0.001 => Ok("***"),
Self::PValue(value) if value < 0.01 => Ok("**"),
Self::PValue(_) | Self::OneStar => Ok("*"),
Self::NotSignificant => Ok("ns"),
Self::TwoStars => Ok("**"),
Self::ThreeStars => Ok("***"),
Self::FourStars => Ok("****"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SignificanceTarget {
Category(RawKey),
CategorySeries {
category: RawKey,
series: RawKey,
},
}
impl SignificanceTarget {
#[must_use]
pub fn category(value: impl Into<RawKey>) -> Self {
Self::Category(value.into())
}
#[must_use]
pub fn category_series(category: impl Into<RawKey>, series: impl Into<RawKey>) -> Self {
Self::CategorySeries {
category: category.into(),
series: series.into(),
}
}
pub fn get_category(&self) -> &RawKey {
match self {
Self::Category(category) | Self::CategorySeries { category, .. } => category,
}
}
pub fn get_series(&self) -> Option<&RawKey> {
match self {
Self::Category(_) => None,
Self::CategorySeries { series, .. } => Some(series),
}
}
}
impl From<String> for SignificanceTarget {
fn from(value: String) -> Self {
Self::category(value)
}
}
impl From<&str> for SignificanceTarget {
fn from(value: &str) -> Self {
Self::category(value)
}
}
impl From<RawKey> for SignificanceTarget {
fn from(value: RawKey) -> Self {
Self::category(value)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FacetCell {
layout: FacetCellLayout,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum FacetCellLayout {
Single(RawKey),
Grid { row: RawKey, column: RawKey },
}
impl FacetCell {
pub(crate) fn try_copy(&self) -> crate::Result<Self> {
let copy = |key: &RawKey| match key {
RawKey::String(level) => {
crate::data::source::copy_source_string(level).map(RawKey::String)
}
_ => Ok(key.clone()),
};
match &self.layout {
FacetCellLayout::Single(level) => Ok(Self::single(copy(level)?)),
FacetCellLayout::Grid { row, column } => Ok(Self::grid(copy(row)?, copy(column)?)),
}
}
pub fn get_single(&self) -> Option<&RawKey> {
match &self.layout {
FacetCellLayout::Single(level) => Some(level),
FacetCellLayout::Grid { .. } => None,
}
}
pub fn get_grid(&self) -> Option<(&RawKey, &RawKey)> {
match &self.layout {
FacetCellLayout::Grid { row, column } => Some((row, column)),
FacetCellLayout::Single(_) => None,
}
}
pub fn single_level(&self) -> Option<&str> {
match self.get_single()? {
RawKey::String(level) => Some(level),
_ => None,
}
}
pub fn grid_levels(&self) -> Option<(&str, &str)> {
match self.get_grid()? {
(RawKey::String(row), RawKey::String(column)) => Some((row, column)),
_ => None,
}
}
#[must_use]
pub fn single(level: impl Into<RawKey>) -> Self {
Self {
layout: FacetCellLayout::Single(level.into()),
}
}
#[must_use]
pub fn grid(row: impl Into<RawKey>, column: impl Into<RawKey>) -> Self {
Self {
layout: FacetCellLayout::Grid {
row: row.into(),
column: column.into(),
},
}
}
pub(crate) const fn dimensions(&self) -> usize {
match self.layout {
FacetCellLayout::Single(_) => 1,
FacetCellLayout::Grid { .. } => 2,
}
}
fn validate(&self) -> Result<(), Error> {
let key = |role, key: &RawKey| match key {
RawKey::String(value) => validate_text(role, value),
_ => Ok(()),
};
match &self.layout {
FacetCellLayout::Single(level) => key("facet level", level),
FacetCellLayout::Grid { row, column } => {
key("facet row level", row)?;
key("facet column level", column)
}
}
}
}
impl From<&str> for FacetCell {
fn from(level: &str) -> Self {
Self::single(level)
}
}
impl From<String> for FacetCell {
fn from(level: String) -> Self {
Self::single(level)
}
}
impl From<RawKey> for FacetCell {
fn from(level: RawKey) -> Self {
Self::single(level)
}
}
impl<R: Into<RawKey>, C: Into<RawKey>> From<(R, C)> for FacetCell {
fn from((row, column): (R, C)) -> Self {
Self::grid(row, column)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Attached;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Pairwise;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceAnnotation {
#[non_exhaustive]
Attached {
target: SignificanceTarget,
mark: SignificanceMark,
facet: Option<FacetCell>,
origin: Option<SignificanceOrigin>,
},
#[non_exhaustive]
Pairwise {
endpoint_a: SignificanceTarget,
endpoint_b: SignificanceTarget,
mark: SignificanceMark,
facet: Option<FacetCell>,
origin: Option<SignificanceOrigin>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct Significance<P> {
annotation: SignificanceAnnotation,
placement: PhantomData<P>,
}
impl Significance<Attached> {
#[must_use]
pub fn at(target: impl Into<SignificanceTarget>, mark: SignificanceMark) -> Self {
Self {
annotation: SignificanceAnnotation::Attached {
target: target.into(),
mark,
facet: None,
origin: None,
},
placement: PhantomData,
}
}
}
impl Significance<Pairwise> {
#[must_use]
pub fn between(
endpoint_a: impl Into<SignificanceTarget>,
endpoint_b: impl Into<SignificanceTarget>,
mark: SignificanceMark,
) -> Self {
Self {
annotation: SignificanceAnnotation::Pairwise {
endpoint_a: endpoint_a.into(),
endpoint_b: endpoint_b.into(),
mark,
facet: None,
origin: None,
},
placement: PhantomData,
}
}
}
impl<P> Significance<P> {
#[must_use]
pub fn facet(mut self, cell: FacetCell) -> Self {
*self.annotation.facet_mut() = Some(cell);
if let Some(origin) = self.annotation.origin_mut().as_mut() {
origin.facet_overridden = true;
}
self
}
pub(crate) fn with_origin(mut self, binding: Arc<SignificanceBinding>, row: usize) -> Self {
*self.annotation.origin_mut() = Some(SignificanceOrigin {
binding,
row,
facet_overridden: false,
});
self
}
pub fn get_annotation(&self) -> &SignificanceAnnotation {
&self.annotation
}
pub(crate) fn into_annotation(self) -> SignificanceAnnotation {
self.annotation
}
}
impl SignificanceAnnotation {
pub const fn mark(&self) -> SignificanceMark {
match self {
Self::Attached { mark, .. } | Self::Pairwise { mark, .. } => *mark,
}
}
pub fn at_target(&self) -> Option<&SignificanceTarget> {
match self {
Self::Attached { target, .. } => Some(target),
Self::Pairwise { .. } => None,
}
}
pub fn endpoints(&self) -> Option<(&SignificanceTarget, &SignificanceTarget)> {
match self {
Self::Attached { .. } => None,
Self::Pairwise {
endpoint_a,
endpoint_b,
..
} => Some((endpoint_a, endpoint_b)),
}
}
pub const fn facet_cell(&self) -> Option<&FacetCell> {
match self {
Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet.as_ref(),
}
}
pub fn binding(&self) -> Option<&SignificanceBinding> {
self.origin().map(|origin| origin.binding.as_ref())
}
pub fn binding_row(&self) -> Option<usize> {
self.origin().map(|origin| origin.row)
}
pub fn get_significance_split(&self) -> Option<&crate::layout::FacetBinding> {
let origin = self.origin()?;
if origin.facet_overridden {
return None;
}
match origin.binding.facets() {
SignificanceFacetInput::Split(binding) => Some(binding),
_ => None,
}
}
fn origin(&self) -> Option<&SignificanceOrigin> {
match self {
Self::Attached { origin, .. } | Self::Pairwise { origin, .. } => origin.as_ref(),
}
}
fn origin_mut(&mut self) -> &mut Option<SignificanceOrigin> {
match self {
Self::Attached { origin, .. } | Self::Pairwise { origin, .. } => origin,
}
}
pub(crate) fn validate(&self) -> Result<(), Error> {
self.mark().glyph()?;
match self {
Self::Attached { target, .. } => validate_target(target)?,
Self::Pairwise {
endpoint_a,
endpoint_b,
..
} => {
validate_target(endpoint_a)?;
validate_target(endpoint_b)?;
if endpoint_a == endpoint_b {
return Err(Error::Data(
"significance comparison endpoints must be different".into(),
));
}
}
}
if let Some(cell) = self.facet_cell() {
cell.validate()?;
}
Ok(())
}
fn facet_mut(&mut self) -> &mut Option<FacetCell> {
match self {
Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet,
}
}
}
fn validate_target(target: &SignificanceTarget) -> Result<(), Error> {
if let RawKey::String(category) = target.get_category() {
validate_text("target category", category)?;
}
if let Some(RawKey::String(series)) = target.get_series() {
validate_text("target series", series)?;
}
Ok(())
}
fn validate_text(role: &str, value: &str) -> Result<(), Error> {
if value.trim().is_empty() || value.trim() != value || value.chars().any(char::is_control) {
return Err(Error::Data(
format!(
"significance {role} must be nonempty, trimmed, and free of control characters"
)
.into(),
));
}
Ok(())
}