1use std::collections::BTreeMap;
4use std::ops::Range;
5
6use super::column::{CellValue, Column, ColumnType, ColumnValues};
7use super::lineage::{Lineage, LineageStep};
8
9#[derive(Clone, Debug, Default, PartialEq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub 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 pub fn new() -> Self {
28 Self::default()
29 }
30
31 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 pub fn with_rows(rows: usize) -> Self {
46 Self {
47 len: rows,
48 ..Self::default()
49 }
50 }
51
52 pub fn row_count(&self) -> usize {
54 self.len
55 }
56
57 pub fn width(&self) -> usize {
59 self.columns.len()
60 }
61
62 pub fn is_empty(&self) -> bool {
64 self.columns.is_empty() && self.len == 0
65 }
66
67 pub fn columns(&self) -> &[Column] {
69 &self.columns
70 }
71
72 pub fn column(&self, index: usize) -> Option<&Column> {
74 self.columns.get(index)
75 }
76
77 pub fn column_named(&self, name: &str) -> Option<&Column> {
79 self.columns.iter().find(|column| column.name == name)
80 }
81
82 pub fn index_of(&self, name: &str) -> Option<usize> {
84 self.columns.iter().position(|column| column.name == name)
85 }
86
87 pub fn metadata(&self) -> &BTreeMap<String, String> {
89 &self.metadata
90 }
91
92 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 pub fn lineage(&self) -> &Lineage {
99 &self.lineage
100 }
101
102 pub fn record_lineage(&mut self, step: LineageStep) {
104 self.lineage.record(step);
105 }
106
107 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 pub fn push_column(&mut self, column: Column) {
114 self.len = self.len.max(column.len());
115 self.columns.push(column);
116 }
117
118 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 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 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 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 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 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 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
329#[non_exhaustive]
330pub struct ColumnStats {
336 pub count: usize,
338 pub nulls: usize,
340 pub min: Option<f64>,
342 pub max: Option<f64>,
344 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}