1use std::sync::Arc;
4
5use super::{collect_input, numeric_key, validated_alpha, AlphaValues};
6use crate::data::source::{collect_source, sort_source_by, source_arc};
7use crate::{
8 data::{Bounds, KeyColumns, KeyValues, NamedKeyValues, RawKey, RawKeyValues},
9 CategoryValues, Error, Result,
10};
11
12#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct AlphaEncoding {
36 binding: Binding,
37}
38
39#[derive(Debug, Clone, Default, PartialEq)]
40enum Binding {
41 #[default]
42 Theme,
43 Fixed(f64),
44 Observations(AlphaValues),
45 Single(AlphaValues),
46 Keyed(Arc<SelectorTable>, AlphaValues),
47 Bins(Arc<BinTable>, AlphaValues),
48}
49
50impl Eq for Binding {}
51
52#[derive(Debug)]
53struct SelectorTable {
54 columns: KeyColumns,
55 member_keys: Option<RawKeyValues>,
56 fields: Vec<RawKey>,
57 rows: Vec<Vec<Vec<u8>>>,
58 order: Vec<usize>,
59}
60
61#[derive(Debug, PartialEq, Eq)]
62struct BinTable {
63 facets: SelectorTable,
64 original_bounds: Bounds,
65 member_keys: RawKeyValues,
66 bounds: Vec<[u64; 2]>,
67 order: Vec<usize>,
68}
69
70impl PartialEq for SelectorTable {
71 fn eq(&self, other: &Self) -> bool {
72 self.fields == other.fields
73 && self.rows == other.rows
74 && self.order == other.order
75 && self.columns.len() == other.columns.len()
76 && self.columns.columns().iter().all(|column| {
77 other
78 .columns
79 .get(&column.key)
80 .is_ok_and(|values| *values == column.values)
81 })
82 }
83}
84
85impl Eq for SelectorTable {}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub(crate) enum AlphaUnitKind {
90 Observation,
91 Series,
92 Aggregate,
93 Bin,
94 Single,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub(crate) struct PreparedAlpha {
99 encoding: AlphaEncoding,
100 unit: AlphaUnitKind,
101 original_len: usize,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq)]
106pub(crate) struct ResolvedAlpha {
107 pub(crate) index: Option<usize>,
108 pub(crate) alpha: f64,
109}
110
111impl Eq for ResolvedAlpha {}
112
113impl TryFrom<f64> for AlphaEncoding {
114 type Error = Error;
115
116 fn try_from(value: f64) -> Result<Self> {
117 Self::fixed(value)
118 }
119}
120
121impl AlphaEncoding {
122 #[must_use]
124 pub const fn theme() -> Self {
125 Self {
126 binding: Binding::Theme,
127 }
128 }
129
130 pub fn fixed(alpha: f64) -> Result<Self> {
132 Ok(Self {
133 binding: Binding::Fixed(validated_alpha(alpha)?),
134 })
135 }
136
137 #[must_use]
139 pub const fn get_fixed(&self) -> Option<f64> {
140 match self.binding {
141 Binding::Fixed(alpha) => Some(alpha),
142 _ => None,
143 }
144 }
145
146 #[must_use]
148 pub fn observations(values: AlphaValues) -> Self {
149 Self {
150 binding: Binding::Observations(values),
151 }
152 }
153
154 pub fn single(values: AlphaValues) -> Result<Self> {
156 if values.len() != 1 {
157 return Err(Error::Data(
158 "single alpha requires exactly one value".into(),
159 ));
160 }
161 Ok(Self {
162 binding: Binding::Single(values),
163 })
164 }
165
166 pub fn keyed(
174 keys: impl IntoIterator<Item = CategoryValues>,
175 values: AlphaValues,
176 ) -> Result<Self> {
177 let mut table = SelectorTable::new(keys, values.len())?;
178 if table.fields.is_empty() {
179 return Err(Error::Data(
180 "keyed alpha requires at least one selector field".into(),
181 ));
182 }
183 if table
184 .order
185 .windows(2)
186 .any(|pair| table.rows[pair[0]] == table.rows[pair[1]])
187 {
188 return Err(Error::Data(
189 "keyed alpha contains duplicate selector tuples".into(),
190 ));
191 }
192 table.member_keys = Some(RawKeyValues::new(
193 "alpha keys",
194 (0..values.len()).map(|slot| {
195 let keys = table
196 .columns
197 .row_keys(slot)
198 .expect("validated actual selector row");
199 if let [key] = keys.as_slice() {
200 key.clone()
201 } else {
202 RawKey::Tuple(keys)
203 }
204 }),
205 )?);
206 Ok(Self {
207 binding: Binding::Keyed(source_arc(table)?, values),
208 })
209 }
210
211 pub fn bins(
218 bounds: Bounds,
219 facets: impl IntoIterator<Item = CategoryValues>,
220 values: AlphaValues,
221 ) -> Result<Self> {
222 if bounds.lower().len() != values.len() || bounds.upper().len() != values.len() {
223 return Err(Error::Data(
224 "alpha bin bounds must align with the alpha values".into(),
225 ));
226 }
227 let facets = SelectorTable::new(facets, values.len())?;
228 let original_bounds = bounds;
229 let bounds = collect_source((0..values.len()).map(|index| {
230 let low = original_bounds.lower().get(index).flatten();
231 let high = original_bounds.upper().get(index).flatten();
232 match (low, high) {
233 (Some(low), Some(high)) if low.is_finite() && high.is_finite() && low < high => {
234 Ok([numeric_key(low), numeric_key(high)])
235 }
236 _ => Err(Error::Data(
237 format!(
238 "alpha bin at index {index} requires finite nonmissing lower < upper bounds"
239 )
240 .into(),
241 )),
242 }
243 }))?;
244 let mut order = collect_source((0..values.len()).map(Ok))?;
245 sort_source_by(&mut order, |a, b| {
246 facets.rows[*a]
247 .cmp(&facets.rows[*b])
248 .then(bounds[*a].cmp(&bounds[*b]))
249 })?;
250 if order.windows(2).any(|pair| {
251 facets.rows[pair[0]] == facets.rows[pair[1]] && bounds[pair[0]] == bounds[pair[1]]
252 }) {
253 return Err(Error::Data(
254 "alpha bins contain duplicate exact interval/facet keys".into(),
255 ));
256 }
257 let member_keys = RawKeyValues::new(
258 "alpha bins",
259 (0..values.len()).map(|slot| {
260 let mut key = vec![
261 RawKey::Float(
262 original_bounds
263 .lower()
264 .get(slot)
265 .flatten()
266 .expect("validated lower bound"),
267 ),
268 RawKey::Float(
269 original_bounds
270 .upper()
271 .get(slot)
272 .flatten()
273 .expect("validated upper bound"),
274 ),
275 ];
276 key.extend(
277 facets
278 .columns
279 .row_keys(slot)
280 .expect("validated actual selector row"),
281 );
282 RawKey::Tuple(key)
283 }),
284 )?;
285 Ok(Self {
286 binding: Binding::Bins(
287 source_arc(BinTable {
288 facets,
289 original_bounds,
290 member_keys,
291 bounds,
292 order,
293 })?,
294 values,
295 ),
296 })
297 }
298
299 pub(crate) fn member_keys(&self) -> Option<&RawKeyValues> {
300 match &self.binding {
301 Binding::Keyed(table, _) => table.member_keys.as_ref(),
302 Binding::Bins(table, _) => Some(&table.member_keys),
303 _ => None,
304 }
305 }
306
307 #[must_use]
309 pub const fn is_theme(&self) -> bool {
310 matches!(self.binding, Binding::Theme)
311 }
312
313 #[must_use]
315 pub const fn values(&self) -> Option<&AlphaValues> {
316 match &self.binding {
317 Binding::Theme | Binding::Fixed(_) => None,
318 Binding::Observations(values)
319 | Binding::Single(values)
320 | Binding::Keyed(_, values)
321 | Binding::Bins(_, values) => Some(values),
322 }
323 }
324
325 #[must_use]
327 pub const fn get_observations(&self) -> Option<&AlphaValues> {
328 match &self.binding {
329 Binding::Observations(values) => Some(values),
330 _ => None,
331 }
332 }
333
334 #[must_use]
336 pub const fn get_single(&self) -> Option<&AlphaValues> {
337 match &self.binding {
338 Binding::Single(values) => Some(values),
339 _ => None,
340 }
341 }
342
343 #[must_use]
346 pub fn get_keyed(&self) -> Option<(&KeyColumns, &AlphaValues)> {
347 match &self.binding {
348 Binding::Keyed(table, values) => Some((&table.columns, values)),
349 _ => None,
350 }
351 }
352
353 #[must_use]
355 pub fn get_bins(&self) -> Option<(&Bounds, &KeyColumns, &AlphaValues)> {
356 match &self.binding {
357 Binding::Bins(table, values) => {
358 Some((&table.original_bounds, &table.facets.columns, values))
359 }
360 _ => None,
361 }
362 }
363
364 pub(crate) fn replace_mapped_values(mut self, incoming: AlphaValues) -> Result<Self> {
365 let (Binding::Observations(values)
366 | Binding::Single(values)
367 | Binding::Keyed(_, values)
368 | Binding::Bins(_, values)) = &mut self.binding
369 else {
370 return Err(Error::Data("opacity style requires a bound target".into()));
371 };
372 if values.len() != incoming.len() {
373 return Err(Error::Data(
374 "opacity style changed the original value domain".into(),
375 ));
376 }
377 *values = incoming;
378 Ok(self)
379 }
380
381 pub(crate) fn prepare(
384 &self,
385 unit: AlphaUnitKind,
386 original_len: usize,
387 required_fields: &[RawKey],
388 facet_fields: &[RawKey],
389 ) -> Result<PreparedAlpha> {
390 match &self.binding {
391 Binding::Theme | Binding::Fixed(_) | Binding::Single(_) => {}
392 Binding::Observations(values) if unit == AlphaUnitKind::Observation => {
393 if values.len() != original_len {
394 use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
395 return Err(Error::Data(Diagnostic::new(DiagnosticKind::ShapeMismatch {
396 expected: vec![original_len], actual: vec![values.len()],
397 }, format!("observation alpha {:?} has length {}, expected all {original_len} original input slots", values.name(), values.len()))
398 .with_context(ErrorContext::new().with_operation(OperationPhase::Prepare))));
399 }
400 }
401 Binding::Keyed(table, _)
402 if matches!(unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) =>
403 {
404 table.validate_schema(required_fields, facet_fields)?;
405 }
406 Binding::Bins(table, _) if unit == AlphaUnitKind::Bin => {
407 table.facets.validate_schema(&[], facet_fields)?;
408 }
409 _ => {
410 return Err(Error::Data(
411 format!("alpha binding does not support {unit:?} units").into(),
412 ))
413 }
414 }
415 Ok(PreparedAlpha {
416 encoding: self.clone(),
417 unit,
418 original_len,
419 })
420 }
421}
422
423impl SelectorTable {
424 fn new(keys: impl IntoIterator<Item = CategoryValues>, len: usize) -> Result<Self> {
425 let keys = collect_input(keys)?;
426 let columns = collect_source(keys.iter().map(|column| {
427 let source = column.get_source();
428 let source_field = source
429 .selected_keys()
430 .filter(|keys| keys.len() == 1 && source.generation().is_none())
431 .and_then(|_| source.field(0));
432 let values = match column.key_values() {
433 KeyValues::Strings(values) => {
434 KeyValues::Strings(if let Some((key, name)) = source_field {
438 values.with_field_name(&name).with_field_key(key, name)
439 } else {
440 values
441 })
442 }
443 KeyValues::Raw(values) => KeyValues::Raw(if let Some((_, name)) = source_field {
444 values.with_name(&name)
445 } else {
446 values
447 }),
448 };
449 Ok(NamedKeyValues {
450 key: column.original_field(),
451 values,
452 })
453 }))?;
454 let mut keys = collect_source(keys.into_iter().map(|column| {
455 let field = column.original_field();
456 Ok((crate::data::key_bytes(&field)?, field, column))
457 }))?;
458 sort_source_by(&mut keys, |a, b| a.0.cmp(&b.0))?;
459 let fields = collect_source(keys.iter().map(|(_, field, column)| {
460 if column.len() != len {
461 return Err(Error::Data(
462 format!(
463 "alpha selector {:?} has length {}, expected {len}",
464 column.name(),
465 column.len()
466 )
467 .into(),
468 ));
469 }
470 Ok(field.clone())
471 }))?;
472 if fields.windows(2).any(|pair| pair[0] == pair[1]) {
473 return Err(Error::Data(
474 "alpha selector field names must be unique".into(),
475 ));
476 }
477 let rows = collect_source((0..len).map(|index| {
478 collect_source(keys.iter().map(|(_, _, column)| {
479 let raw = column.key_at(index).ok_or_else(|| {
480 Error::Data(
481 format!(
482 "alpha selector {:?} is missing at index {index}",
483 column.name()
484 )
485 .into(),
486 )
487 })?;
488 crate::data::key_bytes(&raw)
489 }))
490 }))?;
491 let mut order = collect_source((0..len).map(Ok))?;
492 sort_source_by(&mut order, |a, b| rows[*a].cmp(&rows[*b]))?;
493 Ok(Self {
494 columns: KeyColumns::new(columns)?,
495 member_keys: None,
496 fields,
497 rows,
498 order,
499 })
500 }
501
502 fn validate_schema(&self, required: &[RawKey], facets: &[RawKey]) -> Result<()> {
503 for field in &self.fields {
504 if !required.contains(field) && !facets.contains(field) {
505 return Err(Error::Data(
506 format!("alpha selector {field:?} is not an actual unit or owning facet field")
507 .into(),
508 ));
509 }
510 }
511 for field in required {
512 if !self.fields.iter().any(|name| name == field) {
513 return Err(Error::Data(
514 format!("alpha binding is missing required unit field {field:?}").into(),
515 ));
516 }
517 }
518 Ok(())
519 }
520
521 fn tuple(&self, keys: &[(RawKey, RawKey)]) -> Result<Vec<Vec<u8>>> {
522 for (index, (field, value)) in keys.iter().enumerate() {
523 if keys[..index]
524 .iter()
525 .any(|(other, raw)| other == field && raw != value)
526 {
527 return Err(Error::Data(
528 format!("actual alpha unit has conflicting raw values for field {field:?}")
529 .into(),
530 ));
531 }
532 }
533 collect_source(self.fields.iter().map(|field| {
534 keys.iter()
535 .find(|(name, _)| name == field)
536 .ok_or_else(|| {
537 Error::Data(
538 format!("actual alpha unit has no value for selector field {field:?}")
539 .into(),
540 )
541 })
542 .and_then(|(_, raw)| crate::data::key_bytes(raw))
543 }))
544 }
545
546 fn compare_row(&self, index: usize, tuple: &[Vec<u8>]) -> std::cmp::Ordering {
547 self.rows[index].as_slice().cmp(tuple)
548 }
549}
550
551impl PreparedAlpha {
552 pub(crate) fn selector_fields(&self) -> &[RawKey] {
553 match &self.encoding.binding {
554 Binding::Keyed(table, _) => &table.fields,
555 Binding::Bins(table, _) => &table.facets.fields,
556 Binding::Theme | Binding::Fixed(_) | Binding::Observations(_) | Binding::Single(_) => {
557 &[]
558 }
559 }
560 }
561
562 fn resolved(&self, index: usize) -> Result<Option<ResolvedAlpha>> {
563 if let Some(alpha) = self.encoding.get_fixed() {
564 return Ok(Some(ResolvedAlpha { index: None, alpha }));
565 }
566 self.encoding
567 .values()
568 .map(|values| {
569 values
570 .get(index)
571 .map(|alpha| ResolvedAlpha {
572 index: Some(index),
573 alpha,
574 })
575 .ok_or_else(|| {
576 Error::Data(
577 format!(
578 "alpha source {:?} has no original slot {index}",
579 values.name()
580 )
581 .into(),
582 )
583 })
584 })
585 .transpose()
586 }
587
588 fn constant(&self) -> Option<Result<Option<ResolvedAlpha>>> {
589 match &self.encoding.binding {
590 Binding::Theme => Some(Ok(None)),
591 Binding::Fixed(_) | Binding::Single(_) => Some(self.resolved(0)),
592 _ => None,
593 }
594 }
595
596 pub(crate) fn observation(
597 &self,
598 index: usize,
599 source_row: usize,
600 ) -> Result<Option<ResolvedAlpha>> {
601 if self.unit != AlphaUnitKind::Observation {
602 return Err(Error::Data(
603 "alpha source requires an observation unit".into(),
604 ));
605 }
606 if index >= self.original_len {
607 return Err(Error::Data(format!(
608 "alpha original slot {index} is outside length {} at diagnostic source row {source_row}",
609 self.original_len,
610 ).into()));
611 }
612 self.constant()
613 .unwrap_or_else(|| self.resolved(index))
614 .map_err(|error| {
615 Error::Data(format!("{error} at diagnostic source row {source_row}").into())
616 })
617 }
618
619 pub(crate) fn single(&self) -> Result<Option<ResolvedAlpha>> {
620 if self.unit != AlphaUnitKind::Single {
621 return Err(Error::Data("alpha source requires a single unit".into()));
622 }
623 self.resolved(0)
624 }
625
626 pub(crate) fn keyed(&self, keys: &[(RawKey, RawKey)]) -> Result<Option<ResolvedAlpha>> {
627 if !matches!(self.unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) {
628 return Err(Error::Data(
629 "alpha source requires a series or aggregate unit".into(),
630 ));
631 }
632 if let Some(value) = self.constant() {
633 return value;
634 }
635 let Binding::Keyed(table, _) = &self.encoding.binding else {
636 unreachable!("prepared keyed binding")
637 };
638 let tuple = table.tuple(keys)?;
639 let position = table
640 .order
641 .binary_search_by(|&index| table.compare_row(index, &tuple))
642 .map_err(|_| {
643 Error::Data(
644 format!("alpha binding has no value for actual raw unit {keys:?}").into(),
645 )
646 })?;
647 self.resolved(table.order[position])
648 }
649
650 pub(crate) fn bin(
651 &self,
652 bounds: (f64, f64),
653 facets: &[(RawKey, RawKey)],
654 ) -> Result<Option<ResolvedAlpha>> {
655 if self.unit != AlphaUnitKind::Bin {
656 return Err(Error::Data("alpha source requires a bin unit".into()));
657 }
658 if !bounds.0.is_finite() || !bounds.1.is_finite() || bounds.0 >= bounds.1 {
659 return Err(Error::Data(
660 "actual alpha bin must have finite lower < upper bounds".into(),
661 ));
662 }
663 if let Some(value) = self.constant() {
664 return value;
665 }
666 let Binding::Bins(table, _) = &self.encoding.binding else {
667 unreachable!("prepared bin binding")
668 };
669 let tuple = table.facets.tuple(facets)?;
670 let key = [numeric_key(bounds.0), numeric_key(bounds.1)];
671 let position = table
672 .order
673 .binary_search_by(|&index| {
674 table
675 .facets
676 .compare_row(index, &tuple)
677 .then(table.bounds[index].cmp(&key))
678 })
679 .map_err(|_| {
680 Error::Data(
681 format!(
682 "alpha binding has no value for exact actual bin {bounds:?} in {facets:?}"
683 )
684 .into(),
685 )
686 })?;
687 self.resolved(table.order[position])
688 }
689}
690
691#[cfg(test)]
692mod tests;