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, PartialEq)]
112struct AlphaData {
113 values: Vec<f64>,
114 members: AlphaMembers,
115}
116
117#[derive(Debug, 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 #[must_use]
338 pub fn name(&self) -> &str {
339 if let Some(values) = self.get_numeric_source() {
340 if values.name().is_empty() && values.field_key().is_none() {
341 &self.name
342 } else {
343 values.name()
344 }
345 } else if let Some(KeyValues::Strings(values)) = self.get_category_source() {
346 values.original_name()
347 } else {
348 &self.name
349 }
350 }
351
352 pub(crate) fn raw_name(&self) -> &str {
353 &self.name
354 }
355
356 #[must_use]
358 pub fn len(&self) -> usize {
359 self.data.values.len()
360 }
361
362 #[must_use]
364 pub fn is_empty(&self) -> bool {
365 self.data.values.is_empty()
366 }
367
368 #[must_use]
370 pub fn get(&self, index: usize) -> Option<f64> {
371 self.data.values.get(index).copied()
372 }
373
374 #[must_use]
376 pub fn values(&self) -> &[f64] {
377 &self.data.values
378 }
379
380 #[must_use]
382 pub fn semantics(&self) -> AlphaSemantics {
383 match &self.declaration.mapping {
384 AlphaMapping::Undeclared => AlphaSemantics::Undeclared,
385 AlphaMapping::Linear { .. }
386 | AlphaMapping::Log10 { .. }
387 | AlphaMapping::Continuous { .. } => AlphaSemantics::Continuous,
388 AlphaMapping::Categorical(_) => AlphaSemantics::Categorical,
389 AlphaMapping::Threshold { .. } => AlphaSemantics::Threshold,
390 }
391 }
392
393 #[must_use]
395 pub fn get_numeric_source(&self) -> Option<&NumericValues> {
396 match &self.data.members {
397 AlphaMembers::Undeclared(source)
398 | AlphaMembers::Numeric(source)
399 | AlphaMembers::Threshold(source, _) => Some(source),
400 AlphaMembers::Categorical(..) => None,
401 }
402 }
403
404 #[must_use]
406 pub fn get_category_source(&self) -> Option<&KeyValues> {
407 match &self.data.members {
408 AlphaMembers::Categorical(source, _) => Some(source),
409 _ => None,
410 }
411 }
412
413 #[must_use]
415 pub fn get_threshold_indices(&self) -> Option<&[usize]> {
416 match &self.data.members {
417 AlphaMembers::Threshold(_, indices) => Some(indices),
418 _ => None,
419 }
420 }
421
422 #[must_use]
424 pub fn get_mapping(&self) -> &AlphaMapping {
425 &self.declaration.mapping
426 }
427
428 #[must_use]
430 pub fn examples(&self) -> &[(f64, f64)] {
431 &self.declaration.examples
432 }
433
434 fn from_parts(
435 name: String,
436 values: Vec<f64>,
437 members: AlphaMembers,
438 declaration: AlphaDeclaration,
439 ) -> Result<Self> {
440 Ok(Self {
441 name: source_arc(name)?,
442 data: source_arc(AlphaData { values, members })?,
443 declaration: source_arc(declaration)?,
444 })
445 }
446}
447
448impl TryFrom<NumericValues> for AlphaValues {
449 type Error = Error;
450
451 fn try_from(source: NumericValues) -> Result<Self> {
452 let name = if source.raw_name().is_empty() && source.field_key().is_none() {
453 "Alpha"
454 } else {
455 source.raw_name()
456 };
457 let name = crate::data::source::copy_source_string(name)?;
458 let values = collect_source((0..source.len()).map(|index| {
459 let value = source.get(index).flatten().ok_or_else(|| {
460 Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
461 })?;
462 validated_alpha(value).map_err(|error| {
463 Error::Data(format!("alpha source {name:?} at index {index}: {error}").into())
464 })
465 }))?;
466 Self::from_parts(
467 name,
468 values,
469 AlphaMembers::Undeclared(source),
470 AlphaDeclaration::default(),
471 )
472 }
473}
474
475fn select_categories(source: &KeyValues, indices: &[usize]) -> Result<KeyValues> {
476 source.select(indices)
477}
478
479fn validated_name(name: String) -> Result<String> {
480 if name.is_empty() || name.trim() != name || name.chars().any(char::is_control) {
481 return Err(Error::Data(
482 "alpha source names must be nonempty, already trimmed and control-free".into(),
483 ));
484 }
485 Ok(name)
486}
487
488fn numeric_key(value: f64) -> u64 {
489 if value == 0.0 {
490 0
491 } else {
492 value.to_bits()
493 }
494}
495
496fn collect_input<T>(values: impl IntoIterator<Item = T>) -> Result<Vec<T>> {
497 let values = values.into_iter();
498 let mut retained = Vec::new();
499 let (minimum, maximum) = values.size_hint();
500 if maximum == Some(minimum) {
501 reserve_source(&mut retained, minimum)?;
502 }
503 for value in values {
504 if retained.len() == retained.capacity() {
505 let additional = retained.capacity().max(1);
506 reserve_source(&mut retained, additional)?;
507 }
508 retained.push(value);
509 }
510 Ok(retained)
511}
512
513#[cfg(test)]
514mod tests;