lichtung_plot_ndarray/frontend/
grid.rs1use super::{context, Context, PlotAdapter};
2use crate::error::{binding, length, BindingResult};
3use crate::{
4 kind, AdapterError, ArraySource, BooleanInput, CategoryInput, CategoryValues, ColumnsInput,
5 NumericValues, Plot,
6};
7
8#[derive(Clone)]
9pub(super) struct Grid {
10 x: Vec<String>,
11 y: Vec<String>,
12 origins: Vec<usize>,
13}
14impl Grid {
15 pub(super) fn columns(&self) -> usize {
16 self.x.len()
17 }
18}
19impl<K: kind::Marker> PlotAdapter<'_, K> {
20 pub(super) fn cell_shape(
21 &self,
22 input: &impl crate::input::sealed::Sealed,
23 role: &'static str,
24 ) -> BindingResult<()> {
25 let shape = if let Some(indices) = input.selected_columns() {
26 let first = *indices
27 .first()
28 .ok_or_else(|| binding(role, "select at least one column"))?;
29 let source = crate::source::lookup(self.source.as_deref(), first, role)?;
30 Some((source.shape().0, indices.len()))
31 } else {
32 input.cell_shape()
33 };
34 if let Some(shape) = shape {
35 let expected = self
36 .bindings
37 .grid
38 .as_ref()
39 .map(|grid| (grid.y.len(), grid.x.len()))
40 .or_else(|| {
41 self.bindings
42 .expansion
43 .as_ref()
44 .map(|wide| (wide.rows, wide.keys.len()))
45 });
46 if expected != Some(shape) {
47 return Err(binding(
48 role,
49 format!("expected cell shape {expected:?}, got {shape:?}; selected source columns {:?}", self.bindings.grid.as_ref().map(|grid| &grid.origins)),
50 ));
51 }
52 }
53 Ok(())
54 }
55}
56impl<'source> PlotAdapter<'source, kind::Heatmap> {
57 pub fn new(grid: impl ColumnsInput) -> std::result::Result<Self, AdapterError> {
59 Self::grid_input(None, grid)
60 }
61 pub fn from_data(
63 source: impl ArraySource + 'source,
64 columns: impl ColumnsInput,
65 ) -> std::result::Result<Self, AdapterError> {
66 Self::grid_input(context(source)?, columns)
67 }
68 fn grid_input(source: Context<'source>, columns: impl ColumnsInput) -> BindingResult<Self> {
69 let (rows, columns) = columns.bind_columns(source.as_deref())?;
70 let cells = rows
71 .checked_mul(columns.len())
72 .ok_or_else(|| binding("heatmap", "cell count exceeds usize"))?;
73 let xkeys = (0..columns.len())
74 .map(|index| format!("__lichtung_grid_x_{index}"))
75 .collect::<Vec<_>>();
76 let ykeys = (0..rows)
77 .map(|index| format!("__lichtung_grid_y_{index}"))
78 .collect::<Vec<_>>();
79 let mut xs = crate::snapshot::allocate(cells, "heatmap x")?;
80 let mut ys = crate::snapshot::allocate(cells, "heatmap y")?;
81 let mut fill = crate::snapshot::allocate(cells, "heatmap fill")?;
82 for (row, y) in ykeys.iter().enumerate() {
83 for (column, x) in xkeys.iter().enumerate() {
84 xs.push(x.as_str());
85 ys.push(y.as_str());
86 fill.push(columns[column].1[row]);
87 }
88 }
89 let plot = Plot::heatmap(
90 CategoryValues::new("Column", xs)?,
91 CategoryValues::new("Row", ys)?,
92 NumericValues::nullable("Value", fill),
93 );
94 let mut adapter = Self::bound(plot, source, Some(cells));
95 adapter.bindings.grid = Some(Grid {
96 x: xkeys,
97 y: ykeys,
98 origins: columns.iter().map(|(index, _)| *index).collect(),
99 });
100 adapter
101 .x_labels(columns.iter().map(|(index, _)| crate::source::name(*index)))?
102 .y_labels((0..rows).map(|row| format!("Row {}", row + 1)))
103 }
104 fn axis_labels<I, S>(mut self, axis: &'static str, values: I) -> BindingResult<Self>
105 where
106 I: IntoIterator<Item = S>,
107 S: Into<String>,
108 {
109 let grid = self
110 .bindings
111 .grid
112 .as_ref()
113 .ok_or_else(|| binding(axis, "axis metadata requires a rectangular heatmap"))?;
114 let keys = if axis == "x labels" { &grid.x } else { &grid.y };
115 let mut aliases = crate::snapshot::allocate(keys.len(), axis)?;
116 for value in values {
117 if aliases.len() == keys.len() {
118 return Err(binding(axis, "more labels than grid positions"));
119 }
120 aliases.push(value.into());
121 }
122 length(axis, axis, keys.len(), aliases.len())?;
123 self.bindings.labels = self
124 .bindings
125 .labels
126 .aliases(keys.iter().cloned().zip(aliases));
127 self.plot = self.plot.labels(self.bindings.labels.clone());
128 Ok(self)
129 }
130 pub fn x_labels<I, S>(self, labels: I) -> std::result::Result<Self, AdapterError>
132 where
133 I: IntoIterator<Item = S>,
134 S: Into<String>,
135 {
136 self.axis_labels("x labels", labels)
137 }
138 pub fn y_labels<I, S>(self, labels: I) -> std::result::Result<Self, AdapterError>
140 where
141 I: IntoIterator<Item = S>,
142 S: Into<String>,
143 {
144 self.axis_labels("y labels", labels)
145 }
146 pub fn row_labels(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError> {
148 let (_, values) = values.raw_category(self.source.as_deref(), "row labels")?;
149 let values = values
150 .into_iter()
151 .enumerate()
152 .map(|(slot, value)| {
153 value.ok_or_else(|| binding("row labels", format!("missing label at slot {slot}")))
154 })
155 .collect::<BindingResult<Vec<_>>>()?;
156 self.y_labels(values)
157 }
158 pub fn heatmap_highlight(
160 mut self,
161 values: impl BooleanInput,
162 ) -> std::result::Result<Self, AdapterError> {
163 self.cell_shape(&values, "heatmap highlights")?;
164 let values = values.bind_boolean(self.source.as_deref(), "heatmap highlights")?;
165 self.aligned("heatmap highlights", values.name(), values.len())?;
166 self.plot = self.plot.heatmap_highlight(values);
167 Ok(self)
168 }
169 pub fn heatmap_highlight_cells(
171 self,
172 values: impl BooleanInput,
173 ) -> std::result::Result<Self, AdapterError> {
174 self.heatmap_highlight(values)
175 }
176}