Skip to main content

lichtung_plot/theme/
scale_values.rs

1//! Immutable, validated opaque scale inputs. Backend stops are publication operands.
2
3use std::sync::Arc;
4
5use crate::spec::CategoricalColorMap;
6use crate::{Error, Result};
7
8use super::OpaqueColor;
9
10fn invalid(message: &str) -> Error {
11    Error::Data(message.into())
12}
13
14/// Checked, fallible construction of immutable scale inputs.
15fn retain<T>(values: impl IntoIterator<Item = T>) -> Result<Arc<Vec<T>>> {
16    let values = values.into_iter();
17    let (minimum, maximum) = values.size_hint();
18    let mut retained = Vec::new();
19    if maximum == Some(minimum) && minimum > 0 {
20        reserve_input(&mut retained, minimum)?;
21    }
22    for value in values {
23        let next = retained
24            .len()
25            .checked_add(1)
26            .ok_or_else(|| invalid("scale input length overflow"))?;
27
28        if next > retained.capacity() {
29            let capacity = retained
30                .capacity()
31                .checked_mul(2)
32                .ok_or_else(|| invalid("scale input capacity overflow"))?
33                .max(next);
34            reserve_input(&mut retained, capacity)?;
35        }
36        retained.push(value);
37    }
38    if retained.is_empty() {
39        return Err(invalid("scale input must be nonempty"));
40    }
41    Ok(Arc::new(retained))
42}
43
44fn reserve_input<T>(values: &mut Vec<T>, capacity: usize) -> Result<()> {
45    values
46        .try_reserve_exact(capacity - values.len())
47        .map_err(|_| invalid("cannot reserve scale input"))
48}
49
50/// Whether categorical seeds are a fixed supply or may be extended deterministically.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum PaletteCapacity {
53    /// Reject if the active domain requires more colors than supplied.
54    Fixed,
55    /// Extend the exact prefix using the first-party deterministic color algorithm.
56    Extendable,
57}
58
59/// Nonempty opaque categorical colors and their explicit capacity policy.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct QualitativePalette {
62    colors: Arc<Vec<OpaqueColor>>,
63    capacity: PaletteCapacity,
64}
65
66impl QualitativePalette {
67    /// Construct a fixed nonempty color supply, preserving its exact order.
68    pub fn fixed(colors: impl IntoIterator<Item = OpaqueColor>) -> Result<Self> {
69        Ok(Self {
70            colors: retain(colors)?,
71            capacity: PaletteCapacity::Fixed,
72        })
73    }
74    /// Construct nonempty ordered seeds for deterministic extension without cycling.
75    pub fn extendable(colors: impl IntoIterator<Item = OpaqueColor>) -> Result<Self> {
76        Ok(Self {
77            colors: retain(colors)?,
78            capacity: PaletteCapacity::Extendable,
79        })
80    }
81    /// Borrow the supplied ordered colors, including any deliberate repeats.
82    pub fn colors(&self) -> &[OpaqueColor] {
83        &self.colors
84    }
85    /// Inspect the explicit supply policy.
86    pub fn capacity(&self) -> PaletteCapacity {
87        self.capacity
88    }
89}
90
91/// Independent nonempty mark-accent seeds, always deterministically extendable.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct AccentPalette {
94    seeds: Arc<Vec<OpaqueColor>>,
95}
96
97impl AccentPalette {
98    /// Retain nonempty ordered opaque seeds independently of categorical scales.
99    pub fn new(seeds: impl IntoIterator<Item = OpaqueColor>) -> Result<Self> {
100        Ok(Self {
101            seeds: retain(seeds)?,
102        })
103    }
104    /// Borrow the supplied ordered seeds.
105    pub fn seeds(&self) -> &[OpaqueColor] {
106        &self.seeds
107    }
108}
109
110/// One complete categorical selection: an ordered palette or an exact raw-key map.
111///
112/// ```
113/// use lichtung_plot::{CategoricalColorMap, CategoricalColorScale, OpaqueColor};
114/// let map = CategoricalColorMap::new([
115///     ("A  B".into(), OpaqueColor::rgb(17, 53, 89)),
116///     ("A B".into(), OpaqueColor::rgb(131, 47, 29)),
117/// ])?;
118/// let scale = CategoricalColorScale::from_map(map);
119/// assert!(scale.palette().is_none());
120/// # Ok::<(), lichtung_plot::Error>(())
121/// ```
122///
123/// Data scale colors do not silently discard element alpha:
124/// ```compile_fail
125/// use lichtung_plot::{Color, QualitativePalette};
126/// let _ = QualitativePalette::fixed([Color::rgba(17, 53, 89, 128)]);
127/// ```
128/// ```compile_fail
129/// use lichtung_plot::CategoricalColors;
130/// ```
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct CategoricalColorScale {
133    source: CategoricalSource,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137enum CategoricalSource {
138    Palette(QualitativePalette),
139    Map(CategoricalColorMap),
140}
141
142impl CategoricalColorScale {
143    /// Select a complete palette and its capacity policy.
144    pub fn from_palette(palette: QualitativePalette) -> Self {
145        Self {
146            source: CategoricalSource::Palette(palette),
147        }
148    }
149    /// Select an exact raw-key map; every active identity must be present.
150    pub fn from_map(map: CategoricalColorMap) -> Self {
151        Self {
152            source: CategoricalSource::Map(map),
153        }
154    }
155    /// Borrow the palette, or None for a map selection.
156    pub fn palette(&self) -> Option<&QualitativePalette> {
157        match &self.source {
158            CategoricalSource::Palette(palette) => Some(palette),
159            CategoricalSource::Map(_) => None,
160        }
161    }
162    /// Borrow the exact map, or None for a palette selection.
163    pub fn map(&self) -> Option<&CategoricalColorMap> {
164        match &self.source {
165            CategoricalSource::Map(map) => Some(map),
166            CategoricalSource::Palette(_) => None,
167        }
168    }
169}
170
171/// An exact semantic gradient offset in zero through one and an opaque color.
172#[derive(Debug, Clone, Copy, PartialEq)]
173pub struct ColorStop {
174    offset: f64,
175    color: OpaqueColor,
176}
177impl Eq for ColorStop {}
178
179impl ColorStop {
180    /// Construct a finite offset in zero through one, normalizing signed zero.
181    pub fn new(offset: f64, color: OpaqueColor) -> Result<Self> {
182        if !offset.is_finite() || !(0.0..=1.0).contains(&offset) {
183            return Err(invalid("gradient offset must be finite in 0..=1"));
184        }
185        Ok(Self {
186            offset: zero(offset),
187            color,
188        })
189    }
190    const fn builtin(offset: f64, color: OpaqueColor) -> Self {
191        assert!(offset.is_finite() && offset >= 0.0 && offset <= 1.0);
192        Self {
193            offset: if offset == 0.0 { 0.0 } else { offset },
194            color,
195        }
196    }
197    /// Inspect the exact normalized semantic offset.
198    pub fn offset(&self) -> f64 {
199        self.offset
200    }
201    /// Inspect the opaque chromatic mapping color.
202    pub fn color(&self) -> OpaqueColor {
203        self.color
204    }
205    pub(crate) fn backend_stop(&self) -> crate::render::backend::GradientStop {
206        crate::render::backend::GradientStop::new(self.offset(), self.color().as_rgb())
207    }
208}
209
210pub(crate) const HEATMAP_SEQUENTIAL_STOPS: [ColorStop; 2] = [
211    ColorStop::builtin(0.0, OpaqueColor::rgb(247, 251, 255)),
212    ColorStop::builtin(1.0, OpaqueColor::rgb(8, 48, 107)),
213];
214pub(crate) const HEATMAP_DIVERGING_STOPS: [ColorStop; 3] = [
215    ColorStop::builtin(0.0, OpaqueColor::rgb(49, 130, 189)),
216    ColorStop::builtin(0.5, OpaqueColor::rgb(247, 247, 247)),
217    ColorStop::builtin(1.0, OpaqueColor::rgb(222, 45, 38)),
218];
219
220fn validate_stops(stops: &[ColorStop], diverging: bool) -> Result<()> {
221    if stops.len() < if diverging { 3 } else { 2 }
222        || stops.first().is_none_or(|s| s.offset.to_bits() != 0)
223        || stops
224            .last()
225            .is_none_or(|s| s.offset.to_bits() != 1.0_f64.to_bits())
226        || stops
227            .windows(2)
228            .any(|pair| pair[0].offset >= pair[1].offset)
229        || (diverging
230            && !stops
231                .iter()
232                .any(|s| s.offset.to_bits() == 0.5_f64.to_bits()))
233    {
234        return Err(invalid("gradient must increase strictly from exactly 0 to 1 with an explicit diverging neutral center stop at 0.5"));
235    }
236    Ok(())
237}
238
239macro_rules! gradient {
240    ($name:ident, $diverging:expr) => {
241        #[derive(Debug, Clone, PartialEq, Eq)]
242        #[doc = concat!("Complete strictly ordered opaque `", stringify!($name), "` with exact zero/one endpoints.")]
243        pub struct $name {
244            stops: Arc<Vec<ColorStop>>,
245        }
246        impl $name {
247            /// Retain and validate every ordered semantic stop without sorting or repair.
248            /// Diverging input also requires one explicit neutral stop at exactly 0.5.
249            pub fn new(stops: impl IntoIterator<Item = ColorStop>) -> Result<Self> {
250                let stops = retain(stops)?;
251                validate_stops(&stops, $diverging)?;
252                Ok(Self { stops })
253            }
254            /// Borrow the complete ordered semantic stop sequence.
255            pub fn stops(&self) -> &[ColorStop] {
256                &self.stops
257            }
258        }
259    };
260}
261gradient!(SequentialGradient, false);
262gradient!(DivergingGradient, true);
263
264impl SequentialGradient {
265    /// Compare complete normalized content; immutable
266    /// payload sharing is a constant-work witness for the same exact value.
267    pub(crate) fn same_in(&self, other: &Self) -> bool {
268        if Arc::ptr_eq(&self.stops, &other.stops) {
269            return true;
270        }
271        if self.stops.len() != other.stops.len() {
272            return false;
273        }
274        for (left, right) in self.stops.iter().zip(other.stops.iter()) {
275            if left != right {
276                return false;
277            }
278        }
279        true
280    }
281}
282
283impl DivergingGradient {
284    /// Inspect the unique explicitly supplied neutral stop color at exactly 0.5.
285    pub fn neutral(&self) -> OpaqueColor {
286        self.stops()
287            .iter()
288            .find(|s| s.offset.to_bits() == 0.5_f64.to_bits())
289            .expect("validated neutral stop")
290            .color()
291    }
292}
293
294/// Complete default qualitative, sequential and diverging mappings of one theme.
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct ColorScales {
297    qualitative: QualitativePalette,
298    sequential: SequentialGradient,
299    diverging: DivergingGradient,
300}
301
302impl ColorScales {
303    /// Construct three complete validated default mappings.
304    pub fn new(
305        qualitative: QualitativePalette,
306        sequential: SequentialGradient,
307        diverging: DivergingGradient,
308    ) -> Result<Self> {
309        Ok(Self {
310            qualitative,
311            sequential,
312            diverging,
313        })
314    }
315    /// Borrow the default categorical palette, independent of mark accents.
316    pub fn get_qualitative(&self) -> &QualitativePalette {
317        &self.qualitative
318    }
319    /// Borrow the default sequential gradient.
320    pub fn get_sequential(&self) -> &SequentialGradient {
321        &self.sequential
322    }
323    /// Borrow the default diverging gradient.
324    pub fn get_diverging(&self) -> &DivergingGradient {
325        &self.diverging
326    }
327    /// Replace only the complete default categorical palette.
328    pub fn qualitative(self, value: QualitativePalette) -> Result<Self> {
329        Self::new(value, self.sequential, self.diverging)
330    }
331    /// Replace only the complete default sequential gradient.
332    pub fn sequential(self, value: SequentialGradient) -> Result<Self> {
333        Self::new(self.qualitative, value, self.diverging)
334    }
335    /// Replace only the complete default diverging gradient.
336    pub fn diverging(self, value: DivergingGradient) -> Result<Self> {
337        Self::new(self.qualitative, self.sequential, value)
338    }
339}
340
341fn zero(value: f64) -> f64 {
342    if value == 0.0 {
343        0.0
344    } else {
345        value
346    }
347}
348
349/// Finite exact color limits, including a constant domain.
350#[derive(Debug, Clone, PartialEq)]
351pub struct ColorDomain {
352    minimum: f64,
353    maximum: f64,
354}
355impl Eq for ColorDomain {}
356
357impl ColorDomain {
358    /// Construct finite minimum/maximum with maximum at least minimum; normalize zero.
359    pub fn exact(minimum: f64, maximum: f64) -> Result<Self> {
360        if !minimum.is_finite() || !maximum.is_finite() || maximum < minimum {
361            return Err(invalid(
362                "color domain must be finite and ascending, including a constant domain",
363            ));
364        }
365        Ok(Self {
366            minimum: zero(minimum),
367            maximum: zero(maximum),
368        })
369    }
370    /// Inspect the finite normalized minimum.
371    pub fn minimum(&self) -> f64 {
372        self.minimum
373    }
374    /// Inspect the finite normalized maximum.
375    pub fn maximum(&self) -> f64 {
376        self.maximum
377    }
378    pub(crate) fn as_pair(&self) -> (f64, f64) {
379        (self.minimum(), self.maximum())
380    }
381}
382
383/// Closed kind of a complete continuous-color selection.
384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385pub enum ContinuousScaleKind {
386    /// Sequential chromatic mapping.
387    Sequential,
388    /// Two semantic branches around an exact neutral center.
389    Diverging,
390}
391
392/// One complete continuous kind, optional gradient and optional exact domain.
393///
394/// ```
395/// use lichtung_plot::{ColorDomain, ColorStop, ContinuousColorScale,
396///     DivergingGradient, OpaqueColor};
397/// let gradient = DivergingGradient::new([
398///     ColorStop::new(0.0, OpaqueColor::hex("#204080")?)?,
399///     ColorStop::new(0.5, OpaqueColor::hex("#EEEEEE")?)?,
400///     ColorStop::new(1.0, OpaqueColor::hex("#A04020")?)?,
401/// ])?;
402/// let scale = ContinuousColorScale::diverging(
403///     0.0, Some(gradient), Some(ColorDomain::exact(-1.0, 3.0)?),
404/// )?;
405/// assert_eq!(scale.get_center(), Some(0.0));
406/// # Ok::<(), lichtung_plot::Error>(())
407/// ```
408///
409/// The replaced Heatmap-only selector is removed:
410/// ```compile_fail
411/// use lichtung_plot::HeatmapScale;
412/// ```
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub struct ContinuousColorScale {
415    selection: ContinuousSelection,
416    domain: Option<ColorDomain>,
417}
418#[derive(Debug, Clone, PartialEq)]
419enum ContinuousSelection {
420    Sequential(Option<SequentialGradient>),
421    Diverging {
422        center: f64,
423        gradient: Option<DivergingGradient>,
424    },
425}
426impl Eq for ContinuousSelection {}
427
428impl ContinuousColorScale {
429    /// Select sequential mapping; None gradient/domain means owner default/automatic domain.
430    pub fn sequential(
431        gradient: Option<SequentialGradient>,
432        domain: Option<ColorDomain>,
433    ) -> Result<Self> {
434        Ok(Self {
435            selection: ContinuousSelection::Sequential(gradient),
436            domain,
437        })
438    }
439    /// Select a finite center and optional complete gradient/domain containing that center.
440    pub fn diverging(
441        center: f64,
442        gradient: Option<DivergingGradient>,
443        domain: Option<ColorDomain>,
444    ) -> Result<Self> {
445        let value = Self {
446            selection: ContinuousSelection::Diverging {
447                center: zero(center),
448                gradient,
449            },
450            domain,
451        };
452        value.validate()?;
453        Ok(value)
454    }
455    fn validate(&self) -> Result<()> {
456        if let Some(center) = self.get_center() {
457            if !center.is_finite()
458                || self
459                    .domain
460                    .as_ref()
461                    .is_some_and(|domain| center < domain.minimum || center > domain.maximum)
462            {
463                return Err(invalid(
464                    "diverging center must be finite and the exact domain must contain center",
465                ));
466            }
467        }
468        Ok(())
469    }
470    /// Inspect the closed mapping kind.
471    pub fn kind(&self) -> ContinuousScaleKind {
472        match self.selection {
473            ContinuousSelection::Sequential(_) => ContinuousScaleKind::Sequential,
474            ContinuousSelection::Diverging { .. } => ContinuousScaleKind::Diverging,
475        }
476    }
477    /// Inspect the exact diverging center, or None for sequential mapping.
478    pub fn get_center(&self) -> Option<f64> {
479        match self.selection {
480            ContinuousSelection::Sequential(_) => None,
481            ContinuousSelection::Diverging { center, .. } => Some(center),
482        }
483    }
484    /// Borrow the optional exact domain; None means automatic from active finite values.
485    pub fn get_domain(&self) -> Option<&ColorDomain> {
486        self.domain.as_ref()
487    }
488    /// Borrow a supplied sequential gradient, if this is its selected kind.
489    pub fn get_sequential_gradient(&self) -> Option<&SequentialGradient> {
490        match &self.selection {
491            ContinuousSelection::Sequential(gradient) => gradient.as_ref(),
492            ContinuousSelection::Diverging { .. } => None,
493        }
494    }
495    /// Borrow a supplied diverging gradient, if this is its selected kind.
496    pub fn get_diverging_gradient(&self) -> Option<&DivergingGradient> {
497        match &self.selection {
498            ContinuousSelection::Diverging { gradient, .. } => gradient.as_ref(),
499            ContinuousSelection::Sequential(_) => None,
500        }
501    }
502    /// Replace the optional exact domain, preserving kind and any center containment.
503    pub fn domain(mut self, domain: Option<ColorDomain>) -> Result<Self> {
504        self.domain = domain;
505        self.validate()?;
506        Ok(self)
507    }
508    /// Replace a diverging center; reject sequential kind or an excluding exact domain.
509    pub fn center(mut self, value: f64) -> Result<Self> {
510        let ContinuousSelection::Diverging { center, .. } = &mut self.selection else {
511            return Err(invalid("sequential scale has no center"));
512        };
513        *center = zero(value);
514        self.validate()?;
515        Ok(self)
516    }
517    /// Replace the optional sequential gradient; reject a diverging selection.
518    pub fn sequential_gradient(mut self, value: Option<SequentialGradient>) -> Result<Self> {
519        let ContinuousSelection::Sequential(gradient) = &mut self.selection else {
520            return Err(invalid("diverging scale cannot take a sequential gradient"));
521        };
522        *gradient = value;
523        self.validate()?;
524        Ok(self)
525    }
526    /// Replace the optional diverging gradient; reject a sequential selection.
527    pub fn diverging_gradient(mut self, value: Option<DivergingGradient>) -> Result<Self> {
528        let ContinuousSelection::Diverging { gradient, .. } = &mut self.selection else {
529            return Err(invalid("sequential scale cannot take a diverging gradient"));
530        };
531        *gradient = value;
532        self.validate()?;
533        Ok(self)
534    }
535    pub(crate) fn stops(&self) -> Result<&[ColorStop]> {
536        match &self.selection {
537            ContinuousSelection::Sequential(Some(gradient)) => Ok(gradient.stops()),
538            ContinuousSelection::Diverging {
539                gradient: Some(gradient),
540                ..
541            } => Ok(gradient.stops()),
542            _ => Err(Error::Render(
543                "prepared continuous selection has no retained gradient".into(),
544            )),
545        }
546    }
547}
548
549#[cfg(test)]
550mod tests;