lichtung-plot-ndarray 0.3.0

Direct scientific plotting from logical ndarray views and columns
Documentation
use super::{context, Context, PlotAdapter};
use crate::capture::Capture;
use crate::error::{binding, length, BindingResult};
use crate::{
    binding::{ArraySource, BooleanInput, CategoryInput, ColumnsInput},
    data::{KeyValues, RawKey, RawKeyValues},
    kind, AdapterError, CategoryValues, NumericValues, Plot,
};

#[derive(Clone)]
pub(super) struct Grid {
    x: Vec<String>,
    y: Vec<String>,
    origins: Vec<usize>,
}
impl Grid {
    pub(super) fn restore(
        source: &crate::data::DataSourceInfo,
        x: &CategoryValues,
        y: &CategoryValues,
    ) -> Self {
        Self {
            x: x.levels().to_vec(),
            y: y.levels().to_vec(),
            origins: source
                .selected_indices()
                .map_or_else(|| (0..x.levels().len()).collect(), <[usize]>::to_vec),
        }
    }
    pub(super) fn rows(&self) -> usize {
        self.y.len()
    }

    pub(super) fn columns(&self) -> usize {
        self.x.len()
    }
}
impl<K: kind::Marker> PlotAdapter<'_, K> {
    pub(super) fn cell_shape(
        &self,
        input: &impl crate::input::sealed::Sealed,
        role: &'static str,
    ) -> BindingResult<()> {
        let shape = if let Some(indices) = input.selected_columns() {
            let first = *indices
                .first()
                .ok_or_else(|| binding(role, "select at least one column"))?;
            let source = crate::source::lookup(self.source.as_deref(), first, role)?;
            Some((source.shape().0, indices.len()))
        } else {
            input.cell_shape()
        };
        if let Some(shape) = shape {
            let expected = self.bindings.cell_shape();
            if expected != Some(shape) {
                return Err(binding(
                    role,
                    format!("expected cell shape {expected:?}, got {shape:?}; selected source columns {:?}", self.bindings.grid.as_ref().map(|grid| &grid.origins)),
                ));
            }
        }
        Ok(())
    }
}
impl<'source> PlotAdapter<'source, kind::Heatmap> {
    /// Bind a numeric matrix with logical rows top-to-bottom and columns left-to-right.
    pub fn new(grid: impl ColumnsInput) -> std::result::Result<Self, AdapterError> {
        Self::grid_input(None, grid)
    }
    /// Select ordered source columns, or `..` for every column.
    pub fn from_data(
        source: impl ArraySource + 'source,
        columns: impl ColumnsInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::grid_input(context(source)?, columns)
    }
    fn grid_input(source: Context<'source>, columns: impl ColumnsInput) -> BindingResult<Self> {
        let capture = Capture::new(source.as_deref());
        let ((rows, columns), origin) = capture.columns(columns)?;
        let cells = rows
            .checked_mul(columns.len())
            .ok_or_else(|| binding("heatmap", "cell count exceeds usize"))?;
        let xkeys = (0..columns.len())
            .map(|index| format!("__lichtung_grid_x_{index}"))
            .collect::<Vec<_>>();
        let ykeys = (0..rows)
            .map(|index| format!("__lichtung_grid_y_{index}"))
            .collect::<Vec<_>>();
        let mut xs = crate::snapshot::allocate(cells, "heatmap x")?;
        let mut ys = crate::snapshot::allocate(cells, "heatmap y")?;
        let mut fill = crate::snapshot::allocate(cells, "heatmap fill")?;
        for (row, y) in ykeys.iter().enumerate() {
            for (column, x) in xkeys.iter().enumerate() {
                xs.push(x.as_str());
                ys.push(y.as_str());
                fill.push(columns[column].1[row]);
            }
        }
        let width = columns.len();
        let x = CategoryValues::new("Column", xs)?
            .with_key_values(KeyValues::Raw(RawKeyValues::new(
                "Column",
                (0..rows).flat_map(|_| (0..width).map(|column| RawKey::Integer(column.into()))),
            )?))?
            .with_cycled_source(origin.clone().generated_grid_axis(1, width))?;
        let y = CategoryValues::new("Row", ys)?
            .with_key_values(KeyValues::Raw(RawKeyValues::new(
                "Row",
                (0..rows).flat_map(|row| std::iter::repeat_n(RawKey::Integer(row.into()), width)),
            )?))?
            .with_repeated_source(origin.clone().generated_grid_axis(0, rows), width)?;
        let xlabels = origin.selected_names().map_or_else(
            || {
                columns
                    .iter()
                    .map(|(index, _)| crate::source::name(*index))
                    .collect()
            },
            <[String]>::to_vec,
        );
        let plot = Plot::heatmap(
            x,
            y,
            NumericValues::nullable("Value", fill).with_source(origin)?,
        );
        let reference = capture.reference();
        let mut adapter = Self::bound(plot, source, Some(cells), reference);
        adapter.bindings.grid = Some(Grid {
            x: xkeys,
            y: ykeys,
            origins: columns.iter().map(|(index, _)| *index).collect(),
        });
        let grid = adapter.bindings.grid.as_ref().expect("actual grid");
        let ylabels = (0..rows).map(|row| format!("Row {}", row + 1));
        let mut labels = adapter.bindings.labels.clone();
        for (index, (raw, display)) in grid.x.iter().zip(xlabels).enumerate() {
            labels = labels.capture_grid_label(raw, 1, index, display);
        }
        for (index, (raw, display)) in grid.y.iter().zip(ylabels).enumerate() {
            labels = labels.capture_grid_label(raw, 0, index, display);
        }
        adapter = adapter.labels(labels);
        Ok(adapter)
    }
    fn axis_labels<I, S>(mut self, axis: &'static str, values: I) -> BindingResult<Self>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let grid = self
            .bindings
            .grid
            .as_ref()
            .ok_or_else(|| binding(axis, "axis metadata requires a rectangular heatmap"))?;
        let keys = if axis == "x labels" { &grid.x } else { &grid.y };
        let mut aliases = crate::snapshot::allocate(keys.len(), axis)?;
        for value in values {
            if aliases.len() == keys.len() {
                return Err(binding(axis, "more labels than grid positions"));
            }
            aliases.push(value.into());
        }
        length(axis, axis, keys.len(), aliases.len())?;
        self.bindings.labels = self
            .bindings
            .labels
            .grid_axis_labels(usize::from(axis == "x labels"), aliases);
        self.plot = self.plot.labels(self.bindings.labels.clone());
        Ok(self)
    }
    /// Assign literal column display labels without merging positional identities.
    pub fn x_labels<I, S>(self, labels: I) -> std::result::Result<Self, AdapterError>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.axis_labels("x labels", labels)
    }
    /// Assign literal row display labels without changing source membership.
    pub fn y_labels<I, S>(self, labels: I) -> std::result::Result<Self, AdapterError>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.axis_labels("y labels", labels)
    }
    /// Bind row display metadata from a categorical source column or direct vector.
    pub fn row_labels(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError> {
        let capture = self.capture();
        let values = capture.bind(values, 1, |input, source| {
            input.bind_category(source, "row labels")
        })?;
        let displays = values
            .iter()
            .enumerate()
            .map(|(slot, value)| {
                value
                    .map(str::to_owned)
                    .ok_or_else(|| binding("row labels", format!("missing label at slot {slot}")))
            })
            .collect::<BindingResult<Vec<_>>>()?;
        self.bound_row_labels(values, displays)
    }

    /// Retain the captured row-label source and its exact host display projection.
    #[doc(hidden)]
    pub fn bound_row_labels(
        mut self,
        values: CategoryValues,
        displays: Vec<String>,
    ) -> BindingResult<Self> {
        let grid =
            self.bindings.grid.as_ref().ok_or_else(|| {
                binding("row labels", "axis metadata requires a rectangular heatmap")
            })?;
        length("row labels", "grid rows", grid.rows(), values.len())?;
        self.bindings.labels = self.bindings.labels.bind_grid_rows(values, displays)?;
        self.plot = self.plot.labels(self.bindings.labels.clone());
        Ok(self)
    }
    /// Bind Boolean records or a same-shape cell grid; true highlights, not masks.
    pub fn highlight_cells(
        mut self,
        values: impl BooleanInput,
    ) -> std::result::Result<Self, AdapterError> {
        self.cell_shape(&values, "heatmap highlights")?;
        let capture = self.capture();
        let values = capture.bind(values, 1, |input, source| {
            input.bind_boolean(source, "heatmap highlights")
        })?;
        self.aligned("heatmap highlights", values.name(), values.len())?;
        self.plot = self.plot.highlight_cells(values);
        Ok(self)
    }
}