Skip to main content

lichtung_plot/builder/
alpha.rs

1use super::{Plot, PlotDescription};
2use crate::alpha::{
3    AlphaEncoding, AlphaInputs, AlphaTarget, AlphaUnitKind, PreparedAlpha, ResolvedAlpha,
4};
5use crate::{data::RawKey, CategoryValues};
6
7pub(crate) struct ScopedAlpha {
8    prepared: PreparedAlpha,
9    facets: Vec<(RawKey, RawKey)>,
10}
11
12fn raw_unit(values: &CategoryValues, level: &str) -> crate::Result<(RawKey, RawKey)> {
13    let key = values.key_for_level(level).ok_or_else(|| {
14        crate::Error::Render("actual alpha unit has no original category key".into())
15    })?;
16    Ok((values.original_field(), key))
17}
18
19impl ScopedAlpha {
20    pub(crate) fn bin(&self, bounds: (f64, f64)) -> crate::Result<Option<ResolvedAlpha>> {
21        self.prepared.bin(bounds, &self.facets)
22    }
23
24    pub(crate) fn keyed(&self, unit: &[(RawKey, RawKey)]) -> crate::Result<Option<ResolvedAlpha>> {
25        if self.prepared.selector_fields().is_empty() {
26            return self.prepared.keyed(&[]);
27        }
28        let count = unit
29            .len()
30            .checked_add(self.facets.len())
31            .ok_or_else(|| crate::Error::Data("alpha actual unit key count overflow".into()))?;
32        let mut keys = Vec::new();
33        crate::data::source::reserve_source(&mut keys, count)?;
34        keys.extend_from_slice(unit);
35        keys.extend_from_slice(&self.facets);
36        self.prepared.keyed(&keys)
37    }
38
39    pub(crate) fn collective(
40        &self,
41        chart: &PlotDescription,
42        identity: &crate::data::CollectivePair,
43    ) -> crate::Result<Option<ResolvedAlpha>> {
44        if self.prepared.selector_fields().is_empty() {
45            return self.prepared.keyed(&[]);
46        }
47        let group = chart
48            .legend_group_values()
49            .zip(identity.group.as_deref())
50            .map(|(values, level)| raw_unit(values, level))
51            .transpose()?;
52        let hue = chart
53            .legend_hue_values()
54            .zip(identity.hue.as_deref())
55            .map(|(values, level)| raw_unit(values, level))
56            .transpose()?;
57        match (group, hue) {
58            (Some(group), Some(hue)) => self.keyed(&[group, hue]),
59            (Some(group), None) => self.keyed(&[group]),
60            (None, Some(hue)) => self.keyed(&[hue]),
61            (None, None) => self.keyed(&[]),
62        }
63    }
64
65    pub(crate) fn aggregate(
66        &self,
67        category: (&CategoryValues, &str),
68        series: Option<(&CategoryValues, &str)>,
69    ) -> crate::Result<Option<ResolvedAlpha>> {
70        if self.prepared.selector_fields().is_empty() {
71            return self.prepared.keyed(&[]);
72        }
73        let category = raw_unit(category.0, category.1)?;
74        if let Some(series) = series {
75            self.keyed(&[category, raw_unit(series.0, series.1)?])
76        } else {
77            self.keyed(&[category])
78        }
79    }
80}
81
82impl<K: crate::kind::Marker> Plot<K> {
83    /// Replace point-fill alpha using original observations or explicit Single.
84    ///
85    /// Outlines and supplemental layers remain independently owned. Repeated
86    /// calls replace the complete target; [`AlphaEncoding::theme`] resets it.
87    /// Resolve normal RGB/role/exact paint first, then replace alpha, never multiply.
88    /// Declared mappings add a common-guide section; fixed or undeclared coefficients do not.
89    ///
90    /// ```
91    /// use lichtung_plot::{NumericValues, Plot, scales::{AlphaEncoding, AlphaValues}};
92    /// let plot = Plot::scatter(NumericValues::new("x", [0.0, 1.0]),
93    ///     NumericValues::new("y", [1.0, 0.0]))
94    ///     .point_alpha(AlphaEncoding::observations(AlphaValues::linear(
95    ///         NumericValues::new("confidence", [0.2, 0.8]), (0.0, 1.0), (0.0, 1.0),
96    ///     )?))?;
97    /// # let _ = plot;
98    /// # Ok::<(), lichtung_plot::Error>(())
99    /// ```
100    ///
101    /// ```compile_fail
102    /// use lichtung_plot::{Plot, scales::AlphaEncoding};
103    /// fn erased(plot: Plot) { let _ = plot.point_alpha(AlphaEncoding::theme()); }
104    /// ```
105    /// ```compile_fail
106    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
107    /// fn unsupported(plot: Plot<kind::Density>) { let _ = plot.point_alpha(AlphaEncoding::theme()); }
108    /// ```
109    /// ```compile_fail
110    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
111    /// fn unsupported(plot: Plot<kind::Heatmap>, alpha: AlphaEncoding) { let _ = plot.point_alpha(alpha); }
112    /// ```
113    /// ```compile_fail
114    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
115    /// fn unsupported(plot: Plot<kind::Bar>, alpha: AlphaEncoding) { let _ = plot.point_alpha(alpha); }
116    /// ```
117    /// ```compile_fail
118    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
119    /// fn unsupported(plot: Plot<kind::Waterfall>, alpha: AlphaEncoding) { let _ = plot.point_alpha(alpha); }
120    /// ```
121    pub fn point_alpha(
122        self,
123        alpha: impl TryInto<AlphaEncoding, Error: Into<crate::Error>>,
124    ) -> crate::Result<Self>
125    where
126        K: crate::kind::PointAlpha,
127    {
128        Ok(self.with_alpha(AlphaTarget::Point, alpha.try_into().map_err(Into::into)?))
129    }
130
131    /// Replace admitted scientific-stroke alpha using explicit actual-unit values.
132    ///
133    /// Qq/Regression/optional Histogram curves use Single; estimates and Dumbbell
134    /// use original records; paths/Density/Interaction use actual series; categorical
135    /// summaries use category/positioned-series aggregates. Unlisted references,
136    /// points, fills, outlines and supplemental layers retain their own paints.
137    /// Absent optional components still validate binding kind/schema before fonts.
138    ///
139    /// ```compile_fail
140    /// use lichtung_plot::{Plot, scales::AlphaEncoding};
141    /// fn erased(plot: Plot) { let _ = plot.line_alpha(AlphaEncoding::theme()); }
142    /// ```
143    /// ```compile_fail
144    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
145    /// fn unsupported(plot: Plot<kind::Scatter>) { let _ = plot.line_alpha(AlphaEncoding::theme()); }
146    /// ```
147    /// ```compile_fail
148    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
149    /// fn unsupported(plot: Plot<kind::StackedBar>, alpha: AlphaEncoding) { let _ = plot.line_alpha(alpha); }
150    /// ```
151    /// ```compile_fail
152    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
153    /// fn unsupported(plot: Plot<kind::Marginal>, alpha: AlphaEncoding) { let _ = plot.line_alpha(alpha); }
154    /// ```
155    pub fn line_alpha(
156        self,
157        alpha: impl TryInto<AlphaEncoding, Error: Into<crate::Error>>,
158    ) -> crate::Result<Self>
159    where
160        K: crate::kind::LineAlpha,
161    {
162        Ok(self.with_alpha(AlphaTarget::Line, alpha.try_into().map_err(Into::into)?))
163    }
164
165    /// Replace admitted scientific area/body/cell fill alpha, independently of outlines.
166    ///
167    /// Histogram uses exact bins; Heatmap/Waterfall use original records; Line and
168    /// Density/native densities use actual series; categorical bodies use actual
169    /// aggregates; Regression bands use Single. Zero preserves scientific members.
170    /// Normal RGB/role/exact paint resolves before alpha replacement. Repeated calls
171    /// replace only this complete target; [`AlphaEncoding::theme`] resets it.
172    ///
173    /// ```compile_fail
174    /// use lichtung_plot::{Plot, scales::AlphaEncoding};
175    /// fn erased(plot: Plot) { let _ = plot.fill_alpha(AlphaEncoding::theme()); }
176    /// ```
177    /// ```compile_fail
178    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
179    /// fn unsupported(plot: Plot<kind::Trajectory>) { let _ = plot.fill_alpha(AlphaEncoding::theme()); }
180    /// ```
181    /// ```compile_fail
182    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
183    /// fn unsupported(plot: Plot<kind::Scatter>, alpha: AlphaEncoding) { let _ = plot.fill_alpha(alpha); }
184    /// ```
185    /// ```compile_fail
186    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
187    /// fn unsupported(plot: Plot<kind::Interaction>, alpha: AlphaEncoding) { let _ = plot.fill_alpha(alpha); }
188    /// ```
189    /// ```compile_fail
190    /// use lichtung_plot::{kind, Plot, scales::AlphaEncoding};
191    /// fn unsupported(plot: Plot<kind::Beeswarm>, alpha: AlphaEncoding) { let _ = plot.fill_alpha(alpha); }
192    /// ```
193    pub fn fill_alpha(
194        self,
195        alpha: impl TryInto<AlphaEncoding, Error: Into<crate::Error>>,
196    ) -> crate::Result<Self>
197    where
198        K: crate::kind::FillAlpha,
199    {
200        Ok(self.with_alpha(AlphaTarget::Fill, alpha.try_into().map_err(Into::into)?))
201    }
202
203    pub(crate) fn with_alpha(mut self, target: AlphaTarget, encoding: AlphaEncoding) -> Self {
204        self.description.replace_alpha(target, encoding);
205        self
206    }
207}
208
209impl PlotDescription {
210    pub(super) fn replace_alpha(&mut self, target: AlphaTarget, encoding: AlphaEncoding) {
211        self.payload_mut().alpha.set(target, encoding);
212        let role = match target {
213            AlphaTarget::Point => crate::data::DataRole::PointAlpha,
214            AlphaTarget::Line => crate::data::DataRole::LineAlpha,
215            AlphaTarget::Fill => crate::data::DataRole::FillAlpha,
216        };
217        self.renew_role(role);
218        self.renew_domain(crate::data::DomainSlot::Alpha(role));
219    }
220}
221
222impl<K: crate::kind::Marker> Plot<K> {
223    /// Inspect the authored point-fill encoding. An absent target has Theme
224    /// as its default declaration and no bound values.
225    #[must_use]
226    pub fn get_point_alpha(&self) -> &AlphaEncoding {
227        self.description.alpha_inputs().get(AlphaTarget::Point)
228    }
229
230    /// Inspect the authored scientific-stroke encoding.
231    #[must_use]
232    pub fn get_line_alpha(&self) -> &AlphaEncoding {
233        self.description.alpha_inputs().get(AlphaTarget::Line)
234    }
235
236    /// Inspect the authored area/body/cell fill encoding.
237    #[must_use]
238    pub fn get_fill_alpha(&self) -> &AlphaEncoding {
239        self.description.alpha_inputs().get(AlphaTarget::Fill)
240    }
241}
242
243impl PlotDescription {
244    pub(crate) fn alpha_inputs(&self) -> &AlphaInputs {
245        &self.payload.alpha
246    }
247
248    pub(crate) fn prepare_alpha(
249        &self,
250        target: AlphaTarget,
251        unit: AlphaUnitKind,
252        required_fields: &[RawKey],
253    ) -> Result<PreparedAlpha, crate::Error> {
254        let mut facets = Vec::new();
255        if let Some(facet) = &self.payload.facet {
256            crate::data::source::reserve_source(&mut facets, 3)?;
257            facets.extend(facet.values().map(CategoryValues::original_field));
258        }
259        let original_len = if let Some(geometry) = self.raincloud_geometry_input() {
260            geometry.data.point_y.len()
261        } else {
262            self.row_count()
263        };
264        self.payload
265            .alpha
266            .get(target)
267            .prepare(unit, original_len, required_fields, &facets)
268    }
269
270    pub(crate) fn prepare_scoped_alpha(
271        &self,
272        target: AlphaTarget,
273        unit: AlphaUnitKind,
274        required_fields: &[RawKey],
275        facet: Option<crate::orchestrator::registration::FacetSelector<'_, '_>>,
276    ) -> crate::Result<ScopedAlpha> {
277        let prepared = self.prepare_alpha(target, unit, required_fields)?;
278        let mut facets = Vec::new();
279        if let Some(facet) = facet {
280            for (_, values, raw) in facet.fields() {
281                if !prepared
282                    .selector_fields()
283                    .contains(&values.original_field())
284                {
285                    continue;
286                }
287                crate::data::source::reserve_source(&mut facets, 1)?;
288                facets.push(raw_unit(values, raw)?);
289            }
290        }
291        Ok(ScopedAlpha { prepared, facets })
292    }
293
294    pub(crate) fn prepare_collective_alpha(
295        &self,
296        target: AlphaTarget,
297        unit: AlphaUnitKind,
298        include_hue: bool,
299        facet: Option<crate::orchestrator::registration::FacetSelector<'_, '_>>,
300    ) -> crate::Result<ScopedAlpha> {
301        let mut fields = Vec::new();
302        crate::data::source::reserve_source(&mut fields, 2)?;
303        fields.extend(
304            self.legend_group_values()
305                .map(CategoryValues::original_field),
306        );
307        if include_hue {
308            fields.extend(self.legend_hue_values().map(CategoryValues::original_field));
309        }
310        self.prepare_scoped_alpha(target, unit, &fields, facet)
311    }
312}