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