fmi-rs 0.1.0

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
404
405
406
407
408
409
410
411
412
413
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)]
pub mod file;
pub mod validation;

use std::{ops::Range, str::FromStr};

use crate::{
    fmi2::types::fmi2ValueReference,
    model_description::{Category, DefaultExperiment, ModelDescriptionError, Unit},
};

pub type VariableIndex = u32;

#[derive(Debug, PartialEq)]
pub enum VariableType {
    Real {
        declaredType: Option<String>,
        quantity: Option<String>,
        unit: Option<String>,
        displayUnit: Option<String>,
        relativeQuantity: bool,
        min: Option<String>,
        max: Option<String>,
        nominal: Option<String>,
        unbounded: bool,
        start: Option<String>,
        derivative: Option<VariableIndex>,
        reinit: bool,
    },
    Integer {
        declaredType: Option<String>,
        quantity: Option<String>,
        min: Option<String>,
        max: Option<String>,
        start: Option<String>,
    },
    Boolean {
        declaredType: Option<String>,
        start: Option<String>,
    },
    String {
        declaredType: Option<String>,
        start: Option<String>,
    },
    Enumeration {
        declaredType: String,
        quantity: Option<String>,
        min: Option<String>,
        max: Option<String>,
        start: Option<String>,
    },
}

impl VariableType {
    /// Returns the name of the variable type regardless of the variant.
    pub fn name(&self) -> &'static str {
        match self {
            VariableType::Real { .. } => "Real",
            VariableType::Integer { .. } => "Integer",
            VariableType::Boolean { .. } => "Boolean",
            VariableType::String { .. } => "String",
            VariableType::Enumeration { .. } => "Enumeration",
        }
    }

    /// Returns true if the start attribute is set.
    pub fn has_start(&self) -> bool {
        match self {
            VariableType::Real { start, .. } => start.is_some(),
            VariableType::Integer { start, .. } => start.is_some(),
            VariableType::Boolean { start, .. } => start.is_some(),
            VariableType::String { start, .. } => start.is_some(),
            VariableType::Enumeration { start, .. } => start.is_some(),
        }
    }

    /// Returns the index of the variable this variable is the derivative of.
    pub fn derivative(&self) -> Result<u32, ModelDescriptionError> {
        if let VariableType::Real {
            derivative: Some(index),
            ..
        } = self
        {
            Ok(*index)
        } else {
            Err(ModelDescriptionError::MissingAttribute(
                "derivative".to_owned(),
            ))
        }
    }
}

#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash)]
pub enum Causality {
    Parameter,
    CalculatedParameter,
    Input,
    Output,
    Local,
    Independent,
}

impl FromStr for Causality {
    type Err = ModelDescriptionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "parameter" => Ok(Causality::Parameter),
            "calculatedParameter" => Ok(Causality::CalculatedParameter),
            "input" => Ok(Causality::Input),
            "output" => Ok(Causality::Output),
            "local" => Ok(Causality::Local),
            "independent" => Ok(Causality::Independent),
            _ => Err(ModelDescriptionError::Parse(format!(
                "Unknown causality: {}",
                s
            ))),
        }
    }
}

#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash)]
pub enum Variability {
    Constant,
    Fixed,
    Tunable,
    Discrete,
    Continuous,
}

impl FromStr for Variability {
    type Err = ModelDescriptionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "constant" => Ok(Variability::Constant),
            "fixed" => Ok(Variability::Fixed),
            "tunable" => Ok(Variability::Tunable),
            "discrete" => Ok(Variability::Discrete),
            "continuous" => Ok(Variability::Continuous),
            _ => Err(ModelDescriptionError::Parse(format!(
                "Unknown variability: {}",
                s
            ))),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Initial {
    Exact,
    Approx,
    Calculated,
}

impl FromStr for Initial {
    type Err = ModelDescriptionError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "exact" => Ok(Initial::Exact),
            "approx" => Ok(Initial::Approx),
            "calculated" => Ok(Initial::Calculated),
            _ => Err(ModelDescriptionError::Parse(format!(
                "Unknown intial: {}",
                s
            ))),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Hash)]
pub enum DependencyKind {
    Dependent,
    Constant,
    Fixed,
    Tunable,
    Discrete,
}

impl FromStr for DependencyKind {
    type Err = ModelDescriptionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "dependent" => Ok(DependencyKind::Dependent),
            "constant" => Ok(DependencyKind::Constant),
            "fixed" => Ok(DependencyKind::Fixed),
            "tunable" => Ok(DependencyKind::Tunable),
            "discrete" => Ok(DependencyKind::Discrete),
            _ => Err(ModelDescriptionError::Parse(format!(
                "Unknown dependency kind: {}",
                s
            ))),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Hash)]
pub enum VariableNamingConvention {
    Flat,
    Structured,
}

impl FromStr for VariableNamingConvention {
    type Err = ModelDescriptionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "flat" => Ok(VariableNamingConvention::Flat),
            "structured" => Ok(VariableNamingConvention::Structured),
            _ => Err(ModelDescriptionError::Parse(format!(
                "Unknown variable naming convention: {}",
                s
            ))),
        }
    }
}

#[derive(Debug)]
pub struct Item {
    pub name: String,
    pub value: i32,
    pub description: Option<String>,
    pub range: Range<usize>,
}

#[derive(Debug)]
pub enum SimpleType {
    Real {
        name: String,
        description: Option<String>,
        quantity: Option<String>,
        unit: Option<String>,
        displayUnit: Option<String>,
        relativeQuantity: bool,
        min: Option<f32>,
        max: Option<f32>,
        nominal: Option<f32>,
        unbounded: bool,
        range: Range<usize>,
    },
    Integer {
        name: String,
        description: Option<String>,
        quantity: Option<String>,
        min: Option<i32>,
        max: Option<i32>,
        range: Range<usize>,
    },
    Boolean {
        name: String,
        description: Option<String>,
        range: Range<usize>,
    },
    String {
        name: String,
        description: Option<String>,
        range: Range<usize>,
    },
    Enumeration {
        name: String,
        description: Option<String>,
        items: Vec<Item>,
        quantity: Option<String>,
        range: Range<usize>,
    },
}

impl SimpleType {
    /// Returns the name of the type definition regardless of the variant.
    pub fn name(&self) -> &str {
        match self {
            SimpleType::Real { name, .. }
            | SimpleType::Integer { name, .. }
            | SimpleType::Boolean { name, .. }
            | SimpleType::String { name, .. }
            | SimpleType::Enumeration { name, .. } => name,
        }
    }
}

#[derive(Debug)]
pub struct CoSimulation {
    pub sourceFiles: Vec<String>,
    pub modelIdentifier: String,
    pub needsExecutionTool: bool,
    pub canHandleVariableCommunicationStepSize: bool,
    pub canInterpolateInputs: bool,
    pub maxOutputDerivativeOrder: u32,
    pub canRunAsynchronuously: bool,
    pub canBeInstantiatedOnlyOncePerProcess: bool,
    pub canNotUseMemoryManagementFunctions: bool,
    pub canGetAndSetFMUstate: bool,
    pub canSerializeFMUstate: bool,
    pub providesDirectionalDerivative: bool,
    pub range: Range<usize>,
}

#[derive(Debug)]
pub struct ModelExchange {
    pub sourceFiles: Vec<String>,
    pub modelIdentifier: String,
    pub needsExecutionTool: bool,
    pub completedIntegratorStepNotNeeded: bool,
    pub canBeInstantiatedOnlyOncePerProcess: bool,
    pub canNotUseMemoryManagementFunctions: bool,
    pub canGetAndSetFMUstate: bool,
    pub canSerializeFMUstate: bool,
    pub providesDirectionalDerivative: bool,
    pub range: Range<usize>,
}

#[derive(Debug)]
pub struct ScalarVariable {
    pub variableType: VariableType,
    pub name: String,
    pub valueReference: fmi2ValueReference,
    pub description: Option<String>,
    pub causality: Causality,
    pub variability: Variability,
    pub initial: Option<Initial>,
    pub canHandleMultipleSetPerTimeInstant: bool,
    pub range: Range<usize>,
}

#[derive(Debug)]
pub struct Unknown {
    pub index: VariableIndex,
    pub dependencies: Option<Vec<VariableIndex>>,
    pub dependenciesKind: Option<Vec<DependencyKind>>,
    pub range: Range<usize>,
}

#[derive(Debug)]
pub struct ModelDescription {
    pub modelName: String,
    pub guid: String,
    pub description: Option<String>,
    pub author: Option<String>,
    pub version: Option<String>,
    pub copyright: Option<String>,
    pub license: Option<String>,
    pub generationTool: Option<String>,
    pub generationDateAndTime: Option<String>,
    pub variableNamingConvention: VariableNamingConvention,
    pub logCategories: Vec<Category>,
    pub defaultExperiment: Option<DefaultExperiment>,
    pub modelExchange: Option<ModelExchange>,
    pub coSimulation: Option<CoSimulation>,
    pub unitDefintions: Vec<Unit>,
    pub typeDefinitions: Vec<SimpleType>,
    pub modelVariables: Vec<ScalarVariable>,
    pub numberOfEventIndicators: u32,
    pub outputs: Vec<Unknown>,
    pub derivatives: Vec<Unknown>,
    pub initialUnknowns: Vec<Unknown>,
}

impl ModelDescription {
    /// Returns the variable found with the given name.
    pub fn variable_by_name(&self, name: &str) -> Result<&ScalarVariable, ModelDescriptionError> {
        self.modelVariables
            .iter()
            .find(|v| v.name == name)
            .ok_or_else(|| ModelDescriptionError::VariableName(name.to_owned()))
    }

    /// Returns the index for the given variable name
    pub fn variable_index_by_name(&self, name: &str) -> Result<usize, ModelDescriptionError> {
        self.modelVariables
            .iter()
            .position(|v| v.name == name)
            .ok_or_else(|| ModelDescriptionError::VariableName(name.to_owned()))
    }

    /// Returns the variable with the given index as a Result
    pub fn variable_by_index(
        &self,
        index: VariableIndex,
    ) -> Result<&ScalarVariable, ModelDescriptionError> {
        let Some(zero_based_index) = index.checked_sub(1) else {
            return Err(ModelDescriptionError::VariableIndex(index));
        };

        self.modelVariables
            .get(zero_based_index as usize)
            .ok_or(ModelDescriptionError::VariableIndex(index))
    }

    pub fn get_unit<'a>(&'a self, variable: &'a ScalarVariable) -> Option<&'a str> {
        if let VariableType::Real {
            unit, declaredType, ..
        } = &variable.variableType
        {
            if let Some(unit) = unit {
                return Some(unit);
            } else if let Some(declaredType) = declaredType {
                for simple_type in &self.typeDefinitions {
                    if let SimpleType::Real { name, unit, .. } = simple_type
                        && name == declaredType
                    {
                        return unit.as_deref();
                    }
                }
            }
        }
        None
    }

    pub fn get_type_definition(&self, name: &str) -> Option<&SimpleType> {
        self.typeDefinitions.iter().find(|t| t.name() == name)
    }
}