-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathensightreader.py
2719 lines (2220 loc) · 107 KB
/
ensightreader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2022-2025 Tomas Karabela
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import io
import mmap as _mmap
import os
import os.path as op
import re
import warnings
from contextlib import contextmanager
from dataclasses import dataclass, field
from enum import Enum
from typing import BinaryIO, Dict, Generator, List, Optional, TextIO, Tuple, Type, TypeVar, Union, Iterator, Mapping
import numpy as np
import numpy.typing as npt
T = TypeVar('T')
TNum = TypeVar('TNum', np.int32, np.float32)
SeekableBufferedReader = Union[BinaryIO, _mmap.mmap]
SeekableBufferedWriter = Union[BinaryIO, _mmap.mmap]
Float32NDArray = npt.NDArray[np.float32]
Int32NDArray = npt.NDArray[np.int32]
__version__ = "0.12.0"
__all__ = [
"read_case",
"EnsightReaderError",
"EnsightReaderWarning",
"IdHandling",
"ChangingGeometry",
"VariableLocation",
"VariableType",
"ElementType",
"Timeset",
"UnstructuredElementBlock",
"GeometryPart",
"EnsightGeometryFile",
"EnsightVariableFile",
"EnsightGeometryFileSet",
"EnsightVariableFileSet",
"EnsightConstantVariable",
"EnsightCaseFile",
]
def add_exception_note(e: Exception, note: str) -> None:
if hasattr(e, "add_note"): # Python 3.11+
e.add_note(note)
@contextmanager
def add_exception_note_block(note: str) -> Iterator[None]:
try:
yield
except Exception as e:
add_exception_note(e, note)
raise
class EnsightReaderError(Exception):
"""
Error raised when parsing EnSight Gold binary files
Attributes:
file_path (str): path to file where the error was encountered
file_offset (int): approximate seek position of the error (this may be a bit past the place where
the error is - it's the seek position when this exception was raised)
file_lineno (int): line number of the error (this only applies to errors in ``*.case`` file,
as other files are binary)
"""
def __init__(self, msg: str, fp: Optional[Union[TextIO, SeekableBufferedReader]] = None, lineno: Optional[int] = None):
self.file_path = getattr(fp, "name", None)
try:
self.file_offset = fp.tell() if fp else None
except OSError:
self.file_offset = None
self.file_lineno = lineno
if lineno is not None:
message = f"{msg} (path={self.file_path}, line={self.file_lineno})"
else:
message = f"{msg} (path={self.file_path}, offset={self.file_offset})"
super(EnsightReaderError, self).__init__(message)
class EnsightReaderWarning(Warning):
"""
Warning raised when parsing EnSight Gold binary files
Attributes:
file_path (str): path to file where the error was encountered
file_offset (int): approximate seek position of the error (this may be a bit past the place where
the error is - it's the seek position when this exception was raised)
file_lineno (int): line number of the error (this only applies to errors in ``*.case`` file,
as other files are binary)
"""
def __init__(
self,
msg: str,
fp: Optional[Union[TextIO, SeekableBufferedReader]] = None,
lineno: Optional[int] = None,
file_path: Optional[Union[str, os.PathLike[str]]] = None
):
self.file_path = file_path if file_path is not None else getattr(fp, "name", None)
try:
self.file_offset = fp.tell() if fp else None
except OSError:
self.file_offset = None
self.file_lineno = lineno
if self.file_path is None:
message = msg
else:
if self.file_lineno is not None:
message = f"{msg} (path={self.file_path}, line={self.file_lineno})"
elif self.file_offset is not None:
message = f"{msg} (path={self.file_path}, offset={self.file_offset})"
else:
message = f"{msg} (path={self.file_path})"
super(EnsightReaderWarning, self).__init__(message)
class IdHandling(Enum):
"""
Handling of node/element IDs in EnSight Gold geometry file.
This is defined in geometry file header and describes whether
IDs are present in the file or not.
"""
OFF = "off"
GIVEN = "given"
ASSIGN = "assign"
IGNORE = "ignore"
@property
def ids_present(self) -> bool:
"""Return True if IDs are present in geometry file, otherwise False"""
return self in (self.GIVEN, self.IGNORE) # type: ignore[comparison-overlap]
def __str__(self) -> str:
return self.value
class ChangingGeometry(Enum):
"""
Additional information about transient geometry
"""
NO_CHANGE = "no_change"
COORD_CHANGE = "coord_change"
CONN_CHANGE = "conn_change"
def __str__(self) -> str:
return self.value
class VariableLocation(Enum):
"""
Location of variable in EnSight Gold case
Whether the variable is defined for cells or nodes.
"""
PER_ELEMENT = "element"
PER_NODE = "node"
def __str__(self) -> str:
return self.value
class VariableType(Enum):
"""
Type of variable in EnSight Gold case
.. Note::
Complex variables and "per measured" variables are not supported.
"""
SCALAR = "scalar"
VECTOR = "vector"
TENSOR_SYMM = "tensor symm"
TENSOR_ASYM = "tensor asym"
# COMPLEX_SCALAR = "complex scalar"
# COMPLEX_VECTOR = "complex vector"
def __str__(self) -> str:
return self.value
VALUES_FOR_VARIABLE_TYPE = {
VariableType.SCALAR: 1,
VariableType.VECTOR: 3,
VariableType.TENSOR_SYMM: 6,
VariableType.TENSOR_ASYM: 9,
}
class ElementType(Enum):
"""
Element type in EnSight Gold geometry file
.. Note::
Ghost cell variants ``g_*`` are not supported.
"""
POINT = "point"
BAR2 = "bar2"
BAR3 = "bar3"
TRIA3 = "tria3"
TRIA6 = "tria6"
QUAD4 = "quad4"
QUAD8 = "quad8"
TETRA4 = "tetra4"
TETRA10 = "tetra10"
PYRAMID5 = "pyramid5"
PYRAMID13 = "pyramid13"
PENTA6 = "penta6"
PENTA15 = "penta15"
HEXA8 = "hexa8"
HEXA20 = "hexa20"
NSIDED = "nsided"
NFACED = "nfaced"
# G_POINT = "g_point"
# G_BAR2 = "g_bar2"
# G_BAR3 = "g_bar3"
# G_TRIA3 = "g_tria3"
# G_TRIA6 = "g_tria6"
# G_QUAD4 = "g_quad4"
# G_QUAD8 = "g_quad8"
# G_TETRA4 = "g_tetra4"
# G_TETRA10 = "g_tetra10"
# G_PYRAMID5 = "g_pyramid5"
# G_PYRAMID13 = "g_pyramid13"
# G_PENTA6 = "g_penta6"
# G_PENTA15 = "g_penta15"
# G_HEXA8 = "g_hexa8"
# G_HEXA20 = "g_hexa20"
# G_NSIDED = "g_nsided"
# G_NFACED = "g_nfaced"
@classmethod
def parse_from_line(cls, element_type_line: str) -> "ElementType":
m = re.match(r"[a-z0-9_]+", element_type_line)
if not m:
raise ValueError(f"Unexpected element type line {element_type_line!r}")
element_name = m.group(0)
element_type = cls(element_name)
return element_type
@property
def dimension(self) -> int:
"""
Return dimension of element
Returns 3 for volume elements, 2 for surface elements, 1 for line elements
and 0 for point elements.
"""
return DIMENSION_PER_ELEMENT[self]
@property
def nodes_per_element(self) -> int:
"""
Return number nodes defining the element
This only makes sense for elements consisting of constant number of nodes.
For NSIDED and NFACED element type, this raises and exception.
"""
return NODES_PER_ELEMENT[self]
def has_constant_number_of_nodes_per_element(self) -> bool:
"""
Return True if element type has constant number of nodes defining each element, else False
This is True for all element types except NSIDED and NFACED.
"""
return self in NODES_PER_ELEMENT
def __str__(self) -> str:
return self.value
NODES_PER_ELEMENT = {
ElementType.POINT: 1,
ElementType.BAR2: 2,
ElementType.BAR3: 3,
ElementType.TRIA3: 3,
ElementType.TRIA6: 6,
ElementType.QUAD4: 4,
ElementType.QUAD8: 8,
ElementType.TETRA4: 4,
ElementType.TETRA10: 10,
ElementType.PYRAMID5: 5,
ElementType.PYRAMID13: 13,
ElementType.PENTA6: 6,
ElementType.PENTA15: 15,
ElementType.HEXA8: 8,
ElementType.HEXA20: 20,
}
DIMENSION_PER_ELEMENT = {
ElementType.POINT: 0,
ElementType.BAR2: 1,
ElementType.BAR3: 1,
ElementType.TRIA3: 2,
ElementType.TRIA6: 2,
ElementType.QUAD4: 2,
ElementType.QUAD8: 2,
ElementType.TETRA4: 3,
ElementType.TETRA10: 3,
ElementType.PYRAMID5: 3,
ElementType.PYRAMID13: 3,
ElementType.PENTA6: 3,
ElementType.PENTA15: 3,
ElementType.HEXA8: 3,
ElementType.HEXA20: 3,
ElementType.NSIDED: 2,
ElementType.NFACED: 3,
}
SIZE_INT = SIZE_FLOAT = 4
@dataclass
class Timeset:
"""
Description of time set in EnSight Gold case
This means a non-decreasing sequence of times
for which geometry and/or variable values are known.
Attributes:
timeset_id: ID of the time set
description: label of the time set, or None
number_of_steps: number of timesteps
filename_numbers: list of numbers for filenames (to be filled in place of ``*`` wildcards)
time_values: list of time values (ie. seconds, or something else)
"""
timeset_id: int
description: Optional[str]
number_of_steps: int
filename_numbers: List[int]
time_values: List[float]
@staticmethod
def filename_numbers_from_arithmetic_sequence(file_start_number: int, number_of_steps: int, filename_increment: int) -> List[int]:
assert filename_increment >= 0
assert number_of_steps >= 0
assert file_start_number >= 0
return [file_start_number + i*filename_increment for i in range(number_of_steps)]
@dataclass
class UnstructuredElementBlock:
"""
A block of elements of the same type in a part in EnSight Gold binary geometry file
To use it:
>>> from ensightreader import read_case, ElementType
>>> case = read_case("example.case")
>>> geofile = case.get_geometry_model()
>>> part_names = geofile.get_part_names()
>>> part = geofile.get_part_by_name(part_names[0])
>>> with open(geofile.file_path, "rb") as fp_geo:
... for block in part.element_blocks:
... if block.element_type == ElementType.NFACED:
... polyhedra_face_counts, face_node_counts, face_connectivity = block.read_connectivity_nfaced(fp_geo)
... elif block.element_type == ElementType.NSIDED:
... polygon_node_counts, polygon_connectivity = block.read_connectivity_nsided(fp_geo)
... else:
... connectivity = block.read_connectivity(fp_geo)
Attributes:
offset: offset to 'element type' line in file (eg. 'tria3')
number_of_elements: number of elements in this block
element_type: type of elements in this block
element_id_handling: element ID presence
part_id: part number
"""
offset: int
number_of_elements: int
element_type: ElementType
element_id_handling: IdHandling
part_id: int
def read_element_ids(self, fp: SeekableBufferedReader) -> Optional[Int32NDArray]:
"""
Read element IDs for this element block, if present
.. note::
This method simply returns the element ID array as present
in the file; it does not differentiate between ``element id given``
and ``element id ignore``, etc.
Args:
fp: opened geometry file object in ``"rb"`` mode
Returns:
1D array of int32 with element IDs, or None if element IDs are not
present in the file
"""
if not self.element_id_handling.ids_present:
return None
fp.seek(self.offset)
assert read_line(fp).startswith(self.element_type.value)
assert read_int(fp) == self.number_of_elements
arr = read_ints(fp, self.number_of_elements)
return arr
def read_connectivity(self, fp: SeekableBufferedReader) -> Int32NDArray:
"""
Read connectivity (for elements other than NSIDED/NFACED)
Use this for elements which have constant number of nodes
per element (ie. any element type except polygons and polyhedra).
Args:
fp: opened geometry file object in ``"rb"`` mode
Returns:
2D ``(n, k)`` array of int32 with node indices (numbered from 1), where
``n`` is the number of elements and
``k`` is the number of nodes defining each element
"""
if self.element_type not in NODES_PER_ELEMENT:
raise ValueError("Please use other methods for nsided/nfaced")
fp.seek(self.offset)
assert read_line(fp).startswith(self.element_type.value)
assert read_int(fp) == self.number_of_elements
if self.element_id_handling.ids_present:
fp.seek(self.number_of_elements * SIZE_INT, os.SEEK_CUR)
nodes_per_element = NODES_PER_ELEMENT[self.element_type]
arr = read_ints(fp, self.number_of_elements * nodes_per_element)
return arr.reshape((self.number_of_elements, nodes_per_element), order="C")
def read_connectivity_nsided(self, fp: SeekableBufferedReader) -> Tuple[Int32NDArray, Int32NDArray]:
"""
Read connectivity (for NSIDED elements)
Args:
fp: opened geometry file object in ``"rb"`` mode
Returns:
tuple ``(polygon_node_counts, polygon_connectivity)`` where
``polygon_node_counts`` is 1D array of type int32
giving number of nodes for each polygon and
``polygon_connectivity`` is 1D array of type int32
giving node indices (numbered from 1) for every polygon
"""
if self.element_type != ElementType.NSIDED:
raise ValueError("Please use other methods for not nsided")
fp.seek(self.offset)
assert read_line(fp).startswith(self.element_type.value)
assert read_int(fp) == self.number_of_elements
if self.element_id_handling.ids_present:
fp.seek(self.number_of_elements * SIZE_INT, os.SEEK_CUR)
polygon_node_counts = read_ints(fp, self.number_of_elements)
polygon_connectivity = read_ints(fp, polygon_node_counts.sum())
return polygon_node_counts, polygon_connectivity
def read_connectivity_nfaced(self, fp: SeekableBufferedReader) -> Tuple[Int32NDArray, Int32NDArray, Int32NDArray]:
"""
Read connectivity (for NFACED elements)
Args:
fp: opened geometry file object in ``"rb"`` mode
Returns:
tuple ``(polyhedra_face_counts, face_node_counts, face_connectivity)`` where
``polyhedra_face_counts`` is 1D array of type int32
giving number of faces for each polygon,
``face_node_counts`` is 1D array of type int32
giving number of nodes for each face for each polygon (ordered as
1st polygon 1st face, 1st polygon 2nd face, ..., 2nd polygon 1st face, ...),
``face_connectivity`` is 1D array of type int32 giving node indices
(numbered from 1)
"""
if self.element_type != ElementType.NFACED:
raise ValueError("Please use other methods for not nfaced")
fp.seek(self.offset)
assert read_line(fp).startswith(self.element_type.value)
assert read_int(fp) == self.number_of_elements
if self.element_id_handling.ids_present:
fp.seek(self.number_of_elements * SIZE_INT, os.SEEK_CUR)
polyhedra_face_counts = read_ints(fp, self.number_of_elements)
face_node_counts = read_ints(fp, polyhedra_face_counts.sum())
face_connectivity = read_ints(fp, face_node_counts.sum())
return polyhedra_face_counts, face_node_counts, face_connectivity
@classmethod
def from_file(cls, fp: SeekableBufferedReader, element_id_handling: IdHandling, part_id: int) -> "UnstructuredElementBlock":
"""Used internally by `GeometryPart.from_file()`"""
offset = fp.tell()
element_type_line = read_line(fp)
try:
element_type = ElementType.parse_from_line(element_type_line)
except ValueError as e:
raise EnsightReaderError("Unexpected element type", fp) from e
with add_exception_note_block(f"element_type = {element_type}"):
number_of_elements = read_int(fp)
# skip element IDs
if element_id_handling.ids_present:
fp.seek(number_of_elements*SIZE_INT, os.SEEK_CUR)
if element_type in NODES_PER_ELEMENT:
nodes_per_element = NODES_PER_ELEMENT[element_type]
fp.seek(nodes_per_element * number_of_elements * SIZE_INT, os.SEEK_CUR) # skip connectivity
elif element_type == ElementType.NSIDED:
polygon_node_counts = read_ints(fp, number_of_elements)
fp.seek(polygon_node_counts.sum() * SIZE_INT, os.SEEK_CUR)
elif element_type == ElementType.NFACED:
polyhedra_face_counts = read_ints(fp, number_of_elements)
face_node_counts = read_ints(fp, polyhedra_face_counts.sum())
fp.seek(face_node_counts.sum() * SIZE_INT, os.SEEK_CUR) # skip connectivity
else:
raise EnsightReaderError(f"Unsupported element type: {element_type}", fp)
return cls(
offset=offset,
number_of_elements=number_of_elements,
element_type=element_type,
element_id_handling=element_id_handling,
part_id=part_id,
)
@staticmethod
def write_element_block(fp: SeekableBufferedWriter, element_type: ElementType, connectivity: Int32NDArray,
element_ids: Optional[Int32NDArray] = None) -> None:
"""
Write element block (not NSIDED/NFACED) to given opened file
See `UnstructuredElementBlock.read_connectivity()`.
"""
assert element_type not in (ElementType.NFACED, ElementType.NFACED)
number_of_elements = connectivity.shape[0]
assert connectivity.shape[1] == element_type.nodes_per_element
if element_ids is not None:
assert element_ids.shape == (number_of_elements,)
write_line(fp, f"{element_type}")
write_int(fp, number_of_elements)
if element_ids is not None:
write_ints(fp, element_ids)
write_ints(fp, connectivity.ravel("C"))
@staticmethod
def write_element_block_nsided(fp: SeekableBufferedWriter, polygon_node_counts: Int32NDArray,
polygon_connectivity: Int32NDArray, element_ids: Optional[Int32NDArray] = None) -> None:
"""
Write NSIDED element block to given opened file
See `UnstructuredElementBlock.read_connectivity_nsided()`.
"""
number_of_elements, = polygon_node_counts.shape
assert polygon_connectivity.shape == (polygon_node_counts.sum(),)
if element_ids is not None:
assert element_ids.shape == (number_of_elements,)
write_line(fp, f"{ElementType.NSIDED}")
write_int(fp, number_of_elements)
if element_ids is not None:
write_ints(fp, element_ids)
write_ints(fp, polygon_node_counts)
write_ints(fp, polygon_connectivity)
@staticmethod
def write_element_block_nfaced(fp: SeekableBufferedWriter, polyhedra_face_counts: Int32NDArray,
face_node_counts: Int32NDArray, face_connectivity: Int32NDArray,
element_ids: Optional[Int32NDArray] = None) -> None:
"""
Write NFACED element block to given opened file
See `UnstructuredElementBlock.read_connectivity_nfaced()`.
"""
number_of_elements, = polyhedra_face_counts.shape
assert face_node_counts.shape == (polyhedra_face_counts.sum(),)
assert face_connectivity.shape == (face_node_counts.sum(),)
if element_ids is not None:
assert element_ids.shape == (number_of_elements,)
write_line(fp, f"{ElementType.NFACED}")
write_int(fp, number_of_elements)
if element_ids is not None:
write_ints(fp, element_ids)
write_ints(fp, polyhedra_face_counts)
write_ints(fp, face_node_counts)
write_ints(fp, face_connectivity)
@dataclass
class GeometryPart:
"""
A part in EnSight Gold geometry file
To use it:
>>> import ensightreader
>>> case = ensightreader.read_case("example.case")
>>> geofile = case.get_geometry_model()
>>> part_names = geofile.get_part_names()
>>> part = geofile.get_part_by_name(part_names[0])
>>> print(part.is_volume())
>>> print(part.number_of_nodes)
Each geometry part has its own set of nodes not shared
with other parts. Elements are defined in blocks, where
each block may have different type (tetrahedra, wedge, etc.)
but all elements in the block have the same type.
Attributes:
offset: offset to 'part' line in the geometry file
part_id: part number
part_name: part name ('description' line)
number_of_nodes: number of nodes for this part
element_blocks: list of element blocks, in order of definition in the file
node_id_handling: node ID presence
element_id_handling: element ID presence
changing_geometry: type of transient changes (coordinate/connectivity/none)
"""
offset: int
part_id: int
part_name: str
number_of_nodes: int
element_blocks: List[UnstructuredElementBlock]
node_id_handling: IdHandling
element_id_handling: IdHandling
changing_geometry: Optional[ChangingGeometry] = None
def read_nodes(self, fp: SeekableBufferedReader) -> Float32NDArray:
"""
Read node coordinates for this part
Args:
fp: opened geometry file object in ``"rb"`` mode
Returns:
2D ``(n, 3)`` array of float32 with node coordinates
"""
fp.seek(self.offset)
assert read_line(fp).startswith("part")
assert read_int(fp) == self.part_id
assert read_line(fp).startswith(self.part_name)
assert read_line(fp).startswith("coordinates")
assert read_int(fp) == self.number_of_nodes
if self.node_id_handling.ids_present:
fp.seek(self.number_of_nodes * SIZE_INT, os.SEEK_CUR)
arr = read_floats(fp, 3*self.number_of_nodes)
return arr.reshape((self.number_of_nodes, 3), order="F")
def read_node_ids(self, fp: SeekableBufferedReader) -> Optional[Int32NDArray]:
"""
Read node IDs for this part, if present
.. note::
This method simply returns the node ID array as present
in the file; it does not differentiate between ``node id given``
and ``node id ignore``, etc.
Args:
fp: opened geometry file object in ``"rb"`` mode
Returns:
1D array of int32 with node IDs, or None if node IDs are not
present in the file
"""
if not self.node_id_handling.ids_present:
return None
fp.seek(self.offset)
assert read_line(fp).startswith("part")
assert read_int(fp) == self.part_id
assert read_line(fp).startswith(self.part_name)
assert read_line(fp).startswith("coordinates")
assert read_int(fp) == self.number_of_nodes
arr = read_ints(fp, self.number_of_nodes)
return arr
def is_volume(self) -> bool:
"""Return True if part contains volume elements"""
return any(block.element_type.dimension == 3 for block in self.element_blocks)
def is_surface(self) -> bool:
"""Return True if part contains surface elements"""
return any(block.element_type.dimension == 2 for block in self.element_blocks)
@property
def number_of_elements(self) -> int:
"""Return number of elements (of all types)"""
return sum(block.number_of_elements for block in self.element_blocks)
def get_number_of_elements_of_type(self, element_type: ElementType) -> int:
"""Return number of elements (of given type)"""
return sum(block.number_of_elements for block in self.element_blocks if block.element_type == element_type)
@classmethod
def from_file(cls, fp: SeekableBufferedReader, node_id_handling: IdHandling,
element_id_handling: IdHandling, changing_geometry_per_part: bool) -> "GeometryPart":
"""Used internally by `EnsightGeometryFile.from_file_path()`"""
offset = fp.tell()
fp.seek(0, os.SEEK_END)
file_len = fp.tell()
fp.seek(offset)
element_blocks = []
changing_geometry = None
part_line = read_line(fp)
if not part_line.startswith("part"):
raise EnsightReaderError("Expected 'part' line", fp)
if changing_geometry_per_part:
for changing_geometry_ in ChangingGeometry:
if changing_geometry_.value in part_line:
changing_geometry = changing_geometry_
break
else:
raise EnsightReaderError("Expected no_change/coord_change/conn_change in 'part' line", fp)
part_id = read_int(fp)
part_name = read_line(fp).rstrip("\x00 ")
coordinates_line = read_line(fp)
if not coordinates_line.startswith("coordinates"):
raise EnsightReaderError("Expected 'coordinates' line (other part types not implemented)", fp)
number_of_nodes = read_int(fp)
# skip node IDs
if node_id_handling.ids_present:
fp.seek(number_of_nodes * SIZE_INT, os.SEEK_CUR)
# skip node coordinates
fp.seek(3 * number_of_nodes * SIZE_FLOAT, os.SEEK_CUR)
# read element blocks
while fp.tell() != file_len:
element_type_line = peek_line(fp)
if element_type_line.startswith("part"):
break # end of this part, stop
else:
with add_exception_note_block(f"part_id = {part_id} ({part_name})"):
element_block = UnstructuredElementBlock.from_file(fp,
element_id_handling=element_id_handling,
part_id=part_id)
element_blocks.append(element_block)
return cls(
offset=offset,
part_id=part_id,
part_name=part_name,
number_of_nodes=number_of_nodes,
element_blocks=element_blocks,
node_id_handling=node_id_handling,
element_id_handling=element_id_handling,
changing_geometry=changing_geometry,
)
@staticmethod
def write_part_header(fp: BinaryIO, part_id: int, part_name: str,
node_coordinates: Float32NDArray, node_ids: Optional[Int32NDArray] = None) -> None:
"""
Write part header to given opened file
``node_coordiantes`` are supposed to be (N, 3)-shaped float32 array.
"""
number_of_nodes = node_coordinates.shape[0]
assert node_coordinates.shape[1] == 3
if node_ids is not None:
assert node_ids.shape == (number_of_nodes,)
write_line(fp, "part")
write_int(fp, part_id)
write_line(fp, part_name)
write_line(fp, "coordinates")
write_int(fp, number_of_nodes)
if node_ids is not None:
write_ints(fp, node_ids)
write_floats(fp, node_coordinates.ravel("F"))
def write_part(
self,
in_fp: SeekableBufferedReader,
out_fp: BinaryIO,
out_node_id_handling: IdHandling,
out_element_id_handling: IdHandling,
out_part_id: Optional[int] = None,
out_part_name: Optional[str] = None,
) -> None:
"""
Write part to other geometry file
This method will seek to the end of the file automatically.
Usage:
>>> import ensightreader, io
>>> source_case = ensightreader.read_case("source.case")
>>> dest_case = ensightreader.read_case("dest.case")
>>> source_geo = source_case.get_geometry_model()
>>> dest_geo = dest_case.get_geometry_model()
>>> source_part = source_geo.get_part_by_name("my_part")
>>> with source_geo.mmap() as source_mm, dest_geo.open_writeable() as dest_fp:
.... source_part.write_part(
.... source_mm,
.... dest_fp,
.... out_node_id_handling=dest_geo.node_id_handling,
.... out_element_id_handling=dest_geo.element_id_handling,
.... )
See Also:
`EnsightCaseFile.append_part_geometry()` for high-level method for part copying
Args:
in_fp: Opened input geometry file (where this `GeometryPart` is from)
out_fp: Opened output geometry file for writing (use `EnsightGeometryFile.open_writeable()`, not mmap)
out_node_id_handling: Node ID handling of output geometry file
out_element_id_handling: Element ID handling of output geometry file
out_part_id: Write with different part ID than in input file (default: use current ID)
out_part_name: Write with different part name than in input file (default: use current name)
"""
if out_node_id_handling.ids_present:
if self.node_id_handling.ids_present:
node_ids = self.read_node_ids(in_fp)
else:
node_ids = np.arange(self.number_of_nodes, dtype=np.int32)
else:
node_ids = None
out_fp.seek(0, io.SEEK_END)
self.write_part_header(
out_fp,
part_id=self.part_id if out_part_id is None else out_part_id,
part_name=self.part_name if out_part_name is None else out_part_name,
node_coordinates=self.read_nodes(in_fp),
node_ids=node_ids,
)
for block in self.element_blocks:
if out_element_id_handling.ids_present:
if self.element_id_handling.ids_present:
element_ids = block.read_element_ids(in_fp)
else:
element_ids = np.arange(block.number_of_elements, dtype=np.int32)
else:
element_ids = None
if block.element_type == ElementType.NSIDED:
polygon_node_counts, polygon_connectivity = block.read_connectivity_nsided(in_fp)
UnstructuredElementBlock.write_element_block_nsided(
out_fp,
polygon_node_counts=polygon_node_counts,
polygon_connectivity=polygon_connectivity,
element_ids=element_ids,
)
elif block.element_type == ElementType.NFACED:
polyhedra_face_counts, face_node_counts, face_connectivity = block.read_connectivity_nfaced(in_fp)
UnstructuredElementBlock.write_element_block_nfaced(
out_fp,
polyhedra_face_counts=polyhedra_face_counts,
face_node_counts=face_node_counts,
face_connectivity=face_connectivity,
element_ids=element_ids,
)
else:
connectivity = block.read_connectivity(in_fp)
UnstructuredElementBlock.write_element_block(
out_fp,
element_type=block.element_type,
connectivity=connectivity,
element_ids=element_ids,
)
def read_array(fp: SeekableBufferedReader, count: int, dtype: Type[TNum]) -> npt.NDArray[TNum]:
if isinstance(fp, _mmap.mmap):
offset = fp.tell()
bytes_to_read = count * dtype().itemsize
buffer = fp.read(bytes_to_read)
if len(buffer) != bytes_to_read:
raise EnsightReaderError(f"Only read {len(buffer)} bytes, expected {bytes_to_read} bytes", fp)
# TODO figure out a sane way to ask `mmap.mmap` about its access mode
if "ACCESS_WRITE" in str(fp):
# For write-through memory-mapped access, simply create an `ndarray` backed by the
# mmap, which results in writable `ndarray`; the `fp.read()` call is only used to advance
# the file pointer in this case.
arr: npt.NDArray[TNum] = np.ndarray((count,), dtype=dtype, buffer=memoryview(fp), offset=offset)
return arr
else:
# For read-only memory-mapped access, we want to wrap `bytes` as returned from the mmap;
# this results in non-writeable `ndarray`.
arr = np.frombuffer(buffer, dtype=dtype) # type: ignore[no-untyped-call]
return arr
else:
# For regular file access, we allocate buffer first and then read into it,
# this results in writeable `ndarray`.
arr = np.empty((count,), dtype=dtype)
bytes_to_read = arr.data.nbytes
n = fp.readinto(arr.data) # type: ignore[attr-defined]
if n != bytes_to_read:
raise EnsightReaderError(f"Only read {n} bytes, expected {bytes_to_read} bytes", fp)
return arr
def write_array(fp: SeekableBufferedWriter, data: npt.NDArray[TNum]) -> None:
fp.write(data.data)
def read_ints(fp: SeekableBufferedReader, count: int) -> Int32NDArray:
return read_array(fp, count, np.int32)
def write_ints(fp: SeekableBufferedWriter, data: Int32NDArray) -> None:
assert np.issubdtype(data.dtype, np.int32)
write_array(fp, data)
def read_int(fp: SeekableBufferedReader) -> int:
return int(read_ints(fp, 1)[0])
def write_int(fp: SeekableBufferedReader, value: int) -> None:
write_ints(fp, np.asarray([value], dtype=np.int32))
def read_floats(fp: SeekableBufferedReader, count: int) -> Float32NDArray:
return read_array(fp, count, np.float32)
def write_floats(fp: SeekableBufferedWriter, data: Float32NDArray) -> None:
assert np.issubdtype(data.dtype, np.float32)
write_array(fp, data)
def read_float(fp: SeekableBufferedReader) -> float:
return float(read_floats(fp, 1)[0])
def write_float(fp: SeekableBufferedReader, value: float) -> None:
write_floats(fp, np.asarray([value], dtype=np.float32))
def read_string(fp: SeekableBufferedReader, count: int) -> str:
data = fp.read(count)
if len(data) != count:
raise EnsightReaderError(f"Only read {len(data)} bytes, expected {count} bytes", fp)
return data.decode("ascii", "replace")
def write_string(fp: SeekableBufferedWriter, s: Union[str, bytes]) -> None:
if isinstance(s, str):
data = s.encode("ascii", "replace")
else:
data = s
fp.write(data)
def read_line(fp: SeekableBufferedReader) -> str: