mdxml 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mdxml/__init__.py +39 -0
- mdxml/__main__.py +5 -0
- mdxml/_cli.py +96 -0
- mdxml/_convert.py +151 -0
- mdxml/_dict.py +42 -0
- mdxml/_errors.py +39 -0
- mdxml/_grammar.py +259 -0
- mdxml/_header.py +92 -0
- mdxml/_lookup.py +54 -0
- mdxml/_protocols.py +135 -0
- mdxml/_read.py +75 -0
- mdxml/_reader.py +191 -0
- mdxml/_schema.py +131 -0
- mdxml/_source.py +192 -0
- mdxml/_variables.py +426 -0
- mdxml/fmi2/__init__.py +73 -0
- mdxml/fmi2/_annotations.py +34 -0
- mdxml/fmi2/_header.py +525 -0
- mdxml/fmi2/_model.py +73 -0
- mdxml/fmi2/_structure.py +100 -0
- mdxml/fmi2/_variables.py +323 -0
- mdxml/fmi3/__init__.py +125 -0
- mdxml/fmi3/_annotations.py +43 -0
- mdxml/fmi3/_header.py +635 -0
- mdxml/fmi3/_model.py +59 -0
- mdxml/fmi3/_structure.py +103 -0
- mdxml/fmi3/_variables.py +603 -0
- mdxml/py.typed +0 -0
- mdxml-0.1.0.dist-info/METADATA +202 -0
- mdxml-0.1.0.dist-info/RECORD +33 -0
- mdxml-0.1.0.dist-info/WHEEL +4 -0
- mdxml-0.1.0.dist-info/entry_points.txt +3 -0
- mdxml-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""FMI 2.0 Tool Annotations: ``<Tool name="…">`` elements, kept as raw XML."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from mdxml._grammar import Collect, Raw
|
|
8
|
+
from mdxml._schema import Frame, attributes, required_text, table
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
12
|
+
class ToolAnnotation:
|
|
13
|
+
"""A ``<Tool>`` element of ``VendorAnnotations`` or a variable's ``Annotations``.
|
|
14
|
+
|
|
15
|
+
``xml`` is the element's content exactly as written in the file, so it can
|
|
16
|
+
be parsed again by the caller; mdxml doesn't interpret it.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
name: str
|
|
20
|
+
xml: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
TOOL_ATTRS = table(required_text("name", "name"))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _build_tool(frame: Frame, xml: str, *, strict: bool) -> ToolAnnotation:
|
|
27
|
+
return ToolAnnotation(**attributes(frame, TOOL_ATTRS, strict=strict), xml=xml)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
TOOL = Raw(_build_tool)
|
|
31
|
+
"""Rule for a ``<Tool>`` element."""
|
|
32
|
+
|
|
33
|
+
CONTAINER = Collect("Tool")
|
|
34
|
+
"""Rule for ``VendorAnnotations`` / ``Annotations``: the tuple of its Tool Annotations."""
|
mdxml/fmi2/_header.py
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
"""The FMI 2.0 Model Header: everything in ``fmiModelDescription`` before ``ModelVariables``.
|
|
2
|
+
|
|
3
|
+
Classes mirror the FMI 2.0 XSD (``schema/fmi2``): one per element, field
|
|
4
|
+
names are the XSD attribute names in snake_case, and defaults are the XSD
|
|
5
|
+
defaults. ``SourceFiles/File`` elements, which only carry a name, become a
|
|
6
|
+
tuple of file names.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from enum import Enum
|
|
15
|
+
from types import MappingProxyType
|
|
16
|
+
from typing import Any, cast
|
|
17
|
+
|
|
18
|
+
from mdxml import _convert as c
|
|
19
|
+
from mdxml._grammar import SKIP, Builder, Grammar
|
|
20
|
+
from mdxml._lookup import Named
|
|
21
|
+
from mdxml._schema import EMPTY, Attr, Frame, attributes, double, flag, required_text, table, text
|
|
22
|
+
from mdxml.fmi2 import _annotations as annotations_rule
|
|
23
|
+
from mdxml.fmi2._annotations import ToolAnnotation
|
|
24
|
+
|
|
25
|
+
# --- Enums ----------------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class VariableNamingConvention(str, Enum):
|
|
29
|
+
"""``variableNamingConvention`` on ``fmiModelDescription``."""
|
|
30
|
+
|
|
31
|
+
FLAT = "flat"
|
|
32
|
+
STRUCTURED = "structured"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# --- Interface Types ------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
39
|
+
class ModelExchange:
|
|
40
|
+
"""The ``ModelExchange`` Interface Type."""
|
|
41
|
+
|
|
42
|
+
model_identifier: str
|
|
43
|
+
needs_execution_tool: bool = False
|
|
44
|
+
completed_integrator_step_not_needed: bool = False
|
|
45
|
+
can_be_instantiated_only_once_per_process: bool = False
|
|
46
|
+
can_not_use_memory_management_functions: bool = False
|
|
47
|
+
can_get_and_set_fmu_state: bool = False
|
|
48
|
+
can_serialize_fmu_state: bool = False
|
|
49
|
+
provides_directional_derivative: bool = False
|
|
50
|
+
source_files: tuple[str, ...] = ()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
54
|
+
class CoSimulation:
|
|
55
|
+
"""The ``CoSimulation`` Interface Type."""
|
|
56
|
+
|
|
57
|
+
model_identifier: str
|
|
58
|
+
needs_execution_tool: bool = False
|
|
59
|
+
can_handle_variable_communication_step_size: bool = False
|
|
60
|
+
can_interpolate_inputs: bool = False
|
|
61
|
+
max_output_derivative_order: int = 0
|
|
62
|
+
can_run_asynchronuously: bool = False # sic: the XSD's spelling
|
|
63
|
+
can_be_instantiated_only_once_per_process: bool = False
|
|
64
|
+
can_not_use_memory_management_functions: bool = False
|
|
65
|
+
can_get_and_set_fmu_state: bool = False
|
|
66
|
+
can_serialize_fmu_state: bool = False
|
|
67
|
+
provides_directional_derivative: bool = False
|
|
68
|
+
source_files: tuple[str, ...] = ()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# --- Units ----------------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
75
|
+
class BaseUnit:
|
|
76
|
+
"""A unit's exponents of the SI base units, plus ``factor`` and ``offset`` to convert to them.
|
|
77
|
+
|
|
78
|
+
Field names keep the XSD's case-sensitive SI symbols (``A`` is ampere, ``K`` is kelvin).
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
kg: int = 0
|
|
82
|
+
m: int = 0
|
|
83
|
+
s: int = 0
|
|
84
|
+
A: int = 0
|
|
85
|
+
K: int = 0
|
|
86
|
+
mol: int = 0
|
|
87
|
+
cd: int = 0
|
|
88
|
+
rad: int = 0
|
|
89
|
+
factor: float = 1.0
|
|
90
|
+
offset: float = 0.0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
94
|
+
class DisplayUnit:
|
|
95
|
+
"""A unit to display values in, converted from the unit by ``factor`` and ``offset``."""
|
|
96
|
+
|
|
97
|
+
name: str
|
|
98
|
+
factor: float = 1.0
|
|
99
|
+
offset: float = 0.0
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
103
|
+
class Unit:
|
|
104
|
+
"""A ``Unit`` in ``UnitDefinitions``."""
|
|
105
|
+
|
|
106
|
+
name: str
|
|
107
|
+
base_unit: BaseUnit | None = None
|
|
108
|
+
display_units: tuple[DisplayUnit, ...] = ()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# --- Type definitions -----------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
115
|
+
class RealType:
|
|
116
|
+
"""A ``SimpleType`` with a ``Real`` element."""
|
|
117
|
+
|
|
118
|
+
name: str
|
|
119
|
+
description: str | None = None
|
|
120
|
+
quantity: str | None = None
|
|
121
|
+
unit: str | None = None
|
|
122
|
+
display_unit: str | None = None
|
|
123
|
+
relative_quantity: bool = False
|
|
124
|
+
min: float | None = None
|
|
125
|
+
max: float | None = None
|
|
126
|
+
nominal: float | None = None
|
|
127
|
+
unbounded: bool = False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
131
|
+
class IntegerType:
|
|
132
|
+
"""A ``SimpleType`` with an ``Integer`` element."""
|
|
133
|
+
|
|
134
|
+
name: str
|
|
135
|
+
description: str | None = None
|
|
136
|
+
quantity: str | None = None
|
|
137
|
+
min: int | None = None
|
|
138
|
+
max: int | None = None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
142
|
+
class BooleanType:
|
|
143
|
+
"""A ``SimpleType`` with a ``Boolean`` element."""
|
|
144
|
+
|
|
145
|
+
name: str
|
|
146
|
+
description: str | None = None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
150
|
+
class StringType:
|
|
151
|
+
"""A ``SimpleType`` with a ``String`` element."""
|
|
152
|
+
|
|
153
|
+
name: str
|
|
154
|
+
description: str | None = None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
158
|
+
class Item:
|
|
159
|
+
"""One allowed value of an ``Enumeration`` type."""
|
|
160
|
+
|
|
161
|
+
name: str
|
|
162
|
+
value: int
|
|
163
|
+
description: str | None = None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
167
|
+
class EnumerationType:
|
|
168
|
+
"""A ``SimpleType`` with an ``Enumeration`` element."""
|
|
169
|
+
|
|
170
|
+
name: str
|
|
171
|
+
description: str | None = None
|
|
172
|
+
quantity: str | None = None
|
|
173
|
+
items: tuple[Item, ...] = ()
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
TypeDefinition = RealType | IntegerType | BooleanType | StringType | EnumerationType
|
|
177
|
+
"""Any ``SimpleType`` in ``TypeDefinitions``."""
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# --- Log categories and default experiment --------------------------------------------------
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
184
|
+
class Category:
|
|
185
|
+
"""A log category in ``LogCategories``."""
|
|
186
|
+
|
|
187
|
+
name: str
|
|
188
|
+
description: str | None = None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
192
|
+
class DefaultExperiment:
|
|
193
|
+
"""Default simulation settings suggested by the FMU."""
|
|
194
|
+
|
|
195
|
+
start_time: float | None = None
|
|
196
|
+
stop_time: float | None = None
|
|
197
|
+
tolerance: float | None = None
|
|
198
|
+
step_size: float | None = None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# --- Model Header ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
205
|
+
class ModelHeader:
|
|
206
|
+
"""Everything in an FMI 2.0 Model Description before ``ModelVariables``.
|
|
207
|
+
|
|
208
|
+
Annotations (``VendorAnnotations``) aren't part of the Model Header.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
fmi_version: str
|
|
212
|
+
model_name: str
|
|
213
|
+
guid: str
|
|
214
|
+
description: str | None = None
|
|
215
|
+
author: str | None = None
|
|
216
|
+
version: str | None = None
|
|
217
|
+
copyright: str | None = None
|
|
218
|
+
license: str | None = None
|
|
219
|
+
generation_tool: str | None = None
|
|
220
|
+
generation_date_and_time: datetime | None = None
|
|
221
|
+
variable_naming_convention: VariableNamingConvention | str = VariableNamingConvention.FLAT
|
|
222
|
+
number_of_event_indicators: int | None = None
|
|
223
|
+
model_exchange: ModelExchange | None = None
|
|
224
|
+
co_simulation: CoSimulation | None = None
|
|
225
|
+
unit_definitions: Named[Unit] = field(default_factory=Named)
|
|
226
|
+
type_definitions: Named[TypeDefinition] = field(default_factory=Named)
|
|
227
|
+
log_categories: Named[Category] = field(default_factory=Named)
|
|
228
|
+
default_experiment: DefaultExperiment | None = None
|
|
229
|
+
vendor_annotations: tuple[ToolAnnotation, ...] | None = None
|
|
230
|
+
"""``None`` unless read with ``annotations=True``."""
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def instantiation_token(self) -> str:
|
|
234
|
+
"""The ``guid``, under its FMI 3.0 name, so version-independent code can use one name."""
|
|
235
|
+
return self.guid
|
|
236
|
+
|
|
237
|
+
def __post_init__(self) -> None:
|
|
238
|
+
"""Accept plain tuples for the definition lists, so headers can be built by hand."""
|
|
239
|
+
for name in ("unit_definitions", "type_definitions", "log_categories"):
|
|
240
|
+
value = getattr(self, name)
|
|
241
|
+
if not isinstance(value, Named):
|
|
242
|
+
object.__setattr__(self, name, Named(value))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# --- Attribute tables -----------------------------------------------------------------------
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _int(xml: str, field: str) -> Attr:
|
|
249
|
+
return Attr(xml, field, c.INT)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
ROOT_ATTRS = table(
|
|
253
|
+
required_text("fmiVersion", "fmi_version"),
|
|
254
|
+
required_text("modelName", "model_name"),
|
|
255
|
+
required_text("guid", "guid"),
|
|
256
|
+
text("description", "description"),
|
|
257
|
+
text("author", "author"),
|
|
258
|
+
text("version", "version"),
|
|
259
|
+
text("copyright", "copyright"),
|
|
260
|
+
text("license", "license"),
|
|
261
|
+
text("generationTool", "generation_tool"),
|
|
262
|
+
Attr("generationDateAndTime", "generation_date_and_time", c.to_datetime),
|
|
263
|
+
Attr("variableNamingConvention", "variable_naming_convention", c.EnumConverter(VariableNamingConvention)),
|
|
264
|
+
Attr("numberOfEventIndicators", "number_of_event_indicators", c.UNSIGNED_INT),
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
_COMMON_INTERFACE_ATTRS = (
|
|
268
|
+
required_text("modelIdentifier", "model_identifier"),
|
|
269
|
+
flag("needsExecutionTool", "needs_execution_tool"),
|
|
270
|
+
flag("canBeInstantiatedOnlyOncePerProcess", "can_be_instantiated_only_once_per_process"),
|
|
271
|
+
flag("canNotUseMemoryManagementFunctions", "can_not_use_memory_management_functions"),
|
|
272
|
+
flag("canGetAndSetFMUstate", "can_get_and_set_fmu_state"),
|
|
273
|
+
flag("canSerializeFMUstate", "can_serialize_fmu_state"),
|
|
274
|
+
flag("providesDirectionalDerivative", "provides_directional_derivative"),
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
MODEL_EXCHANGE_ATTRS = table(
|
|
278
|
+
*_COMMON_INTERFACE_ATTRS,
|
|
279
|
+
flag("completedIntegratorStepNotNeeded", "completed_integrator_step_not_needed"),
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
CO_SIMULATION_ATTRS = table(
|
|
283
|
+
*_COMMON_INTERFACE_ATTRS,
|
|
284
|
+
flag("canHandleVariableCommunicationStepSize", "can_handle_variable_communication_step_size"),
|
|
285
|
+
flag("canInterpolateInputs", "can_interpolate_inputs"),
|
|
286
|
+
Attr("maxOutputDerivativeOrder", "max_output_derivative_order", c.UNSIGNED_INT),
|
|
287
|
+
flag("canRunAsynchronuously", "can_run_asynchronuously"),
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
FILE_ATTRS = table(required_text("name", "name"))
|
|
291
|
+
|
|
292
|
+
UNIT_ATTRS = table(required_text("name", "name"))
|
|
293
|
+
|
|
294
|
+
BASE_UNIT_ATTRS = table(
|
|
295
|
+
*(_int(symbol, symbol) for symbol in ("kg", "m", "s", "A", "K", "mol", "cd", "rad")),
|
|
296
|
+
double("factor", "factor"),
|
|
297
|
+
double("offset", "offset"),
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
DISPLAY_UNIT_ATTRS = table(
|
|
301
|
+
required_text("name", "name"),
|
|
302
|
+
double("factor", "factor"),
|
|
303
|
+
double("offset", "offset"),
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
SIMPLE_TYPE_ATTRS = table(
|
|
307
|
+
required_text("name", "name"),
|
|
308
|
+
text("description", "description"),
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
REAL_ATTRS = table(
|
|
312
|
+
text("quantity", "quantity"),
|
|
313
|
+
text("unit", "unit"),
|
|
314
|
+
text("displayUnit", "display_unit"),
|
|
315
|
+
flag("relativeQuantity", "relative_quantity"),
|
|
316
|
+
double("min", "min"),
|
|
317
|
+
double("max", "max"),
|
|
318
|
+
double("nominal", "nominal"),
|
|
319
|
+
flag("unbounded", "unbounded"),
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
INTEGER_ATTRS = table(
|
|
323
|
+
text("quantity", "quantity"),
|
|
324
|
+
_int("min", "min"),
|
|
325
|
+
_int("max", "max"),
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
ENUMERATION_ATTRS = table(text("quantity", "quantity"))
|
|
329
|
+
|
|
330
|
+
ITEM_ATTRS = table(
|
|
331
|
+
required_text("name", "name"),
|
|
332
|
+
Attr("value", "value", c.INT, required=True),
|
|
333
|
+
text("description", "description"),
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
CATEGORY_ATTRS = table(
|
|
337
|
+
required_text("name", "name"),
|
|
338
|
+
text("description", "description"),
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
DEFAULT_EXPERIMENT_ATTRS = table(
|
|
342
|
+
double("startTime", "start_time"),
|
|
343
|
+
double("stopTime", "stop_time"),
|
|
344
|
+
double("tolerance", "tolerance"),
|
|
345
|
+
double("stepSize", "step_size"),
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# --- Builders -------------------------------------------------------------------------------
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _source_files(frame: Frame, *, strict: bool) -> tuple[str, ...]:
|
|
353
|
+
files = frame.one("SourceFiles", strict=strict)
|
|
354
|
+
return tuple(files) if files else ()
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _build_model_exchange(frame: Frame, *, strict: bool) -> ModelExchange:
|
|
358
|
+
return ModelExchange(
|
|
359
|
+
**attributes(frame, MODEL_EXCHANGE_ATTRS, strict=strict), source_files=_source_files(frame, strict=strict)
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _build_co_simulation(frame: Frame, *, strict: bool) -> CoSimulation:
|
|
364
|
+
return CoSimulation(
|
|
365
|
+
**attributes(frame, CO_SIMULATION_ATTRS, strict=strict), source_files=_source_files(frame, strict=strict)
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _build_source_files(frame: Frame, *, strict: bool) -> tuple[str, ...]:
|
|
370
|
+
attributes(frame, EMPTY, strict=strict)
|
|
371
|
+
return tuple(frame.all("File"))
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _build_file(frame: Frame, *, strict: bool) -> str:
|
|
375
|
+
name: str = attributes(frame, FILE_ATTRS, strict=strict)["name"]
|
|
376
|
+
return name
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _build_unit(frame: Frame, *, strict: bool) -> Unit:
|
|
380
|
+
return Unit(
|
|
381
|
+
**attributes(frame, UNIT_ATTRS, strict=strict),
|
|
382
|
+
base_unit=frame.one("BaseUnit", strict=strict),
|
|
383
|
+
display_units=tuple(frame.all("DisplayUnit")),
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _build_base_unit(frame: Frame, *, strict: bool) -> BaseUnit:
|
|
388
|
+
return BaseUnit(**attributes(frame, BASE_UNIT_ATTRS, strict=strict))
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _build_display_unit(frame: Frame, *, strict: bool) -> DisplayUnit:
|
|
392
|
+
return DisplayUnit(**attributes(frame, DISPLAY_UNIT_ATTRS, strict=strict))
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _build_simple_type(frame: Frame, *, strict: bool) -> TypeDefinition:
|
|
396
|
+
common = attributes(frame, SIMPLE_TYPE_ATTRS, strict=strict)
|
|
397
|
+
kinds = [(tag, obj) for tag, obj in frame.children if tag in _TYPE_KINDS]
|
|
398
|
+
if not kinds:
|
|
399
|
+
raise frame.error(f"<SimpleType name={common['name']!r}> has no Real, Integer, Boolean, String or Enumeration")
|
|
400
|
+
if len(kinds) > 1 and strict:
|
|
401
|
+
raise frame.error(f"<SimpleType name={common['name']!r}> has {len(kinds)} type elements, expected one")
|
|
402
|
+
tag, kind_fields = kinds[0]
|
|
403
|
+
return _TYPE_KINDS[tag](**common, **cast("dict[str, Any]", kind_fields))
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _build_real(frame: Frame, *, strict: bool) -> dict[str, object]:
|
|
407
|
+
return attributes(frame, REAL_ATTRS, strict=strict)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _build_integer(frame: Frame, *, strict: bool) -> dict[str, object]:
|
|
411
|
+
return attributes(frame, INTEGER_ATTRS, strict=strict)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _build_no_attributes(frame: Frame, *, strict: bool) -> dict[str, object]:
|
|
415
|
+
return attributes(frame, EMPTY, strict=strict)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _build_enumeration(frame: Frame, *, strict: bool) -> dict[str, object]:
|
|
419
|
+
return {**attributes(frame, ENUMERATION_ATTRS, strict=strict), "items": tuple(frame.all("Item"))}
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _build_item(frame: Frame, *, strict: bool) -> Item:
|
|
423
|
+
return Item(**attributes(frame, ITEM_ATTRS, strict=strict))
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _build_category(frame: Frame, *, strict: bool) -> Category:
|
|
427
|
+
return Category(**attributes(frame, CATEGORY_ATTRS, strict=strict))
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _build_default_experiment(frame: Frame, *, strict: bool) -> DefaultExperiment:
|
|
431
|
+
return DefaultExperiment(**attributes(frame, DEFAULT_EXPERIMENT_ATTRS, strict=strict))
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _build_unit_definitions(frame: Frame, *, strict: bool) -> tuple[Unit, ...]:
|
|
435
|
+
attributes(frame, EMPTY, strict=strict)
|
|
436
|
+
return tuple(frame.all("Unit"))
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _build_type_definitions(frame: Frame, *, strict: bool) -> tuple[TypeDefinition, ...]:
|
|
440
|
+
attributes(frame, EMPTY, strict=strict)
|
|
441
|
+
return tuple(frame.all("SimpleType"))
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _build_log_categories(frame: Frame, *, strict: bool) -> tuple[Category, ...]:
|
|
445
|
+
attributes(frame, EMPTY, strict=strict)
|
|
446
|
+
return tuple(frame.all("Category"))
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
class _HeaderBuilder(Builder[ModelHeader]):
|
|
450
|
+
"""Builds the :class:`ModelHeader` from the root element and the children read so far."""
|
|
451
|
+
|
|
452
|
+
__slots__ = ("_annotations",)
|
|
453
|
+
|
|
454
|
+
def __init__(self, *, annotations: bool) -> None:
|
|
455
|
+
self._annotations = annotations
|
|
456
|
+
|
|
457
|
+
def __call__(self, frame: Frame, /, *, strict: bool) -> ModelHeader:
|
|
458
|
+
"""Build the header."""
|
|
459
|
+
units = frame.one("UnitDefinitions", strict=strict)
|
|
460
|
+
types = frame.one("TypeDefinitions", strict=strict)
|
|
461
|
+
categories = frame.one("LogCategories", strict=strict)
|
|
462
|
+
vendor_annotations = frame.one("VendorAnnotations", strict=strict) or () if self._annotations else None
|
|
463
|
+
return ModelHeader(
|
|
464
|
+
**attributes(frame, ROOT_ATTRS, strict=strict),
|
|
465
|
+
model_exchange=frame.one("ModelExchange", strict=strict),
|
|
466
|
+
co_simulation=frame.one("CoSimulation", strict=strict),
|
|
467
|
+
unit_definitions=Named(units or ()),
|
|
468
|
+
type_definitions=Named(types or ()),
|
|
469
|
+
log_categories=Named(categories or ()),
|
|
470
|
+
default_experiment=frame.one("DefaultExperiment", strict=strict),
|
|
471
|
+
vendor_annotations=vendor_annotations,
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
_TYPE_KINDS: Mapping[str, type[TypeDefinition]] = MappingProxyType(
|
|
476
|
+
{
|
|
477
|
+
"Real": RealType,
|
|
478
|
+
"Integer": IntegerType,
|
|
479
|
+
"Boolean": BooleanType,
|
|
480
|
+
"String": StringType,
|
|
481
|
+
"Enumeration": EnumerationType,
|
|
482
|
+
}
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _header_grammar(*, annotations: bool) -> Grammar[ModelHeader]:
|
|
487
|
+
return Grammar(
|
|
488
|
+
root="fmiModelDescription",
|
|
489
|
+
stop_at="ModelVariables",
|
|
490
|
+
build_root=_HeaderBuilder(annotations=annotations),
|
|
491
|
+
children={
|
|
492
|
+
"fmiModelDescription": {
|
|
493
|
+
"ModelExchange": _build_model_exchange,
|
|
494
|
+
"CoSimulation": _build_co_simulation,
|
|
495
|
+
"UnitDefinitions": _build_unit_definitions,
|
|
496
|
+
"TypeDefinitions": _build_type_definitions,
|
|
497
|
+
"LogCategories": _build_log_categories,
|
|
498
|
+
"DefaultExperiment": _build_default_experiment,
|
|
499
|
+
"VendorAnnotations": annotations_rule.CONTAINER if annotations else SKIP,
|
|
500
|
+
},
|
|
501
|
+
"VendorAnnotations": {"Tool": annotations_rule.TOOL},
|
|
502
|
+
"ModelExchange": {"SourceFiles": _build_source_files},
|
|
503
|
+
"CoSimulation": {"SourceFiles": _build_source_files},
|
|
504
|
+
"SourceFiles": {"File": _build_file},
|
|
505
|
+
"UnitDefinitions": {"Unit": _build_unit},
|
|
506
|
+
"Unit": {"BaseUnit": _build_base_unit, "DisplayUnit": _build_display_unit},
|
|
507
|
+
"TypeDefinitions": {"SimpleType": _build_simple_type},
|
|
508
|
+
"SimpleType": {
|
|
509
|
+
"Real": _build_real,
|
|
510
|
+
"Integer": _build_integer,
|
|
511
|
+
"Boolean": _build_no_attributes,
|
|
512
|
+
"String": _build_no_attributes,
|
|
513
|
+
"Enumeration": _build_enumeration,
|
|
514
|
+
},
|
|
515
|
+
"Enumeration": {"Item": _build_item},
|
|
516
|
+
"LogCategories": {"Category": _build_category},
|
|
517
|
+
},
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
HEADER_GRAMMAR = _header_grammar(annotations=False)
|
|
522
|
+
"""The Model Header grammar; Tool Annotations are skipped."""
|
|
523
|
+
|
|
524
|
+
HEADER_GRAMMAR_WITH_ANNOTATIONS = _header_grammar(annotations=True)
|
|
525
|
+
"""The Model Header grammar that keeps ``VendorAnnotations``."""
|
mdxml/fmi2/_model.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The complete FMI 2.0 Model Description, as returned by :func:`mdxml.read`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from mdxml.fmi2._header import ModelHeader
|
|
12
|
+
from mdxml.fmi2._structure import ModelStructure
|
|
13
|
+
from mdxml.fmi2._variables import Variable
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
17
|
+
class ModelDescription:
|
|
18
|
+
"""An FMI 2.0 Model Description: the Model Header, every Model Variable and the Model Structure.
|
|
19
|
+
|
|
20
|
+
References are kept as written (ADR 0002). The ``variable_by_*`` helpers
|
|
21
|
+
look them up; each raises :class:`KeyError` when nothing matches.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
header: ModelHeader
|
|
25
|
+
variables: tuple[Variable, ...] = ()
|
|
26
|
+
model_structure: ModelStructure = field(default_factory=ModelStructure)
|
|
27
|
+
|
|
28
|
+
_by_name: Mapping[str, Variable] = field(init=False, repr=False, compare=False)
|
|
29
|
+
_by_value_reference: Mapping[int, Variable] = field(init=False, repr=False, compare=False)
|
|
30
|
+
_by_typed_value_reference: Mapping[tuple[str, int], Variable] = field(init=False, repr=False, compare=False)
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
"""Index the variables for lookups; when keys repeat, the first variable in file order wins."""
|
|
34
|
+
by_name: dict[str, Variable] = {}
|
|
35
|
+
by_vr: dict[int, Variable] = {}
|
|
36
|
+
by_typed_vr: dict[tuple[str, int], Variable] = {}
|
|
37
|
+
for variable in self.variables:
|
|
38
|
+
by_name.setdefault(variable.name, variable)
|
|
39
|
+
by_vr.setdefault(variable.value_reference, variable)
|
|
40
|
+
by_typed_vr.setdefault((variable.type_name, variable.value_reference), variable)
|
|
41
|
+
object.__setattr__(self, "_by_name", MappingProxyType(by_name))
|
|
42
|
+
object.__setattr__(self, "_by_value_reference", MappingProxyType(by_vr))
|
|
43
|
+
object.__setattr__(self, "_by_typed_value_reference", MappingProxyType(by_typed_vr))
|
|
44
|
+
|
|
45
|
+
def __reduce__(self) -> tuple[Any, ...]:
|
|
46
|
+
"""Pickle only the fields; the lookup indexes are rebuilt when unpickled."""
|
|
47
|
+
fields = {f.name: getattr(self, f.name) for f in dataclasses.fields(self) if f.init}
|
|
48
|
+
return (_unpickle, (type(self), fields))
|
|
49
|
+
|
|
50
|
+
def variable_by_name(self, name: str) -> Variable:
|
|
51
|
+
"""Return the variable with this name."""
|
|
52
|
+
return self._by_name[name]
|
|
53
|
+
|
|
54
|
+
def variable_by_index(self, index: int) -> Variable:
|
|
55
|
+
"""Return the variable with this Variable Index (1-based), as the Model Structure refers to it."""
|
|
56
|
+
if not 1 <= index <= len(self.variables):
|
|
57
|
+
raise KeyError(index)
|
|
58
|
+
return self.variables[index - 1]
|
|
59
|
+
|
|
60
|
+
def variable_by_value_reference(self, value_reference: int, type_name: str | None = None) -> Variable:
|
|
61
|
+
"""Return the first variable in file order with this value reference.
|
|
62
|
+
|
|
63
|
+
In FMI 2.0 value references are only unique per type (``Real``,
|
|
64
|
+
``Integer``, …) and alias variables share one, so pass ``type_name``
|
|
65
|
+
to pick the type.
|
|
66
|
+
"""
|
|
67
|
+
if type_name is None:
|
|
68
|
+
return self._by_value_reference[value_reference]
|
|
69
|
+
return self._by_typed_value_reference[(type_name, value_reference)]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _unpickle(cls: type[ModelDescription], fields: dict[str, Any]) -> ModelDescription:
|
|
73
|
+
return cls(**fields)
|