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::{AdapterError, ArraySource, AxisValues, 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::{ArraySource, ColumnProjection, Line};
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}
46
47impl<'columns> ColumnProjection<'columns> {
48    /// Validate and borrow nonempty, unique, in-bounds one-column descriptors.
49    ///
50    /// Retains original coordinates and positional `Column N` identities without
51    /// reading observations. Each source must have shape `(source_shape.0, 1)`
52    /// and pass its existing validity-shape validation.
53    pub fn new(
54        source_shape: (usize, usize),
55        columns: &'columns [(usize, &'columns dyn ArraySource)],
56    ) -> std::result::Result<Self, AdapterError> {
57        let projection = Self {
58            source_shape,
59            columns,
60            identities: None,
61        };
62        projection.validate()?;
63        Ok(projection)
64    }
65
66    /// Borrow an explicit original namespace without projecting observations.
67    ///
68    /// The shape is the actual source shape, not the number of identities or
69    /// selector rows. Indices and raw identities follow [`Self::with_identities`]
70    /// validation. An empty identity table remains explicit: it does not enable
71    /// positional-name fallback. Every value lookup still fails as unprojected.
72    ///
73    /// This uses the same descriptor representation; [`Self::new`] continues to
74    /// require at least one value entry.
75    pub fn from_identities(
76        source_shape: (usize, usize),
77        identities: &'columns [(usize, &'columns str)],
78    ) -> std::result::Result<Self, AdapterError> {
79        let projection = Self {
80            source_shape,
81            columns: &[],
82            identities: Some(identities),
83        };
84        projection.validate()?;
85        Ok(projection)
86    }
87
88    /// Supply exact raw field identities separately from coordinates and labels.
89    ///
90    /// Indices and raw strings must each be unique, all indices must be in the
91    /// original bounds, and every value entry needs an identity. Additional
92    /// in-bounds identities may describe unprojected columns, for example targets
93    /// named by a generated-column alpha key variable. They do not grant value
94    /// lookup. An explicit table never falls back to positional identities.
95    ///
96    /// Replaces any previous table completely. Strings are borrowed unchanged:
97    /// empty/whitespace names and display collisions retain native validation.
98    /// No observation is read, and neither this table nor its borrow enters the
99    /// owned native Plot or binding metadata.
100    pub fn with_identities(
101        mut self,
102        identities: &'columns [(usize, &'columns str)],
103    ) -> std::result::Result<Self, AdapterError> {
104        self.validate_identities(identities)?;
105        self.identities = Some(identities);
106        Ok(self)
107    }
108
109    fn validate_identities(&self, identities: &[(usize, &str)]) -> BindingResult<()> {
110        let mut indices = HashSet::new();
111        let mut names = HashSet::new();
112        indices
113            .try_reserve(identities.len())
114            .map_err(|source| AdapterError::Allocation {
115                operation: "column identities",
116                source,
117            })?;
118        names
119            .try_reserve(identities.len())
120            .map_err(|source| AdapterError::Allocation {
121                operation: "column identities",
122                source,
123            })?;
124        for &(index, identity) in identities {
125            crate::source::lookup(Some(self), index, "column identities")?;
126            if !indices.insert(index) {
127                return Err(binding(
128                    "column identities",
129                    format!("duplicate logical column {index}"),
130                ));
131            }
132            if !names.insert(identity) {
133                return Err(binding(
134                    "column identities",
135                    format!("duplicate raw identity {identity:?}"),
136                ));
137            }
138        }
139        for &(index, _) in self.columns {
140            if !indices.contains(&index) {
141                return Err(binding(
142                    "column identities",
143                    format!("no raw identity supplied for logical column {index}"),
144                ));
145            }
146        }
147        Ok(())
148    }
149
150    fn column(&self, index: usize, role: &'static str) -> BindingResult<&dyn ArraySource> {
151        crate::source::lookup(Some(self), index, role)?;
152        self.columns
153            .iter()
154            .find(|(column, _)| *column == index)
155            .map(|(_, source)| *source)
156            .ok_or_else(|| binding(role, format!("logical column {index} was not projected")))
157    }
158}
159
160fn original_column(error: AdapterError, index: usize) -> AdapterError {
161    match error {
162        AdapterError::UnsupportedElement { role, element, .. } => {
163            AdapterError::UnsupportedElement {
164                role,
165                element,
166                column: Some(index),
167            }
168        }
169        AdapterError::SourceRow { slot, value, .. } => AdapterError::SourceRow {
170            slot,
171            value,
172            column: Some(index),
173        },
174        other => other,
175    }
176}
177
178impl sealed::Sealed for ColumnProjection<'_> {
179    fn column_identities(&self) -> Option<&[(usize, &str)]> {
180        self.identities
181    }
182
183    fn axis_kind(&self, index: usize, role: &'static str) -> BindingResult<AxisKind> {
184        sealed::Sealed::axis_kind(self.column(index, role)?, 0, role)
185            .map_err(|error| original_column(error, index))
186    }
187}
188
189macro_rules! projected_column {
190    ($method:ident, $ty:ty) => {
191        fn $method(&self, index: usize, role: &'static str) -> BindingResult<Vec<$ty>> {
192            self.column(index, role)?
193                .$method(0, role)
194                .map_err(|error| original_column(error, index))
195        }
196    };
197}
198
199impl ArraySource for ColumnProjection<'_> {
200    fn validate(&self) -> BindingResult<()> {
201        if self.columns.is_empty() && self.identities.is_none() {
202            return Err(binding(
203                "column projection",
204                "supply at least one value column",
205            ));
206        }
207        let mut indices = HashSet::new();
208        indices
209            .try_reserve(self.columns.len())
210            .map_err(|source| AdapterError::Allocation {
211                operation: "column projection",
212                source,
213            })?;
214        for &(index, source) in self.columns {
215            crate::source::lookup(Some(self), index, "column projection")?;
216            if !indices.insert(index) {
217                return Err(binding(
218                    "column projection",
219                    format!("duplicate logical column {index}"),
220                ));
221            }
222            source.validate()?;
223            let actual = source.shape();
224            if actual != (self.source_shape.0, 1) {
225                return Err(AdapterError::Shape {
226                    operation: "column projection",
227                    expected: vec![self.source_shape.0, 1],
228                    actual: vec![actual.0, actual.1],
229                });
230            }
231        }
232        if let Some(identities) = self.identities {
233            self.validate_identities(identities)?;
234        }
235        Ok(())
236    }
237
238    fn shape(&self) -> (usize, usize) {
239        self.source_shape
240    }
241
242    projected_column!(numeric_column, Option<f64>);
243    projected_column!(category_column, Option<String>);
244    projected_column!(boolean_column, Option<bool>);
245    projected_column!(id_column, usize);
246    projected_column!(byte_column, u8);
247
248    fn axis_column(&self, index: usize, role: &'static str) -> BindingResult<AxisValues> {
249        match sealed::Sealed::axis_kind(self, index, role)? {
250            AxisKind::Numeric => {
251                let values = self.numeric_column(index, role)?;
252                Ok(AxisValues::Numeric(NumericValues::nullable(
253                    crate::source::identity(Some(self), index, role)?,
254                    values,
255                )))
256            }
257            AxisKind::Category => {
258                let values = self.category_column(index, role)?;
259                Ok(AxisValues::Category(CategoryValues::nullable(
260                    crate::source::identity(Some(self), index, role)?,
261                    values,
262                )?))
263            }
264        }
265    }
266}