crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! A columnar, typed table.

use std::collections::BTreeMap;
use std::ops::Range;

use super::column::{CellValue, Column, ColumnType, ColumnValues};
use super::lineage::{Lineage, LineageStep};

/// A typed table: columns of equal length with dataset metadata.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// # Example
///
/// ```
/// use crisol_core::data::Dataset;
/// ```
pub struct Dataset {
    columns: Vec<Column>,
    len: usize,
    metadata: BTreeMap<String, String>,
    #[cfg_attr(feature = "serde", serde(default))]
    lineage: Lineage,
}

impl Dataset {
    /// An empty dataset.
    pub fn new() -> Self {
        Self::default()
    }

    /// A dataset from columns. The longest column sets the row count; shorter columns
    /// are treated as invalid at the end.
    pub fn from_columns(columns: impl IntoIterator<Item = Column>) -> Self {
        let columns: Vec<Column> = columns.into_iter().collect();
        let len = columns.iter().map(Column::len).max().unwrap_or(0);
        Self {
            columns,
            len,
            metadata: BTreeMap::new(),
            lineage: Lineage::new(),
        }
    }

    /// A dataset with `rows` empty rows and no columns.
    pub fn with_rows(rows: usize) -> Self {
        Self {
            len: rows,
            ..Self::default()
        }
    }

    /// Number of rows.
    pub fn row_count(&self) -> usize {
        self.len
    }

    /// Number of columns.
    pub fn width(&self) -> usize {
        self.columns.len()
    }

    /// Whether the dataset has no columns and no rows.
    pub fn is_empty(&self) -> bool {
        self.columns.is_empty() && self.len == 0
    }

    /// The columns.
    pub fn columns(&self) -> &[Column] {
        &self.columns
    }

    /// A column by index.
    pub fn column(&self, index: usize) -> Option<&Column> {
        self.columns.get(index)
    }

    /// A column by name.
    pub fn column_named(&self, name: &str) -> Option<&Column> {
        self.columns.iter().find(|column| column.name == name)
    }

    /// A column index by name.
    pub fn index_of(&self, name: &str) -> Option<usize> {
        self.columns.iter().position(|column| column.name == name)
    }

    /// The dataset metadata.
    pub fn metadata(&self) -> &BTreeMap<String, String> {
        &self.metadata
    }

    /// Add or replace metadata.
    pub fn set_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.metadata.insert(key.into(), value.into());
    }

    /// The dataset lineage.
    pub fn lineage(&self) -> &Lineage {
        &self.lineage
    }

    /// Record one transformation.
    pub fn record_lineage(&mut self, step: LineageStep) {
        self.lineage.record(step);
    }

    /// Record a source and operation.
    pub fn derived_from(&mut self, source: impl Into<String>, operation: impl Into<String>) {
        self.lineage.record(LineageStep::new(source, operation));
    }

    /// Append a column, padding shorter existing columns with nulls.
    pub fn push_column(&mut self, column: Column) {
        self.len = self.len.max(column.len());
        self.columns.push(column);
    }

    /// A cell by row and column.
    pub fn cell(&self, row: usize, column: usize) -> CellValue<'_> {
        self.columns
            .get(column)
            .map_or(CellValue::Null, |column| column.cell(row))
    }

    /// The row as owned values, for a query or a channel.
    pub fn row(&self, row: usize) -> Vec<super::column::DataValue> {
        self.columns
            .iter()
            .map(|column| column.cell(row).to_owned_value())
            .collect()
    }

    /// A dataset of rows in `range`.
    pub fn slice(&self, range: Range<usize>) -> Self {
        let start = range.start.min(self.len);
        let end = range.end.min(self.len).max(start);
        let columns = self.columns.iter().map(|column| column.slice(start..end)).collect();
        Self {
            columns,
            len: end - start,
            metadata: self.metadata.clone(),
            lineage: self.lineage.clone(),
        }
    }

    /// Rows whose predicate returns true, in order.
    pub fn matching_rows(&self, mut predicate: impl FnMut(usize, &Self) -> bool) -> Vec<usize> {
        (0..self.len).filter(|row| predicate(*row, self)).collect()
    }

    /// A dataset with only `rows`, in the given order.
    pub fn take(&self, rows: &[usize]) -> Self {
        let columns = self
            .columns
            .iter()
            .map(|column| {
                let values: Vec<super::column::DataValue> =
                    rows.iter().map(|row| column.cell(*row).to_owned_value()).collect();
                column_from_values(
                    &column.name,
                    &column.values,
                    &values,
                    &column.metadata,
                    column.unit.as_deref(),
                )
            })
            .collect();
        Self {
            columns,
            len: rows.len(),
            metadata: self.metadata.clone(),
            lineage: self.lineage.clone(),
        }
    }

    /// Points from two numeric columns, skipping null or non-numeric rows.
    pub fn xy_pairs(&self, x: &str, y: &str) -> Option<Vec<[f64; 2]>> {
        let x = self.column_named(x)?;
        let y = self.column_named(y)?;
        let mut points = Vec::new();
        for row in 0..self.len {
            if let (Some(x), Some(y)) = (
                super::column::DataValue::as_f64(&x.cell(row).to_owned_value()),
                super::column::DataValue::as_f64(&y.cell(row).to_owned_value()),
            ) && x.is_finite()
                && y.is_finite()
            {
                points.push([x, y]);
            }
        }
        Some(points)
    }

    /// One (x, y) point at `row`, when both values are finite numbers.
    pub fn point_at_row(&self, x: &str, y: &str, row: usize) -> Option<[f64; 2]> {
        let x = self.column_named(x)?;
        let y = self.column_named(y)?;
        let x = super::column::DataValue::as_f64(&x.cell(row).to_owned_value())?;
        let y = super::column::DataValue::as_f64(&y.cell(row).to_owned_value())?;
        (x.is_finite() && y.is_finite()).then_some([x, y])
    }

    /// Rows whose two numeric columns fall inside `bounds`.
    pub fn rows_in_bounds(&self, x: &str, y: &str, bounds: super::bounds::Bounds) -> Vec<usize> {
        (0..self.row_count())
            .filter(|row| {
                self.point_at_row(x, y, *row).is_some_and(|[x, y]| {
                    x >= bounds.min_x && x <= bounds.max_x && y >= bounds.min_y && y <= bounds.max_y
                })
            })
            .collect()
    }

    /// Statistics for one column: count, min, max, mean, and nulls.
    pub fn stats(&self, column: usize) -> Option<ColumnStats> {
        let column = self.columns.get(column)?;
        let mut count = 0;
        let mut nulls = 0;
        let mut min = f64::INFINITY;
        let mut max = f64::NEG_INFINITY;
        let mut sum = 0.0;
        for row in 0..self.len {
            if let Some(value) = column.cell(row).to_owned_value().as_f64() {
                count += 1;
                sum += value;
                min = min.min(value);
                max = max.max(value);
            } else if column.cell(row).is_null() {
                nulls += 1;
            }
        }
        Some(ColumnStats {
            count,
            nulls,
            min: (count > 0).then_some(min),
            max: (count > 0).then_some(max),
            mean: (count > 0).then_some(sum / count as f64),
        })
    }
}

fn column_from_values(
    name: &str,
    template: &ColumnValues,
    values: &[super::column::DataValue],
    metadata: &BTreeMap<String, String>,
    unit: Option<&str>,
) -> Column {
    let mut column = match template.kind() {
        ColumnType::Float => Column::floats(
            name,
            values
                .iter()
                .map(|value| value.as_f64().unwrap_or(f64::NAN))
                .collect::<Vec<_>>(),
        ),
        ColumnType::Int => Column::ints(
            name,
            values
                .iter()
                .map(|value| match value {
                    super::column::DataValue::Int(value) => *value,
                    super::column::DataValue::Float(value) => *value as i64,
                    _ => 0,
                })
                .collect::<Vec<_>>(),
        ),
        ColumnType::Bool => Column::bools(
            name,
            values
                .iter()
                .map(|value| matches!(value, super::column::DataValue::Bool(true)))
                .collect::<Vec<_>>(),
        ),
        ColumnType::Text | ColumnType::Category => {
            let texts: Vec<String> = values
                .iter()
                .map(|value| value.as_text().unwrap_or_default().to_owned())
                .collect();
            if template.kind() == ColumnType::Category {
                Column::categories(name, texts)
            } else {
                Column::text(name, texts)
            }
        }
        ColumnType::Date => Column::dates(
            name,
            values
                .iter()
                .map(|value| {
                    if let super::column::DataValue::Date(value) = value {
                        *value
                    } else {
                        0
                    }
                })
                .collect::<Vec<_>>(),
        ),
        ColumnType::Time => Column::times(
            name,
            values
                .iter()
                .map(|value| {
                    if let super::column::DataValue::Time(value) = value {
                        *value
                    } else {
                        0
                    }
                })
                .collect::<Vec<_>>(),
        ),
    };
    let validity: Vec<bool> = values
        .iter()
        .map(|value| !matches!(value, super::column::DataValue::Null))
        .collect();
    if validity.iter().any(|valid| !valid) {
        column = column.with_validity(validity);
    }
    column.metadata = metadata.clone();
    if let Some(unit) = unit {
        column = column.with_unit(unit);
    }
    column
}

/// Summary statistics of one numeric column.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::data::ColumnStats;
/// ```
pub struct ColumnStats {
    /// Non-null numeric values.
    pub count: usize,
    /// Null values.
    pub nulls: usize,
    /// Minimum, when there is a value.
    pub min: Option<f64>,
    /// Maximum, when there is a value.
    pub max: Option<f64>,
    /// Mean, when there is a value.
    pub mean: Option<f64>,
}

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

    fn dataset() -> Dataset {
        Dataset::from_columns([
            Column::floats("voltage", vec![0.1, 0.4, 0.2, 0.5]),
            Column::ints("cycle", vec![1, 2, 3, 4]),
            Column::text("name", ["a", "b", "c", "d"]),
        ])
    }

    #[test]
    fn columns_and_cells_are_typed() {
        let data = dataset();
        assert_eq!(data.row_count(), 4);
        assert_eq!(data.width(), 3);
        assert_eq!(data.cell(1, 0), CellValue::Float(0.4));
        assert_eq!(data.cell(1, 1), CellValue::Int(2));
        assert_eq!(data.index_of("name"), Some(2));
        assert!(data.column_named("missing").is_none());
    }

    #[test]
    fn lineage_survives_slices_and_take() {
        let mut data = dataset();
        data.derived_from("input.csv", "csv");
        assert_eq!(data.lineage().sources(), ["input.csv"]);
        assert_eq!(data.slice(0..1).lineage(), data.lineage());
        assert_eq!(data.take(&[0]).lineage(), data.lineage());
    }

    #[test]
    fn slices_and_take_keep_types_and_metadata() {
        let mut data = dataset();
        data.set_metadata("source", "test");
        let slice = data.slice(1..3);
        assert_eq!(slice.row_count(), 2);
        assert_eq!(slice.cell(0, 0), CellValue::Float(0.4));
        assert_eq!(slice.metadata().get("source").map(String::as_str), Some("test"));
        let taken = data.take(&[3, 1]);
        assert_eq!(taken.row_count(), 2);
        assert_eq!(taken.cell(0, 1), CellValue::Int(4));
        assert_eq!(taken.cell(1, 2), CellValue::Text("b"));
    }

    #[test]
    fn statistics_ignore_nulls() {
        let data =
            Dataset::from_columns([Column::floats("v", vec![1.0, f64::NAN, 3.0]).with_validity([true, false, true])]);
        let stats = data.stats(0).expect("stats");
        assert_eq!(stats.count, 2);
        assert_eq!(stats.nulls, 1);
        assert_eq!(stats.min, Some(1.0));
        assert_eq!(stats.max, Some(3.0));
        assert_eq!(stats.mean, Some(2.0));
    }
}