1use std::sync::Arc;
4
5use crate::data::source::{collect_source, reserve_source, source_arc};
6use crate::data::{KeyValues, RawKey};
7use crate::{CategoryValues, Error, NumericValues, Result};
8
9mod encoding;
10mod guide;
11pub(crate) mod marks;
12mod materialize;
13
14pub use encoding::AlphaEncoding;
15pub(crate) use encoding::{AlphaUnitKind, PreparedAlpha, ResolvedAlpha};
16pub(crate) use guide::AlphaExampleKey;
17
18pub(crate) fn validated_alpha(value: f64) -> Result<f64> {
19 if !(0.0..=1.0).contains(&value) {
20 use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
21 return Err(Error::Data(
22 Diagnostic::new(
23 DiagnosticKind::InvalidValue {
24 value: Some(RawKey::Float(value)),
25 constraint: "finite alpha in [0, 1]".to_owned(),
26 },
27 format!("alpha must be finite and in [0, 1], got {value}"),
28 )
29 .with_context(ErrorContext::new().with_operation(OperationPhase::Bind)),
30 ));
31 }
32 Ok(if value == 0.0 { 0.0 } else { value })
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub(crate) enum AlphaTarget {
37 Point,
38 Line,
39 Fill,
40}
41
42impl AlphaTarget {
43 pub(crate) const fn index(self) -> usize {
44 match self {
45 Self::Point => 0,
46 Self::Line => 1,
47 Self::Fill => 2,
48 }
49 }
50}
51
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub(crate) struct AlphaInputs([AlphaEncoding; 3]);
54
55impl AlphaInputs {
56 pub(crate) fn get(&self, target: AlphaTarget) -> &AlphaEncoding {
57 &self.0[target.index()]
58 }
59
60 pub(crate) fn set(&mut self, target: AlphaTarget, encoding: AlphaEncoding) {
61 self.0[target.index()] = encoding;
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum AlphaSemantics {
71 Undeclared,
73 Continuous,
75 Categorical,
77 Threshold,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct AlphaValues {
106 name: Arc<String>,
107 data: Arc<AlphaData>,
108 declaration: Arc<AlphaDeclaration>,
109}
110
111#[derive(Debug, Clone, PartialEq)]
112struct AlphaData {
113 values: Vec<f64>,
114 members: AlphaMembers,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
118enum AlphaMembers {
119 Undeclared(NumericValues),
120 Numeric(NumericValues),
121 Categorical(KeyValues, Vec<usize>),
122 Threshold(NumericValues, Vec<usize>),
123}
124
125#[derive(Debug, Clone, Default)]
128#[non_exhaustive]
129pub enum AlphaMapping {
130 #[default]
132 Undeclared,
133 Linear {
135 domain: [f64; 2],
137 range: [f64; 2],
139 },
140 Log10 {
142 domain: [f64; 2],
144 range: [f64; 2],
146 },
147 Continuous {
149 domain: [f64; 2],
151 evaluated: Vec<(f64, f64)>,
153 },
154 Categorical(Vec<(RawKey, f64)>),
156 Threshold {
158 boundaries: Vec<f64>,
160 alphas: Vec<f64>,
162 },
163}
164
165impl PartialEq for AlphaMapping {
166 fn eq(&self, other: &Self) -> bool {
167 fn numbers(left: &[f64], right: &[f64]) -> bool {
168 left.iter()
169 .map(|value| value.to_bits())
170 .eq(right.iter().map(|value| value.to_bits()))
171 }
172 fn pairs(left: &[(f64, f64)], right: &[(f64, f64)]) -> bool {
173 left.iter()
174 .map(|(raw, alpha)| (raw.to_bits(), alpha.to_bits()))
175 .eq(right
176 .iter()
177 .map(|(raw, alpha)| (raw.to_bits(), alpha.to_bits())))
178 }
179 match (self, other) {
180 (Self::Undeclared, Self::Undeclared) => true,
181 (
182 Self::Linear { domain, range },
183 Self::Linear {
184 domain: other_domain,
185 range: other_range,
186 },
187 )
188 | (
189 Self::Log10 { domain, range },
190 Self::Log10 {
191 domain: other_domain,
192 range: other_range,
193 },
194 ) => numbers(domain, other_domain) && numbers(range, other_range),
195 (
196 Self::Continuous { domain, evaluated },
197 Self::Continuous {
198 domain: other_domain,
199 evaluated: other_evaluated,
200 },
201 ) => numbers(domain, other_domain) && pairs(evaluated, other_evaluated),
202 (
203 Self::Threshold { boundaries, alphas },
204 Self::Threshold {
205 boundaries: other_boundaries,
206 alphas: other_alphas,
207 },
208 ) => numbers(boundaries, other_boundaries) && numbers(alphas, other_alphas),
209 (Self::Categorical(left), Self::Categorical(right)) => left
210 .iter()
211 .map(|(key, alpha)| (key, alpha.to_bits()))
212 .eq(right.iter().map(|(key, alpha)| (key, alpha.to_bits()))),
213 _ => false,
214 }
215 }
216}
217
218#[derive(Debug, Default, PartialEq)]
220struct AlphaDeclaration {
221 mapping: AlphaMapping,
222 examples: Vec<(f64, f64)>,
223 labels: Vec<String>,
224}
225
226impl Eq for AlphaData {}
228impl Eq for AlphaDeclaration {}
229
230#[expect(
231 clippy::needless_pass_by_value,
232 reason = "public consuming factories materialize and release one complete immutable source input"
233)]
234impl AlphaValues {
235 pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Result<Self> {
240 let name = validated_name(name.into())?;
241 let original = NumericValues::new(&name, collect_input(values)?);
242 Self::try_from(original)
243 }
244
245 pub fn linear(source: NumericValues, domain: (f64, f64), range: (f64, f64)) -> Result<Self> {
251 materialize::builtin(&source, domain, range, false)
252 }
253
254 pub fn log10(source: NumericValues, domain: (f64, f64), range: (f64, f64)) -> Result<Self> {
260 materialize::builtin(&source, domain, range, true)
261 }
262
263 pub fn continuous(
271 source: NumericValues,
272 domain: (f64, f64),
273 f: impl FnMut(f64) -> f64,
274 ) -> Result<Self> {
275 materialize::continuous(&source, domain, f)
276 }
277
278 pub fn categorical(source: CategoryValues, f: impl FnMut(&str) -> f64) -> Result<Self> {
283 materialize::categorical(&source, f)
284 }
285
286 pub fn threshold(
292 source: NumericValues,
293 boundaries: impl IntoIterator<Item = f64>,
294 alphas: impl IntoIterator<Item = f64>,
295 ) -> Result<Self> {
296 materialize::threshold(&source, boundaries, alphas)
297 }
298
299 pub fn select(&self, indices: impl IntoIterator<Item = usize>) -> Result<Self> {
304 let indices = collect_input(indices)?;
305 let values = collect_source(indices.iter().map(|&index| {
306 self.get(index).ok_or_else(|| {
307 Error::Data(
308 format!(
309 "alpha values {:?} selection index {index} is outside length {}",
310 self.name(),
311 self.len(),
312 )
313 .into(),
314 )
315 })
316 }))?;
317 let members = match &self.data.members {
318 AlphaMembers::Undeclared(source) => AlphaMembers::Undeclared(source.select(&indices)?),
319 AlphaMembers::Numeric(source) => AlphaMembers::Numeric(source.select(&indices)?),
320 AlphaMembers::Categorical(source, members) => AlphaMembers::Categorical(
321 select_categories(source, &indices)?,
322 collect_source(indices.iter().map(|&i| Ok(members[i])))?,
323 ),
324 AlphaMembers::Threshold(source, members) => AlphaMembers::Threshold(
325 source.select(&indices)?,
326 collect_source(indices.iter().map(|&i| Ok(members[i])))?,
327 ),
328 };
329 Ok(Self {
330 name: Arc::clone(&self.name),
331 data: source_arc(AlphaData { values, members })?,
332 declaration: Arc::clone(&self.declaration),
333 })
334 }
335
336 #[doc(hidden)]
339 pub fn repeat_rows(&self, copies: usize) -> Result<Self> {
340 if copies == 0 {
341 return Err(Error::Data(
342 "row expansion requires at least one column".into(),
343 ));
344 }
345 self.len()
346 .checked_mul(copies)
347 .ok_or_else(|| Error::Data("expanded alpha count exceeds usize".into()))?;
348 let mut expanded = if copies == 1 {
349 self.clone()
350 } else {
351 self.select((0..self.len()).flat_map(|row| std::iter::repeat_n(row, copies)))?
352 };
353 match (
357 &mut Arc::make_mut(&mut expanded.data).members,
358 &self.data.members,
359 ) {
360 (AlphaMembers::Undeclared(values), AlphaMembers::Undeclared(source))
361 | (AlphaMembers::Numeric(values), AlphaMembers::Numeric(source))
362 | (AlphaMembers::Threshold(values, _), AlphaMembers::Threshold(source, _)) => {
363 retain_repeated(values, source.vector_source(), copies)?;
364 }
365 (
366 AlphaMembers::Categorical(KeyValues::Strings(values), _),
367 AlphaMembers::Categorical(KeyValues::Strings(source), _),
368 ) => retain_repeated(values, source.vector_source(), copies)?,
369 (
370 AlphaMembers::Categorical(KeyValues::Raw(values), _),
371 AlphaMembers::Categorical(KeyValues::Raw(source), _),
372 ) => retain_repeated(values, source.vector_source(), copies)?,
373 _ => unreachable!("alpha selection retains its original native source kind"),
374 }
375 Ok(expanded)
376 }
377
378 #[must_use]
380 pub fn name(&self) -> &str {
381 if let Some(values) = self.get_numeric_source() {
382 if values.name().is_empty() && values.field_key().is_none() {
383 &self.name
384 } else {
385 values.name()
386 }
387 } else if let Some(KeyValues::Strings(values)) = self.get_category_source() {
388 values.original_name()
389 } else {
390 &self.name
391 }
392 }
393
394 pub(crate) fn raw_name(&self) -> &str {
395 &self.name
396 }
397
398 #[must_use]
400 pub fn len(&self) -> usize {
401 self.data.values.len()
402 }
403
404 #[must_use]
406 pub fn is_empty(&self) -> bool {
407 self.data.values.is_empty()
408 }
409
410 #[must_use]
412 pub fn get(&self, index: usize) -> Option<f64> {
413 self.data.values.get(index).copied()
414 }
415
416 #[must_use]
418 pub fn values(&self) -> &[f64] {
419 &self.data.values
420 }
421
422 #[must_use]
424 pub fn semantics(&self) -> AlphaSemantics {
425 match &self.declaration.mapping {
426 AlphaMapping::Undeclared => AlphaSemantics::Undeclared,
427 AlphaMapping::Linear { .. }
428 | AlphaMapping::Log10 { .. }
429 | AlphaMapping::Continuous { .. } => AlphaSemantics::Continuous,
430 AlphaMapping::Categorical(_) => AlphaSemantics::Categorical,
431 AlphaMapping::Threshold { .. } => AlphaSemantics::Threshold,
432 }
433 }
434
435 #[must_use]
437 pub fn get_numeric_source(&self) -> Option<&NumericValues> {
438 match &self.data.members {
439 AlphaMembers::Undeclared(source)
440 | AlphaMembers::Numeric(source)
441 | AlphaMembers::Threshold(source, _) => Some(source),
442 AlphaMembers::Categorical(..) => None,
443 }
444 }
445
446 #[must_use]
448 pub fn get_category_source(&self) -> Option<&KeyValues> {
449 match &self.data.members {
450 AlphaMembers::Categorical(source, _) => Some(source),
451 _ => None,
452 }
453 }
454
455 #[must_use]
457 pub fn get_threshold_indices(&self) -> Option<&[usize]> {
458 match &self.data.members {
459 AlphaMembers::Threshold(_, indices) => Some(indices),
460 _ => None,
461 }
462 }
463
464 #[must_use]
466 pub fn get_mapping(&self) -> &AlphaMapping {
467 &self.declaration.mapping
468 }
469
470 #[must_use]
472 pub fn examples(&self) -> &[(f64, f64)] {
473 &self.declaration.examples
474 }
475
476 fn from_parts(
477 name: String,
478 values: Vec<f64>,
479 members: AlphaMembers,
480 declaration: AlphaDeclaration,
481 ) -> Result<Self> {
482 Ok(Self {
483 name: source_arc(name)?,
484 data: source_arc(AlphaData { values, members })?,
485 declaration: source_arc(declaration)?,
486 })
487 }
488}
489
490impl TryFrom<NumericValues> for AlphaValues {
491 type Error = Error;
492
493 fn try_from(source: NumericValues) -> Result<Self> {
494 let name = if source.raw_name().is_empty() && source.field_key().is_none() {
495 "Alpha"
496 } else {
497 source.raw_name()
498 };
499 let name = crate::data::source::copy_source_string(name)?;
500 let values = collect_source((0..source.len()).map(|index| {
501 let value = source.get(index).flatten().ok_or_else(|| {
502 Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
503 })?;
504 validated_alpha(value).map_err(|error| {
505 Error::Data(format!("alpha source {name:?} at index {index}: {error}").into())
506 })
507 }))?;
508 Self::from_parts(
509 name,
510 values,
511 AlphaMembers::Undeclared(source),
512 AlphaDeclaration::default(),
513 )
514 }
515}
516
517fn retain_repeated<T: crate::data::CapturedValue + Clone>(
518 values: &mut T,
519 source: &crate::data::VectorSource,
520 copies: usize,
521) -> Result<()> {
522 if source.is_identity() {
523 *values = values
524 .clone()
525 .retain(source.info().clone(), copies, None)?
526 .row_scoped();
527 }
528 Ok(())
529}
530
531fn select_categories(source: &KeyValues, indices: &[usize]) -> Result<KeyValues> {
532 source.select(indices)
533}
534
535fn validated_name(name: String) -> Result<String> {
536 if name.is_empty() || name.trim() != name || name.chars().any(char::is_control) {
537 return Err(Error::Data(
538 "alpha source names must be nonempty, already trimmed and control-free".into(),
539 ));
540 }
541 Ok(name)
542}
543
544fn numeric_key(value: f64) -> u64 {
545 if value == 0.0 {
546 0
547 } else {
548 value.to_bits()
549 }
550}
551
552fn collect_input<T>(values: impl IntoIterator<Item = T>) -> Result<Vec<T>> {
553 let values = values.into_iter();
554 let mut retained = Vec::new();
555 let (minimum, maximum) = values.size_hint();
556 if maximum == Some(minimum) {
557 reserve_source(&mut retained, minimum)?;
558 }
559 for value in values {
560 if retained.len() == retained.capacity() {
561 let additional = retained.capacity().max(1);
562 reserve_source(&mut retained, additional)?;
563 }
564 retained.push(value);
565 }
566 Ok(retained)
567}
568
569#[cfg(test)]
570mod tests;