Skip to main content

lichtung_plot/
alpha.rs

1//! Owned byte alpha and explicit, eagerly materialized explanatory semantics.
2
3use std::sync::Arc;
4
5use crate::data::source::{collect_source, reserve_source, source_arc};
6use crate::numeric::set::FormattedSet;
7use crate::{CategoryValues, Error, NumericValues, Result};
8
9mod encoding;
10mod guide;
11pub(crate) mod marks;
12mod materialize;
13
14pub use encoding::AlphaEncoding;
15pub(crate) use encoding::{AlphaUnitKind, PreparedAlpha, ResolvedAlpha};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum AlphaTarget {
19    Point,
20    Line,
21    Fill,
22}
23
24impl AlphaTarget {
25    pub(crate) const fn index(self) -> usize {
26        match self {
27            Self::Point => 0,
28            Self::Line => 1,
29            Self::Fill => 2,
30        }
31    }
32}
33
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub(crate) struct AlphaInputs([AlphaEncoding; 3]);
36
37impl AlphaInputs {
38    pub(crate) fn get(&self, target: AlphaTarget) -> &AlphaEncoding {
39        &self.0[target.index()]
40    }
41
42    pub(crate) fn set(&mut self, target: AlphaTarget, encoding: AlphaEncoding) {
43        self.0[target.index()] = encoding;
44    }
45}
46
47/// Explicit explanatory semantics carried by immutable [`AlphaValues`].
48///
49/// Semantics are declared by construction, never inferred from byte cardinality
50/// or a custom function's outputs. Only declared mappings produce alpha sections.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum AlphaSemantics {
53    /// Caller-computed bytes with no automatic alpha explanation.
54    Undeclared,
55    /// A declared continuous source/domain illustrated by numeric symbols.
56    Continuous,
57    /// A complete ordered raw category-to-alpha mapping.
58    Categorical,
59    /// A complete ordered interval-to-alpha mapping with equality on the right.
60    Threshold,
61}
62
63/// Owned byte alpha values and their complete immutable mapping declaration.
64///
65/// Construction eagerly materializes custom functions; no callback survives in a
66/// Plot, Canvas or output. Alpha zero preserves scientific membership. Attach with
67/// [`AlphaEncoding`] to select observations, explicit collective keys or bins.
68///
69/// ```
70/// use lichtung_plot::{AlphaSemantics, AlphaValues, NumericValues};
71/// let alpha = AlphaValues::linear(
72///     NumericValues::new("confidence", [0.0, 0.25, 0.5, 0.75, 1.0]),
73///     (0.0, 1.0), (0, 255),
74/// )?;
75/// assert_eq!(alpha.semantics(), AlphaSemantics::Continuous);
76/// assert_eq!((0..alpha.len()).map(|i| alpha.get(i).unwrap()).collect::<Vec<_>>(),
77///     [0, 64, 128, 191, 255]);
78/// # Ok::<(), lichtung_plot::Error>(())
79/// ```
80///
81/// The representation is private:
82/// ```compile_fail
83/// use lichtung_plot::AlphaValues;
84/// fn private(values: AlphaValues) { let _ = values.declaration; }
85/// ```
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct AlphaValues {
88    name: Arc<String>,
89    data: Arc<AlphaData>,
90    declaration: Arc<AlphaDeclaration>,
91}
92
93#[derive(Debug, PartialEq, Eq)]
94struct AlphaData {
95    values: Vec<u8>,
96    members: AlphaMembers,
97}
98
99#[derive(Debug, PartialEq, Eq)]
100enum AlphaMembers {
101    Undeclared,
102    Numeric(Vec<u64>),
103    Categorical(Vec<usize>),
104    Threshold(Vec<(u64, usize)>),
105}
106
107/// Recipes retain the complete declaration independently of selected occurrences.
108#[derive(Debug, PartialEq, Eq)]
109enum AlphaDeclaration {
110    Undeclared,
111    Continuous {
112        domain: [u64; 2],
113        rule: ContinuousRule,
114        examples: FormattedSet,
115        alphas: Vec<u8>,
116    },
117    Categorical(Vec<(String, u8)>),
118    Threshold {
119        boundaries: FormattedSet,
120        alphas: Vec<u8>,
121        labels: Vec<String>,
122    },
123}
124
125#[derive(Debug, PartialEq, Eq)]
126enum ContinuousRule {
127    Linear((u8, u8)),
128    Log10 {
129        range: (u8, u8),
130        coordinates: [u64; 2],
131    },
132    Custom(Vec<(u64, u8)>),
133}
134
135#[expect(
136    clippy::needless_pass_by_value,
137    reason = "public consuming factories materialize and release one complete immutable source input"
138)]
139impl AlphaValues {
140    /// Own arbitrary caller-computed bytes without declaring guide semantics.
141    ///
142    /// Names must be nonempty, already trimmed and control-free. Empty values
143    /// are valid; attachment checks the actual unit alignment before fonts.
144    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = u8>) -> Result<Self> {
145        let name = validated_name(name.into())?;
146        Self::from_parts(
147            name,
148            collect_input(values)?,
149            AlphaMembers::Undeclared,
150            AlphaDeclaration::Undeclared,
151        )
152    }
153
154    /// Map finite source values linearly over an explicit increasing domain.
155    ///
156    /// Clamp out-of-domain values. Ascending, descending and constant byte ranges
157    /// are valid; quantization is nearest/ties-to-even. Missing/nonfinite sources
158    /// and nonfinite/nonincreasing domains reject during construction.
159    pub fn linear(source: NumericValues, domain: (f64, f64), range: (u8, u8)) -> Result<Self> {
160        materialize::builtin(&source, domain, range, false)
161    }
162
163    /// Map positive finite source values over an explicit positive log10 domain.
164    ///
165    /// Endpoints must be strictly increasing and remain distinguishable after
166    /// binary64 log10. Nonpositive sources reject rather than clamping. Other
167    /// clamping/quantization rules match [`Self::linear`].
168    pub fn log10(source: NumericValues, domain: (f64, f64), range: (u8, u8)) -> Result<Self> {
169        materialize::builtin(&source, domain, range, true)
170    }
171
172    /// Declare a continuous mapping and eagerly materialize its finite values.
173    ///
174    /// Invoke `f` once for every distinct clamped source coordinate and required
175    /// numeric representative, in numeric order. Retain the complete evaluated
176    /// table and original members; no function, inverse or smooth ramp is stored.
177    /// The domain must be finite and strictly increasing, and sources nonmissing
178    /// and finite. Up to five original-domain examples explain this declaration.
179    pub fn continuous(
180        source: NumericValues,
181        domain: (f64, f64),
182        f: impl FnMut(f64) -> u8,
183    ) -> Result<Self> {
184        materialize::continuous(&source, domain, f)
185    }
186
187    /// Declare a categorical map, invoking `f` once per first-observed raw level.
188    ///
189    /// Null sources reject. Complete table order survives [`Self::select`]; only
190    /// actual consumed categories appear in automatic explanations, including zero.
191    pub fn categorical(source: CategoryValues, f: impl FnMut(&str) -> u8) -> Result<Self> {
192        materialize::categorical(&source, f)
193    }
194
195    /// Declare increasing finite boundaries and exactly one more alpha byte.
196    ///
197    /// Intervals are `< b0`, `[b0,b1)`, ..., `>= blast`; equality belongs to the
198    /// right. No boundaries plus one byte declares `all values`. Sources must be
199    /// finite and nonmissing. Labels come from the actual bounds, not caller text.
200    pub fn threshold(
201        source: NumericValues,
202        boundaries: impl IntoIterator<Item = f64>,
203        alphas: impl IntoIterator<Item = u8>,
204    ) -> Result<Self> {
205        materialize::threshold(&source, boundaries, alphas)
206    }
207
208    /// Select original occurrences while retaining the complete shared declaration.
209    ///
210    /// Repeated indices are allowed; out-of-range indices reject. Construct pooled
211    /// custom/category maps once and select per Plot to preserve Shared recipes.
212    pub fn select(&self, indices: impl IntoIterator<Item = usize>) -> Result<Self> {
213        let indices = collect_input(indices)?;
214        let values = collect_source(indices.iter().map(|&index| {
215            self.get(index).ok_or_else(|| {
216                Error::Data(format!(
217                    "alpha values {:?} selection index {index} is outside length {}",
218                    self.name(),
219                    self.len(),
220                ))
221            })
222        }))?;
223        let members = match &self.data.members {
224            AlphaMembers::Undeclared => AlphaMembers::Undeclared,
225            AlphaMembers::Numeric(members) => {
226                AlphaMembers::Numeric(collect_source(indices.iter().map(|&i| Ok(members[i])))?)
227            }
228            AlphaMembers::Categorical(members) => {
229                AlphaMembers::Categorical(collect_source(indices.iter().map(|&i| Ok(members[i])))?)
230            }
231            AlphaMembers::Threshold(members) => {
232                AlphaMembers::Threshold(collect_source(indices.iter().map(|&i| Ok(members[i])))?)
233            }
234        };
235        Ok(Self {
236            name: Arc::clone(&self.name),
237            data: source_arc(AlphaData { values, members })?,
238            declaration: Arc::clone(&self.declaration),
239        })
240    }
241
242    /// Raw source identity used for automatic titles and diagnostics.
243    #[must_use]
244    pub fn name(&self) -> &str {
245        &self.name
246    }
247
248    /// Number of retained occurrences.
249    #[must_use]
250    pub fn len(&self) -> usize {
251        self.data.values.len()
252    }
253
254    /// Whether no occurrences are retained.
255    #[must_use]
256    pub fn is_empty(&self) -> bool {
257        self.data.values.is_empty()
258    }
259
260    /// One occurrence's final byte, or None outside the retained input.
261    #[must_use]
262    pub fn get(&self, index: usize) -> Option<u8> {
263        self.data.values.get(index).copied()
264    }
265
266    /// Explicit explanatory classification, independent of selected byte values.
267    #[must_use]
268    pub fn semantics(&self) -> AlphaSemantics {
269        match self.declaration.as_ref() {
270            AlphaDeclaration::Undeclared => AlphaSemantics::Undeclared,
271            AlphaDeclaration::Continuous { .. } => AlphaSemantics::Continuous,
272            AlphaDeclaration::Categorical(_) => AlphaSemantics::Categorical,
273            AlphaDeclaration::Threshold { .. } => AlphaSemantics::Threshold,
274        }
275    }
276
277    fn from_parts(
278        name: String,
279        values: Vec<u8>,
280        members: AlphaMembers,
281        declaration: AlphaDeclaration,
282    ) -> Result<Self> {
283        Ok(Self {
284            name: source_arc(name)?,
285            data: source_arc(AlphaData { values, members })?,
286            declaration: source_arc(declaration)?,
287        })
288    }
289}
290
291fn validated_name(name: String) -> Result<String> {
292    if name.is_empty() || name.trim() != name || name.chars().any(char::is_control) {
293        return Err(Error::Data(
294            "alpha source names must be nonempty, already trimmed and control-free".into(),
295        ));
296    }
297    Ok(name)
298}
299
300fn numeric_key(value: f64) -> u64 {
301    if value == 0.0 {
302        0
303    } else {
304        value.to_bits()
305    }
306}
307
308fn collect_input<T>(values: impl IntoIterator<Item = T>) -> Result<Vec<T>> {
309    let values = values.into_iter();
310    let mut retained = Vec::new();
311    let (minimum, maximum) = values.size_hint();
312    if maximum == Some(minimum) {
313        reserve_source(&mut retained, minimum)?;
314    }
315    for value in values {
316        if retained.len() == retained.capacity() {
317            let additional = retained.capacity().max(1);
318            reserve_source(&mut retained, additional)?;
319        }
320        retained.push(value);
321    }
322    Ok(retained)
323}
324
325#[cfg(test)]
326mod tests;