jcmsuite-data-tree 1.0.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,989 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Primitive schema types used to validate data-tree values."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import NoReturn, Protocol, TypeAlias, cast
9
+
10
+ from . import data_primitives as primitives
11
+ from .decorators import accepts
12
+ from .system import FilePath
13
+ from .toolbox import NiL, typename
14
+
15
+ NumericScalar: TypeAlias = int | float | complex
16
+ ScalarType: TypeAlias = type[int] | type[float] | type[complex]
17
+ RangeBound: TypeAlias = NumericScalar | NiL
18
+ StringDefault: TypeAlias = str | NiL
19
+ PathDefault: TypeAlias = FilePath | NiL
20
+ NumericSequenceDefault: TypeAlias = (
21
+ list[NumericScalar] | tuple[NumericScalar, ...] | NiL
22
+ )
23
+ StringSequenceDefault: TypeAlias = list[str] | tuple[str, ...] | NiL
24
+ SchemaScalarType: TypeAlias = ScalarType | type[str]
25
+
26
+
27
+ class PrimitiveValue(Protocol):
28
+ """Primitive protocol exposing the runtime value getter used by schemas."""
29
+
30
+ def GetValue(self) -> object: ...
31
+
32
+
33
+ def _coerce_numeric_scalar(value: NumericScalar, dtype: ScalarType) -> NumericScalar:
34
+ """Convert a numeric default to the requested scalar type."""
35
+
36
+ if dtype is complex:
37
+ return complex(value)
38
+ if dtype is float:
39
+ assert not isinstance(value, complex)
40
+ return float(value)
41
+ assert not isinstance(value, complex)
42
+ return int(value)
43
+
44
+
45
+ #
46
+
47
+ COORDINATE_RENAMING_STRINGS = set()
48
+ COORDINATE_RENAMING_STRINGS.add("-X:-Y:Z")
49
+ COORDINATE_RENAMING_STRINGS.add("-X:-Z:-Y")
50
+ COORDINATE_RENAMING_STRINGS.add("-X:Y:-Z")
51
+ COORDINATE_RENAMING_STRINGS.add("-X:Z:Y")
52
+ COORDINATE_RENAMING_STRINGS.add("-Y:-X:-Z")
53
+ COORDINATE_RENAMING_STRINGS.add("-Y:-Z:X")
54
+ COORDINATE_RENAMING_STRINGS.add("-Y:X:Z")
55
+ COORDINATE_RENAMING_STRINGS.add("-Y:Z:-X")
56
+ COORDINATE_RENAMING_STRINGS.add("-Z:-X:Y")
57
+ COORDINATE_RENAMING_STRINGS.add("-Z:-Y:-X")
58
+ COORDINATE_RENAMING_STRINGS.add("-Z:X:-Y")
59
+ COORDINATE_RENAMING_STRINGS.add("-Z:Y:X")
60
+ COORDINATE_RENAMING_STRINGS.add("X:-Y:-Z")
61
+ COORDINATE_RENAMING_STRINGS.add("X:-Z:Y")
62
+ COORDINATE_RENAMING_STRINGS.add("X:Y:Z")
63
+ COORDINATE_RENAMING_STRINGS.add("X:Z:-Y")
64
+ COORDINATE_RENAMING_STRINGS.add("Y:-X:Z")
65
+ COORDINATE_RENAMING_STRINGS.add("Y:-Z:-X")
66
+ COORDINATE_RENAMING_STRINGS.add("Y:X:-Z")
67
+ COORDINATE_RENAMING_STRINGS.add("Y:Z:X")
68
+ COORDINATE_RENAMING_STRINGS.add("Z:-X:-Y")
69
+ COORDINATE_RENAMING_STRINGS.add("Z:-Y:X")
70
+ COORDINATE_RENAMING_STRINGS.add("Z:X:Y")
71
+ COORDINATE_RENAMING_STRINGS.add("Z:Y:-X")
72
+
73
+
74
+ class Range:
75
+ # @accepts(object, (int, float, NiL), (int, float, NiL), lowerBnD=(int, float, NiL), upperBnD=(int, float, NiL))
76
+ """Store a lower and upper bound."""
77
+
78
+ def __init__(self, lowerBnD: RangeBound, upperBnd: RangeBound) -> None:
79
+ """Initialize the range."""
80
+ self.first: RangeBound = lowerBnD
81
+ self.second: RangeBound = upperBnd
82
+
83
+ def __getitem__(self, key: int) -> RangeBound:
84
+ """Return the lower or upper bound by index."""
85
+ if key == 0:
86
+ return self.first
87
+ elif key == 1:
88
+ return self.second
89
+ else:
90
+ raise ValueError("Out of range.")
91
+
92
+
93
+ #
94
+
95
+
96
+ class PrimitiveSchema:
97
+ """Base interface for primitive schema definitions."""
98
+
99
+ def Copy(self) -> PrimitiveSchema:
100
+ """Return a copy of this Primitive schema."""
101
+ raise RuntimeError(
102
+ "Class PrimitiveSchema should be used only through its subclasses."
103
+ )
104
+
105
+ def CreateTreePrimitive(self) -> object:
106
+ """Create a runtime primitive for this schema."""
107
+ raise RuntimeError(
108
+ "Class PrimitiveSchema should be used only through its subclasses."
109
+ )
110
+
111
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
112
+ """Return whether a primitive satisfies this schema."""
113
+ raise RuntimeError(
114
+ "Class PrimitiveSchema should be used only through its subclasses."
115
+ )
116
+
117
+ def TypeName(self) -> str:
118
+ """Return the type name for this schema."""
119
+ raise RuntimeError(
120
+ "Class PrimitiveSchema should be used only through its subclasses."
121
+ )
122
+
123
+ def RangeAsString(self) -> str:
124
+ """Return the accepted range as text."""
125
+ raise RuntimeError(
126
+ "Class PrimitiveSchema should be used only through its subclasses."
127
+ )
128
+
129
+ def HasDefault(self) -> bool:
130
+ """Return whether this schema defines a default value."""
131
+ raise RuntimeError(
132
+ "Class PrimitiveSchema should be used only through its subclasses."
133
+ )
134
+
135
+
136
+ class NumberSchema(PrimitiveSchema):
137
+ """Schema for scalar numeric values."""
138
+
139
+ def __init__(
140
+ self,
141
+ default: NumericScalar | NiL | None,
142
+ dataRange: Range,
143
+ dtype: ScalarType,
144
+ ) -> None:
145
+ """Initialize the Number schema."""
146
+ if default is None or isinstance(default, NiL):
147
+ self._default = None
148
+ else:
149
+ self._default = _coerce_numeric_scalar(default, dtype)
150
+ try:
151
+ if self._default == dtype(NiL()):
152
+ self._default = None
153
+ except Exception:
154
+ pass
155
+ self._range: Range = dataRange
156
+ self._type: ScalarType = dtype
157
+ self._typename: str = typename(dtype(0), False)
158
+
159
+ @staticmethod
160
+ def Create(
161
+ default: NumericScalar | NiL | None = None,
162
+ dataRange: Range | None = None,
163
+ lowerBound: NumericScalar | NiL | None = None,
164
+ dtype: ScalarType = float,
165
+ ) -> NumberSchema:
166
+ """Create a new NumberSchema instance."""
167
+ if dataRange is not None:
168
+ pass
169
+ elif lowerBound is not None:
170
+ dataRange = Range(lowerBound, NiL())
171
+ else:
172
+ dataRange = Range(NiL(), NiL())
173
+ return NumberSchema(default, dataRange, dtype)
174
+
175
+ def Copy(self) -> NumberSchema:
176
+ """Return a copy of this Number schema."""
177
+ rv = NumberSchema(self._default, self._range, self._type)
178
+ return rv
179
+
180
+ def CreateTreePrimitive(self) -> primitives.NumberPrimitive:
181
+ """Create a runtime primitive for this schema."""
182
+ rv: primitives.NumberPrimitive = primitives.NumberPrimitive(dtype=self._type)
183
+ if self._default is not None:
184
+ rv.SetValue(self._default)
185
+ return rv
186
+
187
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
188
+ """Return whether a primitive satisfies this schema."""
189
+ value = dataPrimitive.GetValue()
190
+ if isinstance(value, NiL):
191
+ return False
192
+ if not isinstance(value, (int, float, complex)):
193
+ return False
194
+ elif value == float("-inf"):
195
+ if not (
196
+ isinstance(self._range.first, NiL) or self._range.first == float("-inf")
197
+ ):
198
+ return False
199
+ elif value == float("inf"):
200
+ if not (
201
+ isinstance(self._range.second, NiL)
202
+ or self._range.second == float("inf")
203
+ ):
204
+ return False
205
+ else:
206
+ if not (
207
+ isinstance(self._range.first, NiL) or self._range.first == float("-inf")
208
+ ):
209
+ assert isinstance(self._range.first, (int, float, complex))
210
+ if (
211
+ value.real < self._range.first.real
212
+ or value.imag < self._range.first.imag
213
+ ):
214
+ return False
215
+ if not (
216
+ isinstance(self._range.second, NiL)
217
+ or self._range.second == float("inf")
218
+ ):
219
+ assert isinstance(self._range.second, (int, float, complex))
220
+ if (
221
+ value.real > self._range.second.real
222
+ or value.imag > self._range.second.imag
223
+ ):
224
+ return False
225
+ return True
226
+
227
+ def TypeName(self) -> str:
228
+ """Return the type name for this schema."""
229
+ return self._typename
230
+
231
+ def RangeAsString(self) -> str:
232
+ """Return the accepted range as text."""
233
+ out = "["
234
+ if isinstance(self._range.first, NiL) and isinstance(self._range.second, NiL):
235
+ out += "unrestricted"
236
+ else:
237
+ if isinstance(self._range.first, NiL) or self._range.first == float("-inf"):
238
+ out += "-inf"
239
+ else:
240
+ out += str(self._range.first)
241
+ out += ", "
242
+ if isinstance(self._range.second, NiL) or self._range.second == float(
243
+ "inf"
244
+ ):
245
+ out += "inf"
246
+ else:
247
+ out += str(self._range.second)
248
+ out += "]"
249
+ return out
250
+
251
+ def HasDefault(self) -> bool:
252
+ """Return whether this schema defines a default value."""
253
+ return self._default is not None
254
+
255
+
256
+ class EnumSchema(PrimitiveSchema):
257
+ """Schema for enumerated string values."""
258
+
259
+ def __init__(self, stringSet: set[str], default: str | NiL) -> None:
260
+ """Initialize the Enum schema."""
261
+ self._default: StringDefault
262
+ if isinstance(default, NiL):
263
+ self._default = default
264
+ else:
265
+ self._default = str(default)
266
+ self._stringSet: set[str] = set(stringSet)
267
+
268
+ @staticmethod
269
+ def Create(stringSet: set[str] = set(), default: str | NiL = NiL()) -> EnumSchema:
270
+ """Create a new EnumSchema instance."""
271
+ return EnumSchema(stringSet, default)
272
+
273
+ def Copy(self) -> EnumSchema:
274
+ """Return a copy of this Enum schema."""
275
+ rv = EnumSchema(self._stringSet.copy(), self._default)
276
+ return rv
277
+
278
+ def CreateTreePrimitive(self) -> primitives.StringPrimitive:
279
+ """Create a runtime primitive for this schema."""
280
+ rv: primitives.StringPrimitive = primitives.StringPrimitive()
281
+ if not isinstance(self._default, NiL):
282
+ rv.SetValue(self._default)
283
+ return rv
284
+
285
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
286
+ """Return whether a primitive satisfies this schema."""
287
+ value = dataPrimitive.GetValue()
288
+ if len(self._stringSet) == 0:
289
+ return True
290
+ if value in self._stringSet:
291
+ return True
292
+ else:
293
+ return False
294
+
295
+ def TypeName(self) -> str:
296
+ """Return the type name for this schema."""
297
+ return "enum"
298
+
299
+ def RangeAsString(self) -> str:
300
+ """Return the accepted range as text."""
301
+ return ", ".join(sorted(self._stringSet))
302
+
303
+ def HasDefault(self) -> bool:
304
+ """Return whether this schema defines a default value."""
305
+ return not isinstance(self._default, NiL)
306
+
307
+
308
+ class BooleanSchema(EnumSchema):
309
+ """Schema for boolean values."""
310
+
311
+ def __init__(self, default: bool) -> None:
312
+ """Initialize the Boolean schema."""
313
+ default_value: str = "yes" if default else "no"
314
+ EnumSchema.__init__(self, set(["yes", "no"]), default_value)
315
+
316
+ @staticmethod
317
+ def Create(stringSet: set[str] = set(), default: object = True) -> BooleanSchema:
318
+ """Create a new BooleanSchema instance."""
319
+ if isinstance(default, str):
320
+ return BooleanSchema(default.lower() == "yes")
321
+ return BooleanSchema(bool(default))
322
+
323
+ def Copy(self) -> BooleanSchema:
324
+ """Return a copy of this Boolean schema."""
325
+ rv = BooleanSchema(self._default == "yes")
326
+ return rv
327
+
328
+
329
+ class StringSchema(PrimitiveSchema):
330
+ """Schema for string values."""
331
+
332
+ def __init__(
333
+ self, default: StringDefault = NiL(), rangeString: str | None = None
334
+ ) -> None:
335
+ """Initialize the String schema."""
336
+ self._default: StringDefault
337
+ if isinstance(default, NiL):
338
+ self._default = default
339
+ else:
340
+ self._default = str(default)
341
+ self._rangeString: str | None = rangeString
342
+
343
+ @staticmethod
344
+ def Create(
345
+ default: StringDefault = NiL(), rangeString: str | None = None
346
+ ) -> StringSchema:
347
+ """Create a new StringSchema instance."""
348
+ return StringSchema(default, rangeString)
349
+
350
+ def Copy(self) -> StringSchema:
351
+ """Return a copy of this String schema."""
352
+ rv = StringSchema(self._default, self._rangeString)
353
+ return rv
354
+
355
+ def CreateTreePrimitive(self) -> primitives.StringPrimitive:
356
+ """Create a runtime primitive for this schema."""
357
+ rv: primitives.StringPrimitive = primitives.StringPrimitive()
358
+ if not isinstance(self._default, NiL):
359
+ rv.SetValue(self._default)
360
+ return rv
361
+
362
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
363
+ """Return whether a primitive satisfies this schema."""
364
+ return True
365
+
366
+ def TypeName(self) -> str:
367
+ """Return the type name for this schema."""
368
+ return "string"
369
+
370
+ def RangeAsString(self) -> str:
371
+ """Return the accepted range as text."""
372
+ out = "[]"
373
+ if self._rangeString:
374
+ out = self._rangeString
375
+ return out
376
+
377
+ def HasDefault(self) -> bool:
378
+ """Return whether this schema defines a default value."""
379
+ return not isinstance(self._default, NiL)
380
+
381
+
382
+ class FileSchema(PrimitiveSchema):
383
+ """Schema for file-path values."""
384
+
385
+ def __init__(self, default: PathDefault = NiL()) -> None:
386
+ """Initialize the File schema."""
387
+ self._default: PathDefault = default
388
+
389
+ @staticmethod
390
+ @accepts((FilePath, NiL), default=(FilePath, NiL))
391
+ def Create(default: PathDefault = NiL()) -> FileSchema:
392
+ """Create a new FileSchema instance."""
393
+ return FileSchema(default)
394
+
395
+ def Copy(self) -> FileSchema:
396
+ """Return a copy of this File schema."""
397
+ rv = FileSchema(self._default)
398
+ return rv
399
+
400
+ def CreateTreePrimitive(self) -> primitives.FilePrimitive:
401
+ """Create a runtime primitive for this schema."""
402
+ rv: primitives.FilePrimitive = primitives.FilePrimitive()
403
+ if not isinstance(self._default, NiL):
404
+ rv.SetValue(self._default)
405
+ return rv
406
+
407
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
408
+ """Return whether a primitive satisfies this schema."""
409
+ return True
410
+
411
+ def TypeName(self) -> str:
412
+ """Return the type name for this schema."""
413
+ return "file"
414
+
415
+ def RangeAsString(self) -> str:
416
+ """Return the accepted range as text."""
417
+ out = "[]"
418
+ return out
419
+
420
+ def HasDefault(self) -> bool:
421
+ """Return whether this schema defines a default value."""
422
+ return not isinstance(self._default, NiL)
423
+
424
+
425
+ class InputFileSchema(PrimitiveSchema):
426
+ """Schema for input file-path values."""
427
+
428
+ def __init__(self, default: PathDefault = NiL()) -> None:
429
+ """Initialize the InputFile schema."""
430
+ self._default: PathDefault = default
431
+
432
+ @staticmethod
433
+ @accepts((FilePath, NiL), default=(FilePath, NiL))
434
+ def Create(default: PathDefault = NiL()) -> InputFileSchema:
435
+ """Create a new InputFileSchema instance."""
436
+ return InputFileSchema(default)
437
+
438
+ def Copy(self) -> InputFileSchema:
439
+ """Return a copy of this InputFile schema."""
440
+ rv = InputFileSchema(self._default)
441
+ return rv
442
+
443
+ def CreateTreePrimitive(self) -> primitives.FilePrimitive:
444
+ """Create a runtime primitive for this schema."""
445
+ rv: primitives.FilePrimitive = primitives.FilePrimitive()
446
+ if not isinstance(self._default, NiL):
447
+ rv.SetValue(self._default)
448
+ return rv
449
+
450
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
451
+ """Return whether a primitive satisfies this schema."""
452
+ return True
453
+
454
+ def TypeName(self) -> str:
455
+ """Return the type name for this schema."""
456
+ return "input file"
457
+
458
+ def RangeAsString(self) -> str:
459
+ """Return the accepted range as text."""
460
+ out = "[]"
461
+ return out
462
+
463
+ def HasDefault(self) -> bool:
464
+ """Return whether this schema defines a default value."""
465
+ return not isinstance(self._default, NiL)
466
+
467
+
468
+ class OutputFileSchema(PrimitiveSchema):
469
+ """Schema for output file-path values."""
470
+
471
+ def __init__(self, default: PathDefault = NiL()) -> None:
472
+ """Initialize the OutputFile schema."""
473
+ self._default: PathDefault = default
474
+
475
+ @staticmethod
476
+ @accepts((FilePath, NiL), default=(FilePath, NiL))
477
+ def Create(default: PathDefault = NiL()) -> OutputFileSchema:
478
+ """Create a new OutputFileSchema instance."""
479
+ return OutputFileSchema(default)
480
+
481
+ def Copy(self) -> OutputFileSchema:
482
+ """Return a copy of this OutputFile schema."""
483
+ rv = OutputFileSchema(self._default)
484
+ return rv
485
+
486
+ def CreateTreePrimitive(self) -> primitives.FilePrimitive:
487
+ """Create a runtime primitive for this schema."""
488
+ rv: primitives.FilePrimitive = primitives.FilePrimitive()
489
+ if not isinstance(self._default, NiL):
490
+ rv.SetValue(self._default)
491
+ return rv
492
+
493
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
494
+ """Return whether a primitive satisfies this schema."""
495
+ return True
496
+
497
+ def TypeName(self) -> str:
498
+ """Return the type name for this schema."""
499
+ return "output file"
500
+
501
+ def RangeAsString(self) -> str:
502
+ """Return the accepted range as text."""
503
+ out = "[]"
504
+ return out
505
+
506
+ def HasDefault(self) -> bool:
507
+ """Return whether this schema defines a default value."""
508
+ return not isinstance(self._default, NiL)
509
+
510
+
511
+ class TreePathSchema(PrimitiveSchema):
512
+ """Schema for tree-path values."""
513
+
514
+ def __init__(self, default: PathDefault = NiL()) -> None:
515
+ """Initialize the TreePath schema."""
516
+ self._default: PathDefault = default
517
+
518
+ @staticmethod
519
+ @accepts((FilePath, NiL), default=(FilePath, NiL))
520
+ def Create(default: PathDefault = NiL()) -> TreePathSchema:
521
+ """Create a new TreePathSchema instance."""
522
+ return TreePathSchema(default)
523
+
524
+ def Copy(self) -> TreePathSchema:
525
+ """Return a copy of this TreePath schema."""
526
+ rv = TreePathSchema(self._default)
527
+ return rv
528
+
529
+ def CreateTreePrimitive(self) -> primitives.FilePrimitive:
530
+ """Create a runtime primitive for this schema."""
531
+ rv: primitives.FilePrimitive = primitives.FilePrimitive()
532
+ if not isinstance(self._default, NiL):
533
+ rv.SetValue(self._default)
534
+ return rv
535
+
536
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
537
+ """Return whether a primitive satisfies this schema."""
538
+ return True
539
+
540
+ def TypeName(self) -> str:
541
+ """Return the type name for this schema."""
542
+ return "file"
543
+
544
+ def RangeAsString(self) -> str:
545
+ """Return the accepted range as text."""
546
+ out = "[]"
547
+ return out
548
+
549
+ def HasDefault(self) -> bool:
550
+ """Return whether this schema defines a default value."""
551
+ return not isinstance(self._default, NiL)
552
+
553
+
554
+ class VectorSchema(PrimitiveSchema):
555
+ """Schema for vector values."""
556
+
557
+ def __init__(
558
+ self,
559
+ upperBoundIndex: int = -1,
560
+ default: object = NiL(),
561
+ dtype: ScalarType = float,
562
+ ) -> None:
563
+ """Initialize the Vector schema."""
564
+ self._default: object = default
565
+ self._upperBoundIndex: int = upperBoundIndex
566
+ inferred_typename, inferred_type = typename(dtype(0), True)
567
+ self._typename: str = inferred_typename
568
+ self._type: object = inferred_type
569
+
570
+ @staticmethod
571
+ def Create(
572
+ upperBoundIndex: int | ScalarType = -1,
573
+ default: object = NiL(),
574
+ dtype: ScalarType = float,
575
+ ) -> VectorSchema:
576
+ """Create a new VectorSchema instance."""
577
+ if isinstance(upperBoundIndex, type):
578
+ dtype = upperBoundIndex
579
+ upperBoundIndex = -1
580
+ return VectorSchema(upperBoundIndex, default, dtype)
581
+
582
+ def Copy(self) -> VectorSchema:
583
+ """Return a copy of this Vector schema."""
584
+ rv = VectorSchema(
585
+ self._upperBoundIndex,
586
+ self._default,
587
+ cast(ScalarType, self._type),
588
+ )
589
+ return rv
590
+
591
+ def CreateTreePrimitive(self) -> primitives.VectorPrimitive:
592
+ """Create a runtime primitive for this schema."""
593
+ rv: primitives.VectorPrimitive = primitives.VectorPrimitive(
594
+ dtype=cast(ScalarType, self._type)
595
+ )
596
+ if not isinstance(self._default, NiL):
597
+ rv.SetValue(
598
+ cast(list[NumericScalar] | tuple[NumericScalar, ...], self._default)
599
+ )
600
+ return rv
601
+
602
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
603
+ """Return whether a primitive satisfies this schema."""
604
+ value = dataPrimitive.GetValue()
605
+ if isinstance(value, NiL):
606
+ return False
607
+ if not isinstance(value, (list, tuple)):
608
+ return False
609
+ elif self._upperBoundIndex != -1 and len(value) != self._upperBoundIndex:
610
+ return False
611
+ return True
612
+
613
+ def TypeName(self) -> str:
614
+ """Return the type name for this schema."""
615
+ return "Vector<" + self._typename + ">"
616
+
617
+ def RangeAsString(self) -> str:
618
+ """Return the accepted range as text."""
619
+ out = "[v_1, ..."
620
+ if self._upperBoundIndex != -1:
621
+ out += ", v_" + str(self._upperBoundIndex)
622
+ out += "]"
623
+ return out
624
+
625
+ def HasDefault(self) -> bool:
626
+ """Return whether this schema defines a default value."""
627
+ return not isinstance(self._default, NiL)
628
+
629
+
630
+ class MatrixSchema(PrimitiveSchema):
631
+ """Schema for matrix values."""
632
+
633
+ def __init__(
634
+ self,
635
+ nRows: int = 0,
636
+ nCols: int = 0,
637
+ default: object = NiL(),
638
+ dtype: ScalarType = float,
639
+ ) -> None:
640
+ """Initialize the Matrix schema."""
641
+ self._nRows: int = nRows
642
+ self._nCols: int = nCols
643
+ self._default: object = default
644
+ inferred_typename, inferred_type = typename(dtype(0), True)
645
+ self._typename: str = inferred_typename
646
+ self._type: object = inferred_type
647
+
648
+ @staticmethod
649
+ def Create(
650
+ nRows: int = 0,
651
+ nCols: int = 0,
652
+ default: object = NiL(),
653
+ dtype: ScalarType = float,
654
+ ) -> MatrixSchema:
655
+ """Create a new MatrixSchema instance."""
656
+ return MatrixSchema(nRows, nCols, default, dtype)
657
+
658
+ def Copy(self) -> MatrixSchema:
659
+ """Return a copy of this Matrix schema."""
660
+ rv = MatrixSchema(
661
+ nRows=self._nRows,
662
+ nCols=self._nCols,
663
+ default=self._default,
664
+ dtype=cast(ScalarType, self._type),
665
+ )
666
+ return rv
667
+
668
+ def CreateTreePrimitive(self) -> primitives.MatrixPrimitive:
669
+ """Create a runtime primitive for this schema."""
670
+ rv: primitives.MatrixPrimitive = primitives.MatrixPrimitive(
671
+ dtype=cast(ScalarType, self._type)
672
+ )
673
+ if not isinstance(self._default, NiL):
674
+ rv.SetValue(
675
+ cast(list[NumericScalar] | tuple[NumericScalar, ...], self._default)
676
+ )
677
+ return rv
678
+
679
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
680
+ """Return whether a primitive satisfies this schema."""
681
+ value = dataPrimitive.GetValue()
682
+ if isinstance(value, NiL):
683
+ return False
684
+ if not isinstance(value, (list, tuple)):
685
+ return False
686
+ elif (
687
+ self._nRows * int(len(value) / self._nRows) != len(value)
688
+ or self._nCols * int(len(value) / self._nCols) != len(value)
689
+ or (self._nCols != -1 and self._nRows != -1)
690
+ and (self._nCols * self._nRows != len(value))
691
+ ):
692
+ return False
693
+ return True
694
+
695
+ def TypeName(self) -> str:
696
+ """Return the type name for this schema."""
697
+ return "Matrix<" + self._typename + ">"
698
+
699
+ def RangeAsString(self) -> str:
700
+ """Return the accepted range as text."""
701
+ out = "[v_11, ..., v_1j; ...; v_i1, ...; v_ij]"
702
+ if self._nRows != -1:
703
+ out += ", i<=" + str(self._nRows)
704
+ if self._nCols != -1:
705
+ out += ", j<=" + str(self._nCols)
706
+ return out
707
+
708
+ def HasDefault(self) -> bool:
709
+ """Return whether this schema defines a default value."""
710
+ return not isinstance(self._default, NiL)
711
+
712
+
713
+ class StringListSchema(VectorSchema):
714
+ """Schema for string-list values."""
715
+
716
+ def __init__(
717
+ self, upperBoundIndex: int = -1, default: StringSequenceDefault = NiL()
718
+ ) -> None:
719
+ """Initialize the StringList schema."""
720
+ self._default: object = default
721
+ self._upperBoundIndex: int = upperBoundIndex
722
+ self._typename: str = "Vector<string>"
723
+ self._type: object = str
724
+
725
+ @staticmethod
726
+ def Create(
727
+ upperBoundIndex: int | ScalarType = -1,
728
+ default: object = NiL(),
729
+ dtype: ScalarType = float,
730
+ ) -> StringListSchema:
731
+ """Create a new StringListSchema instance."""
732
+ if isinstance(upperBoundIndex, type):
733
+ upperBoundIndex = -1
734
+ return StringListSchema(upperBoundIndex, cast(StringSequenceDefault, default))
735
+
736
+ def Copy(self) -> StringListSchema:
737
+ """Return a copy of this StringList schema."""
738
+ rv = StringListSchema(
739
+ self._upperBoundIndex,
740
+ cast(StringSequenceDefault, self._default),
741
+ )
742
+ return rv
743
+
744
+ def TypeName(self) -> str:
745
+ """Return the type name for this schema."""
746
+ return self._typename
747
+
748
+ def CreateTreePrimitive(self) -> primitives.StringListPrimitive:
749
+ """Create a runtime primitive for this schema."""
750
+ rv: primitives.StringListPrimitive = primitives.StringListPrimitive()
751
+ if not isinstance(self._default, NiL):
752
+ rv.SetValue(cast(list[str] | tuple[str, ...], self._default))
753
+ return rv
754
+
755
+
756
+ class EnumListSchema(VectorSchema):
757
+ """Schema for enum-list values."""
758
+
759
+ def __init__(
760
+ self,
761
+ upperBoundIndex: int = -1,
762
+ stringSet: set[str] = set(),
763
+ default: StringSequenceDefault = NiL(),
764
+ ) -> None:
765
+ """Initialize the EnumList schema."""
766
+ self._default: object = default
767
+ self._stringSet: set[str] = set(stringSet)
768
+ self._upperBoundIndex: int = upperBoundIndex
769
+ self._typename: str = "Vector<enum>"
770
+ self._type: object = str
771
+
772
+ @staticmethod
773
+ def Create(
774
+ upperBoundIndex: int | ScalarType = -1,
775
+ default: object = NiL(),
776
+ dtype: ScalarType = float,
777
+ stringSet: set[str] = set(),
778
+ ) -> EnumListSchema:
779
+ """Create a new EnumListSchema instance."""
780
+ if isinstance(upperBoundIndex, type):
781
+ upperBoundIndex = -1
782
+ return EnumListSchema(
783
+ upperBoundIndex,
784
+ stringSet,
785
+ cast(StringSequenceDefault, default),
786
+ )
787
+
788
+ def Copy(self) -> EnumListSchema:
789
+ """Return a copy of this EnumList schema."""
790
+ rv = EnumListSchema(
791
+ self._upperBoundIndex,
792
+ self._stringSet,
793
+ cast(StringSequenceDefault, self._default),
794
+ )
795
+ return rv
796
+
797
+ def TypeName(self) -> str:
798
+ """Return the type name for this schema."""
799
+ return self._typename
800
+
801
+ def RangeAsString(self) -> str:
802
+ """Return the accepted range as text."""
803
+ return (
804
+ VectorSchema.RangeAsString(self)
805
+ + ", v="
806
+ + "|".join(sorted(self._stringSet))
807
+ )
808
+
809
+ def CreateTreePrimitive(self) -> primitives.StringListPrimitive:
810
+ """Create a runtime primitive for this schema."""
811
+ rv: primitives.StringListPrimitive = primitives.StringListPrimitive()
812
+ if not isinstance(self._default, NiL):
813
+ rv.SetValue(cast(list[str] | tuple[str, ...], self._default))
814
+ return rv
815
+
816
+
817
+ class TensorSchema(PrimitiveSchema):
818
+ """Schema for tensor values."""
819
+
820
+ def __init__(
821
+ self, default: primitives.Tensor3D | NiL = NiL(), rank: int = 0
822
+ ) -> None:
823
+ """Initialize the Tensor schema."""
824
+ self._default: primitives.Tensor3D | NiL = default
825
+ self._rank: int = rank
826
+ self._typename: str = str(rank) + "-Tensor"
827
+
828
+ @staticmethod
829
+ def Create(
830
+ default: primitives.Tensor3D | NiL = NiL(), rank: int = 0
831
+ ) -> TensorSchema:
832
+ """Create a new TensorSchema instance."""
833
+ return TensorSchema(default, rank)
834
+
835
+ def Copy(self) -> TensorSchema:
836
+ """Return a copy of this Tensor schema."""
837
+ rv = TensorSchema(default=self._default, rank=self._rank)
838
+ return rv
839
+
840
+ def CreateTreePrimitive(self) -> primitives.TensorPrimitive:
841
+ """Create a runtime primitive for this schema."""
842
+ rv: primitives.TensorPrimitive = primitives.TensorPrimitive(rank=self._rank)
843
+ if not isinstance(self._default, NiL):
844
+ rv.SetValue(self._default)
845
+ return rv
846
+
847
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
848
+ """Return whether a primitive satisfies this schema."""
849
+ value = dataPrimitive.GetValue()
850
+ if isinstance(value, NiL):
851
+ return False
852
+ if not isinstance(value, (primitives.Tensor3D, list, tuple)):
853
+ return False
854
+ sized_value: primitives.Tensor3D | list[object] | tuple[object, ...] = cast(
855
+ primitives.Tensor3D | list[object] | tuple[object, ...], value
856
+ )
857
+ if len(sized_value) != int(3 ** int(self._rank)):
858
+ return False
859
+ return True
860
+
861
+ def TypeName(self) -> str:
862
+ """Return the type name for this schema."""
863
+ return self._typename
864
+
865
+ def RangeAsString(self) -> str:
866
+ """Return the accepted range as text."""
867
+ out = "[v_1, ..., v_" + str(int(3 ** int(self._rank))) + "]"
868
+ return out
869
+
870
+ def HasDefault(self) -> bool:
871
+ """Return whether this schema defines a default value."""
872
+ return not isinstance(self._default, NiL)
873
+
874
+ @property
875
+ def rank(self) -> int:
876
+ """Return the tensor rank."""
877
+
878
+ return self._rank
879
+
880
+
881
+ class RotationSchema(PrimitiveSchema):
882
+ """Schema for rotation values."""
883
+
884
+ def __init__(self) -> None:
885
+ """Initialize the Rotation schema."""
886
+ self._typename: str = "Rotation"
887
+
888
+ @staticmethod
889
+ def Create() -> RotationSchema:
890
+ """Create a new RotationSchema instance."""
891
+ return RotationSchema()
892
+
893
+ def Copy(self) -> RotationSchema:
894
+ """Return a copy of this Rotation schema."""
895
+ return RotationSchema()
896
+
897
+ def CreateTreePrimitive(self) -> primitives.RotationPrimitive:
898
+ """Create a runtime primitive for this schema."""
899
+ rv: primitives.RotationPrimitive = primitives.RotationPrimitive()
900
+ return rv
901
+
902
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> bool:
903
+ """Return whether a primitive satisfies this schema."""
904
+ r = dataPrimitive.GetValue()
905
+ if isinstance(r, NiL):
906
+ return False
907
+ if not isinstance(r, primitives.Rotation):
908
+ return False
909
+ rotation_value: primitives.Rotation = r
910
+ det = (
911
+ rotation_value.m[0][0]
912
+ * (
913
+ rotation_value.m[1][1] * rotation_value.m[2][2]
914
+ - rotation_value.m[2][1] * rotation_value.m[1][2]
915
+ )
916
+ - rotation_value.m[1][0]
917
+ * (
918
+ rotation_value.m[0][1] * rotation_value.m[2][2]
919
+ - rotation_value.m[2][1] * rotation_value.m[0][2]
920
+ )
921
+ + rotation_value.m[2][0]
922
+ * (
923
+ rotation_value.m[0][1] * rotation_value.m[1][2]
924
+ - rotation_value.m[1][1] * rotation_value.m[0][2]
925
+ )
926
+ )
927
+ if abs(1.0 - det) > 1e-12:
928
+ return False
929
+ # test M^(-1) = MT
930
+ idMat = [[0.0] * 3] * 3
931
+ for i in range(3):
932
+ for j in range(3):
933
+ for k in range(3):
934
+ idMat[i][j] += rotation_value.m[k][i] * rotation_value.m[k][j]
935
+ for i in range(3):
936
+ for j in range(3):
937
+ if (i == j) and abs(idMat[i][j] - 1.0 * int(i == j)) > 1e-12:
938
+ return False
939
+ return True
940
+
941
+ def TypeName(self) -> str:
942
+ """Return the type name for this schema."""
943
+ return self._typename
944
+
945
+ def RangeAsString(self) -> str:
946
+ """Return the accepted range as text."""
947
+ out = "[SO(3)]"
948
+ return out
949
+
950
+ def HasDefault(self) -> bool:
951
+ """Return whether this schema defines a default value."""
952
+ return False
953
+
954
+
955
+ class DictionarySchema(PrimitiveSchema):
956
+ """Schema for dictionary values."""
957
+
958
+ def __init__(self, valueSchema: PrimitiveSchema) -> None:
959
+ """Initialize the Dictionary schema."""
960
+ self._valueSchema: PrimitiveSchema = valueSchema
961
+
962
+ @staticmethod
963
+ def Create(valueSchema: PrimitiveSchema) -> DictionarySchema:
964
+ """Create a new DictionarySchema instance."""
965
+ return DictionarySchema(valueSchema)
966
+
967
+ def Copy(self) -> DictionarySchema:
968
+ """Return a copy of this Dictionary schema."""
969
+ return DictionarySchema(self._valueSchema.Copy())
970
+
971
+ def CreateTreePrimitive(self) -> NoReturn:
972
+ """Create a runtime primitive for this schema."""
973
+ raise Exception("DictionarySchema", "dictionary primitive not implemented")
974
+
975
+ def CheckRange(self, dataPrimitive: PrimitiveValue) -> NoReturn:
976
+ """Return whether a primitive satisfies this schema."""
977
+ raise Exception("DictionarySchema", "dictionary primitive not implemented")
978
+
979
+ def TypeName(self) -> str:
980
+ """Return the type name for this schema."""
981
+ return "Dictionary<%s>" % (self._valueSchema.TypeName())
982
+
983
+ def RangeAsString(self) -> str:
984
+ """Return the accepted range as text."""
985
+ return self._valueSchema.RangeAsString()
986
+
987
+ def HasDefault(self) -> bool:
988
+ """Return whether this schema defines a default value."""
989
+ return False