1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Owned opacity coefficients and explicit, eagerly materialized explanatory semantics.
use std::sync::Arc;
use crate::data::source::{collect_source, reserve_source, source_arc};
use crate::data::{KeyValues, RawKey};
use crate::{CategoryValues, Error, NumericValues, Result};
mod encoding;
mod guide;
pub(crate) mod marks;
mod materialize;
pub use encoding::AlphaEncoding;
pub(crate) use encoding::{AlphaUnitKind, PreparedAlpha, ResolvedAlpha};
pub(crate) use guide::AlphaExampleKey;
pub(crate) fn validated_alpha(value: f64) -> Result<f64> {
if !(0.0..=1.0).contains(&value) {
use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
return Err(Error::Data(
Diagnostic::new(
DiagnosticKind::InvalidValue {
value: Some(RawKey::Float(value)),
constraint: "finite alpha in [0, 1]".to_owned(),
},
format!("alpha must be finite and in [0, 1], got {value}"),
)
.with_context(ErrorContext::new().with_operation(OperationPhase::Bind)),
));
}
Ok(if value == 0.0 { 0.0 } else { value })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AlphaTarget {
Point,
Line,
Fill,
}
impl AlphaTarget {
pub(crate) const fn index(self) -> usize {
match self {
Self::Point => 0,
Self::Line => 1,
Self::Fill => 2,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct AlphaInputs([AlphaEncoding; 3]);
impl AlphaInputs {
pub(crate) fn get(&self, target: AlphaTarget) -> &AlphaEncoding {
&self.0[target.index()]
}
pub(crate) fn set(&mut self, target: AlphaTarget, encoding: AlphaEncoding) {
self.0[target.index()] = encoding;
}
}
/// Explicit explanatory semantics carried by immutable [`AlphaValues`].
///
/// Semantics are declared by construction, never inferred from value cardinality
/// or a custom function's outputs. Only declared mappings produce alpha sections.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlphaSemantics {
/// Caller-computed coefficients with no automatic alpha explanation.
Undeclared,
/// A declared continuous source/domain illustrated by numeric symbols.
Continuous,
/// A complete ordered raw category-to-alpha mapping.
Categorical,
/// A complete ordered interval-to-alpha mapping with equality on the right.
Threshold,
}
/// Owned opacity coefficients and their complete immutable mapping declaration.
///
/// Construction eagerly materializes custom functions; no callback survives in a
/// Plot, Canvas or output. Alpha zero preserves scientific membership. Attach with
/// [`AlphaEncoding`] to select observations, explicit collective keys or bins.
///
/// ```
/// use lichtung_plot::{NumericValues, scales::{AlphaSemantics, AlphaValues}};
/// let alpha = AlphaValues::linear(
/// NumericValues::new("confidence", [0.0, 0.25, 0.5, 0.75, 1.0]),
/// (0.0, 1.0), (0.0, 1.0),
/// )?;
/// assert_eq!(alpha.semantics(), AlphaSemantics::Continuous);
/// assert_eq!((0..alpha.len()).map(|i| alpha.get(i).unwrap()).collect::<Vec<_>>(),
/// [0.0, 0.25, 0.5, 0.75, 1.0]);
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// The representation is private:
/// ```compile_fail
/// use lichtung_plot::scales::AlphaValues;
/// fn private(values: AlphaValues) { let _ = values.declaration; }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlphaValues {
name: Arc<String>,
data: Arc<AlphaData>,
declaration: Arc<AlphaDeclaration>,
}
#[derive(Debug, Clone, PartialEq)]
struct AlphaData {
values: Vec<f64>,
members: AlphaMembers,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum AlphaMembers {
Undeclared(NumericValues),
Numeric(NumericValues),
Categorical(KeyValues, Vec<usize>),
Threshold(NumericValues, Vec<usize>),
}
/// The exact authored opacity mapping, materialized once at binding time.
/// Coefficients are finite values in [0, 1] in an owned AlphaValues declaration.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub enum AlphaMapping {
/// Direct coefficients have no additional mapping.
#[default]
Undeclared,
/// Clamped linear mapping.
Linear {
/// Original domain endpoints.
domain: [f64; 2],
/// Output opacity endpoints.
range: [f64; 2],
},
/// Clamped logarithmic mapping with base 10.
Log10 {
/// Original domain endpoints.
domain: [f64; 2],
/// Output opacity endpoints.
range: [f64; 2],
},
/// A complete evaluated custom continuous declaration.
Continuous {
/// Original domain endpoints.
domain: [f64; 2],
/// Exact evaluated coordinates and opacity coefficients.
evaluated: Vec<(f64, f64)>,
},
/// First-observed raw categories and their mapped coefficients.
Categorical(Vec<(RawKey, f64)>),
/// An ordered threshold mapping, with equality belonging to the right interval.
Threshold {
/// Original ordered boundaries.
boundaries: Vec<f64>,
/// One coefficient per interval, including the two outer intervals.
alphas: Vec<f64>,
},
}
impl PartialEq for AlphaMapping {
fn eq(&self, other: &Self) -> bool {
fn numbers(left: &[f64], right: &[f64]) -> bool {
left.iter()
.map(|value| value.to_bits())
.eq(right.iter().map(|value| value.to_bits()))
}
fn pairs(left: &[(f64, f64)], right: &[(f64, f64)]) -> bool {
left.iter()
.map(|(raw, alpha)| (raw.to_bits(), alpha.to_bits()))
.eq(right
.iter()
.map(|(raw, alpha)| (raw.to_bits(), alpha.to_bits())))
}
match (self, other) {
(Self::Undeclared, Self::Undeclared) => true,
(
Self::Linear { domain, range },
Self::Linear {
domain: other_domain,
range: other_range,
},
)
| (
Self::Log10 { domain, range },
Self::Log10 {
domain: other_domain,
range: other_range,
},
) => numbers(domain, other_domain) && numbers(range, other_range),
(
Self::Continuous { domain, evaluated },
Self::Continuous {
domain: other_domain,
evaluated: other_evaluated,
},
) => numbers(domain, other_domain) && pairs(evaluated, other_evaluated),
(
Self::Threshold { boundaries, alphas },
Self::Threshold {
boundaries: other_boundaries,
alphas: other_alphas,
},
) => numbers(boundaries, other_boundaries) && numbers(alphas, other_alphas),
(Self::Categorical(left), Self::Categorical(right)) => left
.iter()
.map(|(key, alpha)| (key, alpha.to_bits()))
.eq(right.iter().map(|(key, alpha)| (key, alpha.to_bits()))),
_ => false,
}
}
}
/// The mapping and its already-computed whole-set guide presentation.
#[derive(Debug, Default, PartialEq)]
struct AlphaDeclaration {
mapping: AlphaMapping,
examples: Vec<(f64, f64)>,
labels: Vec<String>,
}
// All stored coefficients are validated finite and have a canonical zero.
impl Eq for AlphaData {}
impl Eq for AlphaDeclaration {}
#[expect(
clippy::needless_pass_by_value,
reason = "public consuming factories materialize and release one complete immutable source input"
)]
impl AlphaValues {
/// Own caller-computed coefficients in [0, 1] without guide semantics.
///
/// Names must be nonempty, already trimmed and control-free. Empty values
/// are valid; attachment checks the actual unit alignment before fonts.
pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Result<Self> {
let name = validated_name(name.into())?;
let original = NumericValues::new(&name, collect_input(values)?);
Self::try_from(original)
}
/// Map finite source values linearly over an explicit increasing domain.
///
/// Clamp out-of-domain values. Ascending, descending and constant coefficient
/// ranges are valid. Missing/nonfinite sources
/// and nonfinite/nonincreasing domains reject during construction.
pub fn linear(source: NumericValues, domain: (f64, f64), range: (f64, f64)) -> Result<Self> {
materialize::builtin(&source, domain, range, false)
}
/// Map positive finite source values over an explicit positive log10 domain.
///
/// Endpoints must be strictly increasing and remain distinguishable after
/// binary64 log10. Nonpositive sources reject rather than clamping. Other
/// clamping rules match [`Self::linear`].
pub fn log10(source: NumericValues, domain: (f64, f64), range: (f64, f64)) -> Result<Self> {
materialize::builtin(&source, domain, range, true)
}
/// Declare a continuous mapping and eagerly materialize its finite values.
///
/// Invoke `f` once for every distinct clamped source coordinate and required
/// numeric representative, in numeric order. Retain the complete evaluated
/// table and original members; no function, inverse or smooth ramp is stored.
/// The domain must be finite and strictly increasing, and sources nonmissing
/// and finite. Up to five original-domain examples explain this declaration.
pub fn continuous(
source: NumericValues,
domain: (f64, f64),
f: impl FnMut(f64) -> f64,
) -> Result<Self> {
materialize::continuous(&source, domain, f)
}
/// Declare a categorical map, invoking `f` once per first-observed raw level.
///
/// Null sources reject. Complete table order survives [`Self::select`]; only
/// actual consumed categories appear in automatic explanations, including zero.
pub fn categorical(source: CategoryValues, f: impl FnMut(&str) -> f64) -> Result<Self> {
materialize::categorical(&source, f)
}
/// Declare increasing finite boundaries and exactly one more alpha coefficient.
///
/// Intervals are `< b0`, `[b0,b1)`, ..., `>= blast`; equality belongs to the
/// right. No boundaries plus one coefficient declares `all values`. Sources must be
/// finite and nonmissing. Labels come from the actual bounds, not caller text.
pub fn threshold(
source: NumericValues,
boundaries: impl IntoIterator<Item = f64>,
alphas: impl IntoIterator<Item = f64>,
) -> Result<Self> {
materialize::threshold(&source, boundaries, alphas)
}
/// Select original occurrences while retaining the complete shared declaration.
///
/// Repeated indices are allowed; out-of-range indices reject. Construct pooled
/// custom/category maps once and select per Plot to preserve Shared recipes.
pub fn select(&self, indices: impl IntoIterator<Item = usize>) -> Result<Self> {
let indices = collect_input(indices)?;
let values = collect_source(indices.iter().map(|&index| {
self.get(index).ok_or_else(|| {
Error::Data(
format!(
"alpha values {:?} selection index {index} is outside length {}",
self.name(),
self.len(),
)
.into(),
)
})
}))?;
let members = match &self.data.members {
AlphaMembers::Undeclared(source) => AlphaMembers::Undeclared(source.select(&indices)?),
AlphaMembers::Numeric(source) => AlphaMembers::Numeric(source.select(&indices)?),
AlphaMembers::Categorical(source, members) => AlphaMembers::Categorical(
select_categories(source, &indices)?,
collect_source(indices.iter().map(|&i| Ok(members[i])))?,
),
AlphaMembers::Threshold(source, members) => AlphaMembers::Threshold(
source.select(&indices)?,
collect_source(indices.iter().map(|&i| Ok(members[i])))?,
),
};
Ok(Self {
name: Arc::clone(&self.name),
data: source_arc(AlphaData { values, members })?,
declaration: Arc::clone(&self.declaration),
})
}
/// Repeat explicitly row-scoped opacity without replacing its mapping or
/// the original source relation. Used by the rectangular input bridges.
#[doc(hidden)]
pub fn repeat_rows(&self, copies: usize) -> Result<Self> {
if copies == 0 {
return Err(Error::Data(
"row expansion requires at least one column".into(),
));
}
self.len()
.checked_mul(copies)
.ok_or_else(|| Error::Data("expanded alpha count exceeds usize".into()))?;
let mut expanded = if copies == 1 {
self.clone()
} else {
self.select((0..self.len()).flat_map(|row| std::iter::repeat_n(row, copies)))?
};
// Preserve the exact projection when a native map already refers to
// an independently selected subset. Identity sources have the
// stronger row-major repeat rule, including a current width of one.
match (
&mut Arc::make_mut(&mut expanded.data).members,
&self.data.members,
) {
(AlphaMembers::Undeclared(values), AlphaMembers::Undeclared(source))
| (AlphaMembers::Numeric(values), AlphaMembers::Numeric(source))
| (AlphaMembers::Threshold(values, _), AlphaMembers::Threshold(source, _)) => {
retain_repeated(values, source.vector_source(), copies)?;
}
(
AlphaMembers::Categorical(KeyValues::Strings(values), _),
AlphaMembers::Categorical(KeyValues::Strings(source), _),
) => retain_repeated(values, source.vector_source(), copies)?,
(
AlphaMembers::Categorical(KeyValues::Raw(values), _),
AlphaMembers::Categorical(KeyValues::Raw(source), _),
) => retain_repeated(values, source.vector_source(), copies)?,
_ => unreachable!("alpha selection retains its original native source kind"),
}
Ok(expanded)
}
/// Raw source identity used for automatic titles and diagnostics.
#[must_use]
pub fn name(&self) -> &str {
if let Some(values) = self.get_numeric_source() {
if values.name().is_empty() && values.field_key().is_none() {
&self.name
} else {
values.name()
}
} else if let Some(KeyValues::Strings(values)) = self.get_category_source() {
values.original_name()
} else {
&self.name
}
}
pub(crate) fn raw_name(&self) -> &str {
&self.name
}
/// Number of retained occurrences.
#[must_use]
pub fn len(&self) -> usize {
self.data.values.len()
}
/// Whether no occurrences are retained.
#[must_use]
pub fn is_empty(&self) -> bool {
self.data.values.is_empty()
}
/// One occurrence's final coefficient, or None outside the retained input.
#[must_use]
pub fn get(&self, index: usize) -> Option<f64> {
self.data.values.get(index).copied()
}
/// Borrow all materialized opacity coefficients in their retained order.
#[must_use]
pub fn values(&self) -> &[f64] {
&self.data.values
}
/// Explicit explanatory classification, independent of selected coefficients.
#[must_use]
pub fn semantics(&self) -> AlphaSemantics {
match &self.declaration.mapping {
AlphaMapping::Undeclared => AlphaSemantics::Undeclared,
AlphaMapping::Linear { .. }
| AlphaMapping::Log10 { .. }
| AlphaMapping::Continuous { .. } => AlphaSemantics::Continuous,
AlphaMapping::Categorical(_) => AlphaSemantics::Categorical,
AlphaMapping::Threshold { .. } => AlphaSemantics::Threshold,
}
}
/// The original numeric source, including explicitly supplied coefficients.
#[must_use]
pub fn get_numeric_source(&self) -> Option<&NumericValues> {
match &self.data.members {
AlphaMembers::Undeclared(source)
| AlphaMembers::Numeric(source)
| AlphaMembers::Threshold(source, _) => Some(source),
AlphaMembers::Categorical(..) => None,
}
}
/// The original categorical source, when a category mapping was declared.
#[must_use]
pub fn get_category_source(&self) -> Option<&KeyValues> {
match &self.data.members {
AlphaMembers::Categorical(source, _) => Some(source),
_ => None,
}
}
/// The actual threshold interval of each retained occurrence.
#[must_use]
pub fn get_threshold_indices(&self) -> Option<&[usize]> {
match &self.data.members {
AlphaMembers::Threshold(_, indices) => Some(indices),
_ => None,
}
}
/// Borrow the full original mapping independently of selected occurrences.
#[must_use]
pub fn get_mapping(&self) -> &AlphaMapping {
&self.declaration.mapping
}
/// Actual original-domain examples and their evaluated opacity.
#[must_use]
pub fn examples(&self) -> &[(f64, f64)] {
&self.declaration.examples
}
fn from_parts(
name: String,
values: Vec<f64>,
members: AlphaMembers,
declaration: AlphaDeclaration,
) -> Result<Self> {
Ok(Self {
name: source_arc(name)?,
data: source_arc(AlphaData { values, members })?,
declaration: source_arc(declaration)?,
})
}
}
impl TryFrom<NumericValues> for AlphaValues {
type Error = Error;
fn try_from(source: NumericValues) -> Result<Self> {
let name = if source.raw_name().is_empty() && source.field_key().is_none() {
"Alpha"
} else {
source.raw_name()
};
let name = crate::data::source::copy_source_string(name)?;
let values = collect_source((0..source.len()).map(|index| {
let value = source.get(index).flatten().ok_or_else(|| {
Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
})?;
validated_alpha(value).map_err(|error| {
Error::Data(format!("alpha source {name:?} at index {index}: {error}").into())
})
}))?;
Self::from_parts(
name,
values,
AlphaMembers::Undeclared(source),
AlphaDeclaration::default(),
)
}
}
fn retain_repeated<T: crate::data::CapturedValue + Clone>(
values: &mut T,
source: &crate::data::VectorSource,
copies: usize,
) -> Result<()> {
if source.is_identity() {
*values = values
.clone()
.retain(source.info().clone(), copies, None)?
.row_scoped();
}
Ok(())
}
fn select_categories(source: &KeyValues, indices: &[usize]) -> Result<KeyValues> {
source.select(indices)
}
fn validated_name(name: String) -> Result<String> {
if name.is_empty() || name.trim() != name || name.chars().any(char::is_control) {
return Err(Error::Data(
"alpha source names must be nonempty, already trimmed and control-free".into(),
));
}
Ok(name)
}
fn numeric_key(value: f64) -> u64 {
if value == 0.0 {
0
} else {
value.to_bits()
}
}
fn collect_input<T>(values: impl IntoIterator<Item = T>) -> Result<Vec<T>> {
let values = values.into_iter();
let mut retained = Vec::new();
let (minimum, maximum) = values.size_hint();
if maximum == Some(minimum) {
reserve_source(&mut retained, minimum)?;
}
for value in values {
if retained.len() == retained.capacity() {
let additional = retained.capacity().max(1);
reserve_source(&mut retained, additional)?;
}
retained.push(value);
}
Ok(retained)
}
#[cfg(test)]
mod tests;