1use std::sync::Arc;
4
5use crate::data::source::{collect_source, reserve_source, source_arc};
6use crate::numeric::set::FormattedSet;
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};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum AlphaTarget {
19 Point,
20 Line,
21 Fill,
22}
23
24impl AlphaTarget {
25 pub(crate) const fn index(self) -> usize {
26 match self {
27 Self::Point => 0,
28 Self::Line => 1,
29 Self::Fill => 2,
30 }
31 }
32}
33
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub(crate) struct AlphaInputs([AlphaEncoding; 3]);
36
37impl AlphaInputs {
38 pub(crate) fn get(&self, target: AlphaTarget) -> &AlphaEncoding {
39 &self.0[target.index()]
40 }
41
42 pub(crate) fn set(&mut self, target: AlphaTarget, encoding: AlphaEncoding) {
43 self.0[target.index()] = encoding;
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum AlphaSemantics {
53 Undeclared,
55 Continuous,
57 Categorical,
59 Threshold,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct AlphaValues {
88 name: Arc<String>,
89 data: Arc<AlphaData>,
90 declaration: Arc<AlphaDeclaration>,
91}
92
93#[derive(Debug, PartialEq, Eq)]
94struct AlphaData {
95 values: Vec<u8>,
96 members: AlphaMembers,
97}
98
99#[derive(Debug, PartialEq, Eq)]
100enum AlphaMembers {
101 Undeclared,
102 Numeric(Vec<u64>),
103 Categorical(Vec<usize>),
104 Threshold(Vec<(u64, usize)>),
105}
106
107#[derive(Debug, PartialEq, Eq)]
109enum AlphaDeclaration {
110 Undeclared,
111 Continuous {
112 domain: [u64; 2],
113 rule: ContinuousRule,
114 examples: FormattedSet,
115 alphas: Vec<u8>,
116 },
117 Categorical(Vec<(String, u8)>),
118 Threshold {
119 boundaries: FormattedSet,
120 alphas: Vec<u8>,
121 labels: Vec<String>,
122 },
123}
124
125#[derive(Debug, PartialEq, Eq)]
126enum ContinuousRule {
127 Linear((u8, u8)),
128 Log10 {
129 range: (u8, u8),
130 coordinates: [u64; 2],
131 },
132 Custom(Vec<(u64, u8)>),
133}
134
135#[expect(
136 clippy::needless_pass_by_value,
137 reason = "public consuming factories materialize and release one complete immutable source input"
138)]
139impl AlphaValues {
140 pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = u8>) -> Result<Self> {
145 let name = validated_name(name.into())?;
146 Self::from_parts(
147 name,
148 collect_input(values)?,
149 AlphaMembers::Undeclared,
150 AlphaDeclaration::Undeclared,
151 )
152 }
153
154 pub fn linear(source: NumericValues, domain: (f64, f64), range: (u8, u8)) -> Result<Self> {
160 materialize::builtin(&source, domain, range, false)
161 }
162
163 pub fn log10(source: NumericValues, domain: (f64, f64), range: (u8, u8)) -> Result<Self> {
169 materialize::builtin(&source, domain, range, true)
170 }
171
172 pub fn continuous(
180 source: NumericValues,
181 domain: (f64, f64),
182 f: impl FnMut(f64) -> u8,
183 ) -> Result<Self> {
184 materialize::continuous(&source, domain, f)
185 }
186
187 pub fn categorical(source: CategoryValues, f: impl FnMut(&str) -> u8) -> Result<Self> {
192 materialize::categorical(&source, f)
193 }
194
195 pub fn threshold(
201 source: NumericValues,
202 boundaries: impl IntoIterator<Item = f64>,
203 alphas: impl IntoIterator<Item = u8>,
204 ) -> Result<Self> {
205 materialize::threshold(&source, boundaries, alphas)
206 }
207
208 pub fn select(&self, indices: impl IntoIterator<Item = usize>) -> Result<Self> {
213 let indices = collect_input(indices)?;
214 let values = collect_source(indices.iter().map(|&index| {
215 self.get(index).ok_or_else(|| {
216 Error::Data(format!(
217 "alpha values {:?} selection index {index} is outside length {}",
218 self.name(),
219 self.len(),
220 ))
221 })
222 }))?;
223 let members = match &self.data.members {
224 AlphaMembers::Undeclared => AlphaMembers::Undeclared,
225 AlphaMembers::Numeric(members) => {
226 AlphaMembers::Numeric(collect_source(indices.iter().map(|&i| Ok(members[i])))?)
227 }
228 AlphaMembers::Categorical(members) => {
229 AlphaMembers::Categorical(collect_source(indices.iter().map(|&i| Ok(members[i])))?)
230 }
231 AlphaMembers::Threshold(members) => {
232 AlphaMembers::Threshold(collect_source(indices.iter().map(|&i| Ok(members[i])))?)
233 }
234 };
235 Ok(Self {
236 name: Arc::clone(&self.name),
237 data: source_arc(AlphaData { values, members })?,
238 declaration: Arc::clone(&self.declaration),
239 })
240 }
241
242 #[must_use]
244 pub fn name(&self) -> &str {
245 &self.name
246 }
247
248 #[must_use]
250 pub fn len(&self) -> usize {
251 self.data.values.len()
252 }
253
254 #[must_use]
256 pub fn is_empty(&self) -> bool {
257 self.data.values.is_empty()
258 }
259
260 #[must_use]
262 pub fn get(&self, index: usize) -> Option<u8> {
263 self.data.values.get(index).copied()
264 }
265
266 #[must_use]
268 pub fn semantics(&self) -> AlphaSemantics {
269 match self.declaration.as_ref() {
270 AlphaDeclaration::Undeclared => AlphaSemantics::Undeclared,
271 AlphaDeclaration::Continuous { .. } => AlphaSemantics::Continuous,
272 AlphaDeclaration::Categorical(_) => AlphaSemantics::Categorical,
273 AlphaDeclaration::Threshold { .. } => AlphaSemantics::Threshold,
274 }
275 }
276
277 fn from_parts(
278 name: String,
279 values: Vec<u8>,
280 members: AlphaMembers,
281 declaration: AlphaDeclaration,
282 ) -> Result<Self> {
283 Ok(Self {
284 name: source_arc(name)?,
285 data: source_arc(AlphaData { values, members })?,
286 declaration: source_arc(declaration)?,
287 })
288 }
289}
290
291fn validated_name(name: String) -> Result<String> {
292 if name.is_empty() || name.trim() != name || name.chars().any(char::is_control) {
293 return Err(Error::Data(
294 "alpha source names must be nonempty, already trimmed and control-free".into(),
295 ));
296 }
297 Ok(name)
298}
299
300fn numeric_key(value: f64) -> u64 {
301 if value == 0.0 {
302 0
303 } else {
304 value.to_bits()
305 }
306}
307
308fn collect_input<T>(values: impl IntoIterator<Item = T>) -> Result<Vec<T>> {
309 let values = values.into_iter();
310 let mut retained = Vec::new();
311 let (minimum, maximum) = values.size_hint();
312 if maximum == Some(minimum) {
313 reserve_source(&mut retained, minimum)?;
314 }
315 for value in values {
316 if retained.len() == retained.capacity() {
317 let additional = retained.capacity().max(1);
318 reserve_source(&mut retained, additional)?;
319 }
320 retained.push(value);
321 }
322 Ok(retained)
323}
324
325#[cfg(test)]
326mod tests;