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.payload_mut().alpha.set(target, encoding);
205 let role = match target {
206 AlphaTarget::Point => crate::data::DataRole::PointAlpha,
207 AlphaTarget::Line => crate::data::DataRole::LineAlpha,
208 AlphaTarget::Fill => crate::data::DataRole::FillAlpha,
209 };
210 self.description.renew_role(role);
211 self.description
212 .renew_domain(crate::data::DomainSlot::Alpha(role));
213 self
214 }
215
216 /// Inspect the authored point-fill encoding. An absent target has Theme
217 /// as its default declaration and no bound values.
218 #[must_use]
219 pub fn get_point_alpha(&self) -> &AlphaEncoding {
220 self.description.alpha_inputs().get(AlphaTarget::Point)
221 }
222
223 /// Inspect the authored scientific-stroke encoding.
224 #[must_use]
225 pub fn get_line_alpha(&self) -> &AlphaEncoding {
226 self.description.alpha_inputs().get(AlphaTarget::Line)
227 }
228
229 /// Inspect the authored area/body/cell fill encoding.
230 #[must_use]
231 pub fn get_fill_alpha(&self) -> &AlphaEncoding {
232 self.description.alpha_inputs().get(AlphaTarget::Fill)
233 }
234}
235
236impl PlotDescription {
237 pub(crate) fn alpha_inputs(&self) -> &AlphaInputs {
238 &self.payload.alpha
239 }
240
241 pub(crate) fn prepare_alpha(
242 &self,
243 target: AlphaTarget,
244 unit: AlphaUnitKind,
245 required_fields: &[RawKey],
246 ) -> Result<PreparedAlpha, crate::Error> {
247 let mut facets = Vec::new();
248 if let Some(facet) = &self.payload.facet {
249 crate::data::source::reserve_source(&mut facets, 3)?;
250 facets.extend(facet.values().map(CategoryValues::original_field));
251 }
252 let original_len = if let Some(geometry) = self.raincloud_geometry_input() {
253 geometry.data.point_y.len()
254 } else {
255 self.row_count()
256 };
257 self.payload
258 .alpha
259 .get(target)
260 .prepare(unit, original_len, required_fields, &facets)
261 }
262
263 pub(crate) fn prepare_scoped_alpha(
264 &self,
265 target: AlphaTarget,
266 unit: AlphaUnitKind,
267 required_fields: &[RawKey],
268 facet: Option<crate::orchestrator::registration::FacetSelector<'_, '_>>,
269 ) -> crate::Result<ScopedAlpha> {
270 let prepared = self.prepare_alpha(target, unit, required_fields)?;
271 let mut facets = Vec::new();
272 if let Some(facet) = facet {
273 for (_, values, raw) in facet.fields() {
274 if !prepared
275 .selector_fields()
276 .contains(&values.original_field())
277 {
278 continue;
279 }
280 crate::data::source::reserve_source(&mut facets, 1)?;
281 facets.push(raw_unit(values, raw)?);
282 }
283 }
284 Ok(ScopedAlpha { prepared, facets })
285 }
286
287 pub(crate) fn prepare_collective_alpha(
288 &self,
289 target: AlphaTarget,
290 unit: AlphaUnitKind,
291 include_hue: bool,
292 facet: Option<crate::orchestrator::registration::FacetSelector<'_, '_>>,
293 ) -> crate::Result<ScopedAlpha> {
294 let mut fields = Vec::new();
295 crate::data::source::reserve_source(&mut fields, 2)?;
296 fields.extend(
297 self.legend_group_values()
298 .map(CategoryValues::original_field),
299 );
300 if include_hue {
301 fields.extend(self.legend_hue_values().map(CategoryValues::original_field));
302 }
303 self.prepare_scoped_alpha(target, unit, &fields, facet)
304 }
305}