Skip to main content

sim_components/
dataset.rs

1//! Published measured datasets (`datasets/<id>/`): a `dataset.toml` with the metadata, a README, and per
2//! recording a trace file with its mapping. `check` says what keeps a folder from being published; the
3//! format is described in datasets/README.md.
4
5use crate::identify::parse_sweep;
6use crate::import::{Mapping, decode, import};
7use std::path::Path;
8use toml::{Table, Value};
9
10pub const LICENSES: [&str; 5] = ["CC0-1.0", "CC-BY-4.0", "CC-BY-SA-4.0", "ODbL-1.0", "PDDL-1.0"];
11/// The test moves of docs/measurement-procedure.md.
12pub const TESTS: [&str; 7] = [
13    "inertia-sines",
14    "friction-map",
15    "slow-reversal",
16    "torque-step",
17    "noise-excitation",
18    "frequency-response",
19    "cycle",
20];
21
22/// (table, key, required, kind): `s` text, `n` number, `b` true/false, `a` a list of texts.
23const SCHEMA: &[(&str, &str, bool, char)] = &[
24    ("dataset", "id", true, 's'),
25    ("dataset", "title", true, 's'),
26    ("dataset", "description", true, 's'),
27    ("dataset", "license", true, 's'),
28    ("dataset", "contributor", true, 's'),
29    ("dataset", "recorded", true, 's'),
30    ("dataset", "synthetic", true, 'b'),
31    ("machine", "kind", true, 's'),
32    ("machine", "transmission", true, 's'),
33    ("machine", "mounting", true, 's'),
34    ("machine", "travel_per_motor_rev_m", false, 'n'),
35    ("machine", "payload_kg", false, 'n'),
36    ("machine", "config", false, 's'),
37    ("machine", "simulator", false, 's'),
38    ("machine", "set", false, 'a'),
39    ("drive", "vendor", true, 's'),
40    ("drive", "family", true, 's'),
41    ("drive", "current_cycle_s", false, 'n'),
42    ("drive", "speed_cycle_s", false, 'n'),
43    ("drive", "position_cycle_s", false, 'n'),
44    ("motor", "family", true, 's'),
45    ("motor", "rated_torque_nm", true, 'n'),
46    ("motor", "rotor_inertia_kg_m2", false, 'n'),
47    ("motor", "encoder_counts_per_rev", false, 'n'),
48    ("recording", "file", true, 's'),
49    ("recording", "map", false, 's'),
50    ("recording", "test", true, 's'),
51    ("recording", "sample_time_s", true, 'n'),
52    ("recording", "notes", false, 's'),
53];
54
55fn kind_ok(value: &Value, kind: char) -> bool {
56    match kind {
57        's' => value.is_str(),
58        'b' => value.is_bool(),
59        'a' => value.as_array().is_some_and(|a| a.iter().all(Value::is_str)),
60        _ => value.as_float().or(value.as_integer().map(|i| i as f64)).is_some_and(|v| v.is_finite() && v >= 0.0),
61    }
62}
63
64/// Checks a table against the schema of `name`: required keys there, every key known, values of their kind.
65fn check_table(name: &str, table: &Table, problems: &mut Vec<String>) {
66    let schema: Vec<_> = SCHEMA.iter().filter(|s| s.0 == name).collect();
67    for (_, key, required, kind) in &schema {
68        match table.get(*key) {
69            None if *required => problems.push(format!("{name}.{key} is missing")),
70            Some(v) if !kind_ok(v, *kind) => problems.push(format!("{name}.{key} has the wrong kind of value")),
71            _ => {}
72        }
73    }
74    for key in table.keys().filter(|k| !schema.iter().any(|s| s.1 == k.as_str())) {
75        problems.push(format!("{name}.{key} is not a known key"));
76    }
77}
78
79/// What in a text gives away a person, a network or a machine: e-mail addresses, IP addresses and TwinCAT
80/// AMS Net IDs, absolute paths of a user's or a project's folders, serial numbers. One line per finding.
81pub fn personal_data(file: &str, text: &str) -> Vec<String> {
82    let mut found = Vec::new();
83    for (n, line) in text.lines().enumerate() {
84        let at = |what: &str| format!("{file}, line {}: {what}", n + 1);
85        let lower = line.to_lowercase();
86        if line
87            .split(|c: char| c.is_whitespace() || ",;\t\"'<>()".contains(c))
88            .any(|w| w.contains('@') && w.split('@').nth(1).is_some_and(|d| d.contains('.')))
89        {
90            found.push(at("an e-mail address"));
91        }
92        let dotted = line.split(|c: char| !(c.is_ascii_digit() || c == '.')).any(|w| {
93            // A sentence's full stop is not part of the address.
94            let parts: Vec<&str> = w.trim_matches('.').split('.').collect();
95            (parts.len() == 4 || parts.len() == 6)
96                && parts.iter().all(|p| !p.is_empty() && p.len() <= 3 && p.parse::<u16>().is_ok_and(|v| v < 256))
97        });
98        // IPv6: hex groups with a "::" or all eight of them (a time 12:30:00 has neither).
99        let ipv6 = line.split(|c: char| c.is_whitespace() || ",;\"'()[]<>".contains(c)).any(|w| {
100            let groups = w.split(':').filter(|g| !g.is_empty()).count();
101            w.chars().all(|c| c.is_ascii_hexdigit() || c == ':')
102                && groups >= 2
103                && (w.contains("::") || w.matches(':').count() == 7)
104        });
105        if dotted || ipv6 {
106            found.push(at("an IP address or AMS Net ID"));
107        }
108        // A drive letter with either slash (not the scheme of a URL), a UNC share, or a user's home.
109        let bytes = line.as_bytes();
110        let drive_path = (0..bytes.len().saturating_sub(2)).any(|i| {
111            bytes[i].is_ascii_alphabetic()
112                && bytes[i + 1] == b':'
113                && (bytes[i + 2] == b'\\' || bytes[i + 2] == b'/')
114                && (i == 0 || !bytes[i - 1].is_ascii_alphanumeric())
115        });
116        if drive_path
117            || line.contains("\\\\")
118            || lower.contains("/home/")
119            || lower.contains("/users/")
120            || lower.contains("\\users\\")
121        {
122            found.push(at("an absolute path"));
123        }
124        if ["serial", "serien", "s/n", "s/no"].iter().any(|w| lower.contains(w)) {
125            found.push(at("a serial number"));
126        }
127    }
128    found
129}
130
131/// One `[[recording]]`: its file, its mapping ("" for a frequency response) and its test move.
132pub struct Recording {
133    pub file: String,
134    pub map: String,
135    pub test: String,
136}
137
138/// What `sim-cli fit --dataset` reads of a folder: the metadata it reports and the recordings in their order.
139pub struct Contents {
140    pub id: String,
141    pub title: String,
142    pub license: String,
143    pub synthetic: bool,
144    /// `machine.simulator`, the simulator's machine the dataset is replayed on; "" if not named.
145    pub simulator: String,
146    /// `machine.config`, a file in the folder; "" for the machine's default config.
147    pub config: String,
148    /// `machine.set`, values set on top of the config as `--set` does (`"effects.payload = false"`).
149    pub set: Vec<String>,
150    pub recordings: Vec<Recording>,
151}
152
153/// The folder's `dataset.toml` as `Contents`; its problems are `check`'s business, here only what cannot be read and a
154/// file, map or config that is not a plain name in the folder.
155pub fn contents(dir: &Path) -> Result<Contents, String> {
156    let text = std::fs::read(dir.join("dataset.toml")).map_err(|e| format!("dataset.toml: {e}"))?;
157    let table: Table = decode(&text).parse().map_err(|e| format!("dataset.toml: {e}"))?;
158    let get = |t: &Table, k: &str| t.get(k).and_then(Value::as_str).unwrap_or("").to_string();
159    let empty = Table::new();
160    let part = |name: &str| table.get(name).and_then(Value::as_table).unwrap_or(&empty);
161    let (dataset, machine) = (part("dataset"), part("machine"));
162    let recordings = table.get("recording").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
163    // Only plain names of files in the folder: the report reads them and names its own files after them.
164    let names = recordings.iter().filter_map(Value::as_table).flat_map(|r| [get(r, "file"), get(r, "map")]);
165    if let Some(bad) =
166        names.chain([get(machine, "config")]).find(|f| f.contains(['/', '\\', ':']) || f.starts_with('.'))
167    {
168        return Err(format!("{bad}: has to be the plain name of a file in the folder"));
169    }
170    Ok(Contents {
171        id: get(dataset, "id"),
172        title: get(dataset, "title"),
173        license: get(dataset, "license"),
174        synthetic: dataset.get("synthetic").and_then(Value::as_bool).unwrap_or(false),
175        simulator: get(machine, "simulator"),
176        config: get(machine, "config"),
177        set: machine
178            .get("set")
179            .and_then(Value::as_array)
180            .map_or(Vec::new(), |a| a.iter().filter_map(Value::as_str).map(String::from).collect()),
181        recordings: recordings
182            .iter()
183            .filter_map(Value::as_table)
184            .map(|r| Recording { file: get(r, "file"), map: get(r, "map"), test: get(r, "test") })
185            .collect(),
186    })
187}
188
189/// Everything that keeps the folder `dir` from being published; empty when it is fine.
190pub fn check(dir: &Path) -> Vec<String> {
191    let mut problems = Vec::new();
192    // `.` or `..` has no name of its own: the folder's is that of its full path.
193    let full = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
194    let folder = full.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
195    let read = |name: &str| std::fs::read(dir.join(name)).map(|b| decode(&b));
196    let Ok(text) = read("dataset.toml") else { return vec!["dataset.toml is missing".into()] };
197    if read("README.md").is_err() {
198        problems.push("README.md is missing".into());
199    }
200    let table: Table = match text.parse() {
201        Ok(t) => t,
202        Err(e) => return vec![format!("dataset.toml: {e}")],
203    };
204    for key in table.keys().filter(|k| !["dataset", "machine", "drive", "motor", "recording"].contains(&k.as_str())) {
205        problems.push(format!("{key} is not a known table"));
206    }
207    for name in ["dataset", "machine", "drive", "motor"] {
208        match table.get(name).and_then(Value::as_table) {
209            Some(t) => check_table(name, t, &mut problems),
210            None => problems.push(format!("[{name}] is missing")),
211        }
212    }
213    let get = |t: &str, k: &str| table.get(t).and_then(|v| v.get(k)).and_then(Value::as_str).unwrap_or("");
214    if table.get("dataset").is_some() {
215        if get("dataset", "id") != folder {
216            problems.push(format!("dataset.id has to be the folder's name, {folder}"));
217        }
218        if !LICENSES.contains(&get("dataset", "license")) {
219            problems.push(format!("dataset.license has to be one of {}", LICENSES.join(", ")));
220        }
221        let recorded = get("dataset", "recorded");
222        let month = recorded.len() == 7
223            && recorded.as_bytes()[4] == b'-'
224            && recorded[..4].parse::<u16>().is_ok()
225            && recorded[5..].parse::<u8>().is_ok_and(|m| (1..=12).contains(&m));
226        if !month {
227            problems.push("dataset.recorded has to be year and month only, YYYY-MM".into());
228        }
229    }
230    let recordings = table.get("recording").and_then(Value::as_array).cloned().unwrap_or_default();
231    if recordings.is_empty() {
232        problems.push("[[recording]] is missing".into());
233    }
234    let mut listed = vec!["dataset.toml".to_string(), "README.md".to_string()];
235    // The measured machine as a config of one of the simulator's machines, a TOML file in the folder.
236    let config = get("machine", "config");
237    if !config.is_empty() {
238        listed.push(config.to_string());
239        match read(config).map(|text| text.parse::<Table>()) {
240            _ if config.contains(['/', '\\', ':']) || config.starts_with('.') => {
241                problems.push("machine.config has to be the plain name of a file in the folder".into())
242            }
243            Ok(Ok(_)) => {}
244            Ok(Err(e)) => problems.push(format!("machine.config: {e}")),
245            Err(_) => problems.push(format!("machine.config: {config} is missing")),
246        }
247    }
248    for (i, r) in recordings.iter().enumerate() {
249        let Some(r) = r.as_table() else { continue };
250        let before = problems.len();
251        check_table("recording", r, &mut problems);
252        if problems.len() > before {
253            continue;
254        }
255        let field = |k: &str| r.get(k).and_then(Value::as_str).unwrap_or("").to_string();
256        let (file, map, test) = (field("file"), field("map"), field("test"));
257        let name = format!("recording {} ({file})", i + 1);
258        if !TESTS.contains(&test.as_str()) {
259            problems.push(format!("{name}: test has to be one of {}", TESTS.join(", ")));
260        }
261        // Only files in the folder itself.
262        let inside = |f: &str| !f.is_empty() && !f.contains(['/', '\\', ':']) && !f.starts_with('.');
263        if !inside(&file) || (!map.is_empty() && !inside(&map)) {
264            problems.push(format!("{name}: file and map have to be plain names of files in the folder"));
265            continue;
266        }
267        listed.push(file.clone());
268        listed.push(map.clone());
269        let Ok(trace) = read(&file) else {
270            problems.push(format!("{name}: the file is missing"));
271            continue;
272        };
273        if test == "frequency-response" {
274            match parse_sweep(&trace) {
275                Ok(points) if points.len() >= 10 => {}
276                Ok(_) => problems.push(format!("{name}: fewer than 10 points")),
277                Err(e) => problems.push(format!("{name}: {} {}", e.key, e.detail)),
278            }
279            continue;
280        }
281        if map.is_empty() {
282            problems.push(format!("{name}: a trace needs a map"));
283            continue;
284        }
285        let mapping = match read(&map)
286            .map_err(|e| e.to_string())
287            .and_then(|m| Mapping::parse(&m).map_err(|e| format!("{} {}", e.key, e.detail)))
288        {
289            Ok(m) => m,
290            Err(e) => {
291                problems.push(format!("{name}: map: {e}"));
292                continue;
293            }
294        };
295        match import(&trace, &mapping) {
296            Ok(imported) => {
297                let t = &imported.trace.time;
298                let step = (t[t.len() - 1] - t[0]) / (t.len() - 1) as f64;
299                let stated = r
300                    .get("sample_time_s")
301                    .and_then(|v| v.as_float().or(v.as_integer().map(|i| i as f64)))
302                    .unwrap_or(0.0);
303                if (step - stated).abs() > 0.01 * stated {
304                    problems.push(format!("{name}: sample_time_s is {stated}, the trace has {step:e} s"));
305                }
306                if t.len() < 100 {
307                    problems.push(format!("{name}: fewer than 100 rows"));
308                }
309            }
310            Err(e) => problems.push(format!("{name}: {} {}", e.key, e.detail)),
311        }
312    }
313    // Every file is listed (nothing published by accident) and none gives anyone away.
314    let entries = std::fs::read_dir(dir).map(|d| d.flatten().collect::<Vec<_>>()).unwrap_or_default();
315    for entry in entries {
316        let name = entry.file_name().to_string_lossy().into_owned();
317        if !listed.contains(&name) {
318            problems.push(format!("{name} is not part of any recording; remove it or list it"));
319            continue;
320        }
321        if let Ok(bytes) = std::fs::read(entry.path()) {
322            problems.extend(personal_data(&name, &decode(&bytes)));
323        }
324    }
325    problems
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    #[test]
333    fn personal_data_is_found() {
334        let found = |t: &str| personal_data("f", t).len();
335        assert_eq!(found("contact: jane.doe@example.com"), 1);
336        assert_eq!(found("NetID\t192.168.178.20.1.1"), 1);
337        assert_eq!(found("host 10.0.0.12"), 1);
338        assert_eq!(found("at 10.1.2.3."), 1);
339        assert_eq!(found("C:\\Projekte\\Machine.project"), 1);
340        assert_eq!(found("/home/jane/trace.csv"), 1);
341        assert_eq!(found("SerialNumber;ST12345"), 1);
342        assert_eq!(found("D:/Kunden/Acme/Maschine.project"), 1);
343        assert_eq!(found("\\\\fileserver\\projekte\\trace.csv"), 1);
344        assert_eq!(found("Seriennummer;ST12345"), 1);
345        assert_eq!(found("S/N: 21345"), 1);
346        assert_eq!(found("gateway fe80::1c2:3ff:fe4d:5"), 1);
347        // A time, a URL and numbers with decimal points are none of these.
348        assert_eq!(found("15:56:24.376 12:30:00 https://example.org/data"), 0);
349        assert_eq!(found("0.001,1.25,3.5,4.75\n1.2.3"), 0);
350        assert_eq!(found("time [s],speed [1/min]"), 0);
351    }
352
353    #[test]
354    fn contents_refuses_a_file_outside_the_folder() {
355        let dir = std::env::temp_dir().join("dataset-contents-escape");
356        std::fs::create_dir_all(&dir).unwrap();
357        let toml = |file: &str| {
358            format!(
359                "[machine]
360config = \"machine.toml\"
361[[recording]]
362file = \"{file}\"
363map = \"map.toml\"
364"
365            )
366        };
367        std::fs::write(dir.join("dataset.toml"), toml("../../escape.csv")).unwrap();
368        assert!(contents(&dir).is_err_and(|e| e.contains("escape.csv")));
369        std::fs::write(dir.join("dataset.toml"), toml("cycle.csv")).unwrap();
370        assert_eq!(contents(&dir).unwrap().recordings[0].file, "cycle.csv");
371    }
372}