Skip to main content

lichtung_plot/
alpha.rs

1//! Owned opacity coefficients and explicit, eagerly materialized explanatory semantics.
2
3use std::sync::Arc;
4
5use crate::data::source::{collect_source, reserve_source, source_arc};
6use crate::data::{KeyValues, RawKey};
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};
16pub(crate) use guide::AlphaExampleKey;
17
18pub(crate) fn validated_alpha(value: f64) -> Result<f64> {
19    if !(0.0..=1.0).contains(&value) {
20        use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
21        return Err(Error::Data(
22            Diagnostic::new(
23                DiagnosticKind::InvalidValue {
24                    value: Some(RawKey::Float(value)),
25                    constraint: "finite alpha in [0, 1]".to_owned(),
26                },
27                format!("alpha must be finite and in [0, 1], got {value}"),
28            )
29            .with_context(ErrorContext::new().with_operation(OperationPhase::Bind)),
30        ));
31    }
32    Ok(if value == 0.0 { 0.0 } else { value })
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub(crate) enum AlphaTarget {
37    Point,
38    Line,
39    Fill,
40}
41
42impl AlphaTarget {
43    pub(crate) const fn index(self) -> usize {
44        match self {
45            Self::Point => 0,
46            Self::Line => 1,
47            Self::Fill => 2,
48        }
49    }
50}
51
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub(crate) struct AlphaInputs([AlphaEncoding; 3]);
54
55impl AlphaInputs {
56    pub(crate) fn get(&self, target: AlphaTarget) -> &AlphaEncoding {
57        &self.0[target.index()]
58    }
59
60    pub(crate) fn set(&mut self, target: AlphaTarget, encoding: AlphaEncoding) {
61        self.0[target.index()] = encoding;
62    }
63}
64
65/// Explicit explanatory semantics carried by immutable [`AlphaValues`].
66///
67/// Semantics are declared by construction, never inferred from value cardinality
68/// or a custom function's outputs. Only declared mappings produce alpha sections.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum AlphaSemantics {
71    /// Caller-computed coefficients with no automatic alpha explanation.
72    Undeclared,
73    /// A declared continuous source/domain illustrated by numeric symbols.
74    Continuous,
75    /// A complete ordered raw category-to-alpha mapping.
76    Categorical,
77    /// A complete ordered interval-to-alpha mapping with equality on the right.
78    Threshold,
79}
80
81/// Owned opacity coefficients and their complete immutable mapping declaration.
82///
83/// Construction eagerly materializes custom functions; no callback survives in a
84/// Plot, Canvas or output. Alpha zero preserves scientific membership. Attach with
85/// [`AlphaEncoding`] to select observations, explicit collective keys or bins.
86///
87/// ```
88/// use lichtung_plot::{NumericValues, scales::{AlphaSemantics, AlphaValues}};
89/// let alpha = AlphaValues::linear(
90///     NumericValues::new("confidence", [0.0, 0.25, 0.5, 0.75, 1.0]),
91///     (0.0, 1.0), (0.0, 1.0),
92/// )?;
93/// assert_eq!(alpha.semantics(), AlphaSemantics::Continuous);
94/// assert_eq!((0..alpha.len()).map(|i| alpha.get(i).unwrap()).collect::<Vec<_>>(),
95///     [0.0, 0.25, 0.5, 0.75, 1.0]);
96/// # Ok::<(), lichtung_plot::Error>(())
97/// ```
98///
99/// The representation is private:
100/// ```compile_fail
101/// use lichtung_plot::scales::AlphaValues;
102/// fn private(values: AlphaValues) { let _ = values.declaration; }
103/// ```
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct AlphaValues {
106    name: Arc<String>,
107    data: Arc<AlphaData>,
108    declaration: Arc<AlphaDeclaration>,
109}
110
111#[derive(Debug, PartialEq)]
112struct AlphaData {
113    values: Vec<f64>,
114    members: AlphaMembers,
115}
116
117#[derive(Debug, PartialEq, Eq)]
118enum AlphaMembers {
119    Undeclared(NumericValues),
120    Numeric(NumericValues),
121    Categorical(KeyValues, Vec<usize>),
122    Threshold(NumericValues, Vec<usize>),
123}
124
125/// The exact authored opacity mapping, materialized once at binding time.
126/// Coefficients are finite values in [0, 1] in an owned AlphaValues declaration.
127#[derive(Debug, Clone, Default)]
128#[non_exhaustive]
129pub enum AlphaMapping {
130    /// Direct coefficients have no additional mapping.
131    #[default]
132    Undeclared,
133    /// Clamped linear mapping.
134    Linear {
135        /// Original domain endpoints.
136        domain: [f64; 2],
137        /// Output opacity endpoints.
138        range: [f64; 2],
139    },
140    /// Clamped logarithmic mapping with base 10.
141    Log10 {
142        /// Original domain endpoints.
143        domain: [f64; 2],
144        /// Output opacity endpoints.
145        range: [f64; 2],
146    },
147    /// A complete evaluated custom continuous declaration.
148    Continuous {
149        /// Original domain endpoints.
150        domain: [f64; 2],
151        /// Exact evaluated coordinates and opacity coefficients.
152        evaluated: Vec<(f64, f64)>,
153    },
154    /// First-observed raw categories and their mapped coefficients.
155    Categorical(Vec<(RawKey, f64)>),
156    /// An ordered threshold mapping, with equality belonging to the right interval.
157    Threshold {
158        /// Original ordered boundaries.
159        boundaries: Vec<f64>,
160        /// One coefficient per interval, including the two outer intervals.
161        alphas: Vec<f64>,
162    },
163}
164
165impl PartialEq for AlphaMapping {
166    fn eq(&self, other: &Self) -> bool {
167        fn numbers(left: &[f64], right: &[f64]) -> bool {
168            left.iter()
169                .map(|value| value.to_bits())
170                .eq(right.iter().map(|value| value.to_bits()))
171        }
172        fn pairs(left: &[(f64, f64)], right: &[(f64, f64)]) -> bool {
173            left.iter()
174                .map(|(raw, alpha)| (raw.to_bits(), alpha.to_bits()))
175                .eq(right
176                    .iter()
177                    .map(|(raw, alpha)| (raw.to_bits(), alpha.to_bits())))
178        }
179        match (self, other) {
180            (Self::Undeclared, Self::Undeclared) => true,
181            (
182                Self::Linear { domain, range },
183                Self::Linear {
184                    domain: other_domain,
185                    range: other_range,
186                },
187            )
188            | (
189                Self::Log10 { domain, range },
190                Self::Log10 {
191                    domain: other_domain,
192                    range: other_range,
193                },
194            ) => numbers(domain, other_domain) && numbers(range, other_range),
195            (
196                Self::Continuous { domain, evaluated },
197                Self::Continuous {
198                    domain: other_domain,
199                    evaluated: other_evaluated,
200                },
201            ) => numbers(domain, other_domain) && pairs(evaluated, other_evaluated),
202            (
203                Self::Threshold { boundaries, alphas },
204                Self::Threshold {
205                    boundaries: other_boundaries,
206                    alphas: other_alphas,
207                },
208            ) => numbers(boundaries, other_boundaries) && numbers(alphas, other_alphas),
209            (Self::Categorical(left), Self::Categorical(right)) => left
210                .iter()
211                .map(|(key, alpha)| (key, alpha.to_bits()))
212                .eq(right.iter().map(|(key, alpha)| (key, alpha.to_bits()))),
213            _ => false,
214        }
215    }
216}
217
218/// The mapping and its already-computed whole-set guide presentation.
219#[derive(Debug, Default, PartialEq)]
220struct AlphaDeclaration {
221    mapping: AlphaMapping,
222    examples: Vec<(f64, f64)>,
223    labels: Vec<String>,
224}
225
226// All stored coefficients are validated finite and have a canonical zero.
227impl Eq for AlphaData {}
228impl Eq for AlphaDeclaration {}
229
230#[expect(
231    clippy::needless_pass_by_value,
232    reason = "public consuming factories materialize and release one complete immutable source input"
233)]
234impl AlphaValues {
235    /// Own caller-computed coefficients in [0, 1] without guide semantics.
236    ///
237    /// Names must be nonempty, already trimmed and control-free. Empty values
238    /// are valid; attachment checks the actual unit alignment before fonts.
239    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Result<Self> {
240        let name = validated_name(name.into())?;
241        let original = NumericValues::new(&name, collect_input(values)?);
242        Self::try_from(original)
243    }
244
245    /// Map finite source values linearly over an explicit increasing domain.
246    ///
247    /// Clamp out-of-domain values. Ascending, descending and constant coefficient
248    /// ranges are valid. Missing/nonfinite sources
249    /// and nonfinite/nonincreasing domains reject during construction.
250    pub fn linear(source: NumericValues, domain: (f64, f64), range: (f64, f64)) -> Result<Self> {
251        materialize::builtin(&source, domain, range, false)
252    }
253
254    /// Map positive finite source values over an explicit positive log10 domain.
255    ///
256    /// Endpoints must be strictly increasing and remain distinguishable after
257    /// binary64 log10. Nonpositive sources reject rather than clamping. Other
258    /// clamping rules match [`Self::linear`].
259    pub fn log10(source: NumericValues, domain: (f64, f64), range: (f64, f64)) -> Result<Self> {
260        materialize::builtin(&source, domain, range, true)
261    }
262
263    /// Declare a continuous mapping and eagerly materialize its finite values.
264    ///
265    /// Invoke `f` once for every distinct clamped source coordinate and required
266    /// numeric representative, in numeric order. Retain the complete evaluated
267    /// table and original members; no function, inverse or smooth ramp is stored.
268    /// The domain must be finite and strictly increasing, and sources nonmissing
269    /// and finite. Up to five original-domain examples explain this declaration.
270    pub fn continuous(
271        source: NumericValues,
272        domain: (f64, f64),
273        f: impl FnMut(f64) -> f64,
274    ) -> Result<Self> {
275        materialize::continuous(&source, domain, f)
276    }
277
278    /// Declare a categorical map, invoking `f` once per first-observed raw level.
279    ///
280    /// Null sources reject. Complete table order survives [`Self::select`]; only
281    /// actual consumed categories appear in automatic explanations, including zero.
282    pub fn categorical(source: CategoryValues, f: impl FnMut(&str) -> f64) -> Result<Self> {
283        materialize::categorical(&source, f)
284    }
285
286    /// Declare increasing finite boundaries and exactly one more alpha coefficient.
287    ///
288    /// Intervals are `< b0`, `[b0,b1)`, ..., `>= blast`; equality belongs to the
289    /// right. No boundaries plus one coefficient declares `all values`. Sources must be
290    /// finite and nonmissing. Labels come from the actual bounds, not caller text.
291    pub fn threshold(
292        source: NumericValues,
293        boundaries: impl IntoIterator<Item = f64>,
294        alphas: impl IntoIterator<Item = f64>,
295    ) -> Result<Self> {
296        materialize::threshold(&source, boundaries, alphas)
297    }
298
299    /// Select original occurrences while retaining the complete shared declaration.
300    ///
301    /// Repeated indices are allowed; out-of-range indices reject. Construct pooled
302    /// custom/category maps once and select per Plot to preserve Shared recipes.
303    pub fn select(&self, indices: impl IntoIterator<Item = usize>) -> Result<Self> {
304        let indices = collect_input(indices)?;
305        let values = collect_source(indices.iter().map(|&index| {
306            self.get(index).ok_or_else(|| {
307                Error::Data(
308                    format!(
309                        "alpha values {:?} selection index {index} is outside length {}",
310                        self.name(),
311                        self.len(),
312                    )
313                    .into(),
314                )
315            })
316        }))?;
317        let members = match &self.data.members {
318            AlphaMembers::Undeclared(source) => AlphaMembers::Undeclared(source.select(&indices)?),
319            AlphaMembers::Numeric(source) => AlphaMembers::Numeric(source.select(&indices)?),
320            AlphaMembers::Categorical(source, members) => AlphaMembers::Categorical(
321                select_categories(source, &indices)?,
322                collect_source(indices.iter().map(|&i| Ok(members[i])))?,
323            ),
324            AlphaMembers::Threshold(source, members) => AlphaMembers::Threshold(
325                source.select(&indices)?,
326                collect_source(indices.iter().map(|&i| Ok(members[i])))?,
327            ),
328        };
329        Ok(Self {
330            name: Arc::clone(&self.name),
331            data: source_arc(AlphaData { values, members })?,
332            declaration: Arc::clone(&self.declaration),
333        })
334    }
335
336    /// Raw source identity used for automatic titles and diagnostics.
337    #[must_use]
338    pub fn name(&self) -> &str {
339        if let Some(values) = self.get_numeric_source() {
340            if values.name().is_empty() && values.field_key().is_none() {
341                &self.name
342            } else {
343                values.name()
344            }
345        } else if let Some(KeyValues::Strings(values)) = self.get_category_source() {
346            values.original_name()
347        } else {
348            &self.name
349        }
350    }
351
352    pub(crate) fn raw_name(&self) -> &str {
353        &self.name
354    }
355
356    /// Number of retained occurrences.
357    #[must_use]
358    pub fn len(&self) -> usize {
359        self.data.values.len()
360    }
361
362    /// Whether no occurrences are retained.
363    #[must_use]
364    pub fn is_empty(&self) -> bool {
365        self.data.values.is_empty()
366    }
367
368    /// One occurrence's final coefficient, or None outside the retained input.
369    #[must_use]
370    pub fn get(&self, index: usize) -> Option<f64> {
371        self.data.values.get(index).copied()
372    }
373
374    /// Borrow all materialized opacity coefficients in their retained order.
375    #[must_use]
376    pub fn values(&self) -> &[f64] {
377        &self.data.values
378    }
379
380    /// Explicit explanatory classification, independent of selected coefficients.
381    #[must_use]
382    pub fn semantics(&self) -> AlphaSemantics {
383        match &self.declaration.mapping {
384            AlphaMapping::Undeclared => AlphaSemantics::Undeclared,
385            AlphaMapping::Linear { .. }
386            | AlphaMapping::Log10 { .. }
387            | AlphaMapping::Continuous { .. } => AlphaSemantics::Continuous,
388            AlphaMapping::Categorical(_) => AlphaSemantics::Categorical,
389            AlphaMapping::Threshold { .. } => AlphaSemantics::Threshold,
390        }
391    }
392
393    /// The original numeric source, including explicitly supplied coefficients.
394    #[must_use]
395    pub fn get_numeric_source(&self) -> Option<&NumericValues> {
396        match &self.data.members {
397            AlphaMembers::Undeclared(source)
398            | AlphaMembers::Numeric(source)
399            | AlphaMembers::Threshold(source, _) => Some(source),
400            AlphaMembers::Categorical(..) => None,
401        }
402    }
403
404    /// The original categorical source, when a category mapping was declared.
405    #[must_use]
406    pub fn get_category_source(&self) -> Option<&KeyValues> {
407        match &self.data.members {
408            AlphaMembers::Categorical(source, _) => Some(source),
409            _ => None,
410        }
411    }
412
413    /// The actual threshold interval of each retained occurrence.
414    #[must_use]
415    pub fn get_threshold_indices(&self) -> Option<&[usize]> {
416        match &self.data.members {
417            AlphaMembers::Threshold(_, indices) => Some(indices),
418            _ => None,
419        }
420    }
421
422    /// Borrow the full original mapping independently of selected occurrences.
423    #[must_use]
424    pub fn get_mapping(&self) -> &AlphaMapping {
425        &self.declaration.mapping
426    }
427
428    /// Actual original-domain examples and their evaluated opacity.
429    #[must_use]
430    pub fn examples(&self) -> &[(f64, f64)] {
431        &self.declaration.examples
432    }
433
434    fn from_parts(
435        name: String,
436        values: Vec<f64>,
437        members: AlphaMembers,
438        declaration: AlphaDeclaration,
439    ) -> Result<Self> {
440        Ok(Self {
441            name: source_arc(name)?,
442            data: source_arc(AlphaData { values, members })?,
443            declaration: source_arc(declaration)?,
444        })
445    }
446}
447
448impl TryFrom<NumericValues> for AlphaValues {
449    type Error = Error;
450
451    fn try_from(source: NumericValues) -> Result<Self> {
452        let name = if source.raw_name().is_empty() && source.field_key().is_none() {
453            "Alpha"
454        } else {
455            source.raw_name()
456        };
457        let name = crate::data::source::copy_source_string(name)?;
458        let values = collect_source((0..source.len()).map(|index| {
459            let value = source.get(index).flatten().ok_or_else(|| {
460                Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
461            })?;
462            validated_alpha(value).map_err(|error| {
463                Error::Data(format!("alpha source {name:?} at index {index}: {error}").into())
464            })
465        }))?;
466        Self::from_parts(
467            name,
468            values,
469            AlphaMembers::Undeclared(source),
470            AlphaDeclaration::default(),
471        )
472    }
473}
474
475fn select_categories(source: &KeyValues, indices: &[usize]) -> Result<KeyValues> {
476    source.select(indices)
477}
478
479fn validated_name(name: String) -> Result<String> {
480    if name.is_empty() || name.trim() != name || name.chars().any(char::is_control) {
481        return Err(Error::Data(
482            "alpha source names must be nonempty, already trimmed and control-free".into(),
483        ));
484    }
485    Ok(name)
486}
487
488fn numeric_key(value: f64) -> u64 {
489    if value == 0.0 {
490        0
491    } else {
492        value.to_bits()
493    }
494}
495
496fn collect_input<T>(values: impl IntoIterator<Item = T>) -> Result<Vec<T>> {
497    let values = values.into_iter();
498    let mut retained = Vec::new();
499    let (minimum, maximum) = values.size_hint();
500    if maximum == Some(minimum) {
501        reserve_source(&mut retained, minimum)?;
502    }
503    for value in values {
504        if retained.len() == retained.capacity() {
505            let additional = retained.capacity().max(1);
506            reserve_source(&mut retained, additional)?;
507        }
508        retained.push(value);
509    }
510    Ok(retained)
511}
512
513#[cfg(test)]
514mod tests;