use crate::error::{binding, BindingResult};
use crate::input::sealed;
use crate::{
binding::{ArraySource, CategoryInput, NumericInput},
scales::{AlphaEncoding, AlphaValues},
};
use crate::{capture::Capture, data::DataSourceRef};
impl sealed::Sealed for AlphaEncoding {
fn native_slots(&self) -> bool {
true
}
}
impl sealed::Sealed for AlphaValues {
fn native_slots(&self) -> bool {
true
}
}
impl sealed::Sealed for f64 {}
pub trait AlphaValuesInput: sealed::Sealed {
#[doc(hidden)]
fn bind_alpha_values(
self,
source: Option<&dyn ArraySource>,
reference: Option<&DataSourceRef>,
) -> BindingResult<AlphaValues>;
}
impl AlphaValuesInput for AlphaValues {
fn bind_alpha_values(
self,
_: Option<&dyn ArraySource>,
_: Option<&DataSourceRef>,
) -> BindingResult<AlphaValues> {
Ok(self)
}
}
impl<T: NumericInput> AlphaValuesInput for T {
fn bind_alpha_values(
self,
source: Option<&dyn ArraySource>,
reference: Option<&DataSourceRef>,
) -> BindingResult<AlphaValues> {
let capture = Capture::existing(source, reference);
let values = capture.bind(self, 1, |input, source| input.bind_numeric(source, "Alpha"))?;
Ok(AlphaValues::try_from(values)?)
}
}
pub trait AlphaInput: sealed::Sealed {
#[doc(hidden)]
fn bind_alpha(
self,
source: Option<&dyn ArraySource>,
expected: Option<usize>,
copies: usize,
reference: Option<&DataSourceRef>,
) -> BindingResult<AlphaEncoding>;
}
impl AlphaInput for AlphaEncoding {
fn bind_alpha(
self,
_: Option<&dyn ArraySource>,
_: Option<usize>,
_: usize,
_: Option<&DataSourceRef>,
) -> BindingResult<AlphaEncoding> {
Ok(self)
}
}
impl AlphaInput for f64 {
fn bind_alpha(
self,
_: Option<&dyn ArraySource>,
_: Option<usize>,
_: usize,
_: Option<&DataSourceRef>,
) -> BindingResult<AlphaEncoding> {
Ok(AlphaEncoding::fixed(self)?)
}
}
impl<T: AlphaValuesInput> AlphaInput for T {
fn bind_alpha(
self,
source: Option<&dyn ArraySource>,
expected: Option<usize>,
copies: usize,
reference: Option<&DataSourceRef>,
) -> BindingResult<AlphaEncoding> {
let copies = if self.native_slots() { 1 } else { copies };
let values = expand(self.bind_alpha_values(source, reference)?, expected, copies)?;
Ok(AlphaEncoding::observations(values))
}
}
pub(crate) fn expand(
values: AlphaValues,
expected: Option<usize>,
copies: usize,
) -> BindingResult<AlphaValues> {
if copies == 0 {
return Err(binding("alpha", "no generated columns"));
}
if let Some(expected) = expected {
crate::error::length("alpha", values.name(), expected / copies, values.len())?;
}
if copies == 1 {
Ok(values)
} else {
Ok(values.select((0..values.len()).flat_map(|row| std::iter::repeat_n(row, copies)))?)
}
}
pub(crate) fn keys<I, S, B>(
capture: &Capture<'_>,
keys: I,
) -> BindingResult<Vec<crate::CategoryValues>>
where
I: IntoIterator<Item = (S, B)>,
S: AsRef<str>,
B: CategoryInput,
{
keys.into_iter()
.map(|(field, input)| {
let values = capture.bind(input, 1, |input, source| {
input.bind_category(source, "alpha selector")
})?;
Ok(values.with_field_name(field.as_ref()))
})
.collect()
}