Skip to main content

crisol_core/data/
dataset.rs

1//! A columnar, typed table.
2
3use std::collections::BTreeMap;
4use std::ops::Range;
5
6use super::column::{CellValue, Column, ColumnType, ColumnValues};
7use super::lineage::{Lineage, LineageStep};
8
9/// A typed table: columns of equal length with dataset metadata.
10#[derive(Clone, Debug, Default, PartialEq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12/// # Example
13///
14/// ```
15/// use crisol_core::data::Dataset;
16/// ```
17pub struct Dataset {
18    columns: Vec<Column>,
19    len: usize,
20    metadata: BTreeMap<String, String>,
21    #[cfg_attr(feature = "serde", serde(default))]
22    lineage: Lineage,
23}
24
25impl Dataset {
26    /// An empty dataset.
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    /// A dataset from columns. The longest column sets the row count; shorter columns
32    /// are treated as invalid at the end.
33    pub fn from_columns(columns: impl IntoIterator<Item = Column>) -> Self {
34        let columns: Vec<Column> = columns.into_iter().collect();
35        let len = columns.iter().map(Column::len).max().unwrap_or(0);
36        Self {
37            columns,
38            len,
39            metadata: BTreeMap::new(),
40            lineage: Lineage::new(),
41        }
42    }
43
44    /// A dataset with `rows` empty rows and no columns.
45    pub fn with_rows(rows: usize) -> Self {
46        Self {
47            len: rows,
48            ..Self::default()
49        }
50    }
51
52    /// Number of rows.
53    pub fn row_count(&self) -> usize {
54        self.len
55    }
56
57    /// Number of columns.
58    pub fn width(&self) -> usize {
59        self.columns.len()
60    }
61
62    /// Whether the dataset has no columns and no rows.
63    pub fn is_empty(&self) -> bool {
64        self.columns.is_empty() && self.len == 0
65    }
66
67    /// The columns.
68    pub fn columns(&self) -> &[Column] {
69        &self.columns
70    }
71
72    /// A column by index.
73    pub fn column(&self, index: usize) -> Option<&Column> {
74        self.columns.get(index)
75    }
76
77    /// A column by name.
78    pub fn column_named(&self, name: &str) -> Option<&Column> {
79        self.columns.iter().find(|column| column.name == name)
80    }
81
82    /// A column index by name.
83    pub fn index_of(&self, name: &str) -> Option<usize> {
84        self.columns.iter().position(|column| column.name == name)
85    }
86
87    /// The dataset metadata.
88    pub fn metadata(&self) -> &BTreeMap<String, String> {
89        &self.metadata
90    }
91
92    /// Add or replace metadata.
93    pub fn set_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
94        self.metadata.insert(key.into(), value.into());
95    }
96
97    /// The dataset lineage.
98    pub fn lineage(&self) -> &Lineage {
99        &self.lineage
100    }
101
102    /// Record one transformation.
103    pub fn record_lineage(&mut self, step: LineageStep) {
104        self.lineage.record(step);
105    }
106
107    /// Record a source and operation.
108    pub fn derived_from(&mut self, source: impl Into<String>, operation: impl Into<String>) {
109        self.lineage.record(LineageStep::new(source, operation));
110    }
111
112    /// Append a column, padding shorter existing columns with nulls.
113    pub fn push_column(&mut self, column: Column) {
114        self.len = self.len.max(column.len());
115        self.columns.push(column);
116    }
117
118    /// A cell by row and column.
119    pub fn cell(&self, row: usize, column: usize) -> CellValue<'_> {
120        self.columns
121            .get(column)
122            .map_or(CellValue::Null, |column| column.cell(row))
123    }
124
125    /// The row as owned values, for a query or a channel.
126    pub fn row(&self, row: usize) -> Vec<super::column::DataValue> {
127        self.columns
128            .iter()
129            .map(|column| column.cell(row).to_owned_value())
130            .collect()
131    }
132
133    /// A dataset of rows in `range`.
134    pub fn slice(&self, range: Range<usize>) -> Self {
135        let start = range.start.min(self.len);
136        let end = range.end.min(self.len).max(start);
137        let columns = self.columns.iter().map(|column| column.slice(start..end)).collect();
138        Self {
139            columns,
140            len: end - start,
141            metadata: self.metadata.clone(),
142            lineage: self.lineage.clone(),
143        }
144    }
145
146    /// Rows whose predicate returns true, in order.
147    pub fn matching_rows(&self, mut predicate: impl FnMut(usize, &Self) -> bool) -> Vec<usize> {
148        (0..self.len).filter(|row| predicate(*row, self)).collect()
149    }
150
151    /// A dataset with only `rows`, in the given order.
152    pub fn take(&self, rows: &[usize]) -> Self {
153        let columns = self
154            .columns
155            .iter()
156            .map(|column| {
157                let values: Vec<super::column::DataValue> =
158                    rows.iter().map(|row| column.cell(*row).to_owned_value()).collect();
159                column_from_values(
160                    &column.name,
161                    &column.values,
162                    &values,
163                    &column.metadata,
164                    column.unit.as_deref(),
165                )
166            })
167            .collect();
168        Self {
169            columns,
170            len: rows.len(),
171            metadata: self.metadata.clone(),
172            lineage: self.lineage.clone(),
173        }
174    }
175
176    /// Points from two numeric columns, skipping null or non-numeric rows.
177    pub fn xy_pairs(&self, x: &str, y: &str) -> Option<Vec<[f64; 2]>> {
178        let x = self.column_named(x)?;
179        let y = self.column_named(y)?;
180        let mut points = Vec::new();
181        for row in 0..self.len {
182            if let (Some(x), Some(y)) = (
183                super::column::DataValue::as_f64(&x.cell(row).to_owned_value()),
184                super::column::DataValue::as_f64(&y.cell(row).to_owned_value()),
185            ) && x.is_finite()
186                && y.is_finite()
187            {
188                points.push([x, y]);
189            }
190        }
191        Some(points)
192    }
193
194    /// One (x, y) point at `row`, when both values are finite numbers.
195    pub fn point_at_row(&self, x: &str, y: &str, row: usize) -> Option<[f64; 2]> {
196        let x = self.column_named(x)?;
197        let y = self.column_named(y)?;
198        let x = super::column::DataValue::as_f64(&x.cell(row).to_owned_value())?;
199        let y = super::column::DataValue::as_f64(&y.cell(row).to_owned_value())?;
200        (x.is_finite() && y.is_finite()).then_some([x, y])
201    }
202
203    /// Rows whose two numeric columns fall inside `bounds`.
204    pub fn rows_in_bounds(&self, x: &str, y: &str, bounds: super::bounds::Bounds) -> Vec<usize> {
205        (0..self.row_count())
206            .filter(|row| {
207                self.point_at_row(x, y, *row).is_some_and(|[x, y]| {
208                    x >= bounds.min_x && x <= bounds.max_x && y >= bounds.min_y && y <= bounds.max_y
209                })
210            })
211            .collect()
212    }
213
214    /// Statistics for one column: count, min, max, mean, and nulls.
215    pub fn stats(&self, column: usize) -> Option<ColumnStats> {
216        let column = self.columns.get(column)?;
217        let mut count = 0;
218        let mut nulls = 0;
219        let mut min = f64::INFINITY;
220        let mut max = f64::NEG_INFINITY;
221        let mut sum = 0.0;
222        for row in 0..self.len {
223            if let Some(value) = column.cell(row).to_owned_value().as_f64() {
224                count += 1;
225                sum += value;
226                min = min.min(value);
227                max = max.max(value);
228            } else if column.cell(row).is_null() {
229                nulls += 1;
230            }
231        }
232        Some(ColumnStats {
233            count,
234            nulls,
235            min: (count > 0).then_some(min),
236            max: (count > 0).then_some(max),
237            mean: (count > 0).then_some(sum / count as f64),
238        })
239    }
240}
241
242fn column_from_values(
243    name: &str,
244    template: &ColumnValues,
245    values: &[super::column::DataValue],
246    metadata: &BTreeMap<String, String>,
247    unit: Option<&str>,
248) -> Column {
249    let mut column = match template.kind() {
250        ColumnType::Float => Column::floats(
251            name,
252            values
253                .iter()
254                .map(|value| value.as_f64().unwrap_or(f64::NAN))
255                .collect::<Vec<_>>(),
256        ),
257        ColumnType::Int => Column::ints(
258            name,
259            values
260                .iter()
261                .map(|value| match value {
262                    super::column::DataValue::Int(value) => *value,
263                    super::column::DataValue::Float(value) => *value as i64,
264                    _ => 0,
265                })
266                .collect::<Vec<_>>(),
267        ),
268        ColumnType::Bool => Column::bools(
269            name,
270            values
271                .iter()
272                .map(|value| matches!(value, super::column::DataValue::Bool(true)))
273                .collect::<Vec<_>>(),
274        ),
275        ColumnType::Text | ColumnType::Category => {
276            let texts: Vec<String> = values
277                .iter()
278                .map(|value| value.as_text().unwrap_or_default().to_owned())
279                .collect();
280            if template.kind() == ColumnType::Category {
281                Column::categories(name, texts)
282            } else {
283                Column::text(name, texts)
284            }
285        }
286        ColumnType::Date => Column::dates(
287            name,
288            values
289                .iter()
290                .map(|value| {
291                    if let super::column::DataValue::Date(value) = value {
292                        *value
293                    } else {
294                        0
295                    }
296                })
297                .collect::<Vec<_>>(),
298        ),
299        ColumnType::Time => Column::times(
300            name,
301            values
302                .iter()
303                .map(|value| {
304                    if let super::column::DataValue::Time(value) = value {
305                        *value
306                    } else {
307                        0
308                    }
309                })
310                .collect::<Vec<_>>(),
311        ),
312    };
313    let validity: Vec<bool> = values
314        .iter()
315        .map(|value| !matches!(value, super::column::DataValue::Null))
316        .collect();
317    if validity.iter().any(|valid| !valid) {
318        column = column.with_validity(validity);
319    }
320    column.metadata = metadata.clone();
321    if let Some(unit) = unit {
322        column = column.with_unit(unit);
323    }
324    column
325}
326
327/// Summary statistics of one numeric column.
328#[derive(Clone, Copy, Debug, Default, PartialEq)]
329#[non_exhaustive]
330/// # Example
331///
332/// ```
333/// use crisol_core::data::ColumnStats;
334/// ```
335pub struct ColumnStats {
336    /// Non-null numeric values.
337    pub count: usize,
338    /// Null values.
339    pub nulls: usize,
340    /// Minimum, when there is a value.
341    pub min: Option<f64>,
342    /// Maximum, when there is a value.
343    pub max: Option<f64>,
344    /// Mean, when there is a value.
345    pub mean: Option<f64>,
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    fn dataset() -> Dataset {
353        Dataset::from_columns([
354            Column::floats("voltage", vec![0.1, 0.4, 0.2, 0.5]),
355            Column::ints("cycle", vec![1, 2, 3, 4]),
356            Column::text("name", ["a", "b", "c", "d"]),
357        ])
358    }
359
360    #[test]
361    fn columns_and_cells_are_typed() {
362        let data = dataset();
363        assert_eq!(data.row_count(), 4);
364        assert_eq!(data.width(), 3);
365        assert_eq!(data.cell(1, 0), CellValue::Float(0.4));
366        assert_eq!(data.cell(1, 1), CellValue::Int(2));
367        assert_eq!(data.index_of("name"), Some(2));
368        assert!(data.column_named("missing").is_none());
369    }
370
371    #[test]
372    fn lineage_survives_slices_and_take() {
373        let mut data = dataset();
374        data.derived_from("input.csv", "csv");
375        assert_eq!(data.lineage().sources(), ["input.csv"]);
376        assert_eq!(data.slice(0..1).lineage(), data.lineage());
377        assert_eq!(data.take(&[0]).lineage(), data.lineage());
378    }
379
380    #[test]
381    fn slices_and_take_keep_types_and_metadata() {
382        let mut data = dataset();
383        data.set_metadata("source", "test");
384        let slice = data.slice(1..3);
385        assert_eq!(slice.row_count(), 2);
386        assert_eq!(slice.cell(0, 0), CellValue::Float(0.4));
387        assert_eq!(slice.metadata().get("source").map(String::as_str), Some("test"));
388        let taken = data.take(&[3, 1]);
389        assert_eq!(taken.row_count(), 2);
390        assert_eq!(taken.cell(0, 1), CellValue::Int(4));
391        assert_eq!(taken.cell(1, 2), CellValue::Text("b"));
392    }
393
394    #[test]
395    fn statistics_ignore_nulls() {
396        let data =
397            Dataset::from_columns([Column::floats("v", vec![1.0, f64::NAN, 3.0]).with_validity([true, false, true])]);
398        let stats = data.stats(0).expect("stats");
399        assert_eq!(stats.count, 2);
400        assert_eq!(stats.nulls, 1);
401        assert_eq!(stats.min, Some(1.0));
402        assert_eq!(stats.max, Some(3.0));
403        assert_eq!(stats.mean, Some(2.0));
404    }
405}