Skip to main content

solow_formula/
data.rs

1//! Input data container: named numeric and categorical columns.
2
3use std::collections::HashMap;
4
5/// A lightweight column-oriented data frame holding the variables a formula can
6/// refer to.
7///
8/// Columns are either *numeric* (`Vec<f64>`) or *categorical* (`Vec<String>`).
9/// All columns must share the same length; this is checked when the design
10/// matrix is built.
11#[derive(Debug, Clone, Default)]
12pub struct DataFrame {
13    pub(crate) numeric: HashMap<String, Vec<f64>>,
14    pub(crate) categorical: HashMap<String, Vec<String>>,
15    /// Insertion order is irrelevant to output (patsy orders by the formula),
16    /// but we keep it for deterministic error messages.
17    pub(crate) order: Vec<String>,
18}
19
20impl DataFrame {
21    /// Create an empty frame.
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    /// Insert (or replace) a numeric column.
27    pub fn add_numeric(&mut self, name: &str, values: Vec<f64>) {
28        if !self.numeric.contains_key(name) && !self.categorical.contains_key(name) {
29            self.order.push(name.to_string());
30        }
31        self.categorical.remove(name);
32        self.numeric.insert(name.to_string(), values);
33    }
34
35    /// Insert (or replace) a categorical column.
36    pub fn add_categorical<S: Into<String>>(&mut self, name: &str, values: Vec<S>) {
37        if !self.numeric.contains_key(name) && !self.categorical.contains_key(name) {
38            self.order.push(name.to_string());
39        }
40        self.numeric.remove(name);
41        self.categorical.insert(
42            name.to_string(),
43            values.into_iter().map(Into::into).collect(),
44        );
45    }
46
47    /// Number of observations (rows), or `None` if the frame is empty.
48    pub fn nrows(&self) -> Option<usize> {
49        self.numeric
50            .values()
51            .map(Vec::len)
52            .chain(self.categorical.values().map(Vec::len))
53            .next()
54    }
55
56    pub(crate) fn numeric_col(&self, name: &str) -> Option<&[f64]> {
57        self.numeric.get(name).map(Vec::as_slice)
58    }
59
60    pub(crate) fn categorical_col(&self, name: &str) -> Option<&[String]> {
61        self.categorical.get(name).map(Vec::as_slice)
62    }
63
64    pub(crate) fn is_categorical(&self, name: &str) -> bool {
65        self.categorical.contains_key(name)
66    }
67
68    pub(crate) fn has(&self, name: &str) -> bool {
69        self.numeric.contains_key(name) || self.categorical.contains_key(name)
70    }
71}