use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use crate::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LabelMode {
Humanized,
Raw,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Labels {
mode: LabelMode,
aliases: Option<Arc<BTreeMap<String, String>>>,
key_aliases: Option<Arc<HashMap<crate::data::RawKey, BTreeMap<String, String>>>>,
captured: Option<Arc<BTreeMap<String, CapturedLabel>>>,
positions: Option<Arc<BTreeMap<(usize, usize), String>>>,
grid_axes: [Option<Arc<[String]>>; 2],
grid_rows: Option<Arc<GridRowLabels>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct CapturedLabel {
key: Option<crate::data::RawKey>,
display: String,
position: Option<(usize, usize)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct GridRowLabels {
values: crate::CategoryValues,
displays: Vec<String>,
}
impl Default for Labels {
fn default() -> Self {
Self::humanized()
}
}
impl Labels {
#[must_use]
pub const fn humanized() -> Self {
Self {
mode: LabelMode::Humanized,
aliases: None,
key_aliases: None,
captured: None,
positions: None,
grid_axes: [None, None],
grid_rows: None,
}
}
#[must_use]
pub const fn raw() -> Self {
Self {
mode: LabelMode::Raw,
aliases: None,
key_aliases: None,
captured: None,
positions: None,
grid_axes: [None, None],
grid_rows: None,
}
}
#[must_use]
pub const fn is_humanized(&self) -> bool {
matches!(self.mode, LabelMode::Humanized)
}
pub fn get_aliases(&self) -> Option<impl ExactSizeIterator<Item = (&str, &str)> + '_> {
if self.aliases.is_none() && self.captured.is_none() {
return None;
}
let keys = self
.aliases
.iter()
.flat_map(|aliases| aliases.keys())
.chain(self.captured.iter().flat_map(|captured| captured.keys()))
.collect::<std::collections::BTreeSet<_>>();
Some(
keys.into_iter()
.map(|raw| (raw.as_str(), self.alias_display(raw).expect("actual alias"))),
)
}
pub(crate) fn authored_aliases(&self) -> Option<impl Iterator<Item = (&str, &str)> + '_> {
self.aliases.as_ref().map(|aliases| {
aliases
.iter()
.map(|(raw, display)| (raw.as_str(), display.as_str()))
})
}
pub(crate) fn captured_identity(&self, token: &str) -> Option<(&crate::data::RawKey, &str)> {
let entry = self.captured.as_ref()?.get(token)?;
Some((entry.key.as_ref()?, entry.display.as_str()))
}
pub(crate) fn authored_key_aliases(
&self,
) -> impl Iterator<Item = (&crate::data::RawKey, &str, &str)> {
self.key_aliases.iter().flat_map(|aliases| {
aliases.iter().flat_map(|(key, values)| {
values
.iter()
.map(move |(name, label)| (key, name.as_str(), label.as_str()))
})
})
}
pub(crate) fn key_alias(
mut self,
key: crate::data::RawKey,
name: String,
label: String,
) -> Self {
Arc::make_mut(
self.key_aliases
.get_or_insert_with(|| Arc::new(HashMap::new())),
)
.entry(key)
.or_default()
.insert(name, label);
self
}
#[must_use]
pub fn alias(mut self, raw: impl Into<String>, display: impl Into<String>) -> Self {
Arc::make_mut(
self.aliases
.get_or_insert_with(|| Arc::new(BTreeMap::new())),
)
.insert(raw.into(), display.into());
self
}
#[must_use]
pub fn aliases<I, R, D>(mut self, aliases: I) -> Self
where
I: IntoIterator<Item = (R, D)>,
R: Into<String>,
D: Into<String>,
{
for (raw, display) in aliases {
self = self.alias(raw, display);
}
self
}
#[doc(hidden)]
#[must_use]
pub fn capture_alias(
mut self,
raw: impl Into<String>,
key: Option<crate::data::RawKey>,
display: impl Into<String>,
) -> Self {
Arc::make_mut(
self.captured
.get_or_insert_with(|| Arc::new(BTreeMap::new())),
)
.insert(
raw.into(),
CapturedLabel {
key,
display: display.into(),
position: None,
},
);
self
}
#[doc(hidden)]
#[must_use]
pub fn capture_grid_label(
mut self,
raw: impl Into<String>,
axis: usize,
index: usize,
display: impl Into<String>,
) -> Self {
Arc::make_mut(
self.captured
.get_or_insert_with(|| Arc::new(BTreeMap::new())),
)
.insert(
raw.into(),
CapturedLabel {
key: None,
display: display.into(),
position: Some((axis, index)),
},
);
self
}
pub(crate) fn captured_position(&self, token: &str) -> Option<(usize, usize)> {
self.captured.as_ref()?.get(token)?.position
}
pub(crate) fn authored_positions(&self) -> impl Iterator<Item = ((usize, usize), &str)> {
self.positions.iter().flat_map(|values| {
values
.iter()
.map(|(position, label)| (*position, label.as_str()))
})
}
pub(crate) fn position_alias(mut self, axis: usize, index: usize, label: String) -> Self {
Arc::make_mut(
self.positions
.get_or_insert_with(|| Arc::new(BTreeMap::new())),
)
.insert((axis, index), label);
self
}
fn clear_grid_axis(&mut self, axis: usize) {
self.grid_axes[axis] = None;
if let Some(aliases) = &mut self.positions {
Arc::make_mut(aliases).retain(|(owner, _), _| *owner != axis);
}
if let (Some(aliases), Some(captured)) = (&mut self.aliases, &self.captured) {
Arc::make_mut(aliases).retain(|token, _| {
captured
.get(token)
.and_then(|entry| entry.position)
.is_none_or(|(owner, _)| owner != axis)
});
}
if axis == 0 {
self.grid_rows = None;
}
}
#[doc(hidden)]
#[must_use]
pub fn grid_axis_labels(mut self, axis: usize, labels: Vec<String>) -> Self {
self.clear_grid_axis(axis);
self.grid_axes[axis] = Some(labels.into());
self
}
#[doc(hidden)]
pub fn bind_grid_rows(
mut self,
values: crate::CategoryValues,
displays: Vec<String>,
) -> crate::Result<Self> {
self.clear_grid_axis(0);
self.restore_grid_rows(values, displays)
}
pub(crate) fn restore_grid_rows(
mut self,
values: crate::CategoryValues,
displays: Vec<String>,
) -> crate::Result<Self> {
if values.len() != displays.len()
|| (0..values.len()).any(|slot| values.is_valid(slot) != Some(true))
{
return Err(Error::Data(
"grid row label values must align and be present".into(),
));
}
self.grid_rows = Some(Arc::new(GridRowLabels { values, displays }));
Ok(self)
}
pub(crate) fn grid_axis_values(&self, axis: usize) -> Option<&[String]> {
self.grid_axes[axis].as_deref()
}
pub(crate) fn validate_grid_labels(&self, shape: &[usize]) -> crate::Result<()> {
for (axis, labels) in self.grid_axes.iter().enumerate() {
if let Some(labels) = labels {
if shape.get(axis) != Some(&labels.len()) {
return Err(Error::Data(
"literal grid labels must match the actual axis length".into(),
));
}
}
}
for ((axis, index), _) in self.authored_positions() {
if shape.get(axis).is_none_or(|extent| index >= *extent) {
return Err(Error::Data(
"grid display position is outside its actual axis".into(),
));
}
}
Ok(())
}
pub(crate) fn grid_row_values(&self) -> Option<&crate::CategoryValues> {
self.grid_rows.as_ref().map(|rows| &rows.values)
}
pub(crate) fn captured_display(&self, raw: &str) -> Option<&str> {
self.captured
.as_ref()?
.get(raw)
.map(|entry| entry.display.as_str())
}
pub(crate) fn with_captured_aliases_from(mut self, source: &Self) -> Self {
if let Some(captured) = &mut self.captured {
if let Some(source) = &source.captured {
if !Arc::ptr_eq(captured, source) {
let captured = Arc::make_mut(captured);
for (raw, entry) in source.iter() {
captured.entry(raw.clone()).or_insert_with(|| entry.clone());
}
}
}
} else {
self.captured.clone_from(&source.captured);
}
self
}
pub(crate) fn for_captured_source(&self, source: &Self) -> Self {
Self {
mode: self.mode,
aliases: self.aliases.clone(),
key_aliases: self.key_aliases.clone(),
captured: source.captured.clone(),
positions: self.positions.clone(),
grid_axes: self.grid_axes.clone(),
grid_rows: None,
}
}
fn alias_display(&self, raw: &str) -> Option<&str> {
if let Some(display) = self.aliases.as_ref().and_then(|aliases| aliases.get(raw)) {
return Some(display);
}
let capture = self.captured.as_ref()?.get(raw)?;
if let Some((axis, index)) = capture.position {
if let Some(label) = self
.positions
.as_ref()
.and_then(|values| values.get(&(axis, index)))
{
return Some(label);
}
if let Some(label) = self.grid_axes[axis]
.as_ref()
.and_then(|labels| labels.get(index))
{
return Some(label);
}
if axis == 0 {
if let Some(label) = self
.grid_rows
.as_ref()
.and_then(|rows| rows.displays.get(index))
{
return Some(label);
}
}
}
if let Some(aliases) = capture
.key
.as_ref()
.and_then(|key| self.key_aliases.as_ref()?.get(key))
{
if let Some(label) = aliases.get(&capture.display) {
return Some(label);
}
}
if let Some(crate::data::RawKey::String(original)) = &capture.key {
if let Some(alias) = self
.aliases
.as_ref()
.and_then(|aliases| aliases.get(original))
{
return Some(alias);
}
}
Some(&capture.display)
}
pub fn resolve(&self, raw: &str) -> Result<String, Error> {
let display = if let Some(alias) = self.alias_display(raw) {
copy_label(alias)
} else if self.mode == LabelMode::Humanized {
humanize(raw)
} else {
copy_label(raw)
}?;
crate::text::validate_for(&display, "label")?;
Ok(display)
}
pub(crate) fn resolve_domain<'a>(
&self,
domain: &str,
raw_labels: impl IntoIterator<Item = &'a str>,
) -> Result<Vec<String>, Error> {
let mut identities = Vec::new();
let mut resolved = Vec::new();
let raw_labels = raw_labels.into_iter();
let minimum = raw_labels.size_hint().0;
crate::data::source::reserve_source(&mut identities, minimum)?;
crate::data::source::reserve_source(&mut resolved, minimum)?;
for raw in raw_labels {
crate::data::source::reserve_source(&mut identities, 1)?;
crate::data::source::reserve_source(&mut resolved, 1)?;
let display = self.resolve(raw)?;
let mut collision = None;
for (&previous, prior) in identities.iter().zip(&resolved) {
if prior == &display && previous != raw {
collision = Some(previous);
break;
}
}
if let Some(previous) = collision {
let alias_guidance = if self.aliases.as_ref().is_some_and(|aliases| {
aliases.contains_key(previous) || aliases.contains_key(raw)
}) {
"change or remove the colliding aliases; Labels::raw() does not override explicit aliases"
} else {
"configure an explicit alias or use Labels::raw()"
};
return Err(Error::Render(format!(
"label collision in {domain}: raw identities {previous:?} and {raw:?} both resolve to {display:?}; {alias_guidance}"
).into()));
}
identities.push(raw);
resolved.push(display);
}
Ok(resolved)
}
}
fn copy_label(raw: &str) -> Result<String, Error> {
let mut output = String::new();
reserve_label(&mut output, raw.len())?;
output.push_str(raw);
Ok(output)
}
fn reserve_label(output: &mut String, count: usize) -> Result<(), Error> {
crate::data::source::reserve_source_string(output, count)
}
fn humanize(raw: &str) -> Result<String, Error> {
let mut split = String::new();
reserve_label(
&mut split,
raw.len()
.checked_mul(2)
.ok_or_else(|| Error::Render("humanized label length overflow".into()))?,
)?;
let mut chars = raw.chars().peekable();
let mut previous = None;
let mut last_was_space = true;
while let Some(character) = chars.next() {
let next = chars.peek().copied();
let prior = previous.replace(character);
if matches!(character, '_' | '-' | '.' | ' ' | '\t' | '\n' | '\r') {
if !last_was_space {
split.push(' ');
last_was_space = true;
}
continue;
}
if should_split_before(prior, character, next) && !last_was_space {
split.push(' ');
}
split.push(character);
last_was_space = false;
}
let mut output = String::new();
for (index, word) in split.split_whitespace().enumerate() {
let acronym = acronym(word);
reserve_label(
&mut output,
word.len()
.checked_add(12)
.ok_or_else(|| Error::Render("humanized word length overflow".into()))?,
)?;
if index != 0 {
output.push(' ');
}
if let Some(acronym) = acronym {
output.push_str(acronym);
} else if word.len() > 1 && word.bytes().all(|c| c.is_ascii_uppercase()) {
output.push_str(word);
} else {
for (offset, character) in word.chars().enumerate() {
let character = character.to_ascii_lowercase();
if index == 0 && offset == 0 {
output.extend(character.to_uppercase());
} else {
output.push(character);
}
}
}
}
if output.is_empty() {
copy_label(raw)
} else {
Ok(output)
}
}
fn should_split_before(previous: Option<char>, current: char, next: Option<char>) -> bool {
let Some(previous) = previous else {
return false;
};
(previous.is_ascii_lowercase() && current.is_ascii_uppercase())
|| (previous.is_ascii_digit() && current.is_ascii_alphabetic())
|| (previous.is_ascii_alphabetic() && current.is_ascii_digit())
|| (previous.is_ascii_uppercase()
&& current.is_ascii_uppercase()
&& next.is_some_and(|character| character.is_ascii_lowercase()))
}
fn acronym(word: &str) -> Option<&'static str> {
[
("ci", "CI"),
("dna", "DNA"),
("hwe", "HWE"),
("id", "ID"),
("ms", "MS"),
("mz", "m/z"),
("m/z", "m/z"),
("pca", "PCA"),
("qc", "QC"),
("rna", "RNA"),
("tsne", "t-SNE"),
("t-sne", "t-SNE"),
("umap", "UMAP"),
("x", "X"),
("y", "Y"),
("z", "Z"),
]
.into_iter()
.find_map(|(raw, display)| word.eq_ignore_ascii_case(raw).then_some(display))
}