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.
@@ -0,0 +1,603 @@
1
+ """FMI 3.0 Model Variables: the typed variable elements in ``ModelVariables``.
2
+
3
+ Each element kind (``Float64``, ``Int8``, ``Binary``, ``Clock``, …) has its
4
+ own class; ``type_name`` is the element name. Every variable also gets its
5
+ Variable Index: its 1-based position in ``ModelVariables``.
6
+
7
+ A variable with ``<Dimension>`` children is an array: its ``start`` is a
8
+ tuple of values, in row-major order. A scalar's ``start`` is a single value.
9
+ ``String`` and ``Binary`` start values come from ``<Start value="…">``
10
+ children; ``Binary`` values are converted from hex to ``bytes``.
11
+
12
+ The XSD gives ``variability`` no default; the FMI 3.0 standard defines it
13
+ from causality and type, and that default is applied here.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Mapping
19
+ from dataclasses import dataclass, field
20
+ from enum import Enum
21
+ from types import MappingProxyType
22
+ from typing import Any
23
+
24
+ from mdxml import _convert as c
25
+ from mdxml._grammar import SKIP, Builder, ChildRule, Grammar
26
+ from mdxml._schema import Attr, AttrTable, Frame, attributes, double, flag, required_text, table, text
27
+ from mdxml.fmi3 import _annotations as annotations_rule
28
+ from mdxml.fmi3._annotations import Annotation
29
+ from mdxml.fmi3._header import IntervalVariability
30
+
31
+ # --- Enums ----------------------------------------------------------------------------------
32
+
33
+
34
+ class Causality(str, Enum):
35
+ """``causality`` of a variable."""
36
+
37
+ STRUCTURAL_PARAMETER = "structuralParameter"
38
+ PARAMETER = "parameter"
39
+ CALCULATED_PARAMETER = "calculatedParameter"
40
+ INPUT = "input"
41
+ OUTPUT = "output"
42
+ LOCAL = "local"
43
+ INDEPENDENT = "independent"
44
+
45
+
46
+ class Variability(str, Enum):
47
+ """``variability`` of a variable."""
48
+
49
+ CONSTANT = "constant"
50
+ FIXED = "fixed"
51
+ TUNABLE = "tunable"
52
+ DISCRETE = "discrete"
53
+ CONTINUOUS = "continuous"
54
+
55
+
56
+ class Initial(str, Enum):
57
+ """``initial`` of a variable."""
58
+
59
+ EXACT = "exact"
60
+ APPROX = "approx"
61
+ CALCULATED = "calculated"
62
+
63
+
64
+ _PARAMETERS = frozenset({"parameter", "structuralParameter", "calculatedParameter"})
65
+ _FLOAT_ELEMENTS = frozenset({"Float32", "Float64"})
66
+
67
+
68
+ def default_variability(element: str, causality: str) -> Variability:
69
+ """Return the FMI 3.0 standard's default ``variability`` for a variable element and causality.
70
+
71
+ Parameters default to ``fixed``; otherwise ``Float32``/``Float64`` default to
72
+ ``continuous`` and every other type (including clocks) to ``discrete``.
73
+ """
74
+ if causality in _PARAMETERS:
75
+ return Variability.FIXED
76
+ return Variability.CONTINUOUS if element in _FLOAT_ELEMENTS else Variability.DISCRETE
77
+
78
+
79
+ # Table 22 of the FMI 3.0.2 standard: the default `initial` (the underlined value) for each
80
+ # valid combination of causality and variability. Combinations not listed have no default:
81
+ # either `initial` isn't allowed (the independent variable) or the combination is invalid.
82
+ _DEFAULT_INITIAL: Mapping[tuple[Causality, Variability], Initial] = MappingProxyType(
83
+ {
84
+ (Causality.OUTPUT, Variability.CONSTANT): Initial.EXACT,
85
+ (Causality.LOCAL, Variability.CONSTANT): Initial.EXACT,
86
+ (Causality.STRUCTURAL_PARAMETER, Variability.FIXED): Initial.EXACT,
87
+ (Causality.STRUCTURAL_PARAMETER, Variability.TUNABLE): Initial.EXACT,
88
+ (Causality.PARAMETER, Variability.FIXED): Initial.EXACT,
89
+ (Causality.PARAMETER, Variability.TUNABLE): Initial.EXACT,
90
+ (Causality.CALCULATED_PARAMETER, Variability.FIXED): Initial.CALCULATED,
91
+ (Causality.CALCULATED_PARAMETER, Variability.TUNABLE): Initial.CALCULATED,
92
+ (Causality.LOCAL, Variability.FIXED): Initial.CALCULATED,
93
+ (Causality.LOCAL, Variability.TUNABLE): Initial.CALCULATED,
94
+ (Causality.INPUT, Variability.DISCRETE): Initial.EXACT,
95
+ (Causality.INPUT, Variability.CONTINUOUS): Initial.EXACT,
96
+ (Causality.OUTPUT, Variability.DISCRETE): Initial.CALCULATED,
97
+ (Causality.OUTPUT, Variability.CONTINUOUS): Initial.CALCULATED,
98
+ (Causality.LOCAL, Variability.DISCRETE): Initial.CALCULATED,
99
+ (Causality.LOCAL, Variability.CONTINUOUS): Initial.CALCULATED,
100
+ }
101
+ )
102
+
103
+
104
+ def default_initial(causality: Causality | str, variability: Variability | str) -> Initial | None:
105
+ """Return the FMI 3.0 standard's default ``initial`` for a causality and variability.
106
+
107
+ ``None`` when ``initial`` isn't allowed for the combination, when the
108
+ combination is invalid, or when either value isn't a known enum value.
109
+ """
110
+ if not isinstance(causality, Causality) or not isinstance(variability, Variability):
111
+ return None
112
+ return _DEFAULT_INITIAL.get((causality, variability))
113
+
114
+
115
+ # --- Parts of variables ---------------------------------------------------------------------
116
+
117
+
118
+ @dataclass(frozen=True, slots=True, kw_only=True)
119
+ class Dimension:
120
+ """One dimension of an array variable: a fixed ``start`` size, or the value reference of its size."""
121
+
122
+ start: int | None = None
123
+ value_reference: int | None = None
124
+
125
+
126
+ @dataclass(frozen=True, slots=True, kw_only=True)
127
+ class Alias:
128
+ """Another name for a variable. ``display_unit`` is only allowed on aliases of float variables."""
129
+
130
+ name: str
131
+ description: str | None = None
132
+ display_unit: str | None = None
133
+
134
+
135
+ # --- Variables ------------------------------------------------------------------------------
136
+
137
+
138
+ @dataclass(frozen=True, slots=True, kw_only=True)
139
+ class AbstractVariable:
140
+ """Attributes every FMI 3.0 Model Variable has, whatever its kind."""
141
+
142
+ name: str
143
+ value_reference: int
144
+ index: int
145
+ """The Variable Index: 1-based position in ``ModelVariables``."""
146
+ variability: Variability | str
147
+ """As written, or else the standard's default for this type and causality."""
148
+ description: str | None = None
149
+ causality: Causality | str = Causality.LOCAL
150
+ can_handle_multiple_set_per_time_instant: bool | None = None
151
+ clocks: tuple[int, ...] | None = None
152
+ """Value references of the clocks this variable belongs to."""
153
+ declared_type: str | None = None
154
+ aliases: tuple[Alias, ...] = ()
155
+ annotations: tuple[Annotation, ...] | None = None
156
+ """``None`` unless read with ``annotations=True``."""
157
+
158
+
159
+ @dataclass(frozen=True, slots=True, kw_only=True)
160
+ class ArrayableVariable(AbstractVariable):
161
+ """A variable that can be an array and has ``initial``: every kind except ``Clock``."""
162
+
163
+ initial: Initial | str | None = None
164
+ """``initial`` exactly as written; see :attr:`effective_initial`."""
165
+ dimensions: tuple[Dimension, ...] = ()
166
+ """Empty for a scalar."""
167
+ intermediate_update: bool | None = None
168
+ previous: int | None = None
169
+
170
+ @property
171
+ def is_array(self) -> bool:
172
+ """Whether the variable has ``<Dimension>`` elements."""
173
+ return bool(self.dimensions)
174
+
175
+ @property
176
+ def effective_initial(self) -> Initial | str | None:
177
+ """``initial`` as written, or else the standard's default for this causality and variability."""
178
+ if self.initial is not None:
179
+ return self.initial
180
+ return default_initial(self.causality, self.variability)
181
+
182
+
183
+ @dataclass(frozen=True, slots=True, kw_only=True)
184
+ class _FloatVariable(ArrayableVariable):
185
+ quantity: str | None = None
186
+ unit: str | None = None
187
+ display_unit: str | None = None
188
+ relative_quantity: bool = False
189
+ unbounded: bool = False
190
+ min: float | None = None
191
+ max: float | None = None
192
+ nominal: float | None = None
193
+ start: float | tuple[float, ...] | None = None
194
+ derivative: int | None = None
195
+ """Value reference of the state this variable is the derivative of."""
196
+ reinit: bool = False
197
+
198
+
199
+ @dataclass(frozen=True, slots=True, kw_only=True)
200
+ class Float32Variable(_FloatVariable):
201
+ """A ``Float32`` variable."""
202
+
203
+ type_name: str = field(default="Float32", init=False)
204
+
205
+
206
+ @dataclass(frozen=True, slots=True, kw_only=True)
207
+ class Float64Variable(_FloatVariable):
208
+ """A ``Float64`` variable."""
209
+
210
+ type_name: str = field(default="Float64", init=False)
211
+
212
+
213
+ @dataclass(frozen=True, slots=True, kw_only=True)
214
+ class _IntegerVariable(ArrayableVariable):
215
+ quantity: str | None = None
216
+ min: int | None = None
217
+ max: int | None = None
218
+ start: int | tuple[int, ...] | None = None
219
+
220
+
221
+ @dataclass(frozen=True, slots=True, kw_only=True)
222
+ class Int8Variable(_IntegerVariable):
223
+ """An ``Int8`` variable."""
224
+
225
+ type_name: str = field(default="Int8", init=False)
226
+
227
+
228
+ @dataclass(frozen=True, slots=True, kw_only=True)
229
+ class UInt8Variable(_IntegerVariable):
230
+ """A ``UInt8`` variable."""
231
+
232
+ type_name: str = field(default="UInt8", init=False)
233
+
234
+
235
+ @dataclass(frozen=True, slots=True, kw_only=True)
236
+ class Int16Variable(_IntegerVariable):
237
+ """An ``Int16`` variable."""
238
+
239
+ type_name: str = field(default="Int16", init=False)
240
+
241
+
242
+ @dataclass(frozen=True, slots=True, kw_only=True)
243
+ class UInt16Variable(_IntegerVariable):
244
+ """A ``UInt16`` variable."""
245
+
246
+ type_name: str = field(default="UInt16", init=False)
247
+
248
+
249
+ @dataclass(frozen=True, slots=True, kw_only=True)
250
+ class Int32Variable(_IntegerVariable):
251
+ """An ``Int32`` variable."""
252
+
253
+ type_name: str = field(default="Int32", init=False)
254
+
255
+
256
+ @dataclass(frozen=True, slots=True, kw_only=True)
257
+ class UInt32Variable(_IntegerVariable):
258
+ """A ``UInt32`` variable."""
259
+
260
+ type_name: str = field(default="UInt32", init=False)
261
+
262
+
263
+ @dataclass(frozen=True, slots=True, kw_only=True)
264
+ class Int64Variable(_IntegerVariable):
265
+ """An ``Int64`` variable."""
266
+
267
+ type_name: str = field(default="Int64", init=False)
268
+
269
+
270
+ @dataclass(frozen=True, slots=True, kw_only=True)
271
+ class UInt64Variable(_IntegerVariable):
272
+ """A ``UInt64`` variable."""
273
+
274
+ type_name: str = field(default="UInt64", init=False)
275
+
276
+
277
+ @dataclass(frozen=True, slots=True, kw_only=True)
278
+ class BooleanVariable(ArrayableVariable):
279
+ """A ``Boolean`` variable."""
280
+
281
+ type_name: str = field(default="Boolean", init=False)
282
+ start: bool | tuple[bool, ...] | None = None
283
+
284
+
285
+ @dataclass(frozen=True, slots=True, kw_only=True)
286
+ class StringVariable(ArrayableVariable):
287
+ """A ``String`` variable. Start values come from ``<Start>`` children."""
288
+
289
+ type_name: str = field(default="String", init=False)
290
+ start: str | tuple[str, ...] | None = None
291
+
292
+
293
+ @dataclass(frozen=True, slots=True, kw_only=True)
294
+ class BinaryVariable(ArrayableVariable):
295
+ """A ``Binary`` variable. Start values come from ``<Start>`` children, as ``bytes``."""
296
+
297
+ type_name: str = field(default="Binary", init=False)
298
+ mime_type: str = "application/octet-stream"
299
+ max_size: int | None = None
300
+ start: bytes | tuple[bytes, ...] | None = None
301
+
302
+
303
+ @dataclass(frozen=True, slots=True, kw_only=True)
304
+ class EnumerationVariable(ArrayableVariable):
305
+ """An ``Enumeration`` variable. ``declared_type`` names its EnumerationType."""
306
+
307
+ type_name: str = field(default="Enumeration", init=False)
308
+ quantity: str | None = None
309
+ min: int | None = None
310
+ max: int | None = None
311
+ start: int | tuple[int, ...] | None = None
312
+
313
+
314
+ @dataclass(frozen=True, slots=True, kw_only=True)
315
+ class ClockVariable(AbstractVariable):
316
+ """A ``Clock`` variable. Clocks are never arrays and have no ``initial`` or ``start``."""
317
+
318
+ type_name: str = field(default="Clock", init=False)
319
+ interval_variability: IntervalVariability | str
320
+ can_be_deactivated: bool = False
321
+ priority: int | None = None
322
+ interval_decimal: float | None = None
323
+ shift_decimal: float = 0.0
324
+ supports_fraction: bool = False
325
+ resolution: int | None = None
326
+ interval_counter: int | None = None
327
+ shift_counter: int = 0
328
+
329
+
330
+ Variable = (
331
+ Float32Variable
332
+ | Float64Variable
333
+ | Int8Variable
334
+ | UInt8Variable
335
+ | Int16Variable
336
+ | UInt16Variable
337
+ | Int32Variable
338
+ | UInt32Variable
339
+ | Int64Variable
340
+ | UInt64Variable
341
+ | BooleanVariable
342
+ | StringVariable
343
+ | BinaryVariable
344
+ | EnumerationVariable
345
+ | ClockVariable
346
+ )
347
+ """Any FMI 3.0 Model Variable."""
348
+
349
+
350
+ # --- Attribute tables -----------------------------------------------------------------------
351
+
352
+ _ABSTRACT_ATTRS = (
353
+ required_text("name", "name"),
354
+ Attr("valueReference", "value_reference", c.UNSIGNED_INT, required=True),
355
+ text("description", "description"),
356
+ Attr("causality", "causality", c.EnumConverter(Causality)),
357
+ Attr("variability", "variability", c.EnumConverter(Variability)),
358
+ flag("canHandleMultipleSetPerTimeInstant", "can_handle_multiple_set_per_time_instant"),
359
+ Attr("clocks", "clocks", c.ListOf(c.UNSIGNED_INT)),
360
+ text("declaredType", "declared_type"),
361
+ )
362
+
363
+ _ARRAYABLE_ATTRS = (
364
+ *_ABSTRACT_ATTRS,
365
+ Attr("initial", "initial", c.EnumConverter(Initial)),
366
+ flag("intermediateUpdate", "intermediate_update"),
367
+ Attr("previous", "previous", c.UNSIGNED_INT),
368
+ )
369
+
370
+
371
+ def _float_attrs() -> AttrTable:
372
+ return table(
373
+ *_ARRAYABLE_ATTRS,
374
+ text("quantity", "quantity"),
375
+ text("unit", "unit"),
376
+ text("displayUnit", "display_unit"),
377
+ flag("relativeQuantity", "relative_quantity"),
378
+ flag("unbounded", "unbounded"),
379
+ double("min", "min"),
380
+ double("max", "max"),
381
+ double("nominal", "nominal"),
382
+ Attr("start", "start", c.ListOf(c.to_double)),
383
+ Attr("derivative", "derivative", c.UNSIGNED_INT),
384
+ flag("reinit", "reinit"),
385
+ )
386
+
387
+
388
+ def _integer_attrs(bounds: c.IntRange) -> AttrTable:
389
+ return table(
390
+ *_ARRAYABLE_ATTRS,
391
+ text("quantity", "quantity"),
392
+ Attr("min", "min", bounds),
393
+ Attr("max", "max", bounds),
394
+ Attr("start", "start", c.ListOf(bounds)),
395
+ )
396
+
397
+
398
+ BOOLEAN_ATTRS = table(*_ARRAYABLE_ATTRS, Attr("start", "start", c.ListOf(c.to_bool)))
399
+
400
+ STRING_ATTRS = table(*_ARRAYABLE_ATTRS)
401
+
402
+ BINARY_ATTRS = table(
403
+ *_ARRAYABLE_ATTRS,
404
+ text("mimeType", "mime_type"),
405
+ Attr("maxSize", "max_size", c.to_unsigned_int), # xs:nonNegativeInteger has no upper bound
406
+ )
407
+
408
+ ENUMERATION_ATTRS = table(
409
+ *(a for a in _ARRAYABLE_ATTRS if a.xml != "declaredType"),
410
+ required_text("declaredType", "declared_type"),
411
+ text("quantity", "quantity"),
412
+ Attr("min", "min", c.LONG),
413
+ Attr("max", "max", c.LONG),
414
+ Attr("start", "start", c.ListOf(c.LONG)),
415
+ )
416
+
417
+ CLOCK_ATTRS = table(
418
+ *_ABSTRACT_ATTRS,
419
+ flag("canBeDeactivated", "can_be_deactivated"),
420
+ Attr("priority", "priority", c.UNSIGNED_INT),
421
+ Attr("intervalVariability", "interval_variability", c.EnumConverter(IntervalVariability), required=True),
422
+ double("intervalDecimal", "interval_decimal"),
423
+ double("shiftDecimal", "shift_decimal"),
424
+ flag("supportsFraction", "supports_fraction"),
425
+ Attr("resolution", "resolution", c.UNSIGNED_LONG),
426
+ Attr("intervalCounter", "interval_counter", c.UNSIGNED_LONG),
427
+ Attr("shiftCounter", "shift_counter", c.UNSIGNED_LONG),
428
+ )
429
+
430
+ DIMENSION_ATTRS = table(
431
+ Attr("start", "start", c.UNSIGNED_LONG),
432
+ Attr("valueReference", "value_reference", c.UNSIGNED_INT),
433
+ )
434
+
435
+ ALIAS_ATTRS = table(required_text("name", "name"), text("description", "description"))
436
+
437
+ FLOAT_ALIAS_ATTRS = table(
438
+ required_text("name", "name"), text("description", "description"), text("displayUnit", "display_unit")
439
+ )
440
+
441
+ STRING_START_ATTRS = table(text("value", "value"))
442
+
443
+ BINARY_START_ATTRS = table(Attr("value", "value", c.to_hex_binary))
444
+
445
+ VariableFields = tuple[type[AbstractVariable], dict[str, Any]]
446
+ """A variable's class and constructor arguments, everything but its Variable Index."""
447
+
448
+
449
+ # --- Builders -------------------------------------------------------------------------------
450
+
451
+
452
+ class _Part(Builder[object]):
453
+ """Builds a part of a variable (``Dimension``, ``Alias``) from its attributes."""
454
+
455
+ __slots__ = ("_attrs", "_cls")
456
+
457
+ def __init__(self, cls: type[object], attrs: AttrTable) -> None:
458
+ self._cls = cls
459
+ self._attrs = attrs
460
+
461
+ def __call__(self, frame: Frame, /, *, strict: bool) -> object:
462
+ """Build the part."""
463
+ return self._cls(**attributes(frame, self._attrs, strict=strict))
464
+
465
+
466
+ class _StartValue(Builder[object]):
467
+ """Builds a ``<Start value="…">`` child of a String or Binary variable into its value."""
468
+
469
+ __slots__ = ("_attrs",)
470
+
471
+ def __init__(self, attrs: AttrTable) -> None:
472
+ self._attrs = attrs
473
+
474
+ def __call__(self, frame: Frame, /, *, strict: bool) -> object:
475
+ """Return the start value; a missing ``value`` is the empty string or empty bytes."""
476
+ fields = attributes(frame, self._attrs, strict=strict)
477
+ return fields.get("value", b"" if self._attrs is BINARY_START_ATTRS else "")
478
+
479
+
480
+ def _shape_start(frame: Frame, values: tuple[Any, ...], *, is_array: bool, strict: bool) -> Any:
481
+ """Return a scalar's start as one value and an array's as a tuple."""
482
+ if is_array:
483
+ return values
484
+ if len(values) == 1:
485
+ return values[0]
486
+ if not values:
487
+ return None
488
+ if strict:
489
+ raise frame.error(f"scalar <{frame.tag} name={frame.attrs.get('name')!r}> has {len(values)} start values")
490
+ return values
491
+
492
+
493
+ class _VariableBuilder(Builder[VariableFields]):
494
+ """Builds one variable element into its class and constructor arguments."""
495
+
496
+ __slots__ = ("_annotations", "_attrs", "_cls", "_start_children")
497
+
498
+ def __init__(
499
+ self, cls: type[AbstractVariable], attrs: AttrTable, *, annotations: bool, start_children: bool = False
500
+ ) -> None:
501
+ self._cls = cls
502
+ self._attrs = attrs
503
+ self._annotations = annotations
504
+ self._start_children = start_children
505
+
506
+ def __call__(self, frame: Frame, /, *, strict: bool) -> VariableFields:
507
+ """Merge attributes and children into the variable's fields."""
508
+ fields = attributes(frame, self._attrs, strict=strict)
509
+ if "variability" not in fields:
510
+ causality = fields.get("causality", Causality.LOCAL)
511
+ fields["variability"] = default_variability(frame.tag, str(getattr(causality, "value", causality)))
512
+ aliases = frame.all("Alias")
513
+ if aliases:
514
+ fields["aliases"] = tuple(aliases)
515
+ if self._annotations:
516
+ fields["annotations"] = frame.one("Annotations", strict=strict) or ()
517
+ if self._cls is ClockVariable:
518
+ return self._cls, fields
519
+ dimensions = tuple(frame.all("Dimension"))
520
+ if dimensions:
521
+ fields["dimensions"] = dimensions
522
+ starts = tuple(frame.all("Start")) if self._start_children else fields.pop("start", ())
523
+ start = _shape_start(frame, starts, is_array=bool(dimensions), strict=strict)
524
+ if start is not None:
525
+ fields["start"] = start
526
+ return self._cls, fields
527
+
528
+
529
+ def _variable_grammar(
530
+ tag: str, builder: _VariableBuilder, start_attrs: AttrTable | None, *, annotations: bool
531
+ ) -> Grammar[VariableFields]:
532
+ children: dict[str, ChildRule] = {"Annotations": annotations_rule.CONTAINER if annotations else SKIP}
533
+ alias_attrs = FLOAT_ALIAS_ATTRS if tag in _FLOAT_ELEMENTS else ALIAS_ATTRS
534
+ children["Alias"] = _Part(Alias, alias_attrs)
535
+ if tag != "Clock":
536
+ children["Dimension"] = _Part(Dimension, DIMENSION_ATTRS)
537
+ if start_attrs is not None:
538
+ children["Start"] = _StartValue(start_attrs)
539
+ return Grammar(
540
+ root=tag,
541
+ stop_at="",
542
+ build_root=builder,
543
+ children={tag: children, "Annotations": {"Annotation": annotations_rule.ANNOTATION}},
544
+ )
545
+
546
+
547
+ def _variable_kinds() -> Mapping[str, tuple[type[AbstractVariable], AttrTable]]:
548
+ float_attrs = _float_attrs()
549
+ integer_kinds: dict[str, tuple[type[AbstractVariable], c.IntRange]] = {
550
+ "Int8": (Int8Variable, c.BYTE),
551
+ "UInt8": (UInt8Variable, c.UNSIGNED_BYTE),
552
+ "Int16": (Int16Variable, c.SHORT),
553
+ "UInt16": (UInt16Variable, c.UNSIGNED_SHORT),
554
+ "Int32": (Int32Variable, c.INT),
555
+ "UInt32": (UInt32Variable, c.UNSIGNED_INT),
556
+ "Int64": (Int64Variable, c.LONG),
557
+ "UInt64": (UInt64Variable, c.UNSIGNED_LONG),
558
+ }
559
+ return MappingProxyType(
560
+ {
561
+ "Float32": (Float32Variable, float_attrs),
562
+ "Float64": (Float64Variable, float_attrs),
563
+ **{tag: (cls, _integer_attrs(bounds)) for tag, (cls, bounds) in integer_kinds.items()},
564
+ "Boolean": (BooleanVariable, BOOLEAN_ATTRS),
565
+ "String": (StringVariable, STRING_ATTRS),
566
+ "Binary": (BinaryVariable, BINARY_ATTRS),
567
+ "Enumeration": (EnumerationVariable, ENUMERATION_ATTRS),
568
+ "Clock": (ClockVariable, CLOCK_ATTRS),
569
+ }
570
+ )
571
+
572
+
573
+ VARIABLE_KINDS = _variable_kinds()
574
+ """Each variable element's class and attribute table."""
575
+
576
+ _START_CHILDREN: Mapping[str, AttrTable] = MappingProxyType(
577
+ {"String": STRING_START_ATTRS, "Binary": BINARY_START_ATTRS}
578
+ )
579
+
580
+
581
+ def _grammars(*, annotations: bool) -> Mapping[str, Grammar[VariableFields]]:
582
+ grammars: dict[str, Grammar[VariableFields]] = {}
583
+ for tag, (cls, attrs) in VARIABLE_KINDS.items():
584
+ start_attrs = _START_CHILDREN.get(tag)
585
+ builder = _VariableBuilder(cls, attrs, annotations=annotations, start_children=start_attrs is not None)
586
+ grammars[tag] = _variable_grammar(tag, builder, start_attrs, annotations=annotations)
587
+ return MappingProxyType(grammars)
588
+
589
+
590
+ VARIABLE_GRAMMARS = _grammars(annotations=False)
591
+ """The grammar for each variable element, keyed by element name; annotations are skipped."""
592
+
593
+ VARIABLE_GRAMMARS_WITH_ANNOTATIONS = _grammars(annotations=True)
594
+ """The same, keeping each variable's annotations."""
595
+
596
+
597
+ def filter_values(element: str, attrs: Mapping[str, str]) -> tuple[str, str]:
598
+ """Return a variable's causality and variability from its raw attributes, with defaults applied."""
599
+ causality = attrs.get("causality", Causality.LOCAL.value).strip()
600
+ variability = attrs.get("variability")
601
+ if variability is None:
602
+ return causality, default_variability(element, causality).value
603
+ return causality, variability.strip()
mdxml/py.typed ADDED
File without changes