fmi-rs 0.3.1

Functional Mock-up Interface (FMI) for Rust
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
use std::collections::{HashMap, HashSet};

use crate::{
    fmi3::types::fmi3ValueReference,
    model_description::{
        ValidationError,
        fmi3::{
            Causality, Initial, ModelDescription, ModelVariable, Unknown, Variability,
            VariableNamingConvention, VariableType,
        },
        validation::validate_structured_variable_name,
    },
};

impl ModelDescription {
    pub fn validate(&self) -> Vec<ValidationError> {
        let mut problems = vec![];

        let mut independent_variable: Option<&ModelVariable> = None;
        let mut value_references: HashMap<u32, &ModelVariable> = HashMap::new();
        let mut variable_names: HashMap<&String, &ModelVariable> = HashMap::new();

        if self.modelExchange.is_none()
            && self.coSimulation.is_none()
            && self.scheduledExecution.is_none()
        {
            problems.push(ValidationError {
                range: vec![],
                message: "No interface type defined.".to_string(),
            });
        }

        // validate model variables
        for variable in &self.modelVariables {
            // validate variable name
            if variable.name.is_empty() {
                problems.push(ValidationError {
                    range: vec![variable.range.clone()],
                    message: "Variable name cannot be empty.".to_string(),
                });
            } else if self.variableNamingConvention == VariableNamingConvention::Structured
                && let Err(message) = validate_structured_variable_name(&variable.name)
            {
                problems.push(ValidationError {
                        range: vec![variable.range.clone()],
                        message: format!("Variable name '{}' does not conform to the structured naming convention: {}", variable.name, message),
                    });
            }

            // check for duplicate value references
            if let Some(duplicate) = value_references.get(&variable.valueReference) {
                problems.push(ValidationError {
                    range: vec![duplicate.range.clone(), variable.range.clone()],
                    message: format!("Duplicate value reference: {}", variable.valueReference),
                });
            } else {
                value_references.insert(variable.valueReference, variable);
            }

            // check for duplicate variable names
            if let Some(duplicate) = variable_names.get(&variable.name) {
                problems.push(ValidationError {
                    range: vec![duplicate.range.clone(), variable.range.clone()],
                    message: format!("Duplicate variable name: '{}'", variable.name),
                });
            } else {
                variable_names.insert(&variable.name, variable);
            }

            // assert no start for variability "calculated"
            if let Some(Initial::Calculated) = variable.initial
                && variable.variableType.has_start()
            {
                problems.push(ValidationError {
                    range: vec![variable.range.clone()],
                    message: format!(
                        "Variable '{}' is calculated but provides a start value.",
                        variable.name
                    ),
                });
            }

            // assert required start values
            if !matches!(variable.variableType, VariableType::Clock { .. }) {
                let is_exact_or_approx = matches!(
                    variable.initial,
                    Some(Initial::Exact) | Some(Initial::Approx)
                );

                if (is_exact_or_approx || variable.causality == Causality::Input)
                    && !variable.variableType.has_start()
                {
                    problems.push(ValidationError {
                        range: vec![variable.range.clone()],
                        message: format!("Variable '{}' has no start value.", variable.name),
                    });
                }
            }

            // check independent variable
            if variable.causality == Causality::Independent {
                if let Some(independent_variable) = independent_variable {
                    problems.push(ValidationError {
                        range: vec![independent_variable.range.clone(), variable.range.clone()],
                        message: "There can only be one independent variable.".to_string(),
                    });
                } else {
                    independent_variable = Some(variable);
                }

                if !matches!(
                    variable.variableType,
                    VariableType::Float32 { .. } | VariableType::Float64 { .. }
                ) {
                    problems.push(ValidationError {
                        range: vec![variable.range.clone()],
                        message: "The independent variable must be a Float32 or Float64 variable."
                            .to_string(),
                    });
                }

                if variable.variability != Variability::Continuous {
                    problems.push(ValidationError {
                        range: vec![variable.range.clone()],
                        message: "The independent variable must be continuous.".to_string(),
                    });
                }

                if variable.variableType.has_start() {
                    problems.push(ValidationError {
                        range: vec![variable.range.clone()],
                        message: "The independent variable must not have a start value."
                            .to_string(),
                    });
                }
            }

            // check combination of causality and variability, and initial
            match (
                &variable.causality,
                &variable.variability,
                &variable.initial,
            ) {
                (Causality::StructuralParameter, Variability::Fixed, Some(Initial::Exact)) => {}
                (Causality::StructuralParameter, Variability::Tunable, Some(Initial::Exact)) => {}
                (Causality::Parameter, Variability::Fixed, Some(Initial::Exact)) => {}
                (Causality::Parameter, Variability::Tunable, Some(Initial::Exact)) => {}
                (Causality::CalculatedParameter, Variability::Fixed, Some(Initial::Calculated)) => {
                }
                (Causality::CalculatedParameter, Variability::Fixed, Some(Initial::Approx)) => {}
                (
                    Causality::CalculatedParameter,
                    Variability::Tunable,
                    Some(Initial::Calculated),
                ) => {}
                (Causality::CalculatedParameter, Variability::Tunable, Some(Initial::Approx)) => {}
                (Causality::Input, Variability::Discrete, Some(Initial::Exact)) => {}
                (Causality::Input, Variability::Continuous, Some(Initial::Exact)) => {}
                (Causality::Output, Variability::Constant, Some(Initial::Exact)) => {}
                (Causality::Output, Variability::Discrete, Some(Initial::Calculated)) => {}
                (Causality::Output, Variability::Discrete, Some(Initial::Exact)) => {}
                (Causality::Output, Variability::Discrete, Some(Initial::Approx)) => {}
                (Causality::Output, Variability::Continuous, Some(Initial::Calculated)) => {}
                (Causality::Output, Variability::Continuous, Some(Initial::Exact)) => {}
                (Causality::Output, Variability::Continuous, Some(Initial::Approx)) => {}
                (Causality::Local, Variability::Constant, Some(Initial::Exact)) => {}
                (Causality::Local, Variability::Fixed, Some(Initial::Calculated)) => {}
                (Causality::Local, Variability::Fixed, Some(Initial::Approx)) => {}
                (Causality::Local, Variability::Tunable, Some(Initial::Calculated)) => {}
                (Causality::Local, Variability::Tunable, Some(Initial::Approx)) => {}
                (Causality::Local, Variability::Discrete, Some(Initial::Calculated)) => {}
                (Causality::Local, Variability::Discrete, Some(Initial::Exact)) => {}
                (Causality::Local, Variability::Discrete, Some(Initial::Approx)) => {}
                (Causality::Local, Variability::Continuous, Some(Initial::Calculated)) => {}
                (Causality::Local, Variability::Continuous, Some(Initial::Exact)) => {}
                (Causality::Local, Variability::Continuous, Some(Initial::Approx)) => {}
                (Causality::Independent, Variability::Continuous, None) => {}
                _ => {
                    problems.push(ValidationError {
                        range: vec![variable.range.clone()],
                        message: format!(
                            "Illegal combination of causality '{:?}', variability '{:?}', and initial '{:?}' for variable '{}'.",
                            variable.causality, variable.variability, variable.initial, variable.name
                        ),
                    });
                }
            }
        }

        // validate outputs
        for unknown in &self.outputs {
            problems.extend(self.validate_unknown(unknown));
        }

        let expected_output_vrs = self
            .modelVariables
            .iter()
            .filter(|v| v.causality == Causality::Output)
            .map(|v| v.valueReference)
            .collect::<HashSet<u32>>();

        let actual_output_vrs = self
            .outputs
            .iter()
            .map(|u| u.valueReference)
            .collect::<HashSet<u32>>();

        if expected_output_vrs != actual_output_vrs {
            problems.push(ValidationError {
                range: vec![],
                message: format!("The the outputs do not match the expected set of variables. Expected: {:?}, Actual: {:?}", expected_output_vrs, actual_output_vrs),
            });
        }

        // validate continuous state derivatives
        for unknown in &self.derivatives {
            problems.extend(self.validate_unknown(unknown));
            if let Ok(derivative_variable) =
                self.variable_by_value_reference(unknown.valueReference)
                && !matches!(derivative_variable.variability, Variability::Continuous)
            {
                problems.push(ValidationError {
                    range: vec![unknown.range.clone()],
                    message:
                        "Event indicators must be continuous variables of type Float32 or Float64."
                            .to_string(),
                });
            }
        }

        // validate clocked states
        for unknown in &self.clockedStates {
            problems.extend(self.validate_unknown(unknown));

            if let Ok(clocked_state_variable) =
                self.variable_by_value_reference(unknown.valueReference)
            {
                if clocked_state_variable.clocks.is_empty() {
                    problems.push(ValidationError {
                        range: vec![unknown.range.clone()],
                        message: "Clocked states must have at least one clock.".to_string(),
                    });
                }

                if clocked_state_variable.variableType.previous().is_none() {
                    problems.push(ValidationError {
                        range: vec![clocked_state_variable.range.clone(), unknown.range.clone()],
                        message: "Clocked states must have a previous value.".to_string(),
                    });
                }

                if matches!(
                    clocked_state_variable.variableType,
                    VariableType::Clock { .. }
                ) {
                    problems.push(ValidationError {
                        range: vec![unknown.range.clone()],
                        message: "Clocked states must not be clock variables.".to_string(),
                    });
                }
            }
        }

        // validate initial unknowns
        for unknown in &self.initialUnknowns {
            problems.extend(self.validate_unknown(unknown));
        }

        let mut expected_initial_unknown_vrs = HashSet::new();

        for variable in &self.modelVariables {
            if (variable.causality == Causality::Output
                && matches!(
                    variable.initial,
                    Some(Initial::Approx) | Some(Initial::Calculated)
                )
                && !matches!(variable.variableType, VariableType::Clock { .. })
                && variable.clocks.is_empty())
                || variable.causality == Causality::CalculatedParameter
            {
                expected_initial_unknown_vrs.insert(variable.valueReference);
            }
        }

        for derivative in &self.derivatives {
            if let Ok(derivative_variable) =
                self.variable_by_value_reference(derivative.valueReference)
            {
                if matches!(
                    derivative_variable.initial,
                    Some(Initial::Approx) | Some(Initial::Calculated)
                ) {
                    expected_initial_unknown_vrs.insert(derivative_variable.valueReference);
                }

                if let Some(continuous_state_vr) = derivative_variable.variableType.derivative()
                    && let Ok(continuous_state_variable) =
                        self.variable_by_value_reference(continuous_state_vr)
                    && matches!(
                        continuous_state_variable.initial,
                        Some(Initial::Approx) | Some(Initial::Calculated)
                    )
                {
                    expected_initial_unknown_vrs.insert(continuous_state_vr);
                }
            }
        }

        let actual_initial_unknown_vrs = self
            .initialUnknowns
            .iter()
            .map(|u| u.valueReference)
            .collect::<HashSet<u32>>();

        let clocked_vrs: HashSet<u32> = self
            .modelVariables
            .iter()
            .filter(|v| !v.clocks.is_empty())
            .map(|v| v.valueReference)
            .collect();

        let allowed_initial_unknown_vrs = expected_initial_unknown_vrs
            .union(&clocked_vrs)
            .copied()
            .collect::<HashSet<u32>>();

        if !expected_initial_unknown_vrs.is_subset(&actual_initial_unknown_vrs)
            || !actual_initial_unknown_vrs.is_subset(&allowed_initial_unknown_vrs)
        {
            problems.push(ValidationError {
                range: vec![],
                message: format!(
                    "The initial unknowns do not match the expected set of variables. Expected: {:?}, Actual: {:?}",
                    expected_initial_unknown_vrs, actual_initial_unknown_vrs
                ),
            });
        }

        // validate event indicators
        for unknown in self.eventIndicators.iter() {
            problems.extend(self.validate_unknown(unknown));

            if let Ok(event_indicator_variable) =
                self.variable_by_value_reference(unknown.valueReference)
                && !matches!(
                    event_indicator_variable.variableType,
                    VariableType::Float32 { .. } | VariableType::Float64 { .. }
                )
            {
                problems.push(ValidationError {
                    range: vec![unknown.range.clone()],
                    message: "The variable type of the event indicators must be Float32 or Float64"
                        .to_string(),
                });
            }
        }

        problems
    }

    /// validate the value reference, dependencies, and dependencies kind
    fn validate_unknown(&self, unknown: &Unknown) -> Vec<ValidationError> {
        let mut problems = vec![];

        if !self.is_valid_value_reference(unknown.valueReference) {
            problems.push(ValidationError {
                range: vec![unknown.range.clone()],
                message: format!("Illegal value reference: {}", unknown.valueReference),
            });
        }

        if let Some(dependencies) = &unknown.dependencies {
            for dependency_vr in dependencies {
                if !self.is_valid_value_reference(*dependency_vr) {
                    problems.push(ValidationError {
                        range: vec![unknown.range.clone()],
                        message: format!(
                            "Illegal value reference in dependencies: {}",
                            dependency_vr
                        ),
                    });
                }
            }

            if let Some(dependencies_kind) = &unknown.dependenciesKind
                && dependencies.len() != dependencies_kind.len()
            {
                problems.push(ValidationError {
                    range: vec![unknown.range.clone()],
                    message: "The number of elements in dependenciesKind does not match the number of elements in dependencies.".to_string(),
                });
            }
        }

        problems
    }

    fn is_valid_value_reference(&self, valueReference: fmi3ValueReference) -> bool {
        self.modelVariables
            .iter()
            .any(|v| v.valueReference == valueReference)
    }
}