taktwerk 0.6.0

Fixed-step model execution engine for Linux with its own OPC UA server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Text summaries of a plan and of a run.

use std::fmt::Write as _;
use std::time::Duration;

use taktwerk_core::image::Direction;
use taktwerk_core::plan::Plan;
use taktwerk_core::project::Sink;
use taktwerk_core::schedule::RunSummary;
use taktwerk_core::value::ScalarType;

/// Milliseconds, trimmed: `10`, `2.5`, `0.125`.
pub fn ms(d: Duration) -> String {
    let v = d.as_secs_f64() * 1e3;
    let s = format!("{v:.3}");
    s.trim_end_matches('0').trim_end_matches('.').to_owned()
}

/// The type column: `text` for text (its shape is the capacity, NUL included), else the
/// element type.
pub fn value_type(t: ScalarType, text: bool) -> String {
    if text {
        "text".to_owned()
    } else {
        scalar_type(t)
    }
}

/// Lower-case name of a direction.
pub const fn direction(d: Direction) -> &'static str {
    match d {
        Direction::Input => "input",
        Direction::Output => "output",
        Direction::Tunable => "tunable",
        Direction::System => "system",
    }
}

/// Lower-case name of a type.
pub fn scalar_type(t: ScalarType) -> String {
    format!("{t:?}").to_lowercase()
}

/// `[3, 2]`, or `scalar`.
pub fn shape(dims: &[usize]) -> String {
    if dims.is_empty() {
        return "scalar".to_owned();
    }
    let parts: Vec<String> = dims.iter().map(ToString::to_string).collect();
    format!("[{}]", parts.join(", "))
}

/// Bytes in decimal units, one decimal past 1000: `512 B`, `48.0 kB`, `1.2 GB`.
pub fn bytes(n: u64) -> String {
    const UNITS: [&str; 4] = ["kB", "MB", "GB", "TB"];
    if n < 1000 {
        return format!("{n} B");
    }
    #[allow(clippy::cast_precision_loss, reason = "a display value")]
    let mut v = n as f64 / 1000.0;
    let mut unit = UNITS[0];
    for u in &UNITS[1..] {
        if v < 1000.0 {
            break;
        }
        v /= 1000.0;
        unit = u;
    }
    format!("{v:.1} {unit}")
}

/// Pad `rows` into aligned columns, two spaces apart, the first row a header.
pub fn table(rows: &[Vec<String>]) -> String {
    let cols = rows.iter().map(Vec::len).max().unwrap_or(0);
    let widths: Vec<usize> = (0..cols)
        .map(|c| {
            rows.iter()
                .filter_map(|r| r.get(c))
                .map(|s| s.chars().count())
                .max()
                .unwrap_or(0)
        })
        .collect();
    let mut out = String::new();
    for row in rows {
        let mut line = String::new();
        for (c, cell) in row.iter().enumerate() {
            if c + 1 == row.len() {
                line.push_str(cell);
            } else {
                let w = widths.get(c).copied().unwrap_or(0);
                let _ = write!(line, "{cell:<w$}  ");
            }
        }
        out.push_str("  ");
        out.push_str(line.trim_end());
        out.push('\n');
    }
    out
}

/// The plan as `check` prints it: tick, instances, signals.
pub fn plan(plan: &Plan) -> String {
    let mut out = format!("tick {} ms\n\n", ms(plan.tick));
    let mut rows = vec![vec![
        "instance".to_owned(),
        "model".to_owned(),
        "period".to_owned(),
        "dims".to_owned(),
    ]];
    for inst in &plan.instances {
        let dims: Vec<String> = inst
            .spec
            .dims
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect();
        rows.push(vec![
            inst.id.clone(),
            inst.model.clone(),
            format!("{} ms", ms(plan.tick.saturating_mul(inst.every))),
            if dims.is_empty() {
                "-".to_owned()
            } else {
                dims.join(" ")
            },
        ]);
    }
    out.push_str(&table(&rows));
    out.push('\n');
    let mut rows = vec![vec![
        "signal".to_owned(),
        "direction".to_owned(),
        "type".to_owned(),
        "shape".to_owned(),
        "max age".to_owned(),
    ]];
    for (_, spec) in plan.layout.iter() {
        rows.push(vec![
            spec.name.clone(),
            direction(spec.direction).to_owned(),
            value_type(spec.ty, spec.text),
            shape(&spec.shape),
            spec.max_age
                .map_or_else(|| "-".to_owned(), |d| format!("{} ms", ms(d))),
        ]);
    }
    out.push_str(&table(&rows));
    let mut rows = vec![vec!["composed input".to_owned(), "elements".to_owned()]];
    for inst in &plan.instances {
        for port in inst.inputs.iter().filter(|p| !p.elements.is_empty()) {
            let sources: Vec<String> = port
                .elements
                .iter()
                .map(|e| match plan.layout.spec(e.signal) {
                    Some(s) if s.shape.is_empty() => s.name.clone(),
                    Some(s) => format!("{}[{}]", s.name, e.index),
                    None => "?".to_owned(),
                })
                .collect();
            rows.push(vec![
                format!("{}.{}", inst.id, port.name),
                sources.join(", "),
            ]);
        }
    }
    if rows.len() > 1 {
        out.push('\n');
        out.push_str(&table(&rows));
    }
    let mut rows = vec![
        [
            "recorder",
            "sink",
            "every",
            "columns",
            "ring rows",
            "ring",
            "dir",
        ]
        .map(str::to_owned)
        .to_vec(),
    ];
    for r in &plan.recorders {
        let c = &r.config;
        rows.push(vec![
            c.id.clone(),
            match c.sink {
                Sink::File => "file",
                Sink::Buffer => "buffer",
            }
            .to_owned(),
            c.every.to_string(),
            r.columns.len().to_string(),
            r.capacity.to_string(),
            bytes(r.ring_bytes()),
            match c.sink {
                Sink::File => c.dir.display().to_string(),
                Sink::Buffer => "-".to_owned(),
            },
        ]);
    }
    if rows.len() > 1 {
        out.push('\n');
        out.push_str(&table(&rows));
    }
    out
}

/// The run summary `run` prints on exit.
pub fn run(s: &RunSummary) -> String {
    format!(
        "cycles {}  published {}  overruns {}  stale {}  cycle mean {} ms  max {} ms",
        s.cycles,
        s.published,
        s.overruns,
        s.stale,
        ms(s.mean_cycle),
        ms(s.max_cycle)
    )
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "tests"
)]
mod tests {
    use std::collections::BTreeMap;

    use taktwerk_core::model::{Causality, Dimension, Instances, ModelInterface, Variable};
    use taktwerk_core::project::Project;
    use taktwerk_core::value::{Dim, Layout};

    use super::*;

    fn var(name: &str, causality: Causality, shape: Vec<Dim>) -> Variable {
        Variable {
            name: name.into(),
            causality,
            ty: ScalarType::F64,
            shape,
            layout: Layout::RowMajor,
            unit: None,
            description: None,
            text: false,
        }
    }

    #[test]
    fn formats_durations() {
        assert_eq!(ms(Duration::from_millis(10)), "10");
        assert_eq!(ms(Duration::from_micros(2500)), "2.5");
        assert_eq!(ms(Duration::from_micros(125)), "0.125");
        assert_eq!(ms(Duration::ZERO), "0");
    }

    #[tokio::test]
    async fn prints_instances_and_signals() {
        let iface = ModelInterface {
            name: "gain".into(),
            dimensions: vec![Dimension {
                name: "n".into(),
                min: None,
                max: None,
                default: Some(2),
            }],
            variables: vec![
                var("u", Causality::Input, vec![Dim::Symbol("n".into())]),
                var("k", Causality::Tunable, vec![]),
                var("y", Causality::Output, vec![Dim::Symbol("n".into())]),
            ],
            instances: Instances::Multiple,
        };
        let project: Project = r#"
[engine]
tick_ms = 5.0
input_max_age_ms = 50.0

[models.gain]
kind = "fmi"
path = "gain.fmu"

[[instance]]
id = "g"
model = "gain"
every = 2
dims = { n = 3 }
"#
        .parse()
        .unwrap();
        let interfaces = BTreeMap::from([("gain".to_owned(), iface)]);
        let plan = Plan::resolve(&project, &interfaces, &mut []).await.unwrap();
        let expected = "tick 5 ms

  instance  model  period  dims
  g         gain   10 ms   n=3

  signal              direction  type  shape   max age
  taktwerk.heartbeat  system     u64   scalar  -
  taktwerk.status     system     i32   scalar  -
  taktwerk.cycle      system     u64   scalar  -
  taktwerk.overruns   system     u64   scalar  -
  taktwerk.stale      system     u64   scalar  -
  g.y                 output     f64   [3]     -
  g.u                 input      f64   [3]     50 ms
  g.k                 tunable    f64   scalar  -
";
        assert_eq!(super::plan(&plan), expected);
    }

    #[test]
    fn formats_bytes() {
        assert_eq!(bytes(512), "512 B");
        assert_eq!(bytes(48_000), "48.0 kB");
        assert_eq!(bytes(1_250_000_000), "1.2 GB");
    }

    #[tokio::test]
    async fn lists_the_recorders() {
        let iface = ModelInterface {
            name: "m".into(),
            dimensions: Vec::new(),
            variables: vec![
                var("u", Causality::Input, vec![]),
                var("y", Causality::Output, vec![Dim::Literal(2)]),
            ],
            instances: Instances::Multiple,
        };
        let project: Project = r#"
[engine]
tick_ms = 10.0

[models.m]
kind = "fmi"
path = "m.fmu"

[[instance]]
id = "a"
model = "m"

[[recorder]]
id = "main"
dir = "/data/rec"

[[recorder]]
id = "slow"
signals = ["a.*"]
every = 10
sink = "buffer"
buffer_s = 60.0
"#
        .parse()
        .unwrap();
        let interfaces = BTreeMap::from([("m".to_owned(), iface)]);
        let plan = Plan::resolve(&project, &interfaces, &mut []).await.unwrap();
        let text = super::plan(&plan);
        // main: 2 columns, 60000 rows of 4 words; slow: 3 columns, 600 rows of 5 words.
        assert!(
            text.ends_with(
                "\n  recorder  sink    every  columns  ring rows  ring     dir\n  \
                 main      file    1      2        60000      1.9 MB   /data/rec\n  \
                 slow      buffer  10     3        600        24.0 kB  -\n"
            ),
            "{text}"
        );
    }

    #[tokio::test]
    async fn lists_the_sources_of_a_composed_input() {
        let iface = ModelInterface {
            name: "m".into(),
            dimensions: Vec::new(),
            variables: vec![
                var("u", Causality::Input, vec![Dim::Literal(3)]),
                var("y", Causality::Output, vec![Dim::Literal(2)]),
            ],
            instances: Instances::Multiple,
        };
        let project: Project = r#"
[engine]
tick_ms = 5.0

[models.m]
kind = "fmi"
path = "m.fmu"

[[instance]]
id = "a"
model = "m"

[[instance]]
id = "b"
model = "m"
inputs = { u = ["plc.p", "a.y[1]", "a.y[0]"] }
"#
        .parse()
        .unwrap();
        let interfaces = BTreeMap::from([("m".to_owned(), iface)]);
        let plan = Plan::resolve(&project, &interfaces, &mut []).await.unwrap();
        let text = super::plan(&plan);
        assert!(
            text.ends_with(
                "\n  composed input  elements\n  b.u             plc.p, a.y[1], a.y[0]\n"
            ),
            "{text}"
        );
        assert!(
            text.contains("  b.u                 output     f64   [3]"),
            "{text}"
        );
    }
}