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/fmi3/_header.py ADDED
@@ -0,0 +1,635 @@
1
+ """The FMI 3.0 Model Header: everything in ``fmiModelDescription`` before ``ModelVariables``.
2
+
3
+ Classes mirror the FMI 3.0 XSD (``schema/fmi3``): one per element, field
4
+ names are the XSD attribute names in snake_case, and defaults are the XSD
5
+ defaults. ``Annotations`` children, which FMI 3 allows on most elements,
6
+ are skipped.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from collections.abc import Mapping
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime
15
+ from enum import Enum
16
+ from types import MappingProxyType
17
+
18
+ from mdxml import _convert as c
19
+ from mdxml._grammar import SKIP, Builder, ChildRule, Collect, Grammar
20
+ from mdxml._lookup import Named
21
+ from mdxml._schema import (
22
+ Attr,
23
+ AttrTable,
24
+ Frame,
25
+ attributes,
26
+ double,
27
+ flag,
28
+ required_text,
29
+ table,
30
+ text,
31
+ )
32
+
33
+ # --- Enums ----------------------------------------------------------------------------------
34
+
35
+
36
+ class VariableNamingConvention(str, Enum):
37
+ """``variableNamingConvention`` on ``fmiModelDescription``."""
38
+
39
+ FLAT = "flat"
40
+ STRUCTURED = "structured"
41
+
42
+
43
+ class IntervalVariability(str, Enum):
44
+ """``intervalVariability`` of a clock."""
45
+
46
+ CONSTANT = "constant"
47
+ FIXED = "fixed"
48
+ TUNABLE = "tunable"
49
+ CHANGING = "changing"
50
+ COUNTDOWN = "countdown"
51
+ TRIGGERED = "triggered"
52
+
53
+
54
+ # --- Interface Types ------------------------------------------------------------------------
55
+
56
+
57
+ @dataclass(frozen=True, slots=True, kw_only=True)
58
+ class ModelExchange:
59
+ """The ``ModelExchange`` Interface Type."""
60
+
61
+ model_identifier: str
62
+ needs_execution_tool: bool = False
63
+ can_be_instantiated_only_once_per_process: bool = False
64
+ can_get_and_set_fmu_state: bool = False
65
+ can_serialize_fmu_state: bool = False
66
+ provides_directional_derivatives: bool = False
67
+ provides_adjoint_derivatives: bool = False
68
+ provides_per_element_dependencies: bool = False
69
+ needs_completed_integrator_step: bool = False
70
+ provides_evaluate_discrete_states: bool = False
71
+
72
+
73
+ @dataclass(frozen=True, slots=True, kw_only=True)
74
+ class CoSimulation:
75
+ """The ``CoSimulation`` Interface Type."""
76
+
77
+ model_identifier: str
78
+ needs_execution_tool: bool = False
79
+ can_be_instantiated_only_once_per_process: bool = False
80
+ can_get_and_set_fmu_state: bool = False
81
+ can_serialize_fmu_state: bool = False
82
+ provides_directional_derivatives: bool = False
83
+ provides_adjoint_derivatives: bool = False
84
+ provides_per_element_dependencies: bool = False
85
+ can_handle_variable_communication_step_size: bool = False
86
+ fixed_internal_step_size: float | None = None
87
+ max_output_derivative_order: int = 0
88
+ recommended_intermediate_input_smoothness: int = 0
89
+ provides_intermediate_update: bool = False
90
+ might_return_early_from_do_step: bool = False
91
+ can_return_early_after_intermediate_update: bool = False
92
+ has_event_mode: bool = False
93
+ provides_evaluate_discrete_states: bool = False
94
+
95
+
96
+ @dataclass(frozen=True, slots=True, kw_only=True)
97
+ class ScheduledExecution:
98
+ """The ``ScheduledExecution`` Interface Type."""
99
+
100
+ model_identifier: str
101
+ needs_execution_tool: bool = False
102
+ can_be_instantiated_only_once_per_process: bool = False
103
+ can_get_and_set_fmu_state: bool = False
104
+ can_serialize_fmu_state: bool = False
105
+ provides_directional_derivatives: bool = False
106
+ provides_adjoint_derivatives: bool = False
107
+ provides_per_element_dependencies: bool = False
108
+
109
+
110
+ # --- Units ----------------------------------------------------------------------------------
111
+
112
+
113
+ @dataclass(frozen=True, slots=True, kw_only=True)
114
+ class BaseUnit:
115
+ """A unit's exponents of the SI base units, plus ``factor`` and ``offset`` to convert to them.
116
+
117
+ Field names keep the XSD's case-sensitive SI symbols (``A`` is ampere, ``K`` is kelvin).
118
+ """
119
+
120
+ kg: int = 0
121
+ m: int = 0
122
+ s: int = 0
123
+ A: int = 0
124
+ K: int = 0
125
+ mol: int = 0
126
+ cd: int = 0
127
+ rad: int = 0
128
+ factor: float = 1.0
129
+ offset: float = 0.0
130
+
131
+
132
+ @dataclass(frozen=True, slots=True, kw_only=True)
133
+ class DisplayUnit:
134
+ """A unit to display values in, converted from the unit by ``factor``, ``offset`` and ``inverse``."""
135
+
136
+ name: str
137
+ factor: float = 1.0
138
+ offset: float = 0.0
139
+ inverse: bool = False
140
+
141
+
142
+ @dataclass(frozen=True, slots=True, kw_only=True)
143
+ class Unit:
144
+ """A ``Unit`` in ``UnitDefinitions``."""
145
+
146
+ name: str
147
+ base_unit: BaseUnit | None = None
148
+ display_units: tuple[DisplayUnit, ...] = ()
149
+
150
+
151
+ # --- Type definitions -----------------------------------------------------------------------
152
+
153
+
154
+ @dataclass(frozen=True, slots=True, kw_only=True)
155
+ class _FloatType:
156
+ name: str
157
+ description: str | None = None
158
+ quantity: str | None = None
159
+ unit: str | None = None
160
+ display_unit: str | None = None
161
+ relative_quantity: bool = False
162
+ unbounded: bool = False
163
+ min: float | None = None
164
+ max: float | None = None
165
+ nominal: float | None = None
166
+
167
+
168
+ @dataclass(frozen=True, slots=True, kw_only=True)
169
+ class Float32Type(_FloatType):
170
+ """A ``Float32Type`` type definition."""
171
+
172
+
173
+ @dataclass(frozen=True, slots=True, kw_only=True)
174
+ class Float64Type(_FloatType):
175
+ """A ``Float64Type`` type definition."""
176
+
177
+
178
+ @dataclass(frozen=True, slots=True, kw_only=True)
179
+ class _IntegerType:
180
+ name: str
181
+ description: str | None = None
182
+ quantity: str | None = None
183
+ min: int | None = None
184
+ max: int | None = None
185
+
186
+
187
+ @dataclass(frozen=True, slots=True, kw_only=True)
188
+ class Int8Type(_IntegerType):
189
+ """An ``Int8Type`` type definition."""
190
+
191
+
192
+ @dataclass(frozen=True, slots=True, kw_only=True)
193
+ class UInt8Type(_IntegerType):
194
+ """A ``UInt8Type`` type definition."""
195
+
196
+
197
+ @dataclass(frozen=True, slots=True, kw_only=True)
198
+ class Int16Type(_IntegerType):
199
+ """An ``Int16Type`` type definition."""
200
+
201
+
202
+ @dataclass(frozen=True, slots=True, kw_only=True)
203
+ class UInt16Type(_IntegerType):
204
+ """A ``UInt16Type`` type definition."""
205
+
206
+
207
+ @dataclass(frozen=True, slots=True, kw_only=True)
208
+ class Int32Type(_IntegerType):
209
+ """An ``Int32Type`` type definition."""
210
+
211
+
212
+ @dataclass(frozen=True, slots=True, kw_only=True)
213
+ class UInt32Type(_IntegerType):
214
+ """A ``UInt32Type`` type definition."""
215
+
216
+
217
+ @dataclass(frozen=True, slots=True, kw_only=True)
218
+ class Int64Type(_IntegerType):
219
+ """An ``Int64Type`` type definition."""
220
+
221
+
222
+ @dataclass(frozen=True, slots=True, kw_only=True)
223
+ class UInt64Type(_IntegerType):
224
+ """A ``UInt64Type`` type definition."""
225
+
226
+
227
+ @dataclass(frozen=True, slots=True, kw_only=True)
228
+ class BooleanType:
229
+ """A ``BooleanType`` type definition."""
230
+
231
+ name: str
232
+ description: str | None = None
233
+
234
+
235
+ @dataclass(frozen=True, slots=True, kw_only=True)
236
+ class StringType:
237
+ """A ``StringType`` type definition."""
238
+
239
+ name: str
240
+ description: str | None = None
241
+
242
+
243
+ @dataclass(frozen=True, slots=True, kw_only=True)
244
+ class BinaryType:
245
+ """A ``BinaryType`` type definition."""
246
+
247
+ name: str
248
+ description: str | None = None
249
+ mime_type: str = "application/octet-stream"
250
+ max_size: int | None = None
251
+
252
+
253
+ @dataclass(frozen=True, slots=True, kw_only=True)
254
+ class Item:
255
+ """One allowed value of an ``EnumerationType``."""
256
+
257
+ name: str
258
+ value: int
259
+ description: str | None = None
260
+
261
+
262
+ @dataclass(frozen=True, slots=True, kw_only=True)
263
+ class EnumerationType:
264
+ """An ``EnumerationType`` type definition."""
265
+
266
+ name: str
267
+ description: str | None = None
268
+ quantity: str | None = None
269
+ min: int | None = None
270
+ max: int | None = None
271
+ items: tuple[Item, ...] = ()
272
+
273
+
274
+ @dataclass(frozen=True, slots=True, kw_only=True)
275
+ class ClockType:
276
+ """A ``ClockType`` type definition."""
277
+
278
+ name: str
279
+ interval_variability: IntervalVariability | str
280
+ description: str | None = None
281
+ can_be_deactivated: bool = False
282
+ priority: int | None = None
283
+ interval_decimal: float | None = None
284
+ shift_decimal: float = 0.0
285
+ supports_fraction: bool = False
286
+ resolution: int | None = None
287
+ interval_counter: int | None = None
288
+ shift_counter: int = 0
289
+
290
+
291
+ TypeDefinition = (
292
+ Float32Type
293
+ | Float64Type
294
+ | Int8Type
295
+ | UInt8Type
296
+ | Int16Type
297
+ | UInt16Type
298
+ | Int32Type
299
+ | UInt32Type
300
+ | Int64Type
301
+ | UInt64Type
302
+ | BooleanType
303
+ | StringType
304
+ | BinaryType
305
+ | EnumerationType
306
+ | ClockType
307
+ )
308
+ """Any type definition in ``TypeDefinitions``."""
309
+
310
+
311
+ # --- Log categories and default experiment --------------------------------------------------
312
+
313
+
314
+ @dataclass(frozen=True, slots=True, kw_only=True)
315
+ class Category:
316
+ """A log category in ``LogCategories``."""
317
+
318
+ name: str
319
+ description: str | None = None
320
+
321
+
322
+ @dataclass(frozen=True, slots=True, kw_only=True)
323
+ class DefaultExperiment:
324
+ """Default simulation settings suggested by the FMU."""
325
+
326
+ start_time: float | None = None
327
+ stop_time: float | None = None
328
+ tolerance: float | None = None
329
+ step_size: float | None = None
330
+
331
+
332
+ # --- Model Header ---------------------------------------------------------------------------
333
+
334
+
335
+ @dataclass(frozen=True, slots=True, kw_only=True)
336
+ class ModelHeader:
337
+ """Everything in an FMI 3.0 Model Description before ``ModelVariables``.
338
+
339
+ Annotations aren't part of the Model Header.
340
+ """
341
+
342
+ fmi_version: str
343
+ model_name: str
344
+ instantiation_token: str
345
+ description: str | None = None
346
+ author: str | None = None
347
+ version: str | None = None
348
+ copyright: str | None = None
349
+ license: str | None = None
350
+ generation_tool: str | None = None
351
+ generation_date_and_time: datetime | None = None
352
+ variable_naming_convention: VariableNamingConvention | str = VariableNamingConvention.FLAT
353
+ model_exchange: ModelExchange | None = None
354
+ co_simulation: CoSimulation | None = None
355
+ scheduled_execution: ScheduledExecution | None = None
356
+ unit_definitions: Named[Unit] = field(default_factory=Named)
357
+ type_definitions: Named[TypeDefinition] = field(default_factory=Named)
358
+ log_categories: Named[Category] = field(default_factory=Named)
359
+ default_experiment: DefaultExperiment | None = None
360
+
361
+ def __post_init__(self) -> None:
362
+ """Accept plain tuples for the definition lists, so headers can be built by hand."""
363
+ for name in ("unit_definitions", "type_definitions", "log_categories"):
364
+ value = getattr(self, name)
365
+ if not isinstance(value, Named):
366
+ object.__setattr__(self, name, Named(value))
367
+
368
+
369
+ # --- Attribute tables -----------------------------------------------------------------------
370
+
371
+ FMI_VERSION_PATTERN = re.compile(r"3[.](0|[1-9][0-9]*)([.](0|[1-9][0-9]*))?(-.+)?")
372
+
373
+
374
+ def _fmi_version(value: str, *, strict: bool) -> str:
375
+ """``fmiVersion``: in strict mode it must match the FMI 3 XSD's pattern."""
376
+ if strict and not FMI_VERSION_PATTERN.fullmatch(value):
377
+ raise ValueError(f"{value!r} doesn't match the FMI 3 version pattern")
378
+ return value
379
+
380
+
381
+ ROOT_ATTRS = table(
382
+ Attr("fmiVersion", "fmi_version", _fmi_version, required=True, fallback=""),
383
+ required_text("modelName", "model_name"),
384
+ required_text("instantiationToken", "instantiation_token"),
385
+ text("description", "description"),
386
+ text("author", "author"),
387
+ text("version", "version"),
388
+ text("copyright", "copyright"),
389
+ text("license", "license"),
390
+ text("generationTool", "generation_tool"),
391
+ Attr("generationDateAndTime", "generation_date_and_time", c.to_datetime),
392
+ Attr("variableNamingConvention", "variable_naming_convention", c.EnumConverter(VariableNamingConvention)),
393
+ )
394
+
395
+ _INTERFACE_ATTRS = (
396
+ required_text("modelIdentifier", "model_identifier"),
397
+ flag("needsExecutionTool", "needs_execution_tool"),
398
+ flag("canBeInstantiatedOnlyOncePerProcess", "can_be_instantiated_only_once_per_process"),
399
+ flag("canGetAndSetFMUState", "can_get_and_set_fmu_state"),
400
+ flag("canSerializeFMUState", "can_serialize_fmu_state"),
401
+ flag("providesDirectionalDerivatives", "provides_directional_derivatives"),
402
+ flag("providesAdjointDerivatives", "provides_adjoint_derivatives"),
403
+ flag("providesPerElementDependencies", "provides_per_element_dependencies"),
404
+ )
405
+
406
+ MODEL_EXCHANGE_ATTRS = table(
407
+ *_INTERFACE_ATTRS,
408
+ flag("needsCompletedIntegratorStep", "needs_completed_integrator_step"),
409
+ flag("providesEvaluateDiscreteStates", "provides_evaluate_discrete_states"),
410
+ )
411
+
412
+ CO_SIMULATION_ATTRS = table(
413
+ *_INTERFACE_ATTRS,
414
+ flag("canHandleVariableCommunicationStepSize", "can_handle_variable_communication_step_size"),
415
+ double("fixedInternalStepSize", "fixed_internal_step_size"),
416
+ Attr("maxOutputDerivativeOrder", "max_output_derivative_order", c.UNSIGNED_INT),
417
+ Attr("recommendedIntermediateInputSmoothness", "recommended_intermediate_input_smoothness", c.INT),
418
+ flag("providesIntermediateUpdate", "provides_intermediate_update"),
419
+ flag("mightReturnEarlyFromDoStep", "might_return_early_from_do_step"),
420
+ flag("canReturnEarlyAfterIntermediateUpdate", "can_return_early_after_intermediate_update"),
421
+ flag("hasEventMode", "has_event_mode"),
422
+ flag("providesEvaluateDiscreteStates", "provides_evaluate_discrete_states"),
423
+ )
424
+
425
+ SCHEDULED_EXECUTION_ATTRS = table(*_INTERFACE_ATTRS)
426
+
427
+ UNIT_ATTRS = table(required_text("name", "name"))
428
+
429
+ BASE_UNIT_ATTRS = table(
430
+ *(Attr(symbol, symbol, c.INT) for symbol in ("kg", "m", "s", "A", "K", "mol", "cd", "rad")),
431
+ double("factor", "factor"),
432
+ double("offset", "offset"),
433
+ )
434
+
435
+ DISPLAY_UNIT_ATTRS = table(
436
+ required_text("name", "name"),
437
+ double("factor", "factor"),
438
+ double("offset", "offset"),
439
+ flag("inverse", "inverse"),
440
+ )
441
+
442
+ _TYPE_BASE_ATTRS = (
443
+ required_text("name", "name"),
444
+ text("description", "description"),
445
+ )
446
+
447
+ FLOAT_TYPE_ATTRS = table(
448
+ *_TYPE_BASE_ATTRS,
449
+ text("quantity", "quantity"),
450
+ text("unit", "unit"),
451
+ text("displayUnit", "display_unit"),
452
+ flag("relativeQuantity", "relative_quantity"),
453
+ flag("unbounded", "unbounded"),
454
+ double("min", "min"),
455
+ double("max", "max"),
456
+ double("nominal", "nominal"),
457
+ )
458
+
459
+
460
+ def _integer_type_attrs(bounds: c.IntRange) -> AttrTable:
461
+ return table(
462
+ *_TYPE_BASE_ATTRS,
463
+ text("quantity", "quantity"),
464
+ Attr("min", "min", bounds),
465
+ Attr("max", "max", bounds),
466
+ )
467
+
468
+
469
+ PLAIN_TYPE_ATTRS = table(*_TYPE_BASE_ATTRS)
470
+
471
+ BINARY_TYPE_ATTRS = table(
472
+ *_TYPE_BASE_ATTRS,
473
+ text("mimeType", "mime_type"),
474
+ Attr("maxSize", "max_size", c.to_unsigned_int), # xs:nonNegativeInteger has no upper bound
475
+ )
476
+
477
+ ENUMERATION_TYPE_ATTRS = table(
478
+ *_TYPE_BASE_ATTRS,
479
+ text("quantity", "quantity"),
480
+ Attr("min", "min", c.LONG),
481
+ Attr("max", "max", c.LONG),
482
+ )
483
+
484
+ ITEM_ATTRS = table(
485
+ required_text("name", "name"),
486
+ Attr("value", "value", c.LONG, required=True),
487
+ text("description", "description"),
488
+ )
489
+
490
+ CLOCK_TYPE_ATTRS = table(
491
+ *_TYPE_BASE_ATTRS,
492
+ flag("canBeDeactivated", "can_be_deactivated"),
493
+ Attr("priority", "priority", c.UNSIGNED_INT),
494
+ Attr("intervalVariability", "interval_variability", c.EnumConverter(IntervalVariability), required=True),
495
+ double("intervalDecimal", "interval_decimal"),
496
+ double("shiftDecimal", "shift_decimal"),
497
+ flag("supportsFraction", "supports_fraction"),
498
+ Attr("resolution", "resolution", c.UNSIGNED_LONG),
499
+ Attr("intervalCounter", "interval_counter", c.UNSIGNED_LONG),
500
+ Attr("shiftCounter", "shift_counter", c.UNSIGNED_LONG),
501
+ )
502
+
503
+ CATEGORY_ATTRS = table(
504
+ required_text("name", "name"),
505
+ text("description", "description"),
506
+ )
507
+
508
+ DEFAULT_EXPERIMENT_ATTRS = table(
509
+ double("startTime", "start_time"),
510
+ double("stopTime", "stop_time"),
511
+ double("tolerance", "tolerance"),
512
+ double("stepSize", "step_size"),
513
+ )
514
+
515
+
516
+ # --- Builders -------------------------------------------------------------------------------
517
+
518
+
519
+ class _Simple(Builder[object]):
520
+ """Builds ``cls`` from the element's attributes alone."""
521
+
522
+ __slots__ = ("_attrs", "_cls")
523
+
524
+ def __init__(self, cls: type[object], attrs: AttrTable) -> None:
525
+ self._cls = cls
526
+ self._attrs = attrs
527
+
528
+ def __call__(self, frame: Frame, /, *, strict: bool) -> object:
529
+ """Build the object."""
530
+ return self._cls(**attributes(frame, self._attrs, strict=strict))
531
+
532
+
533
+ def _build_unit(frame: Frame, *, strict: bool) -> Unit:
534
+ return Unit(
535
+ **attributes(frame, UNIT_ATTRS, strict=strict),
536
+ base_unit=frame.one("BaseUnit", strict=strict),
537
+ display_units=tuple(frame.all("DisplayUnit")),
538
+ )
539
+
540
+
541
+ def _build_enumeration_type(frame: Frame, *, strict: bool) -> EnumerationType:
542
+ return EnumerationType(
543
+ **attributes(frame, ENUMERATION_TYPE_ATTRS, strict=strict),
544
+ items=tuple(frame.all("Item")),
545
+ )
546
+
547
+
548
+ def build_header(frame: Frame, *, strict: bool) -> ModelHeader:
549
+ """Build the :class:`ModelHeader` from the root element and the children read so far."""
550
+ return ModelHeader(
551
+ **attributes(frame, ROOT_ATTRS, strict=strict),
552
+ model_exchange=frame.one("ModelExchange", strict=strict),
553
+ co_simulation=frame.one("CoSimulation", strict=strict),
554
+ scheduled_execution=frame.one("ScheduledExecution", strict=strict),
555
+ unit_definitions=Named(frame.one("UnitDefinitions", strict=strict) or ()),
556
+ type_definitions=Named(frame.one("TypeDefinitions", strict=strict) or ()),
557
+ log_categories=Named(frame.one("LogCategories", strict=strict) or ()),
558
+ default_experiment=frame.one("DefaultExperiment", strict=strict),
559
+ )
560
+
561
+
562
+ TYPE_DEFINITIONS: Mapping[str, tuple[type[TypeDefinition], AttrTable]] = MappingProxyType(
563
+ {
564
+ "Float32Type": (Float32Type, FLOAT_TYPE_ATTRS),
565
+ "Float64Type": (Float64Type, FLOAT_TYPE_ATTRS),
566
+ "Int8Type": (Int8Type, _integer_type_attrs(c.BYTE)),
567
+ "UInt8Type": (UInt8Type, _integer_type_attrs(c.UNSIGNED_BYTE)),
568
+ "Int16Type": (Int16Type, _integer_type_attrs(c.SHORT)),
569
+ "UInt16Type": (UInt16Type, _integer_type_attrs(c.UNSIGNED_SHORT)),
570
+ "Int32Type": (Int32Type, _integer_type_attrs(c.INT)),
571
+ "UInt32Type": (UInt32Type, _integer_type_attrs(c.UNSIGNED_INT)),
572
+ "Int64Type": (Int64Type, _integer_type_attrs(c.LONG)),
573
+ "UInt64Type": (UInt64Type, _integer_type_attrs(c.UNSIGNED_LONG)),
574
+ "BooleanType": (BooleanType, PLAIN_TYPE_ATTRS),
575
+ "StringType": (StringType, PLAIN_TYPE_ATTRS),
576
+ "BinaryType": (BinaryType, BINARY_TYPE_ATTRS),
577
+ "EnumerationType": (EnumerationType, ENUMERATION_TYPE_ATTRS),
578
+ "ClockType": (ClockType, CLOCK_TYPE_ATTRS),
579
+ }
580
+ )
581
+ """Each type definition element's class and attribute table."""
582
+
583
+ _TYPE_BUILDERS: Mapping[str, ChildRule] = MappingProxyType(
584
+ {
585
+ tag: _build_enumeration_type if tag == "EnumerationType" else _Simple(cls, attrs)
586
+ for tag, (cls, attrs) in TYPE_DEFINITIONS.items()
587
+ }
588
+ )
589
+
590
+ # Elements that may hold an <Annotations> child, which is skipped.
591
+ _ANNOTATABLE = (
592
+ "ModelExchange",
593
+ "CoSimulation",
594
+ "ScheduledExecution",
595
+ "Unit",
596
+ "DisplayUnit",
597
+ *_TYPE_BUILDERS,
598
+ "Item",
599
+ "Category",
600
+ "DefaultExperiment",
601
+ )
602
+
603
+
604
+ def _header_children() -> dict[str, dict[str, ChildRule]]:
605
+ """Return which children each header element may contain; ``Annotations`` are skipped everywhere."""
606
+ children: dict[str, dict[str, ChildRule]] = {
607
+ "fmiModelDescription": {
608
+ "ModelExchange": _Simple(ModelExchange, MODEL_EXCHANGE_ATTRS),
609
+ "CoSimulation": _Simple(CoSimulation, CO_SIMULATION_ATTRS),
610
+ "ScheduledExecution": _Simple(ScheduledExecution, SCHEDULED_EXECUTION_ATTRS),
611
+ "UnitDefinitions": Collect("Unit"),
612
+ "TypeDefinitions": Collect(),
613
+ "LogCategories": Collect("Category"),
614
+ "DefaultExperiment": _Simple(DefaultExperiment, DEFAULT_EXPERIMENT_ATTRS),
615
+ },
616
+ "UnitDefinitions": {"Unit": _build_unit},
617
+ "Unit": {
618
+ "BaseUnit": _Simple(BaseUnit, BASE_UNIT_ATTRS),
619
+ "DisplayUnit": _Simple(DisplayUnit, DISPLAY_UNIT_ATTRS),
620
+ },
621
+ "TypeDefinitions": dict(_TYPE_BUILDERS),
622
+ "EnumerationType": {"Item": _Simple(Item, ITEM_ATTRS)},
623
+ "LogCategories": {"Category": _Simple(Category, CATEGORY_ATTRS)},
624
+ }
625
+ for parent in _ANNOTATABLE:
626
+ children.setdefault(parent, {})["Annotations"] = SKIP
627
+ return children
628
+
629
+
630
+ HEADER_GRAMMAR = Grammar(
631
+ root="fmiModelDescription",
632
+ stop_at="ModelVariables",
633
+ build_root=build_header,
634
+ children=_header_children(),
635
+ )
mdxml/fmi3/_model.py ADDED
@@ -0,0 +1,59 @@
1
+ """The complete FMI 3.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.fmi3._annotations import Annotation
12
+ from mdxml.fmi3._header import ModelHeader
13
+ from mdxml.fmi3._structure import ModelStructure
14
+ from mdxml.fmi3._variables import Variable
15
+
16
+
17
+ @dataclass(frozen=True, slots=True, kw_only=True)
18
+ class ModelDescription:
19
+ """An FMI 3.0 Model Description: the Model Header, every Model Variable and the Model Structure.
20
+
21
+ References are kept as written (ADR 0002). The ``variable_by_*`` helpers
22
+ look them up; each raises :class:`KeyError` when nothing matches.
23
+ """
24
+
25
+ header: ModelHeader
26
+ variables: tuple[Variable, ...] = ()
27
+ model_structure: ModelStructure = field(default_factory=ModelStructure)
28
+ annotations: tuple[Annotation, ...] | None = None
29
+ """The model-level ``<Annotations>``; ``None`` unless read with ``annotations=True``."""
30
+
31
+ _by_name: Mapping[str, Variable] = field(init=False, repr=False, compare=False)
32
+ _by_value_reference: Mapping[int, Variable] = field(init=False, repr=False, compare=False)
33
+
34
+ def __post_init__(self) -> None:
35
+ """Index the variables for lookups; when keys repeat, the first variable in file order wins."""
36
+ by_name: dict[str, Variable] = {}
37
+ by_vr: dict[int, Variable] = {}
38
+ for variable in self.variables:
39
+ by_name.setdefault(variable.name, variable)
40
+ by_vr.setdefault(variable.value_reference, variable)
41
+ object.__setattr__(self, "_by_name", MappingProxyType(by_name))
42
+ object.__setattr__(self, "_by_value_reference", MappingProxyType(by_vr))
43
+
44
+ def __reduce__(self) -> tuple[Any, ...]:
45
+ """Pickle only the fields; the lookup indexes are rebuilt when unpickled."""
46
+ fields = {f.name: getattr(self, f.name) for f in dataclasses.fields(self) if f.init}
47
+ return (_unpickle, (type(self), fields))
48
+
49
+ def variable_by_name(self, name: str) -> Variable:
50
+ """Return the variable with this name (aliases aren't included)."""
51
+ return self._by_name[name]
52
+
53
+ def variable_by_value_reference(self, value_reference: int) -> Variable:
54
+ """Return the variable with this value reference, as the Model Structure refers to it."""
55
+ return self._by_value_reference[value_reference]
56
+
57
+
58
+ def _unpickle(cls: type[ModelDescription], fields: dict[str, Any]) -> ModelDescription:
59
+ return cls(**fields)