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,1060 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Primitive data containers used in runtime data-tree instances."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Iterator, Sequence, TypeAlias, cast
9
+
10
+ import jcmsuite_data_tree.toolbox as toolbox
11
+
12
+ from . import parser
13
+ from .decorators import accepts, returns
14
+ from .system import FilePath
15
+
16
+ NumericScalar: TypeAlias = int | float | complex
17
+ NumericType: TypeAlias = type[int] | type[float] | type[complex]
18
+
19
+
20
+ def _coerce_numeric_scalar(value: NumericScalar, dtype: NumericType) -> NumericScalar:
21
+ """Convert a numeric scalar to the configured dtype."""
22
+
23
+ if dtype is complex:
24
+ return complex(value)
25
+ if dtype is float:
26
+ assert not isinstance(value, complex)
27
+ return float(value)
28
+ assert not isinstance(value, complex)
29
+ return int(value)
30
+
31
+
32
+ def prettyT(t: object) -> str:
33
+ """Return a compact string representation for tensor entries."""
34
+ if isinstance(t, complex):
35
+ if t.imag == 0:
36
+ return str(t.real)
37
+ else:
38
+ return "(" + str(t.real) + ", " + str(t.imag) + ")"
39
+ return str(t)
40
+
41
+
42
+ class Tensor3D:
43
+ """Store tensor entries as a flat complex-valued sequence."""
44
+
45
+ @accepts(object, (list, tuple), tensorData=(list, tuple))
46
+ def __init__(
47
+ self,
48
+ tensorData: Sequence[NumericScalar | str] = tuple(),
49
+ ) -> None:
50
+ """Initialize the tensor container."""
51
+ self.entries: list[complex] = []
52
+ for dat in tensorData:
53
+ self.entries.append(complex(dat))
54
+
55
+ @accepts(object, int, ii=int)
56
+ def __getitem__(self, ii: int) -> complex:
57
+ """Return the selected entry."""
58
+ if ii > len(self.entries) - 1 or ii < 0:
59
+ raise IndexError("Index out of range.")
60
+ return self.entries[ii]
61
+
62
+ @accepts(object, int, (int, float, complex), ii=int, v=(int, float, complex))
63
+ def __setitem__(self, ii: int, v: NumericScalar) -> None:
64
+ """Store a value at the selected entry."""
65
+ if ii > len(self.entries) - 1 or ii < 0:
66
+ raise IndexError("Index out of range.")
67
+ self.entries[ii] = complex(v)
68
+
69
+ @accepts(object, int, size=int)
70
+ def Resize(self, size: int) -> None:
71
+ """Resize the stored entry list."""
72
+ if len(self.entries) == size:
73
+ pass
74
+ elif len(self.entries) < size:
75
+ self.entries.extend([complex(0)] * (size - len(self.entries)))
76
+ elif size <= 0:
77
+ self.entries = []
78
+ elif size < len(self.entries):
79
+ self.entries = self.entries[0:size]
80
+ else:
81
+ raise Exception("Indexing bug.")
82
+
83
+ def Data(self) -> list[complex]:
84
+ """Return the underlying entry list."""
85
+ return self.entries
86
+
87
+ def __len__(self) -> int:
88
+ """Return the number of stored entries."""
89
+ return len(self.entries)
90
+
91
+ def __eq__(self, other: object) -> bool:
92
+ """Return whether the stored values match `other`."""
93
+ if isinstance(other, Tensor3D):
94
+ if len(self) == len(other) and all(
95
+ [self[ii] == other[ii] for ii in range(len(self))]
96
+ ):
97
+ return True
98
+ return False
99
+
100
+ def __ne__(self, other: object) -> bool:
101
+ """Return whether the stored values differ from `other`."""
102
+ return not self.__eq__(other)
103
+
104
+ def __iter__(self) -> Iterator[complex]:
105
+ """Iterate over the stored tensor entries."""
106
+ return iter(self.entries)
107
+
108
+
109
+ class Rotation:
110
+ """Store a 3x3 rotation matrix."""
111
+
112
+ def __init__(self, m: Sequence[Sequence[float]] | None = None) -> None:
113
+ """Initialize the rotation matrix."""
114
+ self.m: list[list[float]] = [list([0.0] * 3) for ii in range(3)]
115
+ if m is not None:
116
+ for ii in range(3):
117
+ for jj in range(3):
118
+ self.m[ii][jj] = float(m[ii][jj])
119
+
120
+ def __getitem__(self, ii: int | tuple[int, int]) -> list[float] | float:
121
+ """Return the selected entry."""
122
+ jj = None
123
+ if isinstance(ii, tuple):
124
+ if len(ii) == 0:
125
+ raise IndexError("Invalid index.")
126
+ if len(ii) > 1:
127
+ jj = int(ii[1])
128
+ ii = int(ii[0])
129
+ else:
130
+ ii = int(ii)
131
+ if jj is None:
132
+ return self.m[ii]
133
+ else:
134
+ return self.m[ii][jj]
135
+
136
+ def __setitem__(self, ii: int | tuple[int, int], value: float) -> None:
137
+ """Store a value at the selected entry."""
138
+ jj = None
139
+ if isinstance(ii, tuple):
140
+ if len(ii) == 0:
141
+ raise IndexError("Invalid index.")
142
+ if len(ii) > 1:
143
+ jj = int(ii[1])
144
+ ii = int(ii[0])
145
+ else:
146
+ ii = int(ii)
147
+ if jj is not None:
148
+ self.m[ii][jj] = float(value)
149
+ else:
150
+ for jj in range(len(self.m[ii])):
151
+ self.m[ii][jj] = float(value)
152
+
153
+ def __eq__(self, other: object) -> bool:
154
+ """Return whether the stored values match `other`."""
155
+ if not isinstance(other, Rotation):
156
+ return False
157
+ for ii in range(3):
158
+ for jj in range(3):
159
+ if not self.m[ii][jj] == other.m[ii][jj]:
160
+ return False
161
+ return True
162
+
163
+ def __ne__(self, other: object) -> bool:
164
+ """Return whether the stored values differ from `other`."""
165
+ return not self.__eq__(other)
166
+
167
+
168
+ # =======================
169
+ # === Tree Primitives ===
170
+ # =======================
171
+
172
+
173
+ class TreePrimitive:
174
+ """Base interface for runtime primitive values."""
175
+
176
+ def TypeName(self) -> str:
177
+ """Return the type name for this primitive."""
178
+ return "TreePrimitive"
179
+
180
+ def Copy(self) -> TreePrimitive:
181
+ """Return a copy of this Tree primitive."""
182
+ raise Exception("TreePrimitive should only be used through subclasses.")
183
+
184
+ def Write(self) -> str:
185
+ """Serialize the stored value to text."""
186
+ raise Exception("TreePrimitive should only be used through subclasses.")
187
+
188
+ def Read(self, reader: parser.TreeReader) -> bool:
189
+ """Read the stored value from a tree reader."""
190
+ raise Exception("TreePrimitive should only be used through subclasses.")
191
+
192
+ def Nil(self) -> object:
193
+ """Return the NiL representation for the stored value."""
194
+ raise Exception("TreePrimitive should only be used through subclasses.")
195
+
196
+ @staticmethod
197
+ def IsNiL(value: object) -> bool:
198
+ """Return whether `value` is treated as NiL."""
199
+ raise Exception("TreePrimitive should only be used through subclasses.")
200
+
201
+ def GetValue(self) -> object:
202
+ """Return the stored value."""
203
+ raise Exception("TreePrimitive should only be used through subclasses.")
204
+
205
+ def SetValue(self, newVal: object) -> None:
206
+ """Store a new value."""
207
+ raise Exception("TreePrimitive should only be used through subclasses.")
208
+
209
+
210
+ class NumberPrimitive(TreePrimitive):
211
+ """Store one scalar numeric value."""
212
+
213
+ @accepts(
214
+ TreePrimitive,
215
+ (int, float, complex),
216
+ type,
217
+ value=(int, float, complex),
218
+ dtype=type,
219
+ )
220
+ def __init__(
221
+ self,
222
+ value: NumericScalar = 0,
223
+ dtype: NumericType = float,
224
+ ) -> None:
225
+ """Initialize the Number primitive."""
226
+ self.__type: NumericType = dtype
227
+ self.__typename: str = toolbox.typename(dtype())
228
+ self.__value: NumericScalar = _coerce_numeric_scalar(value, dtype)
229
+
230
+ @staticmethod
231
+ def Create(
232
+ value: int | float | complex = 0,
233
+ dtype: type[int] | type[float] | type[complex] = float,
234
+ ) -> NumberPrimitive:
235
+ """Create a new NumberPrimitive instance."""
236
+ return NumberPrimitive(value, dtype)
237
+
238
+ def Copy(self) -> NumberPrimitive:
239
+ """Return a copy of this Number primitive."""
240
+ return NumberPrimitive(self.__value, self.__type)
241
+
242
+ def TypeName(self) -> str:
243
+ """Return the type name for this primitive."""
244
+ return self.__typename
245
+
246
+ def NiL(self) -> object:
247
+ """Return the NiL representation for the stored value."""
248
+ return toolbox.getDerivedNiL(self.__value)
249
+
250
+ @staticmethod
251
+ def IsNiL(value: object) -> bool:
252
+ """Return whether `value` is treated as NiL."""
253
+ return isinstance(value, toolbox.NiL)
254
+
255
+ @accepts(TreePrimitive, (int, float, complex), newVal=(int, float, complex))
256
+ def SetValue(self, newVal: object) -> None:
257
+ """Store a new value."""
258
+ if not isinstance(newVal, (int, float, complex)):
259
+ raise TypeError("Expected numeric scalar.")
260
+ self.__value = _coerce_numeric_scalar(newVal, self.__type)
261
+
262
+ def GetValue(self) -> NumericScalar:
263
+ """Return the stored value."""
264
+ return self.__value
265
+
266
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
267
+ def Read(self, reader: parser.TreeReader) -> bool:
268
+ """Read the stored value from a tree reader."""
269
+ val, success = reader.Get(self.__type)
270
+ if not success:
271
+ return False
272
+ if not isinstance(val, (int, float, complex)):
273
+ return False
274
+ self.__value = _coerce_numeric_scalar(val, self.__type)
275
+ return True
276
+
277
+ def Write(self) -> str:
278
+ """Serialize the stored value to text."""
279
+ return prettyT(self.__value)
280
+
281
+
282
+ class StringPrimitive(TreePrimitive):
283
+ """Store one string value."""
284
+
285
+ @accepts(TreePrimitive, bool, (str), quotMarks=bool, strArg=(str))
286
+ def __init__(self, quotMarks: bool = False, strArg: str = "") -> None:
287
+ """Initialize the String primitive."""
288
+ self.__quotMarks: bool = quotMarks
289
+ self.__value: str = strArg
290
+
291
+ @staticmethod
292
+ def Create(quotMarks: bool = False, strArg: str = "") -> StringPrimitive:
293
+ """Create a new StringPrimitive instance."""
294
+ return StringPrimitive(quotMarks, strArg)
295
+
296
+ def Copy(self) -> StringPrimitive:
297
+ """Return a copy of this String primitive."""
298
+ return StringPrimitive(self.__quotMarks, self.__value)
299
+
300
+ def TypeName(self) -> str:
301
+ """Return the type name for this primitive."""
302
+ return "string"
303
+
304
+ def NiL(self) -> object:
305
+ """Return the NiL representation for the stored value."""
306
+ return toolbox.getDerivedNiL(self.__value)
307
+
308
+ @staticmethod
309
+ def IsNiL(value: object) -> bool:
310
+ """Return whether `value` is treated as NiL."""
311
+ return isinstance(value, toolbox.NiL)
312
+
313
+ @accepts(TreePrimitive, (str), newVal=(str))
314
+ def SetValue(self, newVal: object) -> None:
315
+ """Store a new value."""
316
+ if not isinstance(newVal, str):
317
+ raise TypeError("Expected string value.")
318
+ self.__value = newVal
319
+
320
+ def GetValue(self) -> str:
321
+ """Return the stored value."""
322
+ return self.__value
323
+
324
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
325
+ def Read(self, reader: parser.TreeReader) -> bool:
326
+ """Read the stored value from a tree reader."""
327
+ hasQuotMarks = reader.TestToken('"')
328
+ if hasQuotMarks:
329
+ self.__quotMarks = True
330
+ readValue, success = parser.ReadString(
331
+ type(self.__value), reader, self.__quotMarks
332
+ )
333
+ if not success:
334
+ return False
335
+ if not isinstance(readValue, str):
336
+ return False
337
+ self.__value = readValue
338
+ return True
339
+
340
+ def Write(self) -> str:
341
+ """Serialize the stored value to text."""
342
+ if not self.__quotMarks:
343
+ return str(self.__value)
344
+ else:
345
+ return '"' + self.__value + '"'
346
+
347
+
348
+ class FilePrimitive(TreePrimitive):
349
+ """Store one file-path value."""
350
+
351
+ @accepts(TreePrimitive, bool, FilePath, quotMarks=bool, filePath=FilePath)
352
+ def __init__(
353
+ self,
354
+ quotMarks: bool = False,
355
+ filePath: FilePath = FilePath(),
356
+ ) -> None:
357
+ """Initialize the File primitive."""
358
+ self.__quotMarks: bool = quotMarks
359
+ self.__value: FilePath = filePath
360
+
361
+ @staticmethod
362
+ def Create(
363
+ quotMarks: bool = False, filePath: FilePath = FilePath()
364
+ ) -> FilePrimitive:
365
+ """Create a new FilePrimitive instance."""
366
+ return FilePrimitive(quotMarks, filePath)
367
+
368
+ def Copy(self) -> FilePrimitive:
369
+ """Return a copy of this File primitive."""
370
+ return FilePrimitive(self.__quotMarks, self.__value.Copy())
371
+
372
+ def TypeName(self) -> str:
373
+ """Return the type name for this primitive."""
374
+ return "file"
375
+
376
+ def NiL(self) -> object:
377
+ """Return the NiL representation for the stored value."""
378
+ return toolbox.getDerivedNiL(FilePath())
379
+
380
+ @staticmethod
381
+ def IsNiL(value: object) -> bool:
382
+ """Return whether `value` is treated as NiL."""
383
+ return isinstance(value, toolbox.NiL)
384
+
385
+ @accepts(TreePrimitive, (str, FilePath), newVal=(str, FilePath))
386
+ def SetValue(self, newVal: object) -> None:
387
+ """Store a new value."""
388
+ if isinstance(newVal, str):
389
+ self.__value = FilePath(newVal)
390
+ elif isinstance(newVal, FilePath):
391
+ self.__value = newVal
392
+
393
+ def GetValue(self) -> FilePath:
394
+ """Return the stored value."""
395
+ return self.__value
396
+
397
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
398
+ def Read(self, reader: parser.TreeReader) -> bool:
399
+ """Read the stored value from a tree reader."""
400
+ readValue, success = parser.ReadString(str, reader, quotMarks=True)
401
+ if not success:
402
+ return False
403
+ self.__value = FilePath(readValue, universal=True)
404
+ return True
405
+
406
+ def Write(self) -> str:
407
+ """Serialize the stored value to text."""
408
+ return '"' + str(self.__value.Export()) + '"'
409
+
410
+ def PathAsString(self) -> FilePath:
411
+ """Return the stored path as a string."""
412
+ return (
413
+ self.__value
414
+ ) # @TODO: replace once a file path object exists (now string)
415
+
416
+
417
+ class TreePath(toolbox.AsciiVector):
418
+ """Store a colon-delimited path inside a tree."""
419
+
420
+ @accepts(object, (str), data=(str))
421
+ def __init__(self, data: str = "") -> None:
422
+ """Initialize the tree path."""
423
+ self._delimiter: str = "/"
424
+ self._data: list[str] = []
425
+ self.Import(data)
426
+ self._data = [x for x in self._data if len(x) > 0]
427
+
428
+ def Copy(self) -> TreePath:
429
+ """Return a copy of this tree path."""
430
+ cp = TreePath(data=self.Path())
431
+ return cp
432
+
433
+ def Tag(self) -> str:
434
+ """Return the tag component."""
435
+ return self.At(-1)
436
+
437
+ def Section(self) -> str:
438
+ """Return the section component."""
439
+ return self.ExportParent() + self._delimiter
440
+
441
+ def Path(self) -> str:
442
+ """Return the full path string."""
443
+ return self.Export()
444
+
445
+ def __eq__(self, other: object) -> bool:
446
+ """Return whether the stored values match `other`."""
447
+ return toolbox.AsciiVector.__eq__(self, other)
448
+
449
+ def __ne__(self, other: object) -> bool:
450
+ """Return whether the stored values differ from `other`."""
451
+ return not self.__eq__(other)
452
+
453
+
454
+ class TreePathPrimitive(TreePrimitive):
455
+ """Store one tree-path value."""
456
+
457
+ @accepts(TreePrimitive, TreePath, treePath=TreePath())
458
+ def __init__(self, treePath: TreePath = TreePath()) -> None:
459
+ """Initialize the TreePath primitive."""
460
+ self.__value: TreePath = treePath
461
+
462
+ @staticmethod
463
+ def Create(treePath: TreePath = TreePath()) -> TreePathPrimitive:
464
+ """Create a new TreePathPrimitive instance."""
465
+ return TreePathPrimitive(treePath)
466
+
467
+ def Copy(self) -> TreePathPrimitive:
468
+ """Return a copy of this TreePath primitive."""
469
+ return TreePathPrimitive(self.__value.Copy())
470
+
471
+ def TypeName(self) -> str:
472
+ """Return the type name for this primitive."""
473
+ return "TreePath"
474
+
475
+ def NiL(self) -> object:
476
+ """Return the NiL representation for the stored value."""
477
+ return toolbox.getDerivedNiL(TreePath())
478
+
479
+ @staticmethod
480
+ def IsNiL(value: object) -> bool:
481
+ """Return whether `value` is treated as NiL."""
482
+ return isinstance(value, toolbox.NiL)
483
+
484
+ @accepts(TreePrimitive, (str, TreePath), newVal=(str, TreePath))
485
+ def SetValue(self, newVal: object) -> None:
486
+ """Store a new value."""
487
+ if isinstance(newVal, str):
488
+ self.__value = TreePath(newVal)
489
+ elif isinstance(newVal, TreePath):
490
+ self.__value = newVal
491
+
492
+ def GetValue(self) -> TreePath:
493
+ """Return the stored value."""
494
+ return self.__value
495
+
496
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
497
+ def Read(self, reader: parser.TreeReader) -> bool:
498
+ """Read the stored value from a tree reader."""
499
+ readValue, success = parser.ReadString(str, reader, quotMarks=False)
500
+ if not success:
501
+ return False
502
+ self.__value = TreePath(readValue)
503
+ return True
504
+
505
+ def Write(self) -> str:
506
+ """Serialize the stored value to text."""
507
+ return str(self.__value.Export())
508
+
509
+ def PathAsString(self) -> TreePath:
510
+ """Return the stored path as a string."""
511
+ return (
512
+ self.__value
513
+ ) # @TODO: replace once a file path object exists (now string)
514
+
515
+
516
+ class VectorPrimitive(TreePrimitive):
517
+ """Store one vector value."""
518
+
519
+ @accepts(TreePrimitive, (list, tuple), type, value=(list, tuple), dtype=type)
520
+ def __init__(
521
+ self,
522
+ value: list[NumericScalar] | tuple[NumericScalar, ...] = tuple(),
523
+ dtype: NumericType = float,
524
+ ) -> None:
525
+ """Initialize the Vector primitive."""
526
+ self.__value: list[NumericScalar] = list(value)
527
+ self.__type: NumericType = dtype
528
+ self.__typename: str = toolbox.typename(dtype(0))
529
+ self.__update()
530
+
531
+ def __update(self) -> None:
532
+ """Normalize vector primitive elements to the configured numeric dtype.
533
+
534
+ Parameters
535
+ ----------
536
+ None
537
+ This helper uses internal state only.
538
+
539
+ Returns
540
+ -------
541
+ None
542
+ No value is returned.
543
+
544
+ Notes
545
+ -----
546
+ Internal API: this helper is an implementation detail and may change
547
+ without notice.
548
+ """
549
+
550
+ for ii in range(len(self.__value)):
551
+ self.__value[ii] = _coerce_numeric_scalar(self.__value[ii], self.__type)
552
+
553
+ @staticmethod
554
+ def Create(
555
+ value: list[NumericScalar] | tuple[NumericScalar, ...] = tuple(),
556
+ dtype: NumericType = float,
557
+ ) -> VectorPrimitive:
558
+ """Create a new VectorPrimitive instance."""
559
+ return VectorPrimitive(value, dtype)
560
+
561
+ def Copy(self) -> VectorPrimitive:
562
+ """Return a copy of this Vector primitive."""
563
+ return VectorPrimitive([xx for xx in self.__value], self.__type)
564
+
565
+ def TypeName(self) -> str:
566
+ """Return the type name for this primitive."""
567
+ return "Vector<" + str(self.__typename) + ">"
568
+
569
+ def NiL(self) -> object:
570
+ """Return the NiL representation for the stored value."""
571
+ return toolbox.getDerivedNiL(self.__value)
572
+
573
+ @staticmethod
574
+ def IsNiL(value: object) -> bool:
575
+ """Return whether `value` is treated as NiL."""
576
+ return isinstance(value, toolbox.NiL)
577
+
578
+ @accepts(TreePrimitive, (list, tuple), newVal=(list, tuple))
579
+ def SetValue(self, newVal: object) -> None:
580
+ """Store a new value."""
581
+ if not isinstance(newVal, (list, tuple)):
582
+ raise TypeError("Expected vector data.")
583
+ self.__value = list(newVal)
584
+ self.__update()
585
+
586
+ def GetValue(self) -> Sequence[object]:
587
+ """Return the stored value."""
588
+ return self.__value
589
+
590
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
591
+ def Read(self, reader: parser.TreeReader) -> bool:
592
+ """Read the stored value from a tree reader."""
593
+ entryList, success = parser.ParseNumberVectorAsList(self.__type, reader)
594
+ if not success:
595
+ entryList, success = parser.ParseLegacyTensorFormat(
596
+ self.__type, rank=1, reader=reader
597
+ )
598
+ if not success:
599
+ return False
600
+ if not isinstance(entryList, list):
601
+ return False
602
+ exponent = 1
603
+ if reader.SkipToken("^"):
604
+ exponent_value, success = reader.Get(int)
605
+ if not success:
606
+ return False
607
+ exponent = cast(int, exponent_value)
608
+ self.__value = [entry**exponent for entry in entryList]
609
+ return True
610
+
611
+ def Write(self) -> str:
612
+ """Serialize the stored value to text."""
613
+ rv = "["
614
+ for ii in range(len(self.__value) - 1):
615
+ rv += prettyT(self.__value[ii])
616
+ rv += ", "
617
+ if len(self.__value) > 0:
618
+ rv += prettyT(self.__value[len(self.__value) - 1])
619
+ rv += "]"
620
+ return rv
621
+
622
+
623
+ class MatrixPrimitive(TreePrimitive):
624
+ """Store one matrix value."""
625
+
626
+ @accepts(TreePrimitive, (list, tuple), type, value=(list, tuple), dtype=type)
627
+ def __init__(
628
+ self,
629
+ value: list[NumericScalar] | tuple[NumericScalar, ...] = tuple(),
630
+ dtype: NumericType = float,
631
+ ) -> None:
632
+ """Initialize the Matrix primitive."""
633
+ self.__value: list[NumericScalar] = list(value)
634
+ self.__type: NumericType = dtype
635
+ self.__typename: str = toolbox.typename(dtype(0))
636
+ self.__update()
637
+
638
+ def __update(self) -> None:
639
+ """Normalize matrix primitive elements to the configured numeric dtype.
640
+
641
+ Parameters
642
+ ----------
643
+ None
644
+ This helper uses internal state only.
645
+
646
+ Returns
647
+ -------
648
+ None
649
+ No value is returned.
650
+
651
+ Notes
652
+ -----
653
+ Internal API: this helper is an implementation detail and may change
654
+ without notice.
655
+ """
656
+
657
+ for ii in range(len(self.__value)):
658
+ self.__value[ii] = _coerce_numeric_scalar(self.__value[ii], self.__type)
659
+
660
+ @staticmethod
661
+ def Create(
662
+ value: list[NumericScalar] | tuple[NumericScalar, ...] = tuple(),
663
+ dtype: NumericType = float,
664
+ ) -> MatrixPrimitive:
665
+ """Create a new MatrixPrimitive instance."""
666
+ return MatrixPrimitive(value, dtype)
667
+
668
+ def Copy(self) -> MatrixPrimitive:
669
+ """Return a copy of this Matrix primitive."""
670
+ return MatrixPrimitive([xx for xx in self.__value], self.__type)
671
+
672
+ def TypeName(self) -> str:
673
+ """Return the type name for this primitive."""
674
+ return "Matrix<" + str(self.__typename) + ">"
675
+
676
+ def NiL(self) -> object:
677
+ """Return the NiL representation for the stored value."""
678
+ return toolbox.getDerivedNiL(self.__value)
679
+
680
+ @staticmethod
681
+ def IsNiL(value: object) -> bool:
682
+ """Return whether `value` is treated as NiL."""
683
+ return isinstance(value, toolbox.NiL)
684
+
685
+ @accepts(TreePrimitive, (list, tuple), newVal=(list, tuple))
686
+ def SetValue(self, newVal: object) -> None:
687
+ """Store a new value."""
688
+ if not isinstance(newVal, (list, tuple)):
689
+ raise TypeError("Expected matrix data.")
690
+ self.__value = list(newVal)
691
+ self.__update()
692
+
693
+ def GetValue(self) -> Sequence[object]:
694
+ """Return the stored value."""
695
+ return self.__value
696
+
697
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
698
+ def Read(self, reader: parser.TreeReader) -> bool:
699
+ """Read the stored value from a tree reader."""
700
+ entryList, success = parser.ParseNumberVectorAsList(self.__type, reader)
701
+ if not success:
702
+ return False
703
+ if not isinstance(entryList, list):
704
+ return False
705
+ self.__value = entryList
706
+ return True
707
+
708
+ def Write(self) -> str:
709
+ """Serialize the stored value to text."""
710
+ rv = "["
711
+ for ii in range(len(self.__value) - 1):
712
+ rv += prettyT(self.__value[ii])
713
+ rv += ", "
714
+ if len(self.__value) > 0:
715
+ rv += prettyT(self.__value[len(self.__value) - 1])
716
+ rv += "]"
717
+ return rv
718
+
719
+
720
+ class StringListPrimitive(VectorPrimitive):
721
+ """Store one list of strings."""
722
+
723
+ @accepts(TreePrimitive, (list, tuple), value=(list, tuple))
724
+ def __init__(self, value: list[str] | tuple[str, ...] = tuple()) -> None:
725
+ """Initialize the StringList primitive."""
726
+ self.__value: list[str] = list(value)
727
+ self.__update()
728
+
729
+ def __update(self) -> None:
730
+ """Normalize string-list primitive elements to ``str`` values.
731
+
732
+ Parameters
733
+ ----------
734
+ None
735
+ This helper uses internal state only.
736
+
737
+ Returns
738
+ -------
739
+ None
740
+ No value is returned.
741
+
742
+ Notes
743
+ -----
744
+ Internal API: this helper is an implementation detail and may change
745
+ without notice.
746
+ """
747
+
748
+ for ii in range(len(self.__value)):
749
+ self.__value[ii] = str(self.__value[ii])
750
+
751
+ @staticmethod
752
+ def Create(
753
+ value: object = tuple(), dtype: NumericType = float
754
+ ) -> StringListPrimitive:
755
+ """Create a new StringListPrimitive instance."""
756
+ if not isinstance(value, (list, tuple)):
757
+ raise TypeError("Expected string-list data.")
758
+ return StringListPrimitive(value)
759
+
760
+ def Copy(self) -> StringListPrimitive:
761
+ """Return a copy of this StringList primitive."""
762
+ return StringListPrimitive([xx for xx in self.__value])
763
+
764
+ def TypeName(self) -> str:
765
+ """Return the type name for this primitive."""
766
+ return "Vector<string>"
767
+
768
+ def NiL(self) -> object:
769
+ """Return the NiL representation for the stored value."""
770
+ return toolbox.getDerivedNiL(self.__value)
771
+
772
+ @staticmethod
773
+ def IsNiL(value: object) -> bool:
774
+ """Return whether `value` is treated as NiL."""
775
+ return isinstance(value, toolbox.NiL)
776
+
777
+ @accepts(TreePrimitive, (list, tuple), newVal=(list, tuple))
778
+ def SetValue(self, newVal: object) -> None:
779
+ """Store a new value."""
780
+ if not isinstance(newVal, (list, tuple)):
781
+ raise TypeError("Expected string-list data.")
782
+ self.__value = list(newVal)
783
+ self.__update()
784
+
785
+ def GetValue(self) -> list[str]:
786
+ """Return the stored value."""
787
+ return self.__value
788
+
789
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
790
+ def Read(self, reader: parser.TreeReader) -> bool:
791
+ """Read the stored value from a tree reader."""
792
+ entryList = []
793
+ stopTokens = set([",", "]", ":"])
794
+ if not reader.SkipToken("["):
795
+ return False
796
+ while True:
797
+ if reader.SkipToken("]"):
798
+ break
799
+ entryString, success = reader.Get(
800
+ str, stopTokens=stopTokens, ignoreSpaces=True
801
+ )
802
+ if not success:
803
+ return False
804
+ entryString = cast(str, entryString)
805
+ if len(entryString) < 2:
806
+ return False
807
+ if entryString[0] != '"' or entryString[-1] != '"':
808
+ return False
809
+ entryList.append(entryString[1:-1])
810
+ if reader.SkipToken(","):
811
+ if reader.SkipToken("]"):
812
+ return False
813
+ self.__value = entryList
814
+ return True
815
+
816
+ def Write(self) -> str:
817
+ """Serialize the stored value to text."""
818
+ rv = "["
819
+ for ii in range(len(self.__value)):
820
+ rv += '"' + str(self.__value[ii]) + '"'
821
+ if ii < len(self.__value) - 1:
822
+ rv += ", "
823
+ rv += "]"
824
+ return rv
825
+
826
+
827
+ class TensorPrimitive(TreePrimitive):
828
+ """Store one tensor value."""
829
+
830
+ @accepts(TreePrimitive, Tensor3D, int, value=Tensor3D, rank=int)
831
+ def __init__(self, value: Tensor3D = Tensor3D(), rank: int = 0) -> None:
832
+ """Initialize the Tensor primitive."""
833
+ self.__value: Tensor3D = value
834
+ self.__rank: int = rank
835
+
836
+ @staticmethod
837
+ def Create(value: Tensor3D = Tensor3D(), rank: int = 0) -> TensorPrimitive:
838
+ """Create a new TensorPrimitive instance."""
839
+ return TensorPrimitive(value, rank)
840
+
841
+ def Copy(self) -> TensorPrimitive:
842
+ """Return a copy of this Tensor primitive."""
843
+ return TensorPrimitive(Tensor3D(self.__value.Data()), self.__rank)
844
+
845
+ def TypeName(self) -> str:
846
+ """Return the type name for this primitive."""
847
+ return "Vector<" + str(toolbox.typename(complex(0))) + ">"
848
+
849
+ def NiL(self) -> object:
850
+ """Return the NiL representation for the stored value."""
851
+ return toolbox.getDerivedNiL(self.__value)
852
+
853
+ @staticmethod
854
+ def IsNiL(value: object) -> bool:
855
+ """Return whether `value` is treated as NiL."""
856
+ return isinstance(value, toolbox.NiL)
857
+
858
+ @accepts(TreePrimitive, Tensor3D, newVal=Tensor3D)
859
+ def SetValue(self, newVal: object) -> None:
860
+ # if len(newVal)!=len(self.__value):
861
+ # raise ValueError('Expected Tensor of rank '+str(self.__rank))
862
+ """Store a new value."""
863
+ if not isinstance(newVal, Tensor3D):
864
+ raise TypeError("Expected Tensor3D value.")
865
+ self.__value = newVal
866
+
867
+ def GetValue(self) -> Tensor3D:
868
+ """Return the stored value."""
869
+ return self.__value
870
+
871
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
872
+ def Read(self, reader: parser.TreeReader) -> bool:
873
+ """Read the stored value from a tree reader."""
874
+ entryList, success = parser.ParseNumberVectorAsList(complex, reader)
875
+ if not success:
876
+ entryList, success = parser.ParseLegacyTensorFormat(
877
+ complex, self.__rank, reader
878
+ )
879
+ if not success:
880
+ return False
881
+ if not isinstance(entryList, list):
882
+ return False
883
+ complex_entries: list[complex] = cast(list[complex], entryList)
884
+ if len(entryList) == 3**self.__rank:
885
+ self.__value.entries = complex_entries
886
+ return True
887
+ if self.__rank == 2:
888
+ if len(entryList) == 1:
889
+ for iX in range(3):
890
+ self.__value.entries[iX * 4] = complex_entries[0]
891
+ return True
892
+ elif len(entryList) == 3:
893
+ for iX in range(3):
894
+ self.__value.entries[iX * 4] = complex_entries[iX]
895
+ return True
896
+ elif len(complex_entries) > 0 and complex_entries[0] == complex(0):
897
+ return True
898
+ return False
899
+
900
+ def Write(self) -> str:
901
+ """Serialize the stored value to text."""
902
+ rv = "["
903
+ for ii in range(len(self.__value) - 1):
904
+ rv += prettyT(self.__value[ii])
905
+ rv += ", "
906
+
907
+ if len(self.__value) > 0:
908
+ rv += prettyT(self.__value[len(self.__value) - 1])
909
+ rv += "]"
910
+ return rv
911
+
912
+
913
+ class RotationPrimitive(TreePrimitive):
914
+ """Store one rotation-matrix value."""
915
+
916
+ @accepts(TreePrimitive, Rotation, value=Rotation)
917
+ def __init__(self, value: Rotation = Rotation()) -> None:
918
+ """Initialize the Rotation primitive."""
919
+ self.__value: Rotation = value
920
+
921
+ @staticmethod
922
+ def Create(value: Rotation = Rotation()) -> RotationPrimitive:
923
+ """Create a new RotationPrimitive instance."""
924
+ return RotationPrimitive(value)
925
+
926
+ def Copy(self) -> RotationPrimitive:
927
+ """Return a copy of this Rotation primitive."""
928
+ return RotationPrimitive(Rotation(self.__value.m))
929
+
930
+ def TypeName(self) -> str:
931
+ """Return the type name for this primitive."""
932
+ return "Rotation"
933
+
934
+ def NiL(self) -> object:
935
+ """Return the NiL representation for the stored value."""
936
+ return toolbox.getDerivedNiL(self.__value)
937
+
938
+ @staticmethod
939
+ def IsNiL(value: object) -> bool:
940
+ """Return whether `value` is treated as NiL."""
941
+ return isinstance(value, toolbox.NiL)
942
+
943
+ @accepts(TreePrimitive, (Rotation, str), newVal=(Rotation, str))
944
+ def SetValue(self, newVal: object) -> None:
945
+ """Store a new value."""
946
+ if isinstance(newVal, Rotation):
947
+ self.__value = newVal
948
+ elif isinstance(newVal, str):
949
+ self.__value = GetCoordinateRenamingMatrix(newVal)
950
+ else:
951
+ raise TypeError("Expected rotation value or renaming string.")
952
+
953
+ def GetValue(self) -> Rotation:
954
+ """Return the stored value."""
955
+ return self.__value
956
+
957
+ # @accepts(TreePrimitive, TreeReader, reader=TreeReader)
958
+ def Read(self, reader: parser.TreeReader) -> bool:
959
+ """Read the stored value from a tree reader."""
960
+ entryList, success = parser.ParseNumberVectorAsList(float, reader)
961
+ if not success:
962
+ try:
963
+ if reader.SkipToken("{"):
964
+ parsed_rotation_matrix, success = parser.ParseLegacyRotationFormat(
965
+ reader
966
+ )
967
+ if success:
968
+ self.__value.m = parsed_rotation_matrix
969
+ return True
970
+ renamingString, success = reader.Get(str)
971
+ if not success:
972
+ raise Exception
973
+ parsed_rotation = GetCoordinateRenamingMatrix(
974
+ cast(str, renamingString)
975
+ )
976
+ self.__value = parsed_rotation
977
+ except Exception:
978
+ return False
979
+ else:
980
+ if not isinstance(entryList, list):
981
+ return False
982
+ if len(entryList) != 9:
983
+ return False
984
+ float_entries: list[float] = cast(list[float], entryList)
985
+ for ii in range(3):
986
+ for jj in range(3):
987
+ self.__value.m[ii][jj] = float_entries[ii * 3 + jj]
988
+ return True
989
+
990
+ def Write(self) -> str:
991
+ """Serialize the stored value to text."""
992
+ isPerm = True
993
+ rowIndices = []
994
+ for ir in range(len(self.__value.m)):
995
+ row = self.__value.m[ir]
996
+ irow = [abs(abs(v) - 1.0) < 1e-12 for v in row]
997
+ rowIndices.append(irow.index(True))
998
+ if abs(sum(irow) - 1.0) > 1e-12:
999
+ isPerm = False
1000
+ break
1001
+ xyzChars = "XYZ"
1002
+ rv = ""
1003
+ if isPerm:
1004
+ for iX in range(len(self.__value.m)):
1005
+ char = xyzChars[rowIndices[iX]]
1006
+ if self.__value.m[iX][rowIndices[iX]] < 0.0:
1007
+ sign = "-"
1008
+ else:
1009
+ sign = ""
1010
+ rv += sign
1011
+ rv += char
1012
+ if iX < 2:
1013
+ rv += ":"
1014
+ else:
1015
+ rv += "["
1016
+ for ir in range(len(self.__value.m)):
1017
+ for ic in range(len(self.__value.m[ir])):
1018
+ rv += str(self.__value[ir, ic])
1019
+ if ir != 2 or ic != 2:
1020
+ rv += ", "
1021
+ rv += "]"
1022
+ return rv
1023
+
1024
+
1025
+ # ===========================================
1026
+ # === additional functions (used locally) ===
1027
+ # ===========================================
1028
+
1029
+
1030
+ @accepts((str))
1031
+ @returns(Rotation)
1032
+ def GetCoordinateRenamingMatrix(renamingString: str) -> Rotation:
1033
+ """Return the matrix for one coordinate-renaming string."""
1034
+ r = Rotation()
1035
+ indexing = renamingString.strip().split(":")
1036
+ coordinates = {coord.lstrip("-") for coord in indexing}
1037
+ if len(indexing) != 3 or coordinates != {"X", "Y", "Z"}:
1038
+ raise Exception("No valid coordinate renaming: " + renamingString)
1039
+ for iC in range(3):
1040
+ coord = indexing[iC]
1041
+ if coord == "X":
1042
+ r[0, iC] = 1
1043
+ elif coord == "-X":
1044
+ r[0, iC] = -1
1045
+ elif coord == "Y":
1046
+ r[1, iC] = 1
1047
+ elif coord == "-Y":
1048
+ r[1, iC] = -1
1049
+ elif coord == "Z":
1050
+ r[2, iC] = 1
1051
+ elif coord == "-Z":
1052
+ r[2, iC] = -1
1053
+ else:
1054
+ raise Exception("No valid coordinate renaming: " + renamingString)
1055
+ return r
1056
+
1057
+
1058
+ # ====================
1059
+ # === Unit Testing ===
1060
+ # ====================