1use std::sync::Arc;
4
5use super::{collect_input, numeric_key, validated_name, AlphaValues};
6use crate::data::source::{collect_source, copy_source_string, sort_source_by, source_arc};
7use crate::{Bounds, CategoryValues, Error, Result};
8
9#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct AlphaEncoding {
33 binding: Binding,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Eq)]
37enum Binding {
38 #[default]
39 Theme,
40 Observations(AlphaValues),
41 Single(AlphaValues),
42 Keyed(Arc<SelectorTable>, AlphaValues),
43 Bins(Arc<BinTable>, AlphaValues),
44}
45
46#[derive(Debug, PartialEq, Eq)]
47struct SelectorTable {
48 fields: Vec<String>,
49 rows: Vec<Vec<String>>,
50 order: Vec<usize>,
51}
52
53#[derive(Debug, PartialEq, Eq)]
54struct BinTable {
55 facets: SelectorTable,
56 bounds: Vec<[u64; 2]>,
57 order: Vec<usize>,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub(crate) enum AlphaUnitKind {
63 Observation,
64 Series,
65 Aggregate,
66 Bin,
67 Single,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub(crate) struct PreparedAlpha {
72 encoding: AlphaEncoding,
73 unit: AlphaUnitKind,
74 original_len: usize,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub(crate) struct ResolvedAlpha {
80 pub(crate) index: usize,
81 pub(crate) alpha: u8,
82}
83
84impl AlphaEncoding {
85 #[must_use]
87 pub const fn theme() -> Self {
88 Self {
89 binding: Binding::Theme,
90 }
91 }
92
93 #[must_use]
95 pub fn observations(values: AlphaValues) -> Self {
96 Self {
97 binding: Binding::Observations(values),
98 }
99 }
100
101 pub fn single(values: AlphaValues) -> Result<Self> {
103 if values.len() != 1 {
104 return Err(Error::Data(
105 "single alpha requires exactly one value".into(),
106 ));
107 }
108 Ok(Self {
109 binding: Binding::Single(values),
110 })
111 }
112
113 pub fn keyed(
121 keys: impl IntoIterator<Item = CategoryValues>,
122 values: AlphaValues,
123 ) -> Result<Self> {
124 let table = SelectorTable::new(keys, values.len())?;
125 if table.fields.is_empty() {
126 return Err(Error::Data(
127 "keyed alpha requires at least one selector field".into(),
128 ));
129 }
130 if table
131 .order
132 .windows(2)
133 .any(|pair| table.rows[pair[0]] == table.rows[pair[1]])
134 {
135 return Err(Error::Data(
136 "keyed alpha contains duplicate selector tuples".into(),
137 ));
138 }
139 Ok(Self {
140 binding: Binding::Keyed(source_arc(table)?, values),
141 })
142 }
143
144 #[expect(
151 clippy::needless_pass_by_value,
152 reason = "the public constructor consumes exact bounds while retaining normalized interval keys"
153 )]
154 pub fn bins(
155 bounds: Bounds,
156 facets: impl IntoIterator<Item = CategoryValues>,
157 values: AlphaValues,
158 ) -> Result<Self> {
159 if bounds.lower().len() != values.len() || bounds.upper().len() != values.len() {
160 return Err(Error::Data(
161 "alpha bin bounds must align with the alpha values".into(),
162 ));
163 }
164 let facets = SelectorTable::new(facets, values.len())?;
165 let bounds = collect_source((0..values.len()).map(|index| {
166 let low = bounds.lower().get(index).flatten();
167 let high = bounds.upper().get(index).flatten();
168 match (low, high) {
169 (Some(low), Some(high)) if low.is_finite() && high.is_finite() && low < high => {
170 Ok([numeric_key(low), numeric_key(high)])
171 }
172 _ => Err(Error::Data(format!(
173 "alpha bin at index {index} requires finite nonmissing lower < upper bounds"
174 ))),
175 }
176 }))?;
177 let mut order = collect_source((0..values.len()).map(Ok))?;
178 sort_source_by(&mut order, |a, b| {
179 facets.rows[*a]
180 .cmp(&facets.rows[*b])
181 .then(bounds[*a].cmp(&bounds[*b]))
182 });
183 if order.windows(2).any(|pair| {
184 facets.rows[pair[0]] == facets.rows[pair[1]] && bounds[pair[0]] == bounds[pair[1]]
185 }) {
186 return Err(Error::Data(
187 "alpha bins contain duplicate exact interval/facet keys".into(),
188 ));
189 }
190 Ok(Self {
191 binding: Binding::Bins(
192 source_arc(BinTable {
193 facets,
194 bounds,
195 order,
196 })?,
197 values,
198 ),
199 })
200 }
201
202 #[must_use]
204 pub const fn is_theme(&self) -> bool {
205 matches!(self.binding, Binding::Theme)
206 }
207
208 #[must_use]
210 pub const fn values(&self) -> Option<&AlphaValues> {
211 match &self.binding {
212 Binding::Theme => None,
213 Binding::Observations(values)
214 | Binding::Single(values)
215 | Binding::Keyed(_, values)
216 | Binding::Bins(_, values) => Some(values),
217 }
218 }
219
220 pub(crate) fn prepare(
223 &self,
224 unit: AlphaUnitKind,
225 original_len: usize,
226 required_fields: &[&str],
227 facet_fields: &[&str],
228 ) -> Result<PreparedAlpha> {
229 match &self.binding {
230 Binding::Theme | Binding::Single(_) => {}
231 Binding::Observations(values) if unit == AlphaUnitKind::Observation => {
232 if values.len() != original_len {
233 return Err(Error::Data(format!(
234 "observation alpha {:?} has length {}, expected all {original_len} original input slots",
235 values.name(), values.len(),
236 )));
237 }
238 }
239 Binding::Keyed(table, _)
240 if matches!(unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) =>
241 {
242 table.validate_schema(required_fields, facet_fields)?;
243 }
244 Binding::Bins(table, _) if unit == AlphaUnitKind::Bin => {
245 table.facets.validate_schema(&[], facet_fields)?;
246 }
247 _ => {
248 return Err(Error::Data(format!(
249 "alpha binding does not support {unit:?} units"
250 )))
251 }
252 }
253 Ok(PreparedAlpha {
254 encoding: self.clone(),
255 unit,
256 original_len,
257 })
258 }
259}
260
261impl SelectorTable {
262 fn new(keys: impl IntoIterator<Item = CategoryValues>, len: usize) -> Result<Self> {
263 let mut keys = collect_input(keys)?;
264 sort_source_by(&mut keys, |a, b| a.name().cmp(b.name()));
265 let fields = collect_source(keys.iter().map(|column| {
266 if column.len() != len {
267 return Err(Error::Data(format!(
268 "alpha selector {:?} has length {}, expected {len}",
269 column.name(),
270 column.len()
271 )));
272 }
273 validated_name(copy_source_string(column.name())?)
274 }))?;
275 if fields.windows(2).any(|pair| pair[0] == pair[1]) {
276 return Err(Error::Data(
277 "alpha selector field names must be unique".into(),
278 ));
279 }
280 let rows = collect_source((0..len).map(|index| {
281 collect_source(keys.iter().map(|column| {
282 let raw = column.get(index).flatten().ok_or_else(|| {
283 Error::Data(format!(
284 "alpha selector {:?} is missing at index {index}",
285 column.name()
286 ))
287 })?;
288 copy_source_string(raw)
289 }))
290 }))?;
291 let mut order = collect_source((0..len).map(Ok))?;
292 sort_source_by(&mut order, |a, b| rows[*a].cmp(&rows[*b]));
293 Ok(Self {
294 fields,
295 rows,
296 order,
297 })
298 }
299
300 fn validate_schema(&self, required: &[&str], facets: &[&str]) -> Result<()> {
301 for field in &self.fields {
302 if !required.contains(&field.as_str()) && !facets.contains(&field.as_str()) {
303 return Err(Error::Data(format!(
304 "alpha selector {field:?} is not an actual unit or owning facet field"
305 )));
306 }
307 }
308 for field in required {
309 if !self.fields.iter().any(|name| name == field) {
310 return Err(Error::Data(format!(
311 "alpha binding is missing required unit field {field:?}"
312 )));
313 }
314 }
315 Ok(())
316 }
317
318 fn tuple<'a>(&self, keys: &[(&str, &'a str)]) -> Result<Vec<&'a str>> {
319 for (index, &(field, value)) in keys.iter().enumerate() {
320 if keys[..index]
321 .iter()
322 .any(|&(other, raw)| other == field && raw != value)
323 {
324 return Err(Error::Data(format!(
325 "actual alpha unit has conflicting raw values for field {field:?}"
326 )));
327 }
328 }
329 collect_source(self.fields.iter().map(|field| {
330 keys.iter()
331 .find(|(name, _)| *name == field)
332 .map(|(_, raw)| *raw)
333 .ok_or_else(|| {
334 Error::Data(format!(
335 "actual alpha unit has no value for selector field {field:?}"
336 ))
337 })
338 }))
339 }
340
341 fn compare_row(&self, index: usize, tuple: &[&str]) -> std::cmp::Ordering {
342 self.rows[index]
343 .iter()
344 .map(String::as_str)
345 .cmp(tuple.iter().copied())
346 }
347}
348
349impl PreparedAlpha {
350 pub(crate) fn selector_fields(&self) -> &[String] {
351 match &self.encoding.binding {
352 Binding::Keyed(table, _) => &table.fields,
353 Binding::Bins(table, _) => &table.facets.fields,
354 Binding::Theme | Binding::Observations(_) | Binding::Single(_) => &[],
355 }
356 }
357
358 fn resolved(&self, index: usize) -> Result<Option<ResolvedAlpha>> {
359 self.encoding
360 .values()
361 .map(|values| {
362 values
363 .get(index)
364 .map(|alpha| ResolvedAlpha { index, alpha })
365 .ok_or_else(|| {
366 Error::Data(format!(
367 "alpha source {:?} has no original slot {index}",
368 values.name()
369 ))
370 })
371 })
372 .transpose()
373 }
374
375 fn constant(&self) -> Option<Result<Option<ResolvedAlpha>>> {
376 match &self.encoding.binding {
377 Binding::Theme => Some(Ok(None)),
378 Binding::Single(_) => Some(self.resolved(0)),
379 _ => None,
380 }
381 }
382
383 pub(crate) fn observation(
384 &self,
385 index: usize,
386 source_row: usize,
387 ) -> Result<Option<ResolvedAlpha>> {
388 if self.unit != AlphaUnitKind::Observation {
389 return Err(Error::Data(
390 "alpha source requires an observation unit".into(),
391 ));
392 }
393 if index >= self.original_len {
394 return Err(Error::Data(format!(
395 "alpha original slot {index} is outside length {} at diagnostic source row {source_row}",
396 self.original_len,
397 )));
398 }
399 self.constant()
400 .unwrap_or_else(|| self.resolved(index))
401 .map_err(|error| Error::Data(format!("{error} at diagnostic source row {source_row}")))
402 }
403
404 pub(crate) fn single(&self) -> Result<Option<ResolvedAlpha>> {
405 if self.unit != AlphaUnitKind::Single {
406 return Err(Error::Data("alpha source requires a single unit".into()));
407 }
408 self.resolved(0)
409 }
410
411 pub(crate) fn keyed(&self, keys: &[(&str, &str)]) -> Result<Option<ResolvedAlpha>> {
412 if !matches!(self.unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) {
413 return Err(Error::Data(
414 "alpha source requires a series or aggregate unit".into(),
415 ));
416 }
417 if let Some(value) = self.constant() {
418 return value;
419 }
420 let Binding::Keyed(table, _) = &self.encoding.binding else {
421 unreachable!("prepared keyed binding")
422 };
423 let tuple = table.tuple(keys)?;
424 let position = table
425 .order
426 .binary_search_by(|&index| table.compare_row(index, &tuple))
427 .map_err(|_| {
428 Error::Data(format!(
429 "alpha binding has no value for actual raw unit {keys:?}"
430 ))
431 })?;
432 self.resolved(table.order[position])
433 }
434
435 pub(crate) fn bin(
436 &self,
437 bounds: (f64, f64),
438 facets: &[(&str, &str)],
439 ) -> Result<Option<ResolvedAlpha>> {
440 if self.unit != AlphaUnitKind::Bin {
441 return Err(Error::Data("alpha source requires a bin unit".into()));
442 }
443 if !bounds.0.is_finite() || !bounds.1.is_finite() || bounds.0 >= bounds.1 {
444 return Err(Error::Data(
445 "actual alpha bin must have finite lower < upper bounds".into(),
446 ));
447 }
448 if let Some(value) = self.constant() {
449 return value;
450 }
451 let Binding::Bins(table, _) = &self.encoding.binding else {
452 unreachable!("prepared bin binding")
453 };
454 let tuple = table.facets.tuple(facets)?;
455 let key = [numeric_key(bounds.0), numeric_key(bounds.1)];
456 let position = table
457 .order
458 .binary_search_by(|&index| {
459 table
460 .facets
461 .compare_row(index, &tuple)
462 .then(table.bounds[index].cmp(&key))
463 })
464 .map_err(|_| {
465 Error::Data(format!(
466 "alpha binding has no value for exact actual bin {bounds:?} in {facets:?}"
467 ))
468 })?;
469 self.resolved(table.order[position])
470 }
471}
472
473#[cfg(test)]
474mod tests;