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