Skip to main content

lib_jsl_file_io/
arff.rs

1//! Attribute-Relation File Format (ARFF) files from Weka (SciPy's `io.arff.loadarff`).
2//!
3//! An ARFF file is text: `@relation name`, one `@attribute name type` line per column (`numeric`,
4//! `real`, `integer`, a nominal set `{a, b, c}`, `string` or `date`), then `@data` and one
5//! comma-separated row per instance, `?` marking a missing value. Comments start with `%`.
6//!
7//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#fortran-records-and-arff).
8
9use lib_jsl_core::ErrorsJSL;
10use std::path::Path;
11
12/// The type of an ARFF attribute.
13#[derive(Clone, Debug, PartialEq)]
14#[non_exhaustive]
15pub enum ArffType {
16    /// `numeric`, `real` or `integer`.
17    Numeric,
18    /// A nominal attribute with its allowed values.
19    Nominal(Vec<String>),
20    String,
21    /// A date, with its format (empty for the ISO-8601 default); values are kept as text.
22    Date(String),
23}
24
25/// One value of a row.
26#[derive(Clone, Debug, PartialEq)]
27#[non_exhaustive]
28pub enum ArffValue {
29    /// A numeric value; NaN when missing (as SciPy reads it).
30    Number(f64),
31    /// A nominal, string or date value.
32    Text(String),
33    /// A missing nominal, string or date value (`?`).
34    Missing,
35}
36
37/// The contents of an ARFF file.
38#[derive(Clone, Debug, PartialEq)]
39#[non_exhaustive]
40pub struct Arff {
41    pub relation: String,
42    pub attributes: Vec<(String, ArffType)>,
43    pub rows: Vec<Vec<ArffValue>>,
44}
45
46impl Arff {
47    /// A numeric column as `f64` (NaN where missing).
48    pub fn column_f64(&self, index: usize) -> Option<Vec<f64>> {
49        if self.attributes.get(index)?.1 != ArffType::Numeric {
50            return None;
51        }
52        Some(self.rows.iter().map(|r| if let ArffValue::Number(v) = r[index] { v } else { f64::NAN }).collect())
53    }
54}
55
56fn bad(msg: &'static str) -> ErrorsJSL {
57    ErrorsJSL::InvalidInputRange(msg)
58}
59
60/// Splits on commas outside single or double quotes, trimming and unquoting each field.
61fn split_fields(line: &str) -> Vec<String> {
62    let mut out = Vec::new();
63    let mut cur = String::new();
64    let mut quote: Option<char> = None;
65    let mut chars = line.chars().peekable();
66    while let Some(c) = chars.next() {
67        match quote {
68            Some(q) if c == '\\' => {
69                if let Some(n) = chars.next() {
70                    cur.push(n);
71                }
72                let _ = q;
73            }
74            Some(q) if c == q => quote = None,
75            Some(_) => cur.push(c),
76            None if c == '\'' || c == '"' => quote = Some(c),
77            None if c == ',' => {
78                out.push(cur.trim().to_string());
79                cur.clear();
80            }
81            None => cur.push(c),
82        }
83    }
84    out.push(cur.trim().to_string());
85    out
86}
87
88/// The next token of a header line: a quoted string or a run of non-blank characters.
89fn take_token(s: &str) -> Option<(String, &str)> {
90    let s = s.trim_start();
91    let first = s.chars().next()?;
92    if first == '\'' || first == '"' {
93        let end = s[1..].find(first)? + 1;
94        Some((s[1..end].to_string(), &s[end + 1..]))
95    } else {
96        let end = s.find(char::is_whitespace).unwrap_or(s.len());
97        Some((s[..end].to_string(), &s[end..]))
98    }
99}
100
101// ANCHOR: arff
102/// Parses an ARFF file (SciPy's `loadarff`, which additionally rejects string attributes).
103/// Numeric values are `f64`, with missing values NaN; nominal values are checked against their
104/// declared set.
105pub fn arff_decode(text: &str) -> Result<Arff, ErrorsJSL> {
106    let mut relation = String::new();
107    let mut attributes = Vec::new();
108    let mut rows = Vec::new();
109    let mut in_data = false;
110    for raw in text.lines() {
111        let line = raw.trim();
112        if line.is_empty() || line.starts_with('%') {
113            continue;
114        }
115        if !in_data {
116            let lower = line.to_ascii_lowercase();
117            if lower.starts_with("@relation") {
118                relation = take_token(&line[9..]).map(|t| t.0).unwrap_or_default();
119            } else if lower.starts_with("@attribute") {
120                let (name, rest) = take_token(&line[10..]).ok_or(bad("ARFF: an attribute has no name"))?;
121                let rest = rest.trim();
122                let lr = rest.to_ascii_lowercase();
123                let ty = if rest.starts_with('{') {
124                    let inner = rest.trim_start_matches('{').trim_end_matches('}');
125                    ArffType::Nominal(split_fields(inner))
126                } else if lr.starts_with("numeric") || lr.starts_with("real") || lr.starts_with("integer") {
127                    ArffType::Numeric
128                } else if lr.starts_with("string") {
129                    ArffType::String
130                } else if lr.starts_with("date") {
131                    ArffType::Date(take_token(&rest[4..]).map(|t| t.0).unwrap_or_default())
132                } else {
133                    return Err(bad("ARFF: unsupported attribute type (relational attributes are not supported)"));
134                };
135                attributes.push((name, ty));
136            } else if lower.starts_with("@data") {
137                in_data = true;
138            } else {
139                return Err(bad("ARFF: unexpected line in the header"));
140            }
141            continue;
142        }
143        if line.starts_with('{') {
144            return Err(bad("ARFF: sparse data rows are not supported"));
145        }
146        let fields = split_fields(line);
147        if fields.len() != attributes.len() {
148            return Err(bad("ARFF: a data row has the wrong number of values"));
149        }
150        let mut row = Vec::with_capacity(fields.len());
151        for (f, (_, ty)) in fields.into_iter().zip(&attributes) {
152            let missing = f == "?";
153            row.push(match ty {
154                ArffType::Numeric => ArffValue::Number(if missing { f64::NAN } else { f.parse().map_err(|_| bad("ARFF: a numeric value is not a number"))? }),
155                _ if missing => ArffValue::Missing,
156                ArffType::Nominal(set) => {
157                    if !set.contains(&f) {
158                        return Err(bad("ARFF: a nominal value is not in its declared set"));
159                    }
160                    ArffValue::Text(f)
161                }
162                _ => ArffValue::Text(f),
163            });
164        }
165        rows.push(row);
166    }
167    if !in_data {
168        return Err(bad("ARFF: no @data section"));
169    }
170    Ok(Arff { relation, attributes, rows })
171}
172// ANCHOR_END: arff
173
174fn quote(s: &str) -> String {
175    if s.is_empty() || s.contains([' ', ',', '{', '}', '%', '\'', '"']) {
176        format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'"))
177    } else {
178        s.to_string()
179    }
180}
181
182/// Writes an ARFF file (a dense data section; SciPy has no writer).
183pub fn arff_encode(a: &Arff) -> String {
184    let mut out = format!("@relation {}\n\n", quote(&a.relation));
185    for (name, ty) in &a.attributes {
186        let t = match ty {
187            ArffType::Numeric => "numeric".to_string(),
188            ArffType::Nominal(v) => format!("{{{}}}", v.iter().map(|s| quote(s)).collect::<Vec<_>>().join(", ")),
189            ArffType::String => "string".into(),
190            ArffType::Date(f) if f.is_empty() => "date".into(),
191            ArffType::Date(f) => format!("date {}", quote(f)),
192        };
193        out.push_str(&format!("@attribute {} {t}\n", quote(name)));
194    }
195    out.push_str("\n@data\n");
196    for r in &a.rows {
197        let fields: Vec<String> = r
198            .iter()
199            .map(|v| match v {
200                ArffValue::Number(x) if x.is_nan() => "?".into(),
201                ArffValue::Number(x) => format!("{x}"),
202                ArffValue::Text(s) => quote(s),
203                ArffValue::Missing => "?".into(),
204            })
205            .collect();
206        out.push_str(&fields.join(","));
207        out.push('\n');
208    }
209    out
210}
211
212/// Reads an ARFF file.
213pub fn read_arff_file(path: impl AsRef<Path>) -> Result<Arff, ErrorsJSL> {
214    arff_decode(&std::fs::read_to_string(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the ARFF file"))?)
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn parses_and_round_trips() {
223        let text = "% iris excerpt\n@RELATION iris\n@ATTRIBUTE sepallength NUMERIC\n@ATTRIBUTE 'petal width' REAL\n@ATTRIBUTE class {Iris-setosa,Iris-versicolor}\n@DATA\n5.1,0.2,Iris-setosa\n?,1.3,Iris-versicolor\n4.9,0.2,?\n";
224        let a = arff_decode(text).unwrap();
225        assert_eq!(a.relation, "iris");
226        assert_eq!(a.attributes[1].0, "petal width");
227        let c = a.column_f64(0).unwrap();
228        assert!(c[1].is_nan() && c[2] == 4.9);
229        assert_eq!(a.rows[2][2], ArffValue::Missing);
230        let back = arff_decode(&arff_encode(&a)).unwrap();
231        assert_eq!(back.rows.len(), 3);
232        assert_eq!(back.attributes, a.attributes);
233        assert!(arff_decode("@relation r\n@attribute c {a,b}\n@data\nz\n").is_err());
234    }
235}