Skip to main content

lichtung_plot_ndarray/
projection.rs

1//! Sparse borrowed columns in the original source coordinate system.
2
3use std::collections::HashSet;
4
5use crate::error::{binding, BindingResult};
6use crate::input::sealed::{self, AxisKind};
7use crate::{binding::ArraySource, data::AxisValues, AdapterError, CategoryValues, NumericValues};
8
9/// Borrowed one-column sources addressed by their original logical indices.
10///
11/// The shape is the actual source's `(rows, logical_column_count)`, not the
12/// number of supplied columns. Each entry supplies a two-dimensional view or
13/// values/present pair with shape `(rows, 1)`. Different entries may have
14/// different element types, strides and validity. Construction validates only
15/// descriptor structure; selecting a role snapshots only its supplied values.
16///
17/// Existing scalar and ordered index selectors retain their meaning. An
18/// in-bounds column without a value entry fails explicitly; `..` still means
19/// every original column, not every supplied entry. Grid positions and source
20/// row IDs remain independent of field identities.
21/// [`Self::from_identities`] supplies the same original namespace without any
22/// value entries when only field-identity resolution is needed.
23///
24/// ```
25/// use lichtung_plot_ndarray::{Line, binding::{ArraySource, ColumnProjection}};
26/// use ndarray::array;
27///
28/// let x = array![[0.], [5.], [20.]];
29/// let y7 = array![[4.], [5.], [6.]];
30/// let y2 = array![[1.], [2.], [3.]];
31/// let columns: [(usize, &dyn ArraySource); 3] =
32///     [(4, &x.view()), (7, &y7.view()), (2, &y2.view())];
33/// let identities = [(4, "time"), (7, "treated"), (2, "control")];
34/// let source = ColumnProjection::new((3, 10), &columns)?
35///     .with_identities(&identities)?;
36/// let adapted = Line::from_data(source, 4usize, [7usize, 2usize])?;
37/// let (plot, metadata) = adapted.into_parts(); // releases all source borrows
38/// let _restored = Line::from_parts(plot, metadata);
39/// # Ok::<(), lichtung_plot_ndarray::AdapterError>(())
40/// ```
41pub struct ColumnProjection<'columns> {
42    source_shape: (usize, usize),
43    columns: &'columns [(usize, &'columns dyn ArraySource)],
44    identities: Option<&'columns [(usize, &'columns str)]>,
45    origin: Option<&'columns crate::data::DataSourceInfo>,
46}
47
48impl<'columns> ColumnProjection<'columns> {
49    /// Validate and borrow nonempty, unique, in-bounds one-column descriptors.
50    ///
51    /// Retains original coordinates and positional `Column N` identities without
52    /// reading observations. Each source must have shape `(source_shape.0, 1)`
53    /// and pass its existing validity-shape validation.
54    pub fn new(
55        source_shape: (usize, usize),
56        columns: &'columns [(usize, &'columns dyn ArraySource)],
57    ) -> std::result::Result<Self, AdapterError> {
58        let projection = Self {
59            source_shape,
60            columns,
61            identities: None,
62            origin: None,
63        };
64        projection.validate()?;
65        Ok(projection)
66    }
67
68    /// Borrow an explicit original namespace without projecting observations.
69    ///
70    /// The shape is the actual source shape, not the number of identities or
71    /// selector rows. Indices and raw identities follow [`Self::with_identities`]
72    /// validation. An empty identity table remains explicit: it does not enable
73    /// positional-name fallback. Every value lookup still fails as unprojected.
74    ///
75    /// This uses the same descriptor representation; [`Self::new`] continues to
76    /// require at least one value entry.
77    pub fn from_identities(
78        source_shape: (usize, usize),
79        identities: &'columns [(usize, &'columns str)],
80    ) -> std::result::Result<Self, AdapterError> {
81        let projection = Self {
82            source_shape,
83            columns: &[],
84            identities: Some(identities),
85            origin: None,
86        };
87        projection.validate()?;
88        Ok(projection)
89    }
90
91    /// Supply exact raw field identities separately from coordinates and labels.
92    ///
93    /// Indices and raw strings must each be unique, all indices must be in the
94    /// original bounds, and every value entry needs an identity. Additional
95    /// in-bounds identities may describe unprojected columns, for example targets
96    /// named by a generated-column alpha key variable. They do not grant value
97    /// lookup. An explicit table never falls back to positional identities.
98    ///
99    /// Replaces any previous table completely. Strings are borrowed unchanged:
100    /// empty/whitespace names and display collisions retain native validation.
101    /// No observation is read, and neither this table nor its borrow enters the
102    /// owned native Plot or binding metadata.
103    pub fn with_identities(
104        mut self,
105        identities: &'columns [(usize, &'columns str)],
106    ) -> std::result::Result<Self, AdapterError> {
107        self.validate_identities(identities)?;
108        self.identities = Some(identities);
109        Ok(self)
110    }
111
112    /// Preserve an actual immutable host binding before its projection is discarded.
113    #[doc(hidden)]
114    pub fn with_origin(
115        mut self,
116        origin: &'columns crate::data::DataSourceInfo,
117    ) -> Result<Self, AdapterError> {
118        let rows = self.source_shape.0;
119        let indices = self
120            .columns
121            .iter()
122            .map(|(index, _)| *index)
123            .collect::<Vec<_>>();
124        let expected = if origin.selected_shape().len() == 1 && indices.len() == 1 {
125            vec![rows]
126        } else {
127            vec![rows, indices.len()]
128        };
129        if origin.source_shape() != [rows, self.source_shape.1]
130            || origin.selected_shape() != expected
131            || origin
132                .selected_indices()
133                .is_some_and(|selected| selected != indices)
134        {
135            return Err(binding(
136                "column projection",
137                "captured source selection does not match the projection",
138            ));
139        }
140        self.origin = Some(origin);
141        Ok(self)
142    }
143
144    fn validate_identities(&self, identities: &[(usize, &str)]) -> BindingResult<()> {
145        let mut indices = HashSet::new();
146        let mut names = HashSet::new();
147        indices
148            .try_reserve(identities.len())
149            .map_err(|source| AdapterError::Allocation {
150                operation: "column identities",
151                source,
152            })?;
153        names
154            .try_reserve(identities.len())
155            .map_err(|source| AdapterError::Allocation {
156                operation: "column identities",
157                source,
158            })?;
159        for &(index, identity) in identities {
160            crate::source::lookup(Some(self), index, "column identities")?;
161            if !indices.insert(index) {
162                return Err(binding(
163                    "column identities",
164                    format!("duplicate logical column {index}"),
165                ));
166            }
167            if !names.insert(identity) {
168                return Err(binding(
169                    "column identities",
170                    format!("duplicate raw identity {identity:?}"),
171                ));
172            }
173        }
174        for &(index, _) in self.columns {
175            if !indices.contains(&index) {
176                return Err(binding(
177                    "column identities",
178                    format!("no raw identity supplied for logical column {index}"),
179                ));
180            }
181        }
182        Ok(())
183    }
184
185    fn column(&self, index: usize, role: &'static str) -> BindingResult<&dyn ArraySource> {
186        crate::source::lookup(Some(self), index, role)?;
187        self.columns
188            .iter()
189            .find(|(column, _)| *column == index)
190            .map(|(_, source)| *source)
191            .ok_or_else(|| binding(role, format!("logical column {index} was not projected")))
192    }
193}
194
195fn original_column(error: AdapterError, index: usize) -> AdapterError {
196    match error {
197        AdapterError::UnsupportedElement { role, element, .. } => {
198            AdapterError::UnsupportedElement {
199                role,
200                element,
201                column: Some(index),
202            }
203        }
204        AdapterError::SourceRow { slot, value, .. } => AdapterError::SourceRow {
205            slot,
206            value,
207            column: Some(index),
208        },
209        other => other,
210    }
211}
212
213impl sealed::Sealed for ColumnProjection<'_> {
214    fn binding_origin(&self) -> Option<&crate::data::DataSourceInfo> {
215        self.origin
216    }
217
218    fn column_identities(&self) -> Option<&[(usize, &str)]> {
219        self.identities
220    }
221
222    fn axis_kind(&self, index: usize, role: &'static str) -> BindingResult<AxisKind> {
223        sealed::Sealed::axis_kind(self.column(index, role)?, 0, role)
224            .map_err(|error| original_column(error, index))
225    }
226}
227
228macro_rules! projected_column {
229    ($method:ident, $ty:ty) => {
230        fn $method(&self, index: usize, role: &'static str) -> BindingResult<Vec<$ty>> {
231            self.column(index, role)?
232                .$method(0, role)
233                .map_err(|error| original_column(error, index))
234        }
235    };
236}
237
238impl ArraySource for ColumnProjection<'_> {
239    fn validate(&self) -> BindingResult<()> {
240        if self.columns.is_empty() && self.identities.is_none() {
241            return Err(binding(
242                "column projection",
243                "supply at least one value column",
244            ));
245        }
246        let mut indices = HashSet::new();
247        indices
248            .try_reserve(self.columns.len())
249            .map_err(|source| AdapterError::Allocation {
250                operation: "column projection",
251                source,
252            })?;
253        for &(index, source) in self.columns {
254            crate::source::lookup(Some(self), index, "column projection")?;
255            if !indices.insert(index) {
256                return Err(binding(
257                    "column projection",
258                    format!("duplicate logical column {index}"),
259                ));
260            }
261            source.validate()?;
262            let actual = source.shape();
263            if actual != (self.source_shape.0, 1) {
264                return Err(AdapterError::Shape {
265                    operation: "column projection",
266                    expected: vec![self.source_shape.0, 1],
267                    actual: vec![actual.0, actual.1],
268                });
269            }
270        }
271        if let Some(identities) = self.identities {
272            self.validate_identities(identities)?;
273        }
274        Ok(())
275    }
276
277    fn shape(&self) -> (usize, usize) {
278        self.source_shape
279    }
280
281    projected_column!(numeric_column, Option<f64>);
282    projected_column!(category_column, Option<String>);
283    projected_column!(boolean_column, Option<bool>);
284    projected_column!(id_column, usize);
285
286    fn axis_column(&self, index: usize, role: &'static str) -> BindingResult<AxisValues> {
287        match sealed::Sealed::axis_kind(self, index, role)? {
288            AxisKind::Numeric => {
289                let values = self.numeric_column(index, role)?;
290                Ok(AxisValues::Numeric(NumericValues::nullable(
291                    crate::source::identity(Some(self), index, role)?,
292                    values,
293                )))
294            }
295            AxisKind::Category => {
296                let values = self.category_column(index, role)?;
297                Ok(AxisValues::Category(CategoryValues::nullable(
298                    crate::source::identity(Some(self), index, role)?,
299                    values,
300                )?))
301            }
302        }
303    }
304}
305
306impl sealed::Sealed for &ColumnProjection<'_> {
307    fn binding_origin(&self) -> Option<&crate::data::DataSourceInfo> {
308        self.origin
309    }
310}
311
312impl crate::binding::ColumnsInput for &ColumnProjection<'_> {
313    fn local_identities(&self) -> bool {
314        self.origin
315            .is_some_and(|origin| origin.selector().is_none())
316    }
317
318    fn bind_columns(self, _: Option<&dyn ArraySource>) -> BindingResult<crate::input::Columns> {
319        let indices = self
320            .columns
321            .iter()
322            .map(|(index, _)| *index)
323            .collect::<Vec<_>>();
324        crate::input::selected(Some(self), &indices)
325    }
326}
327
328impl crate::binding::NumericSeriesInput for &ColumnProjection<'_> {
329    fn bind_series(
330        self,
331        source: Option<&dyn ArraySource>,
332        role: &'static str,
333    ) -> BindingResult<crate::input::SeriesBinding> {
334        use crate::binding::ColumnsInput;
335        let local = self.local_identities();
336        crate::input::multiple(self.bind_columns(source)?, local, role)
337    }
338}