crisol_core/data/
polars.rs1use std::ops::Range;
9
10use polars_core::prelude::{AnyValue, DataFrame, DataType, Series};
11
12use super::column::{Column, ColumnType};
13use super::dataset::Dataset;
14use super::source::{ColumnSchema, DataError, DataSource};
15
16#[derive(Clone, Debug)]
29pub struct PolarsSource {
30 frame: DataFrame,
31 schema: Vec<ColumnSchema>,
32}
33
34impl PolarsSource {
35 pub fn new(frame: DataFrame) -> Result<Self, DataError> {
40 let schema = frame
41 .columns()
42 .iter()
43 .map(|series| {
44 let kind = match series.dtype() {
45 DataType::Float64 | DataType::Float32 => ColumnType::Float,
46 DataType::Int64 | DataType::Int32 | DataType::UInt32 | DataType::UInt64 => ColumnType::Int,
47 DataType::String => ColumnType::Text,
48 DataType::Boolean => ColumnType::Bool,
49 other => {
50 return Err(DataError::Unsupported(format!(
51 "Polars column {} has unsupported dtype {other:?}",
52 series.name()
53 )));
54 }
55 };
56 Ok(ColumnSchema::new(series.name().as_str(), kind))
57 })
58 .collect::<Result<Vec<_>, _>>()?;
59 Ok(Self { frame, schema })
60 }
61
62 pub fn frame(&self) -> &DataFrame {
64 &self.frame
65 }
66
67 pub fn to_dataset(&self) -> Result<Dataset, DataError> {
72 let page = self.read_range(0..self.row_count())?;
73 Ok(Dataset::from_columns(page.columns().iter().cloned()))
74 }
75}
76
77impl DataSource for PolarsSource {
78 fn schema(&self) -> &[ColumnSchema] {
79 &self.schema
80 }
81
82 fn row_count(&self) -> usize {
83 self.frame.height()
84 }
85
86 fn read_range(&self, range: Range<usize>) -> Result<Dataset, DataError> {
87 if range.end > self.row_count() || range.start > range.end {
88 return Err(DataError::OutOfRange {
89 start: range.start,
90 end: range.end,
91 rows: self.row_count(),
92 });
93 }
94 let length = range.end - range.start;
95 let frame = self.frame.slice(range.start as i64, length);
96 let columns = frame
97 .columns()
98 .iter()
99 .map(|polars_column| column(polars_column.as_materialized_series()))
100 .collect::<Result<Vec<_>, _>>()?;
101 Ok(Dataset::from_columns(columns))
102 }
103}
104
105fn column(series: &Series) -> Result<Column, DataError> {
106 let name = series.name().as_str();
107 let values: Vec<AnyValue<'_>> = (0..series.len())
108 .map(|index| {
109 series
110 .get(index)
111 .map_err(|error| DataError::Connector(error.to_string()))
112 })
113 .collect::<Result<_, _>>()?;
114 let validity = values.iter().map(|value| !matches!(value, AnyValue::Null));
115 match series.dtype() {
116 DataType::Float64 | DataType::Float32 => {
117 let numbers = values
118 .iter()
119 .map(|value| match value {
120 AnyValue::Float64(value) => *value,
121 AnyValue::Float32(value) => f64::from(*value),
122 AnyValue::Null => 0.0,
123 _ => 0.0,
124 })
125 .collect::<Vec<_>>();
126 Ok(Column::floats(name, numbers).with_validity(validity))
127 }
128 DataType::Int64 | DataType::Int32 | DataType::UInt32 | DataType::UInt64 => {
129 let numbers = values
130 .iter()
131 .map(|value| match value {
132 AnyValue::Int64(value) => *value,
133 AnyValue::Int32(value) => i64::from(*value),
134 AnyValue::UInt32(value) => i64::from(*value),
135 AnyValue::UInt64(value) => i64::try_from(*value).unwrap_or(i64::MAX),
136 AnyValue::Null => 0,
137 _ => 0,
138 })
139 .collect::<Vec<_>>();
140 Ok(Column::ints(name, numbers).with_validity(validity))
141 }
142 DataType::String => {
143 let strings = values
144 .iter()
145 .map(|value| match value {
146 AnyValue::String(value) => (*value).to_owned(),
147 AnyValue::StringOwned(value) => value.to_string(),
148 _ => String::new(),
149 })
150 .collect::<Vec<_>>();
151 Ok(Column::text(name, strings).with_validity(validity))
152 }
153 DataType::Boolean => {
154 let booleans = values
155 .iter()
156 .map(|value| matches!(value, AnyValue::Boolean(true)))
157 .collect::<Vec<_>>();
158 Ok(Column::bools(name, booleans).with_validity(validity))
159 }
160 other => Err(DataError::Unsupported(format!(
161 "Polars column {name} has unsupported dtype {other:?}"
162 ))),
163 }
164}
165
166pub(crate) fn conformance_fixture() -> PolarsSource {
168 let fallback = || PolarsSource {
169 frame: DataFrame::empty(),
170 schema: Vec::new(),
171 };
172 let x = Series::from_any_values(
173 "x".into(),
174 &[AnyValue::Float64(1.0), AnyValue::Null, AnyValue::Float64(3.0)],
175 true,
176 )
177 .unwrap_or_else(|_| Series::new_empty("x".into(), &DataType::Float64));
178 let n = Series::from_any_values(
179 "n".into(),
180 &[AnyValue::Int64(1), AnyValue::Int64(2), AnyValue::Int64(3)],
181 true,
182 )
183 .unwrap_or_else(|_| Series::new_empty("n".into(), &DataType::Int64));
184 let label = Series::from_any_values(
185 "label".into(),
186 &[AnyValue::String("a"), AnyValue::String("b"), AnyValue::String("c")],
187 true,
188 )
189 .unwrap_or_else(|_| Series::new_empty("label".into(), &DataType::String));
190 let frame = DataFrame::new(3, vec![x.into(), n.into(), label.into()]).unwrap_or_else(|_| DataFrame::empty());
191 PolarsSource::new(frame).unwrap_or_else(|_| fallback())
192}
193
194#[cfg(test)]
195mod tests {
196 use super::super::column::CellValue;
197 use super::*;
198
199 #[test]
200 fn a_polars_frame_conforms() {
201 let source = conformance_fixture();
202 assert_eq!(source.row_count(), 3);
203 assert_eq!(source.schema()[0].name, "x");
204 }
205
206 #[test]
207 fn nulls_and_types_survive_a_page() {
208 let source = conformance_fixture();
209 let page = source.read_range(0..2).expect("page");
210 assert_eq!(page.cell(1, 0), CellValue::Null);
211 assert_eq!(page.cell(0, 1), CellValue::Int(1));
212 assert_eq!(page.cell(1, 2), CellValue::Text("b"));
213 }
214
215 #[test]
216 fn an_out_of_range_page_is_rejected() {
217 let source = conformance_fixture();
218 assert!(matches!(source.read_range(2..9), Err(DataError::OutOfRange { .. })));
219 }
220}