crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Joins, window functions, and the pushdown planner.

use std::collections::HashMap;

use super::column::{CellValue, Column};
use super::dataset::Dataset;
use super::query::Query;
use super::source::DataError;

/// How a join treats rows without a match.
///
/// # Example
///
/// ```
/// use crisol_core::data::JoinKind;
///
/// assert_eq!(JoinKind::default(), JoinKind::Inner);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum JoinKind {
    /// Keep only matching pairs.
    #[default]
    Inner,
    /// Keep every left row, with nulls on the right when unmatched.
    Left,
}

/// Join two datasets on two columns. Right columns that collide with a left name get a
/// `_right` suffix.
///
/// # Example
///
/// ```
/// use crisol_core::data::{Column, Dataset, JoinKind, join};
///
/// let left = Dataset::from_columns([Column::ints("id", vec![1])]);
/// let right = Dataset::from_columns([Column::ints("id", vec![1])]);
/// let joined = join(&left, &right, "id", "id", JoinKind::Inner).expect("join");
/// assert_eq!(joined.row_count(), 1);
/// ```
pub fn join(
    left: &Dataset,
    right: &Dataset,
    on_left: &str,
    on_right: &str,
    kind: JoinKind,
) -> Result<Dataset, DataError> {
    let left_key = left
        .column_named(on_left)
        .ok_or_else(|| DataError::Unsupported(format!("missing join column `{on_left}`")))?;
    let right_key = right
        .column_named(on_right)
        .ok_or_else(|| DataError::Unsupported(format!("missing join column `{on_right}`")))?;
    let mut index: HashMap<String, Vec<usize>> = HashMap::new();
    for row in 0..right.row_count() {
        let key = right_key.cell(row);
        if key.is_null() {
            continue;
        }
        index.entry(key.to_text()).or_default().push(row);
    }
    let mut left_rows = Vec::new();
    let mut right_rows = Vec::new();
    for row in 0..left.row_count() {
        let key = left_key.cell(row);
        if key.is_null() {
            if kind == JoinKind::Left {
                left_rows.push(row);
                right_rows.push(usize::MAX);
            }
            continue;
        }
        match index.get(&key.to_text()) {
            Some(matches) => {
                for match_row in matches {
                    left_rows.push(row);
                    right_rows.push(*match_row);
                }
            }
            None if kind == JoinKind::Left => {
                left_rows.push(row);
                right_rows.push(usize::MAX);
            }
            None => {}
        }
    }
    let mut joined = left.take(&left_rows);
    let right_taken = right.take(&right_rows);
    for column in right_taken.columns() {
        let mut column = column.clone();
        if joined.column_named(&column.name).is_some() {
            column.name = format!("{}_right", column.name);
        }
        joined.push_column(column);
    }
    Ok(joined)
}

/// A computed column over one value series.
///
/// # Example
///
/// ```
/// use crisol_core::data::WindowFunction;
///
/// assert_eq!(WindowFunction::RowNumber, WindowFunction::RowNumber);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WindowFunction {
    /// 1-based position in the series.
    RowNumber,
    /// Competition rank: ties share a rank.
    Rank,
    /// The value `n` rows earlier, or NaN at the start.
    Lag(usize),
    /// The value `n` rows later, or NaN at the end.
    Lead(usize),
    /// Centered mean over `n` rows.
    RollingMean(usize),
}

/// Compute a window function over `values`.
///
/// # Example
///
/// ```
/// use crisol_core::data::{WindowFunction, window};
///
/// assert_eq!(window(&[4.0, 5.0], WindowFunction::RowNumber), [1.0, 2.0]);
/// ```
pub fn window(values: &[f64], function: WindowFunction) -> Vec<f64> {
    match function {
        WindowFunction::RowNumber => (1..=values.len()).map(|index| index as f64).collect(),
        WindowFunction::Rank => values
            .iter()
            .map(|value| values.iter().filter(|other| *other < value).count() as f64 + 1.0)
            .collect(),
        WindowFunction::Lag(distance) => (0..values.len())
            .map(|index| {
                index
                    .checked_sub(distance)
                    .and_then(|index| values.get(index))
                    .copied()
                    .unwrap_or(f64::NAN)
            })
            .collect(),
        WindowFunction::Lead(distance) => (0..values.len())
            .map(|index| values.get(index + distance).copied().unwrap_or(f64::NAN))
            .collect(),
        WindowFunction::RollingMean(width) => {
            let width = width.max(1);
            let half = width / 2;
            (0..values.len())
                .map(|index| {
                    let start = index.saturating_sub(half);
                    let end = (index + width - half).min(values.len());
                    let slice = values.get(start..end).unwrap_or_default();
                    if slice.is_empty() {
                        f64::NAN
                    } else {
                        slice.iter().sum::<f64>() / slice.len() as f64
                    }
                })
                .collect()
        }
    }
}

/// A window result as a column.
///
/// # Example
///
/// ```
/// use crisol_core::data::{Column, Dataset, WindowFunction, window_column};
///
/// let data = Dataset::from_columns([Column::floats("v", vec![1.0, 2.0])]);
/// assert!(window_column(&data, "v", WindowFunction::RowNumber).is_ok());
/// ```
/// # Errors
/// When the source column is missing.
pub fn window_column(data: &Dataset, column: &str, function: WindowFunction) -> Result<Column, DataError> {
    let source = data
        .column_named(column)
        .ok_or_else(|| DataError::Unsupported(format!("missing window column `{column}`")))?;
    let values: Vec<f64> = (0..data.row_count())
        .map(|row| match source.cell(row) {
            CellValue::Float(value) => value,
            CellValue::Int(value) => value as f64,
            _ => f64::NAN,
        })
        .collect();
    Ok(Column::floats(format!("{column}_window"), window(&values, function)))
}

/// A filter expression plus the columns a backend should read for it.
///
/// # Example
///
/// ```
/// use crisol_core::data::QueryPlan;
///
/// # use crisol_core::data::{Dataset, Query, plan};
/// let plan = plan(&Query::parse("x > 1").expect("query"), &Dataset::new());
/// assert_eq!(plan.columns, ["x"]);
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryPlan {
    /// Columns referenced by the filter.
    pub columns: Vec<String>,
    /// Rows that pass the filter.
    pub rows: Vec<usize>,
}

/// Build a pushdown plan: the backend reads only `columns`, then applies the filter.
///
/// # Example
///
/// ```
/// use crisol_core::data::{Dataset, Query, plan};
///
/// let data = Dataset::new();
/// let query = Query::parse("x > 1").expect("query");
/// assert_eq!(plan(&query, &data).columns, ["x"]);
/// ```
pub fn plan(query: &Query, data: &Dataset) -> QueryPlan {
    QueryPlan {
        columns: query.columns(),
        rows: query.matching_rows(data),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn left() -> Dataset {
        Dataset::from_columns([Column::ints("id", vec![1, 2, 3]), Column::text("name", ["a", "b", "c"])])
    }

    fn right() -> Dataset {
        Dataset::from_columns([
            Column::ints("id", vec![1, 1, 3]),
            Column::ints("value", vec![10, 11, 30]),
        ])
    }

    #[test]
    fn an_inner_join_repeats_matching_left_rows() {
        let joined = join(&left(), &right(), "id", "id", JoinKind::Inner).expect("join");
        assert_eq!(joined.row_count(), 3);
        assert_eq!(joined.cell(0, 3), CellValue::Int(10));
        assert_eq!(joined.cell(1, 3), CellValue::Int(11));
        assert_eq!(joined.cell(2, 3), CellValue::Int(30));
    }

    #[test]
    fn a_left_join_keeps_unmatched_rows() {
        let joined = join(&left(), &right(), "id", "id", JoinKind::Left).expect("join");
        assert_eq!(joined.row_count(), 4);
        assert_eq!(joined.cell(2, 3), CellValue::Null);
    }

    #[test]
    fn windows_compute_ranks_lags_and_means() {
        let values = [1.0, 3.0, 3.0, 5.0];
        assert_eq!(window(&values, WindowFunction::RowNumber), [1.0, 2.0, 3.0, 4.0]);
        assert_eq!(window(&values, WindowFunction::Rank), [1.0, 2.0, 2.0, 4.0]);
        assert!(window(&values, WindowFunction::Lag(1))[0].is_nan());
        assert_eq!(window(&values, WindowFunction::Lag(1))[1], 1.0);
        assert_eq!(window(&values, WindowFunction::RollingMean(3))[0], 2.0);
    }

    #[test]
    fn a_plan_lists_the_filter_columns_and_rows() {
        let query = Query::parse("id > 1 && name == \"b\"").expect("query");
        let plan = plan(&query, &left());
        assert_eq!(plan.columns, ["id", "name"]);
        assert_eq!(plan.rows, [1]);
    }
}