Skip to main content

lichtung_plot_ndarray/
source.rs

1//! Safe, borrowed descriptors; selecting a column snapshots only that column.
2use ndarray::{ArrayView2, Axis};
3
4use crate::error::{unsupported_column, BindingResult};
5use crate::input::sealed;
6use crate::{binding::ArrayElement, data::AxisValues, CategoryValues, NumericValues};
7
8/// Sealed array-table inputs: two-dimensional views, `(values, present)` pairs
9/// and explicit [`crate::binding::ColumnProjection`] descriptors.
10/// Rows are observations and selectors always address logical columns.
11pub trait ArraySource: sealed::Sealed {
12    #[doc(hidden)]
13    fn validate(&self) -> BindingResult<()>;
14    #[doc(hidden)]
15    fn shape(&self) -> (usize, usize);
16    #[doc(hidden)]
17    fn numeric_column(&self, index: usize, role: &'static str) -> BindingResult<Vec<Option<f64>>>;
18    #[doc(hidden)]
19    fn category_column(
20        &self,
21        index: usize,
22        role: &'static str,
23    ) -> BindingResult<Vec<Option<String>>>;
24    #[doc(hidden)]
25    fn boolean_column(&self, index: usize, role: &'static str) -> BindingResult<Vec<Option<bool>>>;
26    #[doc(hidden)]
27    fn id_column(&self, index: usize, role: &'static str) -> BindingResult<Vec<usize>>;
28    #[doc(hidden)]
29    fn axis_column(&self, index: usize, role: &'static str) -> BindingResult<AxisValues>;
30}
31
32pub(crate) fn name(index: usize) -> String {
33    index.checked_add(1).map_or_else(
34        || format!("Column index {index}"),
35        |position| format!("Column {position}"),
36    )
37}
38pub(crate) fn identity(
39    source: Option<&dyn ArraySource>,
40    index: usize,
41    role: &'static str,
42) -> BindingResult<String> {
43    let Some(identities) = source.and_then(sealed::Sealed::column_identities) else {
44        return Ok(name(index));
45    };
46    lookup(source, index, role)?;
47    identities
48        .iter()
49        .find(|(column, _)| *column == index)
50        .map(|(_, identity)| (*identity).to_owned())
51        .ok_or_else(|| {
52            crate::error::binding(
53                role,
54                format!("no raw identity supplied for logical column {index}"),
55            )
56        })
57}
58pub(crate) fn lookup<'a>(
59    source: Option<&'a dyn ArraySource>,
60    index: usize,
61    role: &'static str,
62) -> BindingResult<&'a dyn ArraySource> {
63    let source = source.ok_or(crate::AdapterError::MissingSource { role, index })?;
64    let (_, columns) = source.shape();
65    if index >= columns {
66        return Err(crate::AdapterError::Column {
67            role,
68            index,
69            columns,
70        });
71    }
72    Ok(source)
73}
74
75fn check<T>(
76    values: ArrayView2<'_, T>,
77    present: Option<ArrayView2<'_, bool>>,
78    index: usize,
79    role: &'static str,
80) -> BindingResult<()> {
81    if let Some(present) = present {
82        if values.shape() != present.shape() {
83            return Err(crate::AdapterError::Shape {
84                operation: role,
85                expected: values.shape().to_vec(),
86                actual: present.shape().to_vec(),
87            });
88        }
89    }
90    if index >= values.ncols() {
91        return Err(crate::AdapterError::Column {
92            role,
93            index,
94            columns: values.ncols(),
95        });
96    }
97    Ok(())
98}
99
100macro_rules! source_method {
101    ($method:ident, $ty:ty, $supported:ident, $convert:expr) => {
102        fn $method(&self, index: usize, role: &'static str) -> BindingResult<Vec<Option<$ty>>> {
103            let (values, present) = self.parts();
104            check(values, present, index, role)?;
105            if !T::$supported {
106                return Err(unsupported_column::<T>(role, index));
107            }
108            crate::snapshot::values(
109                values.index_axis(Axis(1), index),
110                present.as_ref().map(|mask| mask.index_axis(Axis(1), index)),
111                $convert,
112                role,
113            )
114        }
115    };
116}
117
118trait Parts<T> {
119    fn parts(&self) -> (ArrayView2<'_, T>, Option<ArrayView2<'_, bool>>);
120}
121impl<T> Parts<T> for ArrayView2<'_, T> {
122    fn parts(&self) -> (ArrayView2<'_, T>, Option<ArrayView2<'_, bool>>) {
123        (self.view(), None)
124    }
125}
126impl<T> Parts<T> for (ArrayView2<'_, T>, ArrayView2<'_, bool>) {
127    fn parts(&self) -> (ArrayView2<'_, T>, Option<ArrayView2<'_, bool>>) {
128        (self.0.view(), Some(self.1.view()))
129    }
130}
131
132macro_rules! array_source {
133    ($ty:ty) => {
134        impl<T: ArrayElement> ArraySource for $ty {
135            fn validate(&self) -> BindingResult<()> {
136                let (values, present) = self.parts();
137                if let Some(present) = present {
138                    if values.shape() != present.shape() {
139                        return Err(crate::AdapterError::Shape {
140                            operation: "source validity",
141                            expected: values.shape().to_vec(),
142                            actual: present.shape().to_vec(),
143                        });
144                    }
145                }
146                Ok(())
147            }
148            fn shape(&self) -> (usize, usize) {
149                let (values, _) = self.parts();
150                values.dim()
151            }
152            source_method!(numeric_column, f64, NUMERIC, ArrayElement::numeric);
153            source_method!(category_column, String, CATEGORY, |value| value
154                .category()
155                .map(str::to_owned));
156            source_method!(boolean_column, bool, BOOLEAN, ArrayElement::boolean);
157            fn id_column(&self, index: usize, role: &'static str) -> BindingResult<Vec<usize>> {
158                let (values, present) = self.parts();
159                check(values, present, index, role)?;
160                if !T::ID {
161                    return Err(unsupported_column::<T>(role, index));
162                }
163                let values = values.index_axis(Axis(1), index);
164                let present = present.as_ref().map(|mask| mask.index_axis(Axis(1), index));
165                crate::input::ids(values, present, role).map_err(|error| match error {
166                    crate::AdapterError::SourceRow { slot, value, .. } => {
167                        crate::AdapterError::SourceRow {
168                            slot,
169                            value,
170                            column: Some(index),
171                        }
172                    }
173                    other => other,
174                })
175            }
176            fn axis_column(&self, index: usize, role: &'static str) -> BindingResult<AxisValues> {
177                if T::NUMERIC {
178                    Ok(AxisValues::Numeric(NumericValues::nullable(
179                        name(index),
180                        self.numeric_column(index, role)?,
181                    )))
182                } else if T::CATEGORY {
183                    Ok(AxisValues::Category(CategoryValues::nullable(
184                        name(index),
185                        self.category_column(index, role)?,
186                    )?))
187                } else {
188                    Err(unsupported_column::<T>(role, index))
189                }
190            }
191        }
192    };
193}
194array_source!(ArrayView2<'_, T>);
195array_source!((ArrayView2<'_, T>, ArrayView2<'_, bool>));