crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Polars DataFrame backend, validated by the conformance suite.
//!
//! ```
//! use crisol_core::data::polars::PolarsSource;
//! # let _ = PolarsSource::new;
//! ```

use std::ops::Range;

use polars_core::prelude::{AnyValue, DataFrame, DataType, Series};

use super::column::{Column, ColumnType};
use super::dataset::Dataset;
use super::source::{ColumnSchema, DataError, DataSource};

/// A paged [`DataSource`] over an in-memory Polars DataFrame.
///
/// # Example
///
/// ```
/// use crisol_core::data::DataSource;
/// use crisol_core::data::polars::PolarsSource;
/// use polars_core::prelude::DataFrame;
///
/// let source = PolarsSource::new(DataFrame::empty()).expect("empty frame");
/// assert_eq!(source.row_count(), 0);
/// ```
#[derive(Clone, Debug)]
pub struct PolarsSource {
    frame: DataFrame,
    schema: Vec<ColumnSchema>,
}

impl PolarsSource {
    /// A source over `frame`.
    ///
    /// # Errors
    /// When a column has a type the Crisol data model cannot represent.
    pub fn new(frame: DataFrame) -> Result<Self, DataError> {
        let schema = frame
            .columns()
            .iter()
            .map(|series| {
                let kind = match series.dtype() {
                    DataType::Float64 | DataType::Float32 => ColumnType::Float,
                    DataType::Int64 | DataType::Int32 | DataType::UInt32 | DataType::UInt64 => ColumnType::Int,
                    DataType::String => ColumnType::Text,
                    DataType::Boolean => ColumnType::Bool,
                    other => {
                        return Err(DataError::Unsupported(format!(
                            "Polars column {} has unsupported dtype {other:?}",
                            series.name()
                        )));
                    }
                };
                Ok(ColumnSchema::new(series.name().as_str(), kind))
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self { frame, schema })
    }

    /// The backing frame.
    pub fn frame(&self) -> &DataFrame {
        &self.frame
    }

    /// The frame converted to one in-memory dataset.
    ///
    /// # Errors
    /// When a cell has an unsupported Polars value.
    pub fn to_dataset(&self) -> Result<Dataset, DataError> {
        let page = self.read_range(0..self.row_count())?;
        Ok(Dataset::from_columns(page.columns().iter().cloned()))
    }
}

impl DataSource for PolarsSource {
    fn schema(&self) -> &[ColumnSchema] {
        &self.schema
    }

    fn row_count(&self) -> usize {
        self.frame.height()
    }

    fn read_range(&self, range: Range<usize>) -> Result<Dataset, DataError> {
        if range.end > self.row_count() || range.start > range.end {
            return Err(DataError::OutOfRange {
                start: range.start,
                end: range.end,
                rows: self.row_count(),
            });
        }
        let length = range.end - range.start;
        let frame = self.frame.slice(range.start as i64, length);
        let columns = frame
            .columns()
            .iter()
            .map(|polars_column| column(polars_column.as_materialized_series()))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Dataset::from_columns(columns))
    }
}

fn column(series: &Series) -> Result<Column, DataError> {
    let name = series.name().as_str();
    let values: Vec<AnyValue<'_>> = (0..series.len())
        .map(|index| {
            series
                .get(index)
                .map_err(|error| DataError::Connector(error.to_string()))
        })
        .collect::<Result<_, _>>()?;
    let validity = values.iter().map(|value| !matches!(value, AnyValue::Null));
    match series.dtype() {
        DataType::Float64 | DataType::Float32 => {
            let numbers = values
                .iter()
                .map(|value| match value {
                    AnyValue::Float64(value) => *value,
                    AnyValue::Float32(value) => f64::from(*value),
                    AnyValue::Null => 0.0,
                    _ => 0.0,
                })
                .collect::<Vec<_>>();
            Ok(Column::floats(name, numbers).with_validity(validity))
        }
        DataType::Int64 | DataType::Int32 | DataType::UInt32 | DataType::UInt64 => {
            let numbers = values
                .iter()
                .map(|value| match value {
                    AnyValue::Int64(value) => *value,
                    AnyValue::Int32(value) => i64::from(*value),
                    AnyValue::UInt32(value) => i64::from(*value),
                    AnyValue::UInt64(value) => i64::try_from(*value).unwrap_or(i64::MAX),
                    AnyValue::Null => 0,
                    _ => 0,
                })
                .collect::<Vec<_>>();
            Ok(Column::ints(name, numbers).with_validity(validity))
        }
        DataType::String => {
            let strings = values
                .iter()
                .map(|value| match value {
                    AnyValue::String(value) => (*value).to_owned(),
                    AnyValue::StringOwned(value) => value.to_string(),
                    _ => String::new(),
                })
                .collect::<Vec<_>>();
            Ok(Column::text(name, strings).with_validity(validity))
        }
        DataType::Boolean => {
            let booleans = values
                .iter()
                .map(|value| matches!(value, AnyValue::Boolean(true)))
                .collect::<Vec<_>>();
            Ok(Column::bools(name, booleans).with_validity(validity))
        }
        other => Err(DataError::Unsupported(format!(
            "Polars column {name} has unsupported dtype {other:?}"
        ))),
    }
}

/// The conformance fixture as a Polars frame.
pub(crate) fn conformance_fixture() -> PolarsSource {
    let fallback = || PolarsSource {
        frame: DataFrame::empty(),
        schema: Vec::new(),
    };
    let x = Series::from_any_values(
        "x".into(),
        &[AnyValue::Float64(1.0), AnyValue::Null, AnyValue::Float64(3.0)],
        true,
    )
    .unwrap_or_else(|_| Series::new_empty("x".into(), &DataType::Float64));
    let n = Series::from_any_values(
        "n".into(),
        &[AnyValue::Int64(1), AnyValue::Int64(2), AnyValue::Int64(3)],
        true,
    )
    .unwrap_or_else(|_| Series::new_empty("n".into(), &DataType::Int64));
    let label = Series::from_any_values(
        "label".into(),
        &[AnyValue::String("a"), AnyValue::String("b"), AnyValue::String("c")],
        true,
    )
    .unwrap_or_else(|_| Series::new_empty("label".into(), &DataType::String));
    let frame = DataFrame::new(3, vec![x.into(), n.into(), label.into()]).unwrap_or_else(|_| DataFrame::empty());
    PolarsSource::new(frame).unwrap_or_else(|_| fallback())
}

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

    #[test]
    fn a_polars_frame_conforms() {
        let source = conformance_fixture();
        assert_eq!(source.row_count(), 3);
        assert_eq!(source.schema()[0].name, "x");
    }

    #[test]
    fn nulls_and_types_survive_a_page() {
        let source = conformance_fixture();
        let page = source.read_range(0..2).expect("page");
        assert_eq!(page.cell(1, 0), CellValue::Null);
        assert_eq!(page.cell(0, 1), CellValue::Int(1));
        assert_eq!(page.cell(1, 2), CellValue::Text("b"));
    }

    #[test]
    fn an_out_of_range_page_is_rejected() {
        let source = conformance_fixture();
        assert!(matches!(source.read_range(2..9), Err(DataError::OutOfRange { .. })));
    }
}