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