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 prepare(
367 &self,
368 unit: AlphaUnitKind,
369 original_len: usize,
370 required_fields: &[RawKey],
371 facet_fields: &[RawKey],
372 ) -> Result<PreparedAlpha> {
373 match &self.binding {
374 Binding::Theme | Binding::Fixed(_) | Binding::Single(_) => {}
375 Binding::Observations(values) if unit == AlphaUnitKind::Observation => {
376 if values.len() != original_len {
377 use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
378 return Err(Error::Data(Diagnostic::new(DiagnosticKind::ShapeMismatch {
379 expected: vec![original_len], actual: vec![values.len()],
380 }, format!("observation alpha {:?} has length {}, expected all {original_len} original input slots", values.name(), values.len()))
381 .with_context(ErrorContext::new().with_operation(OperationPhase::Prepare))));
382 }
383 }
384 Binding::Keyed(table, _)
385 if matches!(unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) =>
386 {
387 table.validate_schema(required_fields, facet_fields)?;
388 }
389 Binding::Bins(table, _) if unit == AlphaUnitKind::Bin => {
390 table.facets.validate_schema(&[], facet_fields)?;
391 }
392 _ => {
393 return Err(Error::Data(
394 format!("alpha binding does not support {unit:?} units").into(),
395 ))
396 }
397 }
398 Ok(PreparedAlpha {
399 encoding: self.clone(),
400 unit,
401 original_len,
402 })
403 }
404}
405
406impl SelectorTable {
407 fn new(keys: impl IntoIterator<Item = CategoryValues>, len: usize) -> Result<Self> {
408 let keys = collect_input(keys)?;
409 let columns = collect_source(keys.iter().map(|column| {
410 let source = column.get_source();
411 let source_field = source
412 .selected_keys()
413 .filter(|keys| keys.len() == 1 && source.generation().is_none())
414 .and_then(|_| source.field(0));
415 let values = match column.key_values() {
416 KeyValues::Strings(values) => {
417 KeyValues::Strings(if let Some((key, name)) = source_field {
421 values.with_field_name(&name).with_field_key(key, name)
422 } else {
423 values
424 })
425 }
426 KeyValues::Raw(values) => KeyValues::Raw(if let Some((_, name)) = source_field {
427 values.with_name(&name)
428 } else {
429 values
430 }),
431 };
432 Ok(NamedKeyValues {
433 key: column.original_field(),
434 values,
435 })
436 }))?;
437 let mut keys = collect_source(keys.into_iter().map(|column| {
438 let field = column.original_field();
439 Ok((crate::data::key_bytes(&field)?, field, column))
440 }))?;
441 sort_source_by(&mut keys, |a, b| a.0.cmp(&b.0))?;
442 let fields = collect_source(keys.iter().map(|(_, field, column)| {
443 if column.len() != len {
444 return Err(Error::Data(
445 format!(
446 "alpha selector {:?} has length {}, expected {len}",
447 column.name(),
448 column.len()
449 )
450 .into(),
451 ));
452 }
453 Ok(field.clone())
454 }))?;
455 if fields.windows(2).any(|pair| pair[0] == pair[1]) {
456 return Err(Error::Data(
457 "alpha selector field names must be unique".into(),
458 ));
459 }
460 let rows = collect_source((0..len).map(|index| {
461 collect_source(keys.iter().map(|(_, _, column)| {
462 let raw = column.key_at(index).ok_or_else(|| {
463 Error::Data(
464 format!(
465 "alpha selector {:?} is missing at index {index}",
466 column.name()
467 )
468 .into(),
469 )
470 })?;
471 crate::data::key_bytes(&raw)
472 }))
473 }))?;
474 let mut order = collect_source((0..len).map(Ok))?;
475 sort_source_by(&mut order, |a, b| rows[*a].cmp(&rows[*b]))?;
476 Ok(Self {
477 columns: KeyColumns::new(columns)?,
478 member_keys: None,
479 fields,
480 rows,
481 order,
482 })
483 }
484
485 fn validate_schema(&self, required: &[RawKey], facets: &[RawKey]) -> Result<()> {
486 for field in &self.fields {
487 if !required.contains(field) && !facets.contains(field) {
488 return Err(Error::Data(
489 format!("alpha selector {field:?} is not an actual unit or owning facet field")
490 .into(),
491 ));
492 }
493 }
494 for field in required {
495 if !self.fields.iter().any(|name| name == field) {
496 return Err(Error::Data(
497 format!("alpha binding is missing required unit field {field:?}").into(),
498 ));
499 }
500 }
501 Ok(())
502 }
503
504 fn tuple(&self, keys: &[(RawKey, RawKey)]) -> Result<Vec<Vec<u8>>> {
505 for (index, (field, value)) in keys.iter().enumerate() {
506 if keys[..index]
507 .iter()
508 .any(|(other, raw)| other == field && raw != value)
509 {
510 return Err(Error::Data(
511 format!("actual alpha unit has conflicting raw values for field {field:?}")
512 .into(),
513 ));
514 }
515 }
516 collect_source(self.fields.iter().map(|field| {
517 keys.iter()
518 .find(|(name, _)| name == field)
519 .ok_or_else(|| {
520 Error::Data(
521 format!("actual alpha unit has no value for selector field {field:?}")
522 .into(),
523 )
524 })
525 .and_then(|(_, raw)| crate::data::key_bytes(raw))
526 }))
527 }
528
529 fn compare_row(&self, index: usize, tuple: &[Vec<u8>]) -> std::cmp::Ordering {
530 self.rows[index].as_slice().cmp(tuple)
531 }
532}
533
534impl PreparedAlpha {
535 pub(crate) fn selector_fields(&self) -> &[RawKey] {
536 match &self.encoding.binding {
537 Binding::Keyed(table, _) => &table.fields,
538 Binding::Bins(table, _) => &table.facets.fields,
539 Binding::Theme | Binding::Fixed(_) | Binding::Observations(_) | Binding::Single(_) => {
540 &[]
541 }
542 }
543 }
544
545 fn resolved(&self, index: usize) -> Result<Option<ResolvedAlpha>> {
546 if let Some(alpha) = self.encoding.get_fixed() {
547 return Ok(Some(ResolvedAlpha { index: None, alpha }));
548 }
549 self.encoding
550 .values()
551 .map(|values| {
552 values
553 .get(index)
554 .map(|alpha| ResolvedAlpha {
555 index: Some(index),
556 alpha,
557 })
558 .ok_or_else(|| {
559 Error::Data(
560 format!(
561 "alpha source {:?} has no original slot {index}",
562 values.name()
563 )
564 .into(),
565 )
566 })
567 })
568 .transpose()
569 }
570
571 fn constant(&self) -> Option<Result<Option<ResolvedAlpha>>> {
572 match &self.encoding.binding {
573 Binding::Theme => Some(Ok(None)),
574 Binding::Fixed(_) | Binding::Single(_) => Some(self.resolved(0)),
575 _ => None,
576 }
577 }
578
579 pub(crate) fn observation(
580 &self,
581 index: usize,
582 source_row: usize,
583 ) -> Result<Option<ResolvedAlpha>> {
584 if self.unit != AlphaUnitKind::Observation {
585 return Err(Error::Data(
586 "alpha source requires an observation unit".into(),
587 ));
588 }
589 if index >= self.original_len {
590 return Err(Error::Data(format!(
591 "alpha original slot {index} is outside length {} at diagnostic source row {source_row}",
592 self.original_len,
593 ).into()));
594 }
595 self.constant()
596 .unwrap_or_else(|| self.resolved(index))
597 .map_err(|error| {
598 Error::Data(format!("{error} at diagnostic source row {source_row}").into())
599 })
600 }
601
602 pub(crate) fn single(&self) -> Result<Option<ResolvedAlpha>> {
603 if self.unit != AlphaUnitKind::Single {
604 return Err(Error::Data("alpha source requires a single unit".into()));
605 }
606 self.resolved(0)
607 }
608
609 pub(crate) fn keyed(&self, keys: &[(RawKey, RawKey)]) -> Result<Option<ResolvedAlpha>> {
610 if !matches!(self.unit, AlphaUnitKind::Series | AlphaUnitKind::Aggregate) {
611 return Err(Error::Data(
612 "alpha source requires a series or aggregate unit".into(),
613 ));
614 }
615 if let Some(value) = self.constant() {
616 return value;
617 }
618 let Binding::Keyed(table, _) = &self.encoding.binding else {
619 unreachable!("prepared keyed binding")
620 };
621 let tuple = table.tuple(keys)?;
622 let position = table
623 .order
624 .binary_search_by(|&index| table.compare_row(index, &tuple))
625 .map_err(|_| {
626 Error::Data(
627 format!("alpha binding has no value for actual raw unit {keys:?}").into(),
628 )
629 })?;
630 self.resolved(table.order[position])
631 }
632
633 pub(crate) fn bin(
634 &self,
635 bounds: (f64, f64),
636 facets: &[(RawKey, RawKey)],
637 ) -> Result<Option<ResolvedAlpha>> {
638 if self.unit != AlphaUnitKind::Bin {
639 return Err(Error::Data("alpha source requires a bin unit".into()));
640 }
641 if !bounds.0.is_finite() || !bounds.1.is_finite() || bounds.0 >= bounds.1 {
642 return Err(Error::Data(
643 "actual alpha bin must have finite lower < upper bounds".into(),
644 ));
645 }
646 if let Some(value) = self.constant() {
647 return value;
648 }
649 let Binding::Bins(table, _) = &self.encoding.binding else {
650 unreachable!("prepared bin binding")
651 };
652 let tuple = table.facets.tuple(facets)?;
653 let key = [numeric_key(bounds.0), numeric_key(bounds.1)];
654 let position = table
655 .order
656 .binary_search_by(|&index| {
657 table
658 .facets
659 .compare_row(index, &tuple)
660 .then(table.bounds[index].cmp(&key))
661 })
662 .map_err(|_| {
663 Error::Data(
664 format!(
665 "alpha binding has no value for exact actual bin {bounds:?} in {facets:?}"
666 )
667 .into(),
668 )
669 })?;
670 self.resolved(table.order[position])
671 }
672}
673
674#[cfg(test)]
675mod tests;