Skip to main content

lichtung_plot/
labels.rs

1//! Presentation policy for automatically sourced plot labels.
2
3use std::collections::BTreeMap;
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    captured: Option<Arc<BTreeMap<String, CapturedLabel>>>,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27struct CapturedLabel {
28    key: Option<crate::data::RawKey>,
29    display: String,
30}
31
32impl Default for Labels {
33    fn default() -> Self {
34        Self::humanized()
35    }
36}
37
38impl Labels {
39    /// Humanize automatically sourced column names and categorical values.
40    #[must_use]
41    pub const fn humanized() -> Self {
42        Self {
43            mode: LabelMode::Humanized,
44            aliases: None,
45            captured: None,
46        }
47    }
48
49    /// Render automatically sourced labels exactly as represented by the plot data.
50    #[must_use]
51    pub const fn raw() -> Self {
52        Self {
53            mode: LabelMode::Raw,
54            aliases: None,
55            captured: None,
56        }
57    }
58
59    /// Whether automatically sourced labels use the humanized fallback.
60    #[must_use]
61    pub const fn is_humanized(&self) -> bool {
62        matches!(self.mode, LabelMode::Humanized)
63    }
64
65    /// Configured alias projections in raw-key order, before text validation.
66    ///
67    /// `None` preserves the absence of an aliases collection. Reading this view
68    /// neither normalizes display text nor checks a complete label domain.
69    pub fn get_aliases(&self) -> Option<impl ExactSizeIterator<Item = (&str, &str)> + '_> {
70        if self.aliases.is_none() && self.captured.is_none() {
71            return None;
72        }
73        let keys = self
74            .aliases
75            .iter()
76            .flat_map(|aliases| aliases.keys())
77            .chain(self.captured.iter().flat_map(|captured| captured.keys()))
78            .collect::<std::collections::BTreeSet<_>>();
79        Some(
80            keys.into_iter()
81                .map(|raw| (raw.as_str(), self.alias_display(raw).expect("actual alias"))),
82        )
83    }
84
85    /// Add one exact raw-identity to display-label mapping.
86    #[must_use]
87    pub fn alias(mut self, raw: impl Into<String>, display: impl Into<String>) -> Self {
88        Arc::make_mut(
89            self.aliases
90                .get_or_insert_with(|| Arc::new(BTreeMap::new())),
91        )
92        .insert(raw.into(), display.into());
93        self
94    }
95
96    /// Add exact raw-identity to display-label mappings.
97    #[must_use]
98    pub fn aliases<I, R, D>(mut self, aliases: I) -> Self
99    where
100        I: IntoIterator<Item = (R, D)>,
101        R: Into<String>,
102        D: Into<String>,
103    {
104        for (raw, display) in aliases {
105            self = self.alias(raw, display);
106        }
107        self
108    }
109
110    /// Preserve the actual binding-time projection independently of authored aliases.
111    #[doc(hidden)]
112    #[must_use]
113    pub fn capture_alias(
114        mut self,
115        raw: impl Into<String>,
116        key: Option<crate::data::RawKey>,
117        display: impl Into<String>,
118    ) -> Self {
119        Arc::make_mut(
120            self.captured
121                .get_or_insert_with(|| Arc::new(BTreeMap::new())),
122        )
123        .insert(
124            raw.into(),
125            CapturedLabel {
126                key,
127                display: display.into(),
128            },
129        );
130        self
131    }
132
133    /// Retain captured identities when replacing an authored label policy.
134    pub(crate) fn with_captured_aliases_from(mut self, source: &Self) -> Self {
135        if let Some(captured) = &mut self.captured {
136            if let Some(source) = &source.captured {
137                if !Arc::ptr_eq(captured, source) {
138                    let captured = Arc::make_mut(captured);
139                    for (raw, entry) in source.iter() {
140                        captured.entry(raw.clone()).or_insert_with(|| entry.clone());
141                    }
142                }
143            }
144        } else {
145            self.captured.clone_from(&source.captured);
146        }
147        self
148    }
149
150    /// Apply this authored parent policy to one actual captured child.
151    pub(crate) fn for_captured_source(&self, source: &Self) -> Self {
152        Self {
153            mode: self.mode,
154            aliases: self.aliases.clone(),
155            captured: source.captured.clone(),
156        }
157    }
158
159    fn alias_display(&self, raw: &str) -> Option<&str> {
160        if let Some(display) = self.aliases.as_ref().and_then(|aliases| aliases.get(raw)) {
161            return Some(display);
162        }
163        let capture = self.captured.as_ref()?.get(raw)?;
164        if let Some(crate::data::RawKey::String(original)) = &capture.key {
165            if let Some(alias) = self
166                .aliases
167                .as_ref()
168                .and_then(|aliases| aliases.get(original))
169            {
170                return Some(alias);
171            }
172        }
173        Some(&capture.display)
174    }
175
176    /// Resolve one raw name with alias precedence and the selected fallback.
177    ///
178    /// The result uses the shared display-text syntax, preserving explicit alias
179    /// whitespace and mandatory breaks. Collisions between different identities
180    /// are checked when the renderer resolves their complete semantic domain.
181    ///
182    /// ```
183    /// use lichtung_plot::formatting::Labels;
184    /// let labels = Labels::humanized().alias("mean_score", " Score\r\n(points) ");
185    /// assert_eq!(labels.resolve("mean_score")?, " Score\r\n(points) ");
186    /// assert_eq!(labels.resolve("control_group")?, "Control group");
187    /// assert_eq!(Labels::raw().resolve("control_group")?, "control_group");
188    /// assert!(labels.alias("bad", "a\tb").resolve("bad").is_err());
189    /// # Ok::<(), lichtung_plot::Error>(())
190    /// ```
191    pub fn resolve(&self, raw: &str) -> Result<String, Error> {
192        let display = if let Some(alias) = self.alias_display(raw) {
193            copy_label(alias)
194        } else if self.mode == LabelMode::Humanized {
195            humanize(raw)
196        } else {
197            copy_label(raw)
198        }?;
199        crate::text::validate_for(&display, "label")?;
200        Ok(display)
201    }
202
203    pub(crate) fn resolve_domain<'a>(
204        &self,
205        domain: &str,
206        raw_labels: impl IntoIterator<Item = &'a str>,
207    ) -> Result<Vec<String>, Error> {
208        let mut identities = Vec::new();
209        let mut resolved = Vec::new();
210        let raw_labels = raw_labels.into_iter();
211        let minimum = raw_labels.size_hint().0;
212        crate::data::source::reserve_source(&mut identities, minimum)?;
213        crate::data::source::reserve_source(&mut resolved, minimum)?;
214        for raw in raw_labels {
215            crate::data::source::reserve_source(&mut identities, 1)?;
216            crate::data::source::reserve_source(&mut resolved, 1)?;
217            let display = self.resolve(raw)?;
218            let mut collision = None;
219            for (&previous, prior) in identities.iter().zip(&resolved) {
220                if prior == &display && previous != raw {
221                    collision = Some(previous);
222                    break;
223                }
224            }
225            if let Some(previous) = collision {
226                let alias_guidance = if self.aliases.as_ref().is_some_and(|aliases| {
227                    aliases.contains_key(previous) || aliases.contains_key(raw)
228                }) {
229                    "change or remove the colliding aliases; Labels::raw() does not override explicit aliases"
230                } else {
231                    "configure an explicit alias or use Labels::raw()"
232                };
233                return Err(Error::Render(format!(
234                    "label collision in {domain}: raw identities {previous:?} and {raw:?} both resolve to {display:?}; {alias_guidance}"
235                ).into()));
236            }
237            identities.push(raw);
238            resolved.push(display);
239        }
240        Ok(resolved)
241    }
242}
243
244fn copy_label(raw: &str) -> Result<String, Error> {
245    let mut output = String::new();
246    reserve_label(&mut output, raw.len())?;
247    output.push_str(raw);
248    Ok(output)
249}
250
251fn reserve_label(output: &mut String, count: usize) -> Result<(), Error> {
252    crate::data::source::reserve_source_string(output, count)
253}
254
255fn humanize(raw: &str) -> Result<String, Error> {
256    let mut split = String::new();
257    reserve_label(
258        &mut split,
259        raw.len()
260            .checked_mul(2)
261            .ok_or_else(|| Error::Render("humanized label length overflow".into()))?,
262    )?;
263    let mut chars = raw.chars().peekable();
264    let mut previous = None;
265    let mut last_was_space = true;
266    while let Some(character) = chars.next() {
267        let next = chars.peek().copied();
268        let prior = previous.replace(character);
269        if matches!(character, '_' | '-' | '.' | ' ' | '\t' | '\n' | '\r') {
270            if !last_was_space {
271                split.push(' ');
272                last_was_space = true;
273            }
274            continue;
275        }
276        if should_split_before(prior, character, next) && !last_was_space {
277            split.push(' ');
278        }
279        split.push(character);
280        last_was_space = false;
281    }
282    let mut output = String::new();
283
284    for (index, word) in split.split_whitespace().enumerate() {
285        let acronym = acronym(word);
286        reserve_label(
287            &mut output,
288            word.len()
289                .checked_add(12)
290                .ok_or_else(|| Error::Render("humanized word length overflow".into()))?,
291        )?;
292        if index != 0 {
293            output.push(' ');
294        }
295        if let Some(acronym) = acronym {
296            output.push_str(acronym);
297        } else if word.len() > 1 && word.bytes().all(|c| c.is_ascii_uppercase()) {
298            output.push_str(word);
299        } else {
300            for (offset, character) in word.chars().enumerate() {
301                let character = character.to_ascii_lowercase();
302                if index == 0 && offset == 0 {
303                    output.extend(character.to_uppercase());
304                } else {
305                    output.push(character);
306                }
307            }
308        }
309    }
310    if output.is_empty() {
311        copy_label(raw)
312    } else {
313        Ok(output)
314    }
315}
316
317fn should_split_before(previous: Option<char>, current: char, next: Option<char>) -> bool {
318    let Some(previous) = previous else {
319        return false;
320    };
321    (previous.is_ascii_lowercase() && current.is_ascii_uppercase())
322        || (previous.is_ascii_digit() && current.is_ascii_alphabetic())
323        || (previous.is_ascii_alphabetic() && current.is_ascii_digit())
324        || (previous.is_ascii_uppercase()
325            && current.is_ascii_uppercase()
326            && next.is_some_and(|character| character.is_ascii_lowercase()))
327}
328
329fn acronym(word: &str) -> Option<&'static str> {
330    [
331        ("ci", "CI"),
332        ("dna", "DNA"),
333        ("hwe", "HWE"),
334        ("id", "ID"),
335        ("ms", "MS"),
336        ("mz", "m/z"),
337        ("m/z", "m/z"),
338        ("pca", "PCA"),
339        ("qc", "QC"),
340        ("rna", "RNA"),
341        ("tsne", "t-SNE"),
342        ("t-sne", "t-SNE"),
343        ("umap", "UMAP"),
344        ("x", "X"),
345        ("y", "Y"),
346        ("z", "Z"),
347    ]
348    .into_iter()
349    .find_map(|(raw, display)| word.eq_ignore_ascii_case(raw).then_some(display))
350}