Skip to main content

lichtung_plot_ndarray/frontend/
grid.rs

1use super::{context, Context, PlotAdapter};
2use crate::capture::Capture;
3use crate::error::{binding, length, BindingResult};
4use crate::{
5    binding::{ArraySource, BooleanInput, CategoryInput, ColumnsInput},
6    data::{KeyValues, RawKey, RawKeyValues},
7    kind, AdapterError, CategoryValues, NumericValues, Plot,
8};
9
10#[derive(Clone)]
11pub(super) struct Grid {
12    x: Vec<String>,
13    y: Vec<String>,
14    origins: Vec<usize>,
15}
16impl Grid {
17    pub(super) fn restore(
18        source: &crate::data::DataSourceInfo,
19        x: &CategoryValues,
20        y: &CategoryValues,
21    ) -> Self {
22        Self {
23            x: x.levels().to_vec(),
24            y: y.levels().to_vec(),
25            origins: source
26                .selected_indices()
27                .map_or_else(|| (0..x.levels().len()).collect(), <[usize]>::to_vec),
28        }
29    }
30    pub(super) fn rows(&self) -> usize {
31        self.y.len()
32    }
33
34    pub(super) fn columns(&self) -> usize {
35        self.x.len()
36    }
37}
38impl<K: kind::Marker> PlotAdapter<'_, K> {
39    pub(super) fn cell_shape(
40        &self,
41        input: &impl crate::input::sealed::Sealed,
42        role: &'static str,
43    ) -> BindingResult<()> {
44        let shape = if let Some(indices) = input.selected_columns() {
45            let first = *indices
46                .first()
47                .ok_or_else(|| binding(role, "select at least one column"))?;
48            let source = crate::source::lookup(self.source.as_deref(), first, role)?;
49            Some((source.shape().0, indices.len()))
50        } else {
51            input.cell_shape()
52        };
53        if let Some(shape) = shape {
54            let expected = self.bindings.cell_shape();
55            if expected != Some(shape) {
56                return Err(binding(
57                    role,
58                    format!("expected cell shape {expected:?}, got {shape:?}; selected source columns {:?}", self.bindings.grid.as_ref().map(|grid| &grid.origins)),
59                ));
60            }
61        }
62        Ok(())
63    }
64}
65impl<'source> PlotAdapter<'source, kind::Heatmap> {
66    /// Bind a numeric matrix with logical rows top-to-bottom and columns left-to-right.
67    pub fn new(grid: impl ColumnsInput) -> std::result::Result<Self, AdapterError> {
68        Self::grid_input(None, grid)
69    }
70    /// Select ordered source columns, or `..` for every column.
71    pub fn from_data(
72        source: impl ArraySource + 'source,
73        columns: impl ColumnsInput,
74    ) -> std::result::Result<Self, AdapterError> {
75        Self::grid_input(context(source)?, columns)
76    }
77    fn grid_input(source: Context<'source>, columns: impl ColumnsInput) -> BindingResult<Self> {
78        let capture = Capture::new(source.as_deref());
79        let ((rows, columns), origin) = capture.columns(columns)?;
80        let cells = rows
81            .checked_mul(columns.len())
82            .ok_or_else(|| binding("heatmap", "cell count exceeds usize"))?;
83        let xkeys = (0..columns.len())
84            .map(|index| format!("__lichtung_grid_x_{index}"))
85            .collect::<Vec<_>>();
86        let ykeys = (0..rows)
87            .map(|index| format!("__lichtung_grid_y_{index}"))
88            .collect::<Vec<_>>();
89        let mut xs = crate::snapshot::allocate(cells, "heatmap x")?;
90        let mut ys = crate::snapshot::allocate(cells, "heatmap y")?;
91        let mut fill = crate::snapshot::allocate(cells, "heatmap fill")?;
92        for (row, y) in ykeys.iter().enumerate() {
93            for (column, x) in xkeys.iter().enumerate() {
94                xs.push(x.as_str());
95                ys.push(y.as_str());
96                fill.push(columns[column].1[row]);
97            }
98        }
99        let width = columns.len();
100        let x = CategoryValues::new("Column", xs)?
101            .with_key_values(KeyValues::Raw(RawKeyValues::new(
102                "Column",
103                (0..rows).flat_map(|_| (0..width).map(|column| RawKey::Integer(column.into()))),
104            )?))?
105            .with_cycled_source(origin.clone().generated_grid_axis(1, width))?;
106        let y = CategoryValues::new("Row", ys)?
107            .with_key_values(KeyValues::Raw(RawKeyValues::new(
108                "Row",
109                (0..rows).flat_map(|row| std::iter::repeat_n(RawKey::Integer(row.into()), width)),
110            )?))?
111            .with_repeated_source(origin.clone().generated_grid_axis(0, rows), width)?;
112        let xlabels = origin.selected_names().map_or_else(
113            || {
114                columns
115                    .iter()
116                    .map(|(index, _)| crate::source::name(*index))
117                    .collect()
118            },
119            <[String]>::to_vec,
120        );
121        let plot = Plot::heatmap(
122            x,
123            y,
124            NumericValues::nullable("Value", fill).with_source(origin)?,
125        );
126        let reference = capture.reference();
127        let mut adapter = Self::bound(plot, source, Some(cells), reference);
128        adapter.bindings.grid = Some(Grid {
129            x: xkeys,
130            y: ykeys,
131            origins: columns.iter().map(|(index, _)| *index).collect(),
132        });
133        let grid = adapter.bindings.grid.as_ref().expect("actual grid");
134        let ylabels = (0..rows).map(|row| format!("Row {}", row + 1));
135        let mut labels = adapter.bindings.labels.clone();
136        for (index, (raw, display)) in grid.x.iter().zip(xlabels).enumerate() {
137            labels = labels.capture_grid_label(raw, 1, index, display);
138        }
139        for (index, (raw, display)) in grid.y.iter().zip(ylabels).enumerate() {
140            labels = labels.capture_grid_label(raw, 0, index, display);
141        }
142        adapter = adapter.labels(labels);
143        Ok(adapter)
144    }
145    fn axis_labels<I, S>(mut self, axis: &'static str, values: I) -> BindingResult<Self>
146    where
147        I: IntoIterator<Item = S>,
148        S: Into<String>,
149    {
150        let grid = self
151            .bindings
152            .grid
153            .as_ref()
154            .ok_or_else(|| binding(axis, "axis metadata requires a rectangular heatmap"))?;
155        let keys = if axis == "x labels" { &grid.x } else { &grid.y };
156        let mut aliases = crate::snapshot::allocate(keys.len(), axis)?;
157        for value in values {
158            if aliases.len() == keys.len() {
159                return Err(binding(axis, "more labels than grid positions"));
160            }
161            aliases.push(value.into());
162        }
163        length(axis, axis, keys.len(), aliases.len())?;
164        self.bindings.labels = self
165            .bindings
166            .labels
167            .grid_axis_labels(usize::from(axis == "x labels"), aliases);
168        self.plot = self.plot.labels(self.bindings.labels.clone());
169        Ok(self)
170    }
171    /// Assign literal column display labels without merging positional identities.
172    pub fn x_labels<I, S>(self, labels: I) -> std::result::Result<Self, AdapterError>
173    where
174        I: IntoIterator<Item = S>,
175        S: Into<String>,
176    {
177        self.axis_labels("x labels", labels)
178    }
179    /// Assign literal row display labels without changing source membership.
180    pub fn y_labels<I, S>(self, labels: I) -> std::result::Result<Self, AdapterError>
181    where
182        I: IntoIterator<Item = S>,
183        S: Into<String>,
184    {
185        self.axis_labels("y labels", labels)
186    }
187    /// Bind row display metadata from a categorical source column or direct vector.
188    pub fn row_labels(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError> {
189        let capture = self.capture();
190        let values = capture.bind(values, 1, |input, source| {
191            input.bind_category(source, "row labels")
192        })?;
193        let displays = values
194            .iter()
195            .enumerate()
196            .map(|(slot, value)| {
197                value
198                    .map(str::to_owned)
199                    .ok_or_else(|| binding("row labels", format!("missing label at slot {slot}")))
200            })
201            .collect::<BindingResult<Vec<_>>>()?;
202        self.bound_row_labels(values, displays)
203    }
204
205    /// Retain the captured row-label source and its exact host display projection.
206    #[doc(hidden)]
207    pub fn bound_row_labels(
208        mut self,
209        values: CategoryValues,
210        displays: Vec<String>,
211    ) -> BindingResult<Self> {
212        let grid =
213            self.bindings.grid.as_ref().ok_or_else(|| {
214                binding("row labels", "axis metadata requires a rectangular heatmap")
215            })?;
216        length("row labels", "grid rows", grid.rows(), values.len())?;
217        self.bindings.labels = self.bindings.labels.bind_grid_rows(values, displays)?;
218        self.plot = self.plot.labels(self.bindings.labels.clone());
219        Ok(self)
220    }
221    /// Bind Boolean records or a same-shape cell grid; true highlights, not masks.
222    pub fn highlight_cells(
223        mut self,
224        values: impl BooleanInput,
225    ) -> std::result::Result<Self, AdapterError> {
226        self.cell_shape(&values, "heatmap highlights")?;
227        let capture = self.capture();
228        let values = capture.bind(values, 1, |input, source| {
229            input.bind_boolean(source, "heatmap highlights")
230        })?;
231        self.aligned("heatmap highlights", values.name(), values.len())?;
232        self.plot = self.plot.highlight_cells(values);
233        Ok(self)
234    }
235}