Skip to main content

lichtung_plot/
labels.rs

1//! Presentation policy for automatically sourced plot labels.
2
3use std::collections::{BTreeMap, HashMap};
4use std::sync::Arc;
5
6use crate::Error;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9enum LabelMode {
10    Humanized,
11    Raw,
12}
13
14/// Immutable presentation rules for labels inferred from data identities.
15///
16/// Explicit chart text such as axis-label overrides, titles, and captions is
17/// always rendered verbatim. Aliases take precedence over the selected
18/// humanized or raw fallback.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Labels {
21    mode: LabelMode,
22    aliases: Option<Arc<BTreeMap<String, String>>>,
23    key_aliases: Option<Arc<HashMap<crate::data::RawKey, BTreeMap<String, String>>>>,
24    captured: Option<Arc<BTreeMap<String, CapturedLabel>>>,
25    positions: Option<Arc<BTreeMap<(usize, usize), String>>>,
26    grid_axes: [Option<Arc<[String]>>; 2],
27    grid_rows: Option<Arc<GridRowLabels>>,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31struct CapturedLabel {
32    key: Option<crate::data::RawKey>,
33    display: String,
34    position: Option<(usize, usize)>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38struct GridRowLabels {
39    values: crate::CategoryValues,
40    displays: Vec<String>,
41}
42
43impl Default for Labels {
44    fn default() -> Self {
45        Self::humanized()
46    }
47}
48
49impl Labels {
50    /// Humanize automatically sourced column names and categorical values.
51    #[must_use]
52    pub const fn humanized() -> Self {
53        Self {
54            mode: LabelMode::Humanized,
55            aliases: None,
56            key_aliases: None,
57            captured: None,
58            positions: None,
59            grid_axes: [None, None],
60            grid_rows: None,
61        }
62    }
63
64    /// Render automatically sourced labels exactly as represented by the plot data.
65    #[must_use]
66    pub const fn raw() -> Self {
67        Self {
68            mode: LabelMode::Raw,
69            aliases: None,
70            key_aliases: None,
71            captured: None,
72            positions: None,
73            grid_axes: [None, None],
74            grid_rows: None,
75        }
76    }
77
78    /// Whether automatically sourced labels use the humanized fallback.
79    #[must_use]
80    pub const fn is_humanized(&self) -> bool {
81        matches!(self.mode, LabelMode::Humanized)
82    }
83
84    /// Configured alias projections in raw-key order, before text validation.
85    ///
86    /// `None` preserves the absence of an aliases collection. Reading this view
87    /// neither normalizes display text nor checks a complete label domain.
88    pub fn get_aliases(&self) -> Option<impl ExactSizeIterator<Item = (&str, &str)> + '_> {
89        if self.aliases.is_none() && self.captured.is_none() {
90            return None;
91        }
92        let keys = self
93            .aliases
94            .iter()
95            .flat_map(|aliases| aliases.keys())
96            .chain(self.captured.iter().flat_map(|captured| captured.keys()))
97            .collect::<std::collections::BTreeSet<_>>();
98        Some(
99            keys.into_iter()
100                .map(|raw| (raw.as_str(), self.alias_display(raw).expect("actual alias"))),
101        )
102    }
103
104    pub(crate) fn authored_aliases(&self) -> Option<impl Iterator<Item = (&str, &str)> + '_> {
105        self.aliases.as_ref().map(|aliases| {
106            aliases
107                .iter()
108                .map(|(raw, display)| (raw.as_str(), display.as_str()))
109        })
110    }
111
112    pub(crate) fn captured_identity(&self, token: &str) -> Option<(&crate::data::RawKey, &str)> {
113        let entry = self.captured.as_ref()?.get(token)?;
114        Some((entry.key.as_ref()?, entry.display.as_str()))
115    }
116
117    pub(crate) fn authored_key_aliases(
118        &self,
119    ) -> impl Iterator<Item = (&crate::data::RawKey, &str, &str)> {
120        self.key_aliases.iter().flat_map(|aliases| {
121            aliases.iter().flat_map(|(key, values)| {
122                values
123                    .iter()
124                    .map(move |(name, label)| (key, name.as_str(), label.as_str()))
125            })
126        })
127    }
128
129    pub(crate) fn key_alias(
130        mut self,
131        key: crate::data::RawKey,
132        name: String,
133        label: String,
134    ) -> Self {
135        Arc::make_mut(
136            self.key_aliases
137                .get_or_insert_with(|| Arc::new(HashMap::new())),
138        )
139        .entry(key)
140        .or_default()
141        .insert(name, label);
142        self
143    }
144
145    /// Add one exact raw-identity to display-label mapping.
146    #[must_use]
147    pub fn alias(mut self, raw: impl Into<String>, display: impl Into<String>) -> Self {
148        Arc::make_mut(
149            self.aliases
150                .get_or_insert_with(|| Arc::new(BTreeMap::new())),
151        )
152        .insert(raw.into(), display.into());
153        self
154    }
155
156    /// Add exact raw-identity to display-label mappings.
157    #[must_use]
158    pub fn aliases<I, R, D>(mut self, aliases: I) -> Self
159    where
160        I: IntoIterator<Item = (R, D)>,
161        R: Into<String>,
162        D: Into<String>,
163    {
164        for (raw, display) in aliases {
165            self = self.alias(raw, display);
166        }
167        self
168    }
169
170    /// Preserve the actual binding-time projection independently of authored aliases.
171    #[doc(hidden)]
172    #[must_use]
173    pub fn capture_alias(
174        mut self,
175        raw: impl Into<String>,
176        key: Option<crate::data::RawKey>,
177        display: impl Into<String>,
178    ) -> Self {
179        Arc::make_mut(
180            self.captured
181                .get_or_insert_with(|| Arc::new(BTreeMap::new())),
182        )
183        .insert(
184            raw.into(),
185            CapturedLabel {
186                key,
187                display: display.into(),
188                position: None,
189            },
190        );
191        self
192    }
193
194    /// Capture the default display of a genuine grid position.
195    #[doc(hidden)]
196    #[must_use]
197    pub fn capture_grid_label(
198        mut self,
199        raw: impl Into<String>,
200        axis: usize,
201        index: usize,
202        display: impl Into<String>,
203    ) -> Self {
204        Arc::make_mut(
205            self.captured
206                .get_or_insert_with(|| Arc::new(BTreeMap::new())),
207        )
208        .insert(
209            raw.into(),
210            CapturedLabel {
211                key: None,
212                display: display.into(),
213                position: Some((axis, index)),
214            },
215        );
216        self
217    }
218
219    pub(crate) fn captured_position(&self, token: &str) -> Option<(usize, usize)> {
220        self.captured.as_ref()?.get(token)?.position
221    }
222
223    pub(crate) fn authored_positions(&self) -> impl Iterator<Item = ((usize, usize), &str)> {
224        self.positions.iter().flat_map(|values| {
225            values
226                .iter()
227                .map(|(position, label)| (*position, label.as_str()))
228        })
229    }
230
231    pub(crate) fn position_alias(mut self, axis: usize, index: usize, label: String) -> Self {
232        Arc::make_mut(
233            self.positions
234                .get_or_insert_with(|| Arc::new(BTreeMap::new())),
235        )
236        .insert((axis, index), label);
237        self
238    }
239
240    fn clear_grid_axis(&mut self, axis: usize) {
241        self.grid_axes[axis] = None;
242        if let Some(aliases) = &mut self.positions {
243            Arc::make_mut(aliases).retain(|(owner, _), _| *owner != axis);
244        }
245        if let (Some(aliases), Some(captured)) = (&mut self.aliases, &self.captured) {
246            Arc::make_mut(aliases).retain(|token, _| {
247                captured
248                    .get(token)
249                    .and_then(|entry| entry.position)
250                    .is_none_or(|(owner, _)| owner != axis)
251            });
252        }
253        if axis == 0 {
254            self.grid_rows = None;
255        }
256    }
257
258    /// Assign literal display labels to the actual grid axis positions.
259    #[doc(hidden)]
260    #[must_use]
261    pub fn grid_axis_labels(mut self, axis: usize, labels: Vec<String>) -> Self {
262        self.clear_grid_axis(axis);
263        self.grid_axes[axis] = Some(labels.into());
264        self
265    }
266
267    /// Keep the original row-label binding independently of the resolved text.
268    #[doc(hidden)]
269    pub fn bind_grid_rows(
270        mut self,
271        values: crate::CategoryValues,
272        displays: Vec<String>,
273    ) -> crate::Result<Self> {
274        self.clear_grid_axis(0);
275        self.restore_grid_rows(values, displays)
276    }
277
278    pub(crate) fn restore_grid_rows(
279        mut self,
280        values: crate::CategoryValues,
281        displays: Vec<String>,
282    ) -> crate::Result<Self> {
283        if values.len() != displays.len()
284            || (0..values.len()).any(|slot| values.is_valid(slot) != Some(true))
285        {
286            return Err(Error::Data(
287                "grid row label values must align and be present".into(),
288            ));
289        }
290        self.grid_rows = Some(Arc::new(GridRowLabels { values, displays }));
291        Ok(self)
292    }
293
294    pub(crate) fn grid_axis_values(&self, axis: usize) -> Option<&[String]> {
295        self.grid_axes[axis].as_deref()
296    }
297
298    pub(crate) fn validate_grid_labels(&self, shape: &[usize]) -> crate::Result<()> {
299        for (axis, labels) in self.grid_axes.iter().enumerate() {
300            if let Some(labels) = labels {
301                if shape.get(axis) != Some(&labels.len()) {
302                    return Err(Error::Data(
303                        "literal grid labels must match the actual axis length".into(),
304                    ));
305                }
306            }
307        }
308        for ((axis, index), _) in self.authored_positions() {
309            if shape.get(axis).is_none_or(|extent| index >= *extent) {
310                return Err(Error::Data(
311                    "grid display position is outside its actual axis".into(),
312                ));
313            }
314        }
315        Ok(())
316    }
317
318    pub(crate) fn grid_row_values(&self) -> Option<&crate::CategoryValues> {
319        self.grid_rows.as_ref().map(|rows| &rows.values)
320    }
321
322    pub(crate) fn captured_display(&self, raw: &str) -> Option<&str> {
323        self.captured
324            .as_ref()?
325            .get(raw)
326            .map(|entry| entry.display.as_str())
327    }
328
329    /// Retain captured identities when replacing an authored label policy.
330    pub(crate) fn with_captured_aliases_from(mut self, source: &Self) -> Self {
331        if let Some(captured) = &mut self.captured {
332            if let Some(source) = &source.captured {
333                if !Arc::ptr_eq(captured, source) {
334                    let captured = Arc::make_mut(captured);
335                    for (raw, entry) in source.iter() {
336                        captured.entry(raw.clone()).or_insert_with(|| entry.clone());
337                    }
338                }
339            }
340        } else {
341            self.captured.clone_from(&source.captured);
342        }
343        self
344    }
345
346    /// Apply this authored parent policy to one actual captured child.
347    pub(crate) fn for_captured_source(&self, source: &Self) -> Self {
348        Self {
349            mode: self.mode,
350            aliases: self.aliases.clone(),
351            key_aliases: self.key_aliases.clone(),
352            captured: source.captured.clone(),
353            positions: self.positions.clone(),
354            grid_axes: self.grid_axes.clone(),
355            grid_rows: None,
356        }
357    }
358
359    fn alias_display(&self, raw: &str) -> Option<&str> {
360        if let Some(display) = self.aliases.as_ref().and_then(|aliases| aliases.get(raw)) {
361            return Some(display);
362        }
363        let capture = self.captured.as_ref()?.get(raw)?;
364        if let Some((axis, index)) = capture.position {
365            if let Some(label) = self
366                .positions
367                .as_ref()
368                .and_then(|values| values.get(&(axis, index)))
369            {
370                return Some(label);
371            }
372            if let Some(label) = self.grid_axes[axis]
373                .as_ref()
374                .and_then(|labels| labels.get(index))
375            {
376                return Some(label);
377            }
378            if axis == 0 {
379                if let Some(label) = self
380                    .grid_rows
381                    .as_ref()
382                    .and_then(|rows| rows.displays.get(index))
383                {
384                    return Some(label);
385                }
386            }
387        }
388        if let Some(aliases) = capture
389            .key
390            .as_ref()
391            .and_then(|key| self.key_aliases.as_ref()?.get(key))
392        {
393            if let Some(label) = aliases.get(&capture.display) {
394                return Some(label);
395            }
396        }
397        if let Some(crate::data::RawKey::String(original)) = &capture.key {
398            if let Some(alias) = self
399                .aliases
400                .as_ref()
401                .and_then(|aliases| aliases.get(original))
402            {
403                return Some(alias);
404            }
405        }
406        Some(&capture.display)
407    }
408
409    /// Resolve one raw name with alias precedence and the selected fallback.
410    ///
411    /// The result uses the shared display-text syntax, preserving explicit alias
412    /// whitespace and mandatory breaks. Collisions between different identities
413    /// are checked when the renderer resolves their complete semantic domain.
414    ///
415    /// ```
416    /// use lichtung_plot::formatting::Labels;
417    /// let labels = Labels::humanized().alias("mean_score", " Score\r\n(points) ");
418    /// assert_eq!(labels.resolve("mean_score")?, " Score\r\n(points) ");
419    /// assert_eq!(labels.resolve("control_group")?, "Control group");
420    /// assert_eq!(Labels::raw().resolve("control_group")?, "control_group");
421    /// assert!(labels.alias("bad", "a\tb").resolve("bad").is_err());
422    /// # Ok::<(), lichtung_plot::Error>(())
423    /// ```
424    pub fn resolve(&self, raw: &str) -> Result<String, Error> {
425        let display = if let Some(alias) = self.alias_display(raw) {
426            copy_label(alias)
427        } else if self.mode == LabelMode::Humanized {
428            humanize(raw)
429        } else {
430            copy_label(raw)
431        }?;
432        crate::text::validate_for(&display, "label")?;
433        Ok(display)
434    }
435
436    pub(crate) fn resolve_domain<'a>(
437        &self,
438        domain: &str,
439        raw_labels: impl IntoIterator<Item = &'a str>,
440    ) -> Result<Vec<String>, Error> {
441        let mut identities = Vec::new();
442        let mut resolved = Vec::new();
443        let raw_labels = raw_labels.into_iter();
444        let minimum = raw_labels.size_hint().0;
445        crate::data::source::reserve_source(&mut identities, minimum)?;
446        crate::data::source::reserve_source(&mut resolved, minimum)?;
447        for raw in raw_labels {
448            crate::data::source::reserve_source(&mut identities, 1)?;
449            crate::data::source::reserve_source(&mut resolved, 1)?;
450            let display = self.resolve(raw)?;
451            let mut collision = None;
452            for (&previous, prior) in identities.iter().zip(&resolved) {
453                if prior == &display && previous != raw {
454                    collision = Some(previous);
455                    break;
456                }
457            }
458            if let Some(previous) = collision {
459                let alias_guidance = if self.aliases.as_ref().is_some_and(|aliases| {
460                    aliases.contains_key(previous) || aliases.contains_key(raw)
461                }) {
462                    "change or remove the colliding aliases; Labels::raw() does not override explicit aliases"
463                } else {
464                    "configure an explicit alias or use Labels::raw()"
465                };
466                return Err(Error::Render(format!(
467                    "label collision in {domain}: raw identities {previous:?} and {raw:?} both resolve to {display:?}; {alias_guidance}"
468                ).into()));
469            }
470            identities.push(raw);
471            resolved.push(display);
472        }
473        Ok(resolved)
474    }
475}
476
477fn copy_label(raw: &str) -> Result<String, Error> {
478    let mut output = String::new();
479    reserve_label(&mut output, raw.len())?;
480    output.push_str(raw);
481    Ok(output)
482}
483
484fn reserve_label(output: &mut String, count: usize) -> Result<(), Error> {
485    crate::data::source::reserve_source_string(output, count)
486}
487
488fn humanize(raw: &str) -> Result<String, Error> {
489    let mut split = String::new();
490    reserve_label(
491        &mut split,
492        raw.len()
493            .checked_mul(2)
494            .ok_or_else(|| Error::Render("humanized label length overflow".into()))?,
495    )?;
496    let mut chars = raw.chars().peekable();
497    let mut previous = None;
498    let mut last_was_space = true;
499    while let Some(character) = chars.next() {
500        let next = chars.peek().copied();
501        let prior = previous.replace(character);
502        if matches!(character, '_' | '-' | '.' | ' ' | '\t' | '\n' | '\r') {
503            if !last_was_space {
504                split.push(' ');
505                last_was_space = true;
506            }
507            continue;
508        }
509        if should_split_before(prior, character, next) && !last_was_space {
510            split.push(' ');
511        }
512        split.push(character);
513        last_was_space = false;
514    }
515    let mut output = String::new();
516
517    for (index, word) in split.split_whitespace().enumerate() {
518        let acronym = acronym(word);
519        reserve_label(
520            &mut output,
521            word.len()
522                .checked_add(12)
523                .ok_or_else(|| Error::Render("humanized word length overflow".into()))?,
524        )?;
525        if index != 0 {
526            output.push(' ');
527        }
528        if let Some(acronym) = acronym {
529            output.push_str(acronym);
530        } else if word.len() > 1 && word.bytes().all(|c| c.is_ascii_uppercase()) {
531            output.push_str(word);
532        } else {
533            for (offset, character) in word.chars().enumerate() {
534                let character = character.to_ascii_lowercase();
535                if index == 0 && offset == 0 {
536                    output.extend(character.to_uppercase());
537                } else {
538                    output.push(character);
539                }
540            }
541        }
542    }
543    if output.is_empty() {
544        copy_label(raw)
545    } else {
546        Ok(output)
547    }
548}
549
550fn should_split_before(previous: Option<char>, current: char, next: Option<char>) -> bool {
551    let Some(previous) = previous else {
552        return false;
553    };
554    (previous.is_ascii_lowercase() && current.is_ascii_uppercase())
555        || (previous.is_ascii_digit() && current.is_ascii_alphabetic())
556        || (previous.is_ascii_alphabetic() && current.is_ascii_digit())
557        || (previous.is_ascii_uppercase()
558            && current.is_ascii_uppercase()
559            && next.is_some_and(|character| character.is_ascii_lowercase()))
560}
561
562fn acronym(word: &str) -> Option<&'static str> {
563    [
564        ("ci", "CI"),
565        ("dna", "DNA"),
566        ("hwe", "HWE"),
567        ("id", "ID"),
568        ("ms", "MS"),
569        ("mz", "m/z"),
570        ("m/z", "m/z"),
571        ("pca", "PCA"),
572        ("qc", "QC"),
573        ("rna", "RNA"),
574        ("tsne", "t-SNE"),
575        ("t-sne", "t-SNE"),
576        ("umap", "UMAP"),
577        ("x", "X"),
578        ("y", "Y"),
579        ("z", "Z"),
580    ]
581    .into_iter()
582    .find_map(|(raw, display)| word.eq_ignore_ascii_case(raw).then_some(display))
583}