1use lib_jsl_core::ErrorsJSL;
10use std::path::Path;
11
12#[derive(Clone, Debug, PartialEq)]
14#[non_exhaustive]
15pub enum ArffType {
16 Numeric,
18 Nominal(Vec<String>),
20 String,
21 Date(String),
23}
24
25#[derive(Clone, Debug, PartialEq)]
27#[non_exhaustive]
28pub enum ArffValue {
29 Number(f64),
31 Text(String),
33 Missing,
35}
36
37#[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 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
60fn 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
88fn 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
101pub 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}
172fn 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
182pub 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
212pub 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}