Skip to main content

sim_components/
import.rs

1//! Drive traces as the drives' and controllers' own tools export them, turned into a `Trace` at the motor
2//! shaft (rad, rad/s, N m, s) by a mapping file that names the signals and says how to scale them.
3//!
4//! Formats read (see docs/measurement-procedure.md for where each comes from and what is not confirmed):
5//! - `csv`: any table with one header line of names (a unit in `[..]` or `(..)` after a name is read),
6//!   optionally a line of units under it; comma, semicolon or tab; decimal point or comma.
7//! - `sinamics`: the CSV export of a Startdrive / TIA Portal trace. Siemens does not document its layout;
8//!   it is read as `csv`, with the time column found by name. The native `.ttrecx` is not documented and
9//!   not read.
10//! - `twincat`: the CSV export of TwinCAT 3 Scope View: a header block of name/value pairs per channel
11//!   (Name, SymbolName, SampleTime[ms], Unit, ...), then a time and a value column per channel, or one time
12//!   column shared by channels of the same sample time. Times in ms from the start, or full FILETIME stamps.
13//!   The binary `.svdx` is not documented and not read.
14//! - `codesys`: the three exports of a CODESYS trace: `.trace` (XML, UTF-16, values and timestamps per
15//!   variable), `.txt` (one time column in ms or µs, space-separated) and `.trace.csv` (a block per
16//!   variable with its own times).
17
18use crate::trace::{MotorTrace, Trace, TraceError};
19use std::f64::consts::TAU;
20use toml::{Table, Value};
21
22/// One recorded signal with its own time base, in the units of the file.
23#[derive(Debug, Clone, PartialEq)]
24pub struct Channel {
25    /// The names it can be found by: its name, and in a TwinCAT export also its symbol name.
26    pub names: Vec<String>,
27    /// As the file states it; empty where the file does not.
28    pub unit: String,
29    /// s, from the start of the recording.
30    pub time: Vec<f64>,
31    pub values: Vec<f64>,
32}
33
34fn bad(key: &'static str, detail: impl Into<String>) -> TraceError {
35    TraceError { key, detail: detail.into() }
36}
37
38/// Text from a file's bytes: UTF-16 (little or big endian) with its byte order mark, as a CODESYS `.trace`
39/// is written, otherwise UTF-8 (a byte order mark dropped, invalid bytes replaced).
40pub fn decode(bytes: &[u8]) -> String {
41    let utf16 = |big: bool| {
42        let units: Vec<u16> = bytes[2..]
43            .as_chunks::<2>()
44            .0
45            .iter()
46            .map(|p| if big { u16::from_be_bytes([p[0], p[1]]) } else { u16::from_le_bytes([p[0], p[1]]) })
47            .collect();
48        String::from_utf16_lossy(&units)
49    };
50    match bytes {
51        [0xff, 0xfe, ..] => utf16(false),
52        [0xfe, 0xff, ..] => utf16(true),
53        [0xef, 0xbb, 0xbf, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
54        _ => String::from_utf8_lossy(bytes).into_owned(),
55    }
56}
57
58/// The separator of a line: tab if it has one, else semicolon, else comma. Not the most frequent: a row
59/// `0,125;2,5` has more decimal commas than separators.
60fn separator(line: &str) -> char {
61    ['\t', ';'].into_iter().find(|&c| line.contains(c)).unwrap_or(',')
62}
63
64/// The separator of a table: tab or semicolon where at least half of its lines have one, else comma.
65fn table_separator(lines: &[&str]) -> char {
66    ['\t', ';'].into_iter().find(|&c| 2 * lines.iter().filter(|l| l.contains(c)).count() >= lines.len()).unwrap_or(',')
67}
68
69/// The fields of a line, without the empty one a trailing separator leaves.
70fn fields(line: &str, sep: char) -> Vec<&str> {
71    let line = line.trim_end();
72    line.strip_suffix(sep).unwrap_or(line).split(sep).collect()
73}
74
75/// A number in the file's notation: with a decimal comma where the separator is not a comma.
76fn number(field: &str, comma: bool) -> Option<f64> {
77    let field = field.trim().trim_matches('"').trim();
78    let parsed = if comma { field.replace(',', ".").parse::<f64>() } else { field.parse::<f64>() };
79    parsed.ok().filter(|v| v.is_finite())
80}
81
82/// A header name and the unit after it in brackets or parentheses: `speed [1/min]`, `Time (ms)`.
83fn name_and_unit(header: &str) -> (String, String) {
84    let header = header.trim().trim_matches('"').trim();
85    for (open, close) in [('[', ']'), ('(', ')')] {
86        if let (Some(a), Some(b)) = (header.rfind(open), header.rfind(close))
87            && a < b
88            && b == header.len() - 1
89        {
90            return (header[..a].trim().to_string(), header[a + 1..b].trim().to_string());
91        }
92    }
93    (header.to_string(), String::new())
94}
95
96/// Seconds per unit of time; `None` for a unit that is not one.
97fn seconds_per(unit: &str) -> Option<f64> {
98    match normal(unit).as_str() {
99        "" | "s" | "sec" => Some(1.0),
100        "ms" => Some(1e-3),
101        "us" => Some(1e-6),
102        "ns" => Some(1e-9),
103        "min" => Some(60.0),
104        _ => None,
105    }
106}
107
108/// A unit written without spaces, in lower case, with µ as u and ° as deg.
109fn normal(unit: &str) -> String {
110    unit.chars()
111        .filter(|c| !c.is_whitespace() && *c != '·' && *c != '*')
112        .collect::<String>()
113        .to_lowercase()
114        .replace(['µ', 'μ'], "u")
115        .replace('°', "deg")
116}
117
118/// The step of a drive's trace in ms: a whole number of the 125 µs base cycle of SINAMICS and of most EtherCAT
119/// drives, from 0.5 ms on. As seconds such a step (0.5 s and more) is no drive trace.
120fn looks_like_ms(step: f64) -> bool {
121    step >= 0.5 && ((step / 0.125) - (step / 0.125).round()).abs() < 1e-6
122}
123
124/// A table with one shared time column: `csv` and `sinamics`. `time` names the time column; without it the
125/// first one whose name has "time" or "zeit" in it, else the first column. `time_unit` overrides the unit
126/// the file gives the time column. The data are the rows of numbers at the end of the file; the line of names
127/// (and maybe of units) right above them is the header, and what is above that is skipped with a note. A time
128/// column without a unit is in seconds, unless its step is one of a drive's cycles in ms (`looks_like_ms`): then it
129/// is read in ms with a note, and `time_unit = "s"` in the mapping keeps seconds.
130fn read_table(
131    text: &str,
132    time: Option<&str>,
133    time_unit: Option<&str>,
134    notes: &mut Vec<(&'static str, String)>,
135) -> Result<Vec<Channel>, TraceError> {
136    let lines: Vec<&str> = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.trim().is_empty()).collect();
137    let sep = table_separator(&lines);
138    let comma = sep != ',';
139    let numeric = |l: &str| {
140        let f = fields(l, sep);
141        f.len() > 1 && f.iter().all(|f| f.trim().is_empty() || number(f, comma).is_some())
142    };
143    // Not the first line of numbers: a metadata line such as `Sample time;0,001` above the header is one too.
144    let first_data = lines.iter().rposition(|l| !numeric(l)).map(|i| i + 1).filter(|&i| i < lines.len());
145    let Some(first_data) = first_data else {
146        return Err(bad("error-import-layout", "no header line followed by numbers"));
147    };
148    let width = fields(lines[first_data], sep).len();
149    // Names, and under them maybe a line of units: short fields without brackets (a line of names with
150    // units in brackets, or a metadata line, is not one).
151    let mut names_at = first_data - 1;
152    let mut units: Option<Vec<String>> = None;
153    let unit_like = |l: &str| {
154        fields(l, sep).iter().all(|f| f.trim().trim_matches('"').chars().count() <= 8 && !f.contains(['[', '(']))
155    };
156    if first_data >= 2 && fields(lines[first_data - 2], sep).len() == width && unit_like(lines[first_data - 1]) {
157        units =
158            Some(fields(lines[first_data - 1], sep).iter().map(|u| u.trim().trim_matches('"').to_string()).collect());
159        names_at = first_data - 2;
160    }
161    if names_at > 0 {
162        notes.push(("note-import-skipped", format!("{names_at}: {}", lines[..names_at].join(" | "))));
163    }
164    let mut channels: Vec<Channel> = fields(lines[names_at], sep)
165        .into_iter()
166        .enumerate()
167        .map(|(i, h)| {
168            let (name, unit) = name_and_unit(h);
169            let unit = units.as_ref().and_then(|u| u.get(i)).filter(|u| !u.is_empty()).cloned().unwrap_or(unit);
170            Channel { names: vec![name], unit, time: Vec::new(), values: Vec::new() }
171        })
172        .collect();
173    let mut rows: Vec<Vec<f64>> = Vec::new();
174    for line in &lines[first_data..] {
175        let row: Option<Vec<f64>> = fields(line, sep).iter().map(|f| number(f, comma)).collect();
176        match row {
177            Some(row) if row.len() == channels.len() => rows.push(row),
178            _ => return Err(bad("error-trace-row", *line)),
179        }
180    }
181    let lower = |c: &Channel| c.names[0].to_lowercase();
182    let t = match time {
183        Some(name) => find(&channels, name)?,
184        None => channels.iter().position(|c| lower(c).contains("time") || lower(c).contains("zeit")).unwrap_or(0),
185    };
186    let mut unit = time_unit.map_or(channels[t].unit.clone(), str::to_string);
187    let mut steps: Vec<f64> = rows.windows(2).map(|w| w[1][t] - w[0][t]).collect();
188    steps.sort_by(f64::total_cmp);
189    if unit.is_empty() && steps.get(steps.len() / 2).is_some_and(|&step| looks_like_ms(step)) {
190        notes.push(("note-import-time-ms", format!("{}: {}", channels[t].names[0], steps[steps.len() / 2])));
191        unit = "ms".into();
192    }
193    let scale =
194        seconds_per(&unit).ok_or_else(|| bad("error-import-unit", format!("{}: {unit}", channels[t].names[0])))?;
195    let times: Vec<f64> = rows.iter().map(|r| r[t] * scale).collect();
196    for (i, channel) in channels.iter_mut().enumerate() {
197        channel.time.clone_from(&times);
198        channel.values = rows.iter().map(|r| r[i]).collect();
199    }
200    channels.remove(t);
201    Ok(channels)
202}
203
204/// TwinCAT 3 Scope View CSV export.
205fn read_twincat(text: &str) -> Result<Vec<Channel>, TraceError> {
206    let lines: Vec<&str> = text.lines().map(|l| l.trim_end_matches('\r')).collect();
207    let sep = separator(lines.first().copied().unwrap_or(""));
208    let comma = sep != ',';
209    // The channel block starts at the second line that begins with "Name" (the first names the export).
210    let start = lines
211        .iter()
212        .enumerate()
213        .filter(|(_, l)| l.split(sep).next().map(str::trim) == Some("Name"))
214        .nth(1)
215        .map(|(i, _)| i);
216    let Some(start) = start else {
217        return Err(bad("error-import-layout", "no channel header (a second line starting with Name)"));
218    };
219    let end = (start..lines.len()).find(|&i| lines[i].trim().is_empty()).unwrap_or(lines.len());
220    let header: Vec<Vec<&str>> = lines[start..end].iter().map(|l| l.split(sep).collect()).collect();
221    let row = |key: &str| header.iter().find(|r| r.first().map(|k| k.trim()) == Some(key));
222    let names = row("Name").ok_or_else(|| bad("error-import-layout", "Name"))?;
223    // Full header: key and value per channel. Shared time columns: the key once, then the values.
224    let paired = names.get(2).map(|k| k.trim()) == Some("Name");
225    let value_at = |r: &Vec<&str>, c: usize| -> String {
226        r.get(if paired { 2 * c + 1 } else { c + 1 }).map_or(String::new(), |v| v.trim().to_string())
227    };
228    let count = if paired { names.len() / 2 } else { names.len() - 1 };
229    let mut channels: Vec<Channel> = (0..count)
230        .map(|c| {
231            let mut found = vec![value_at(names, c)];
232            if let Some(symbol) = row("SymbolName").map(|r| value_at(r, c)).filter(|s| !s.is_empty()) {
233                found.push(symbol);
234            }
235            let unit = row("Unit").map(|r| value_at(r, c)).unwrap_or_default();
236            // "(None)", or a symbol and its quantity: "V (Voltage)".
237            let unit =
238                if unit.starts_with('(') { String::new() } else { unit.split(" (").next().unwrap_or("").to_string() };
239            Channel { names: found, unit, time: Vec::new(), values: Vec::new() }
240        })
241        .collect();
242    // Data: with the full header a time and a value column per channel. With shared time columns the
243    // layout of columns is not in the header; one time column followed by every channel is read.
244    for line in lines[end..].iter().filter(|l| !l.trim().is_empty() && l.trim() != "EOF") {
245        let fields: Vec<&str> = line.split(sep).collect();
246        for (c, channel) in channels.iter_mut().enumerate() {
247            let (t, v) =
248                if paired { (fields.get(2 * c), fields.get(2 * c + 1)) } else { (fields.first(), fields.get(c + 1)) };
249            // Shorter channels are padded with blank cells.
250            match (t.and_then(|t| number(t, comma)), v.and_then(|v| number(v, comma))) {
251                (Some(t), Some(v)) => {
252                    channel.time.push(t);
253                    channel.values.push(v);
254                }
255                _ if t.is_none_or(|t| t.trim().is_empty()) => {}
256                _ => return Err(bad("error-trace-row", *line)),
257            }
258        }
259    }
260    // Full timestamps are FILETIME (100 ns since 1601), counted from the earliest first stamp of all channels so that
261    // channels starting at different times keep their offset; otherwise ms from the start of the export.
262    let origin =
263        channels.iter().filter_map(|c| c.time.first().copied()).filter(|&t| t > 1e15).fold(f64::INFINITY, f64::min);
264    for channel in &mut channels {
265        let full = channel.time.first().is_some_and(|&t| t > 1e15);
266        channel.time.iter_mut().for_each(|t| *t = if full { (*t - origin) * 1e-7 } else { *t * 1e-3 });
267    }
268    Ok(channels)
269}
270
271/// CODESYS trace exports: `.trace` XML, `.txt` or `.trace.csv`, told apart by their content.
272fn read_codesys(text: &str) -> Result<Vec<Channel>, TraceError> {
273    if text.contains("<TraceVariable") {
274        return read_codesys_xml(text);
275    }
276    let lines: Vec<&str> = text.lines().map(|l| l.trim_end_matches('\r')).collect();
277    if lines.first().is_some_and(|l| l.trim_start().starts_with("[key]")) {
278        return read_codesys_csv(&lines);
279    }
280    // .txt: a title, the project, then a header of names separated by spaces, the first the time with its unit.
281    let first_data =
282        lines.iter().position(|l| !l.trim().is_empty() && l.split_whitespace().all(|f| number(f, false).is_some()));
283    let Some(first_data) = first_data.filter(|&i| i > 0) else {
284        return Err(bad("error-import-layout", "no header line followed by numbers"));
285    };
286    let header: Vec<&str> = lines[first_data - 1].split_whitespace().collect();
287    let Some((time_name, names)) = header.split_first() else {
288        return Err(bad("error-import-layout", "no header line followed by numbers"));
289    };
290    let (_, unit) = name_and_unit(time_name);
291    let scale = seconds_per(&unit).ok_or_else(|| bad("error-import-unit", format!("{time_name}: {unit}")))?;
292    let mut channels: Vec<Channel> = names
293        .iter()
294        .map(|n| Channel { names: vec![n.to_string()], unit: String::new(), time: vec![], values: vec![] })
295        .collect();
296    for line in lines[first_data..].iter().filter(|l| !l.trim().is_empty()) {
297        let row: Option<Vec<f64>> = line.split_whitespace().map(|f| number(f, false)).collect();
298        let row = row.filter(|r| r.len() == channels.len() + 1).ok_or_else(|| bad("error-trace-row", *line))?;
299        for (c, channel) in channels.iter_mut().enumerate() {
300            channel.time.push(row[0] * scale);
301            channel.values.push(row[c + 1]);
302        }
303    }
304    Ok(channels)
305}
306
307/// The text between `<tag>` and `</tag>` from `from` on, and where it ends.
308fn element<'a>(text: &'a str, tag: &str, from: usize) -> Option<(&'a str, usize)> {
309    let open = text[from..].find(&format!("<{tag}>"))? + from + tag.len() + 2;
310    let close = text[open..].find(&format!("</{tag}>"))? + open;
311    Some((&text[open..close], close))
312}
313
314fn read_codesys_xml(text: &str) -> Result<Vec<Channel>, TraceError> {
315    // Timestamps in µs where the configuration says so, otherwise in ms.
316    let micro =
317        text.find("Name=\"MicroSeconds\"").is_some_and(|i| text[i..].split('<').next().unwrap_or("").contains(">True"));
318    let scale = if micro { 1e-6 } else { 1e-3 };
319    let mut channels = Vec::new();
320    let mut at = 0;
321    while let Some(found) = text[at..].find("<TraceVariable") {
322        let start = at + found;
323        let name = text[start..].split("VarName=\"").nth(1).and_then(|r| r.split('"').next()).unwrap_or("").to_string();
324        let end = text[start..].find("</TraceVariable>").map_or(text.len(), |e| start + e);
325        let list = |tag: &str| -> Result<Vec<f64>, TraceError> {
326            let (body, _) = element(&text[..end], tag, start)
327                .ok_or_else(|| bad("error-import-layout", format!("{name}: {tag}")))?;
328            body.split(',')
329                .filter(|v| !v.trim().is_empty())
330                .map(|v| number(v, false).ok_or_else(|| bad("error-trace-row", v.trim())))
331                .collect()
332        };
333        let (values, time) = (list("Values")?, list("Timestamps")?);
334        if values.len() != time.len() {
335            return Err(bad(
336                "error-import-layout",
337                format!("{name}: {} values, {} timestamps", values.len(), time.len()),
338            ));
339        }
340        channels.push(Channel {
341            names: vec![name],
342            unit: String::new(),
343            time: time.iter().map(|t| t * scale).collect(),
344            values,
345        });
346        at = end;
347    }
348    Ok(channels)
349}
350
351fn read_codesys_csv(lines: &[&str]) -> Result<Vec<Channel>, TraceError> {
352    let field = |line: &str, i: usize| line.split(';').nth(i).map(str::trim).unwrap_or("").to_string();
353    // Flags 32 was set in the one µs export seen, 16 in the ms one: an inference, see the module comment.
354    let flags =
355        lines.iter().find(|l| field(l, 0) == "Flags").map(|l| field(l, 1).parse::<u32>().unwrap_or(0)).unwrap_or(0);
356    let scale = if flags & 32 != 0 { 1e-6 } else { 1e-3 };
357    let mut channels: Vec<Channel> = Vec::new();
358    let mut current: Option<usize> = None;
359    for line in lines.iter().filter(|l| !l.trim().is_empty()) {
360        let key = field(line, 0);
361        if key.ends_with(".Variable") {
362            channels.push(Channel { names: vec![field(line, 1)], unit: String::new(), time: vec![], values: vec![] });
363            current = None;
364        } else if key.ends_with(".Data") {
365            current = Some(channels.len().checked_sub(1).ok_or_else(|| bad("error-import-layout", *line))?);
366        } else if key.is_empty() {
367            if let Some(c) = current {
368                let (t, v) = (number(&field(line, 1), false), number(&field(line, 2), false));
369                let (t, v) = t.zip(v).ok_or_else(|| bad("error-trace-row", *line))?;
370                channels[c].time.push(t * scale);
371                channels[c].values.push(v);
372            }
373        } else {
374            current = None;
375        }
376    }
377    Ok(channels)
378}
379
380/// The index of the channel named `name`: an exact match (case and surrounding space ignored) of any of a
381/// channel's names, otherwise the one channel with `name` in one of its names.
382fn find(channels: &[Channel], name: &str) -> Result<usize, TraceError> {
383    let wanted = name.trim().to_lowercase();
384    let exact: Vec<usize> =
385        (0..channels.len()).filter(|&i| channels[i].names.iter().any(|n| n.trim().to_lowercase() == wanted)).collect();
386    let partial: Vec<usize> =
387        (0..channels.len()).filter(|&i| channels[i].names.iter().any(|n| n.to_lowercase().contains(&wanted))).collect();
388    match (exact.as_slice(), partial.as_slice()) {
389        ([i], _) | ([], [i]) => Ok(*i),
390        ([], []) => {
391            let all: Vec<&str> = channels.iter().map(|c| c.names[0].as_str()).collect();
392            Err(bad("error-import-signal", format!("{name} (the file has: {})", all.join(", "))))
393        }
394        _ => Err(bad("error-import-ambiguous", name)),
395    }
396}
397
398/// What a quantity is, for its units.
399#[derive(Clone, Copy, PartialEq)]
400enum Quantity {
401    Angle,
402    Speed,
403    Torque,
404}
405
406/// How one signal of the file becomes a motor quantity in SI units:
407/// `(raw + offset) × unit factor × scale`, with the time shifted by `time_offset_s`.
408#[derive(Debug, Clone, PartialEq)]
409pub struct Signal {
410    pub signal: String,
411    /// Overrides the file's unit; required where the file has none.
412    pub unit: Option<String>,
413    /// Units of the signal per motor revolution: for increments the encoder resolution (counts per turn),
414    /// for a length the lead (mm of travel per motor turn). Not needed for rad, deg, rev.
415    pub per_rev: Option<f64>,
416    /// N m at 100 % (unit `%`) or at 1000 ‰ (unit `‰`, as CiA 402 drives give torque in per mille of rated).
417    pub reference: Option<f64>,
418    pub scale: f64,
419    pub offset: f64,
420    /// The raw value wraps around at this span (a 32-bit encoder count: 4294967296); it is unwrapped.
421    pub wrap: Option<f64>,
422    /// Added to the signal's times: where a device's clock or a bus delay puts it behind the others.
423    pub time_offset_s: f64,
424}
425
426/// The mapping file: which signals of the file are which motor quantities.
427#[derive(Debug, Clone, PartialEq)]
428pub struct Mapping {
429    /// csv, sinamics, twincat or codesys.
430    pub format: String,
431    /// The time column of a `csv`/`sinamics` table, and its unit, which overrides the one the file states.
432    pub time: Option<String>,
433    pub time_unit: Option<String>,
434    /// The step the signals are resampled to; without it, that of the first motor's angle.
435    pub sample_time_s: Option<f64>,
436    pub motors: Vec<MotorMapping>,
437}
438
439#[derive(Debug, Clone, PartialEq)]
440pub struct MotorMapping {
441    pub id: String,
442    pub setpoint: Signal,
443    pub angle: Signal,
444    /// Without it, the speed is the slope of the angle.
445    pub speed: Option<Signal>,
446    pub torque: Signal,
447    pub torque_setpoint: Option<Signal>,
448}
449
450pub const FORMATS: [&str; 4] = ["csv", "sinamics", "twincat", "codesys"];
451
452impl Mapping {
453    /// Reads a mapping file (TOML; see datasets/template/map.toml). Unknown keys are refused, so a
454    /// misspelt one does not pass unnoticed.
455    pub fn parse(text: &str) -> Result<Self, TraceError> {
456        let table: Table = text.parse().map_err(|e: toml::de::Error| bad("error-import-map", e.to_string()))?;
457        known(&table, "", &["format", "time", "time_unit", "sample_time_s", "motor"])?;
458        let text_of = |t: &Table, key: &str| -> Result<Option<String>, TraceError> {
459            t.get(key)
460                .map(|v| v.as_str().map(str::to_string).ok_or_else(|| bad("error-import-map", key.to_string())))
461                .transpose()
462        };
463        let format = text_of(&table, "format")?.ok_or_else(|| bad("error-import-map", "format"))?;
464        if !FORMATS.contains(&format.as_str()) {
465            return Err(bad("error-import-map", format!("format = {format}")));
466        }
467        // TwinCAT and CODESYS state their time column and unit in the file's layout.
468        if ["twincat", "codesys"].contains(&format.as_str())
469            && (table.contains_key("time") || table.contains_key("time_unit"))
470        {
471            return Err(bad("error-import-map", format!("time / time_unit with format = {format}")));
472        }
473        let positive = |t: &Table, key: &str| -> Result<Option<f64>, TraceError> {
474            t.get(key)
475                .map(|v| {
476                    v.as_float()
477                        .or(v.as_integer().map(|i| i as f64))
478                        .filter(|v| *v > 0.0 && v.is_finite())
479                        .ok_or_else(|| bad("error-import-map", key.to_string()))
480                })
481                .transpose()
482        };
483        let motors =
484            table.get("motor").and_then(Value::as_array).ok_or_else(|| bad("error-import-map", "[[motor]]"))?;
485        let motors = motors
486            .iter()
487            .enumerate()
488            .map(|(i, m)| {
489                let m = m.as_table().ok_or_else(|| bad("error-import-map", "[[motor]]"))?;
490                known(m, "motor.", &["id", "setpoint", "angle", "speed", "torque", "torque_setpoint"])?;
491                let signal = |key: &str| -> Result<Option<Signal>, TraceError> {
492                    m.get(key).map(|v| Signal::parse(v, key)).transpose()
493                };
494                let needed = |key: &str| signal(key)?.ok_or_else(|| bad("error-import-map", format!("motor.{key}")));
495                Ok(MotorMapping {
496                    id: text_of(m, "id")?.unwrap_or_else(|| i.to_string()),
497                    setpoint: needed("setpoint")?,
498                    angle: needed("angle")?,
499                    speed: signal("speed")?,
500                    torque: needed("torque")?,
501                    torque_setpoint: signal("torque_setpoint")?,
502                })
503            })
504            .collect::<Result<Vec<_>, TraceError>>()?;
505        if motors.is_empty() {
506            return Err(bad("error-import-map", "[[motor]]"));
507        }
508        Ok(Self {
509            format,
510            time: text_of(&table, "time")?,
511            time_unit: text_of(&table, "time_unit")?,
512            sample_time_s: positive(&table, "sample_time_s")?,
513            motors,
514        })
515    }
516}
517
518fn known(table: &Table, prefix: &str, keys: &[&str]) -> Result<(), TraceError> {
519    match table.keys().find(|k| !keys.contains(&k.as_str())) {
520        Some(k) => Err(bad("error-import-map", format!("{prefix}{k}"))),
521        None => Ok(()),
522    }
523}
524
525impl Signal {
526    fn parse(value: &Value, key: &str) -> Result<Self, TraceError> {
527        let wrong = |what: &str| bad("error-import-map", format!("{key}.{what}"));
528        // A bare name is a signal without options.
529        if let Some(name) = value.as_str() {
530            return Ok(Self {
531                signal: name.into(),
532                unit: None,
533                per_rev: None,
534                reference: None,
535                scale: 1.0,
536                offset: 0.0,
537                wrap: None,
538                time_offset_s: 0.0,
539            });
540        }
541        let t = value.as_table().ok_or_else(|| wrong("signal"))?;
542        known(
543            t,
544            &format!("{key}."),
545            &["signal", "unit", "per_rev", "reference", "scale", "offset", "wrap", "time_offset_s"],
546        )?;
547        let float = |k: &str| -> Result<Option<f64>, TraceError> {
548            t.get(k)
549                .map(|v| {
550                    v.as_float().or(v.as_integer().map(|i| i as f64)).filter(|v| v.is_finite()).ok_or_else(|| wrong(k))
551                })
552                .transpose()
553        };
554        let positive = |k: &str| -> Result<Option<f64>, TraceError> {
555            float(k)?.map(|v| if v > 0.0 { Ok(v) } else { Err(wrong(k)) }).transpose()
556        };
557        Ok(Self {
558            signal: t.get("signal").and_then(Value::as_str).ok_or_else(|| wrong("signal"))?.into(),
559            unit: t.get("unit").map(|v| v.as_str().map(str::to_string).ok_or_else(|| wrong("unit"))).transpose()?,
560            per_rev: positive("per_rev")?,
561            reference: positive("reference")?,
562            scale: float("scale")?.unwrap_or(1.0),
563            offset: float("offset")?.unwrap_or(0.0),
564            wrap: positive("wrap")?,
565            time_offset_s: float("time_offset_s")?.unwrap_or(0.0),
566        })
567    }
568
569    /// The factor from the signal's unit to rad, rad/s or N m.
570    fn factor(&self, unit: &str, quantity: Quantity) -> Result<f64, TraceError> {
571        let unknown = || bad("error-import-unit", format!("{}: {unit}", self.signal));
572        let per_rev = |angle: &str| -> Result<f64, TraceError> {
573            match angle {
574                "rad" => Ok(TAU),
575                "deg" => Ok(360.0),
576                "rev" | "r" | "u" | "turn" | "turns" | "1" => Ok(1.0),
577                _ => self.per_rev.ok_or_else(|| bad("error-import-per-rev", format!("{}: {unit}", self.signal))),
578            }
579        };
580        let u = normal(unit);
581        match quantity {
582            Quantity::Angle => Ok(TAU / per_rev(&u)?),
583            Quantity::Speed => {
584                let (angle, time) = match u.as_str() {
585                    "rpm" => ("rev", "min"),
586                    _ => u.split_once('/').ok_or_else(unknown)?,
587                };
588                Ok(TAU / per_rev(angle)? / seconds_per(time).ok_or_else(unknown)?)
589            }
590            Quantity::Torque => match u.as_str() {
591                "nm" => Ok(1.0),
592                "mnm" => Ok(1e-3),
593                "knm" => Ok(1e3),
594                "%" => {
595                    Ok(self.reference.ok_or_else(|| bad("error-import-reference", format!("{}: %", self.signal)))?
596                        / 100.0)
597                }
598                "‰" | "permille" => {
599                    Ok(self.reference.ok_or_else(|| bad("error-import-reference", format!("{}: ‰", self.signal)))?
600                        / 1000.0)
601                }
602                // Any other unit (A, a raw count) only with a scale that turns it into N m.
603                _ if self.scale != 1.0 => Ok(1.0),
604                _ => Err(unknown()),
605            },
606        }
607    }
608
609    /// The signal's times and SI values.
610    fn convert(&self, channels: &[Channel], quantity: Quantity) -> Result<(Vec<f64>, Vec<f64>), TraceError> {
611        let channel = &channels[find(channels, &self.signal)?];
612        let unit = self.unit.clone().unwrap_or_else(|| channel.unit.clone());
613        let factor = self.factor(&unit, quantity)? * self.scale;
614        let mut raw = channel.values.clone();
615        if let Some(span) = self.wrap {
616            let mut turns = 0.0;
617            for i in 1..raw.len() {
618                let jump = channel.values[i] - channel.values[i - 1];
619                turns -= span * (jump / span).round();
620                raw[i] = channel.values[i] + turns;
621            }
622        }
623        if channel.time.len() < 2 {
624            return Err(bad("error-trace-short", self.signal.clone()));
625        }
626        crate::trace::rising(&channel.time).map_err(|e| bad(e.key, format!("{}: {}", self.signal, e.detail)))?;
627        let time: Vec<f64> = channel.time.iter().map(|t| t + self.time_offset_s).collect();
628        let values: Vec<f64> = raw.iter().map(|v| (v + self.offset) * factor).collect();
629        // A tiny per_rev or a huge scale, offset or time offset can take a value beyond the numbers.
630        if !time.iter().chain(&values).all(|v| v.is_finite()) {
631            return Err(bad("error-import-map", self.signal.clone()));
632        }
633        Ok((time, values))
634    }
635}
636
637/// `values` at `time`, linear between samples; times must rise.
638fn resample(time: &[f64], values: &[f64], at: &[f64]) -> Vec<f64> {
639    at.iter()
640        .map(|&t| {
641            let k = time.partition_point(|&x| x <= t).clamp(1, time.len() - 1);
642            let share = (t - time[k - 1]) / (time[k] - time[k - 1]);
643            values[k - 1] + share * (values[k] - values[k - 1])
644        })
645        .collect()
646}
647
648/// A trace read through a mapping, and per motor the torque setpoint where the mapping names one.
649#[derive(Debug, Clone, PartialEq)]
650pub struct Imported {
651    pub trace: Trace,
652    pub ids: Vec<String>,
653    pub torque_setpoints: Vec<Option<Vec<f64>>>,
654    /// What was read other than the file says, as a translation key and its argument: lines skipped above the
655    /// header, a time column without a unit read in ms.
656    pub notes: Vec<(&'static str, String)>,
657}
658
659/// The channels of a file in one of the `FORMATS`, and the notes on how it was read.
660pub fn channels(
661    text: &str,
662    mapping: &Mapping,
663    notes: &mut Vec<(&'static str, String)>,
664) -> Result<Vec<Channel>, TraceError> {
665    let channels = match mapping.format.as_str() {
666        "twincat" => read_twincat(text)?,
667        "codesys" => read_codesys(text)?,
668        _ => read_table(text, mapping.time.as_deref(), mapping.time_unit.as_deref(), notes)?,
669    };
670    Ok(channels)
671}
672
673/// Reads a file through a mapping: every signal converted to SI units, shifted by its time offset, and all
674/// resampled (linear) onto one grid that spans the time all of them cover, from 0.
675pub fn import(text: &str, mapping: &Mapping) -> Result<Imported, TraceError> {
676    let mut notes = Vec::new();
677    let channels = channels(text, mapping, &mut notes)?;
678    let mut signals = Vec::new();
679    for m in &mapping.motors {
680        signals.push(Some(m.setpoint.convert(&channels, Quantity::Angle)?));
681        signals.push(Some(m.angle.convert(&channels, Quantity::Angle)?));
682        signals.push(m.speed.as_ref().map(|s| s.convert(&channels, Quantity::Speed)).transpose()?);
683        signals.push(Some(m.torque.convert(&channels, Quantity::Torque)?));
684        signals.push(m.torque_setpoint.as_ref().map(|s| s.convert(&channels, Quantity::Torque)).transpose()?);
685    }
686    let from = signals.iter().flatten().map(|(t, _)| t[0]).fold(f64::NEG_INFINITY, f64::max);
687    let to = signals.iter().flatten().map(|(t, _)| t[t.len() - 1]).fold(f64::INFINITY, f64::min);
688    let reference = &signals[1].as_ref().expect("angle").0;
689    let step = mapping.sample_time_s.unwrap_or_else(|| {
690        let mut steps: Vec<f64> = reference.windows(2).map(|w| w[1] - w[0]).collect();
691        steps.sort_by(f64::total_cmp);
692        steps[steps.len() / 2]
693    });
694    if !(to > from) {
695        return Err(bad("error-import-time", "the signals do not overlap in time"));
696    }
697    let count = ((to - from) / step + 1e-9).floor() + 1.0;
698    // A grid far finer than any signal is a mistake in `sample_time_s`, and would not fit in memory.
699    let longest = signals.iter().flatten().map(|(t, _)| t.len()).max().unwrap_or(0) as f64;
700    if count > 10.0 * longest + 10.0 {
701        return Err(bad(
702            "error-import-time",
703            format!("sample_time_s = {step} gives {count} rows for {longest} samples"),
704        ));
705    }
706    let count = count as usize;
707    let grid: Vec<f64> = (0..count).map(|i| from + i as f64 * step).collect();
708    let on_grid = |s: &Option<(Vec<f64>, Vec<f64>)>| s.as_ref().map(|(t, v)| resample(t, v, &grid));
709    let mut trace = Trace { time: grid.iter().map(|t| t - from).collect(), ..Trace::default() };
710    let mut torque_setpoints = Vec::new();
711    for k in 0..mapping.motors.len() {
712        let angle = on_grid(&signals[5 * k + 1]).expect("angle");
713        let speed = on_grid(&signals[5 * k + 2]).unwrap_or_else(|| slope(&trace.time, &angle));
714        trace.motors.push(MotorTrace {
715            setpoint: on_grid(&signals[5 * k]).expect("setpoint"),
716            angle,
717            speed,
718            torque: on_grid(&signals[5 * k + 3]).expect("torque"),
719        });
720        torque_setpoints.push(on_grid(&signals[5 * k + 4]));
721    }
722    if trace.time.len() < 4 {
723        return Err(bad("error-trace-short", String::new()));
724    }
725    Ok(Imported { trace, ids: mapping.motors.iter().map(|m| m.id.clone()).collect(), torque_setpoints, notes })
726}
727
728/// The slope of a signal: central differences, one-sided at the ends.
729fn slope(time: &[f64], values: &[f64]) -> Vec<f64> {
730    let n = values.len();
731    (0..n)
732        .map(|i| {
733            let (a, b) = (i.saturating_sub(1), (i + 1).min(n - 1));
734            (values[b] - values[a]) / (time[b] - time[a])
735        })
736        .collect()
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742
743    #[test]
744    fn units_convert_to_the_motor_shaft() {
745        let s = |unit: &str| Signal {
746            signal: "x".into(),
747            unit: Some(unit.into()),
748            per_rev: Some(10.0),
749            reference: Some(2.0),
750            scale: 1.0,
751            offset: 0.0,
752            wrap: None,
753            time_offset_s: 0.0,
754        };
755        let close = |a: f64, b: f64| assert!((a - b).abs() < 1e-12 * b.abs(), "{a} {b}");
756        close(s("1/min").factor("1/min", Quantity::Speed).unwrap(), TAU / 60.0);
757        close(s("rpm").factor("rpm", Quantity::Speed).unwrap(), TAU / 60.0);
758        close(s("").factor("°/s", Quantity::Speed).unwrap(), TAU / 360.0);
759        close(s("").factor("mm/s", Quantity::Speed).unwrap(), TAU / 10.0);
760        close(s("").factor("mm", Quantity::Angle).unwrap(), TAU / 10.0);
761        close(s("").factor("inc", Quantity::Angle).unwrap(), TAU / 10.0);
762        close(s("").factor("%", Quantity::Torque).unwrap(), 0.02);
763        close(s("").factor("‰", Quantity::Torque).unwrap(), 0.002);
764        close(s("").factor("N m", Quantity::Torque).unwrap(), 1.0);
765        let bare = Signal { per_rev: None, ..s("") };
766        assert_eq!(bare.factor("LU", Quantity::Angle).unwrap_err().key, "error-import-per-rev");
767        assert_eq!(bare.factor("A", Quantity::Torque).unwrap_err().key, "error-import-unit");
768    }
769
770    #[test]
771    fn a_wrapping_counter_is_unwrapped() {
772        let channel = Channel {
773            names: vec!["c".into()],
774            unit: "inc".into(),
775            time: vec![0.0, 1.0, 2.0, 3.0],
776            values: vec![4294967000.0, 4294967200.0, 104.0, 400.0],
777        };
778        let s = Signal {
779            signal: "c".into(),
780            unit: None,
781            per_rev: Some(1.0),
782            reference: None,
783            scale: 1.0,
784            offset: 0.0,
785            wrap: Some(4294967296.0),
786            time_offset_s: 0.0,
787        };
788        let (_, v) = s.convert(&[channel], Quantity::Angle).unwrap();
789        let counts: Vec<f64> = v.iter().map(|v| (v / TAU).round()).collect();
790        assert_eq!(counts, vec![4294967000.0, 4294967200.0, 4294967400.0, 4294967696.0]);
791    }
792
793    #[test]
794    fn twincat_channels_keep_their_start_offset() {
795        // Channel b starts 5e7 FILETIME ticks (100 ns) = 5 s after channel a: it starts at 5 s, not at 0.
796        let text = "Name;export\nName;a;Name;b\n\n130000000000000000;1;130000000050000000;2\n130000000010000000;1;130000000060000000;2\n";
797        let channels = read_twincat(text).unwrap();
798        assert_eq!(channels[0].time, vec![0.0, 1.0]);
799        assert_eq!(channels[1].time, vec![5.0, 6.0]);
800    }
801
802    #[test]
803    fn utf16_is_decoded() {
804        let mut bytes = vec![0xff, 0xfe];
805        "<a>ä</a>".encode_utf16().for_each(|u| bytes.extend(u.to_le_bytes()));
806        assert_eq!(decode(&bytes), "<a>ä</a>");
807    }
808}