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, Clone, PartialEq)]
112struct AlphaData {
113    values: Vec<f64>,
114    members: AlphaMembers,
115}
116
117#[derive(Debug, Clone, 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    /// Repeat explicitly row-scoped opacity without replacing its mapping or
337    /// the original source relation. Used by the rectangular input bridges.
338    #[doc(hidden)]
339    pub fn repeat_rows(&self, copies: usize) -> Result<Self> {
340        if copies == 0 {
341            return Err(Error::Data(
342                "row expansion requires at least one column".into(),
343            ));
344        }
345        self.len()
346            .checked_mul(copies)
347            .ok_or_else(|| Error::Data("expanded alpha count exceeds usize".into()))?;
348        let mut expanded = if copies == 1 {
349            self.clone()
350        } else {
351            self.select((0..self.len()).flat_map(|row| std::iter::repeat_n(row, copies)))?
352        };
353        // Preserve the exact projection when a native map already refers to
354        // an independently selected subset. Identity sources have the
355        // stronger row-major repeat rule, including a current width of one.
356        match (
357            &mut Arc::make_mut(&mut expanded.data).members,
358            &self.data.members,
359        ) {
360            (AlphaMembers::Undeclared(values), AlphaMembers::Undeclared(source))
361            | (AlphaMembers::Numeric(values), AlphaMembers::Numeric(source))
362            | (AlphaMembers::Threshold(values, _), AlphaMembers::Threshold(source, _)) => {
363                retain_repeated(values, source.vector_source(), copies)?;
364            }
365            (
366                AlphaMembers::Categorical(KeyValues::Strings(values), _),
367                AlphaMembers::Categorical(KeyValues::Strings(source), _),
368            ) => retain_repeated(values, source.vector_source(), copies)?,
369            (
370                AlphaMembers::Categorical(KeyValues::Raw(values), _),
371                AlphaMembers::Categorical(KeyValues::Raw(source), _),
372            ) => retain_repeated(values, source.vector_source(), copies)?,
373            _ => unreachable!("alpha selection retains its original native source kind"),
374        }
375        Ok(expanded)
376    }
377
378    /// Raw source identity used for automatic titles and diagnostics.
379    #[must_use]
380    pub fn name(&self) -> &str {
381        if let Some(values) = self.get_numeric_source() {
382            if values.name().is_empty() && values.field_key().is_none() {
383                &self.name
384            } else {
385                values.name()
386            }
387        } else if let Some(KeyValues::Strings(values)) = self.get_category_source() {
388            values.original_name()
389        } else {
390            &self.name
391        }
392    }
393
394    pub(crate) fn raw_name(&self) -> &str {
395        &self.name
396    }
397
398    /// Number of retained occurrences.
399    #[must_use]
400    pub fn len(&self) -> usize {
401        self.data.values.len()
402    }
403
404    /// Whether no occurrences are retained.
405    #[must_use]
406    pub fn is_empty(&self) -> bool {
407        self.data.values.is_empty()
408    }
409
410    /// One occurrence's final coefficient, or None outside the retained input.
411    #[must_use]
412    pub fn get(&self, index: usize) -> Option<f64> {
413        self.data.values.get(index).copied()
414    }
415
416    /// Borrow all materialized opacity coefficients in their retained order.
417    #[must_use]
418    pub fn values(&self) -> &[f64] {
419        &self.data.values
420    }
421
422    /// Explicit explanatory classification, independent of selected coefficients.
423    #[must_use]
424    pub fn semantics(&self) -> AlphaSemantics {
425        match &self.declaration.mapping {
426            AlphaMapping::Undeclared => AlphaSemantics::Undeclared,
427            AlphaMapping::Linear { .. }
428            | AlphaMapping::Log10 { .. }
429            | AlphaMapping::Continuous { .. } => AlphaSemantics::Continuous,
430            AlphaMapping::Categorical(_) => AlphaSemantics::Categorical,
431            AlphaMapping::Threshold { .. } => AlphaSemantics::Threshold,
432        }
433    }
434
435    /// The original numeric source, including explicitly supplied coefficients.
436    #[must_use]
437    pub fn get_numeric_source(&self) -> Option<&NumericValues> {
438        match &self.data.members {
439            AlphaMembers::Undeclared(source)
440            | AlphaMembers::Numeric(source)
441            | AlphaMembers::Threshold(source, _) => Some(source),
442            AlphaMembers::Categorical(..) => None,
443        }
444    }
445
446    /// The original categorical source, when a category mapping was declared.
447    #[must_use]
448    pub fn get_category_source(&self) -> Option<&KeyValues> {
449        match &self.data.members {
450            AlphaMembers::Categorical(source, _) => Some(source),
451            _ => None,
452        }
453    }
454
455    /// The actual threshold interval of each retained occurrence.
456    #[must_use]
457    pub fn get_threshold_indices(&self) -> Option<&[usize]> {
458        match &self.data.members {
459            AlphaMembers::Threshold(_, indices) => Some(indices),
460            _ => None,
461        }
462    }
463
464    /// Borrow the full original mapping independently of selected occurrences.
465    #[must_use]
466    pub fn get_mapping(&self) -> &AlphaMapping {
467        &self.declaration.mapping
468    }
469
470    /// Actual original-domain examples and their evaluated opacity.
471    #[must_use]
472    pub fn examples(&self) -> &[(f64, f64)] {
473        &self.declaration.examples
474    }
475
476    fn from_parts(
477        name: String,
478        values: Vec<f64>,
479        members: AlphaMembers,
480        declaration: AlphaDeclaration,
481    ) -> Result<Self> {
482        Ok(Self {
483            name: source_arc(name)?,
484            data: source_arc(AlphaData { values, members })?,
485            declaration: source_arc(declaration)?,
486        })
487    }
488}
489
490impl TryFrom<NumericValues> for AlphaValues {
491    type Error = Error;
492
493    fn try_from(source: NumericValues) -> Result<Self> {
494        let name = if source.raw_name().is_empty() && source.field_key().is_none() {
495            "Alpha"
496        } else {
497            source.raw_name()
498        };
499        let name = crate::data::source::copy_source_string(name)?;
500        let values = collect_source((0..source.len()).map(|index| {
501            let value = source.get(index).flatten().ok_or_else(|| {
502                Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
503            })?;
504            validated_alpha(value).map_err(|error| {
505                Error::Data(format!("alpha source {name:?} at index {index}: {error}").into())
506            })
507        }))?;
508        Self::from_parts(
509            name,
510            values,
511            AlphaMembers::Undeclared(source),
512            AlphaDeclaration::default(),
513        )
514    }
515}
516
517fn retain_repeated<T: crate::data::CapturedValue + Clone>(
518    values: &mut T,
519    source: &crate::data::VectorSource,
520    copies: usize,
521) -> Result<()> {
522    if source.is_identity() {
523        *values = values
524            .clone()
525            .retain(source.info().clone(), copies, None)?
526            .row_scoped();
527    }
528    Ok(())
529}
530
531fn select_categories(source: &KeyValues, indices: &[usize]) -> Result<KeyValues> {
532    source.select(indices)
533}
534
535fn validated_name(name: String) -> Result<String> {
536    if name.is_empty() || name.trim() != name || name.chars().any(char::is_control) {
537        return Err(Error::Data(
538            "alpha source names must be nonempty, already trimmed and control-free".into(),
539        ));
540    }
541    Ok(name)
542}
543
544fn numeric_key(value: f64) -> u64 {
545    if value == 0.0 {
546        0
547    } else {
548        value.to_bits()
549    }
550}
551
552fn collect_input<T>(values: impl IntoIterator<Item = T>) -> Result<Vec<T>> {
553    let values = values.into_iter();
554    let mut retained = Vec::new();
555    let (minimum, maximum) = values.size_hint();
556    if maximum == Some(minimum) {
557        reserve_source(&mut retained, minimum)?;
558    }
559    for value in values {
560        if retained.len() == retained.capacity() {
561            let additional = retained.capacity().max(1);
562            reserve_source(&mut retained, additional)?;
563        }
564        retained.push(value);
565    }
566    Ok(retained)
567}
568
569#[cfg(test)]
570mod tests;