tecio-python 0.4.1__py3-none-any.whl → 0.4.2__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.
Files changed (35) hide show
  1. tecio/__init__.py +42 -1
  2. tecio/_constants.py +2 -2
  3. tecio/_dat_write.py +32 -0
  4. tecio/_elements.py +1311 -0
  5. tecio/_io.py +49 -4
  6. tecio/_meta.py +8 -0
  7. tecio/_plt_write.py +32 -0
  8. tecio/_reader.py +157 -3
  9. tecio/_szl_read.py +99 -3
  10. tecio/_szl_write.py +261 -0
  11. tecio/_utils.py +10 -10
  12. tecio/_writer.py +234 -3
  13. tecio/cli/tec2mat.py +20 -0
  14. tecio/cli/tecaux.py +11 -1
  15. tecio/cli/tecdump.py +24 -1
  16. tecio/cli/tecelretyp.py +1096 -0
  17. tecio/cli/tecextract.py +21 -2
  18. tecio/cli/tecfix.py +16 -1
  19. tecio/cli/tecmerge.py +226 -34
  20. tecio/cli/teconvert.py +12 -2
  21. tecio/cli/tecscale.py +16 -1
  22. tecio/cli/tecslice.py +24 -3
  23. tecio/libtecio.py +75 -6
  24. {tecio_python-0.4.1.data → tecio_python-0.4.2.data}/data/share/tecio/plugins/paraview/TecplotTecioReader.py +1 -1
  25. {tecio_python-0.4.1.dist-info → tecio_python-0.4.2.dist-info}/METADATA +9 -9
  26. tecio_python-0.4.2.dist-info/RECORD +40 -0
  27. {tecio_python-0.4.1.dist-info → tecio_python-0.4.2.dist-info}/entry_points.txt +1 -0
  28. tecio_python-0.4.1.dist-info/RECORD +0 -38
  29. {tecio_python-0.4.1.data → tecio_python-0.4.2.data}/data/share/tecio/plugins/matlab/contourfe.m +0 -0
  30. {tecio_python-0.4.1.data → tecio_python-0.4.2.data}/data/share/tecio/plugins/matlab/tecmat2struct.m +0 -0
  31. {tecio_python-0.4.1.data → tecio_python-0.4.2.data}/data/share/tecio/plugins/paraview/TecplotTecioWriter.py +0 -0
  32. {tecio_python-0.4.1.dist-info → tecio_python-0.4.2.dist-info}/WHEEL +0 -0
  33. {tecio_python-0.4.1.dist-info → tecio_python-0.4.2.dist-info}/licenses/LICENSE +0 -0
  34. {tecio_python-0.4.1.dist-info → tecio_python-0.4.2.dist-info}/licenses/NOTICE +0 -0
  35. {tecio_python-0.4.1.dist-info → tecio_python-0.4.2.dist-info}/top_level.txt +0 -0
tecio/_elements.py ADDED
@@ -0,0 +1,1311 @@
1
+ """Node-map utilities for unstructured finite-element cells.
2
+
3
+ Many solvers write every volume cell as an ``FEBRICK`` and every surface cell as an
4
+ ``FEQUADRILATERAL``, repeating node indices to describe tetrahedra, pyramids, prisms and
5
+ triangles. The functions here detect such cells, collapse them to their natural zone
6
+ type (``FEBRICK`` to ``FETETRAHEDRON``, ``FEQUADRILATERAL`` to ``FETRIANGLE``) and
7
+ expand them back.
8
+
9
+ Detection does not assume a particular repeat convention. The nodes of a cell are
10
+ compared pairwise and the resulting pattern is matched against every way a brick or quad
11
+ can collapse onto a valid solid (a closed surface made of triangles and quads). Repeats
12
+ need not be adjacent in the node list, for example a brick can have a vertical edge
13
+ collapsed, which repeats node ``i`` at positions ``i`` and ``i + 4``. When a cell is
14
+ collapsed, the handedness of the original cell is kept: the new node order is the order
15
+ of first appearance, with the last two nodes swapped where a collapse would otherwise
16
+ mirror the cell (this affects 18 of the 102 ways a brick can collapse to a tetrahedron).
17
+ A brick also collapses to a pyramid in 54 ways and to a prism in 12, and a cell whose
18
+ nodes have the right face counts but not the right number of edges is not recognized.
19
+
20
+ Node indices are never changed, so nodal and cell-centered variables stay valid for a
21
+ collapsed zone. Only the node map changes. :func:`split_cells_by_shape` goes further and
22
+ separates the cells by shape for a ``FEMIXED`` zone. A pyramid lists the four
23
+ nodes of its base and then its apex, a prism lists one triangle and then the node above
24
+ each of its nodes, and both keep the handedness of the brick they came from.
25
+
26
+ :func:`cell_face_neighbors` finds, for every face of every cell, the cell on the other
27
+ side from the node map alone.
28
+
29
+ :func:`match_nodes` and :func:`match_cells` find how the nodes and cells of a zone are
30
+ ordered relative to a reference zone with the same grid, such as the same mesh read from
31
+ SZPLT, which may reorder large zones, and from PLT or DAT.
32
+
33
+ :func:`faces_by_element` and :func:`nodes_by_element` list the faces and the nodes of
34
+ every element from the left and right element of each face for polygon or polyhedral
35
+ elements.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import functools
41
+ import itertools
42
+ from collections.abc import Iterator, Sequence
43
+ from fractions import Fraction
44
+ from typing import NamedTuple
45
+
46
+ import numpy as np
47
+ import numpy.typing as npt
48
+
49
+ from ._constants import FeCellShape, ZoneType
50
+
51
+ __all__ = [
52
+ "UNKNOWN_SHAPE",
53
+ "CELL_SHAPE_NUM_NODES",
54
+ "CELL_SHAPE_DIMENSION",
55
+ "cell_face_neighbors",
56
+ "classify_cells",
57
+ "collapse_cells",
58
+ "collapsed_zone_type",
59
+ "degenerate_edges",
60
+ "expand_cells",
61
+ "match_cells",
62
+ "match_nodes",
63
+ "shape_counts",
64
+ "split_cells_by_shape",
65
+ ]
66
+
67
+ #: Value returned by :func:`classify_cells` for a cell that is not a recognized shape.
68
+ UNKNOWN_SHAPE = -1
69
+
70
+ #: Nodes per cell for each linear (grid order 1) cell shape.
71
+ CELL_SHAPE_NUM_NODES: dict[FeCellShape, int] = {
72
+ FeCellShape.BAR: 2,
73
+ FeCellShape.TRIANGLE: 3,
74
+ FeCellShape.QUADRILATERAL: 4,
75
+ FeCellShape.TETRAHEDRON: 4,
76
+ FeCellShape.HEXAHEDRON: 8,
77
+ FeCellShape.PYRAMID: 5,
78
+ FeCellShape.PRISM: 6,
79
+ }
80
+
81
+ #: The spatial dimension of each shape.
82
+ CELL_SHAPE_DIMENSION: dict[FeCellShape, int] = {
83
+ FeCellShape.BAR: 1,
84
+ FeCellShape.TRIANGLE: 2,
85
+ FeCellShape.QUADRILATERAL: 2,
86
+ FeCellShape.TETRAHEDRON: 3,
87
+ FeCellShape.HEXAHEDRON: 3,
88
+ FeCellShape.PYRAMID: 3,
89
+ FeCellShape.PRISM: 3,
90
+ }
91
+
92
+ # Cells processed at a time, bounds the size of temporary arrays.
93
+ _CHUNK_CELLS = 2**18
94
+
95
+ _NODES_PER_CELL: dict[ZoneType, int] = {
96
+ ZoneType.FELINESEG: 2,
97
+ ZoneType.FETRIANGLE: 3,
98
+ ZoneType.FEQUADRILATERAL: 4,
99
+ ZoneType.FETETRAHEDRON: 4,
100
+ ZoneType.FEBRICK: 8,
101
+ }
102
+
103
+ # Shape of every cell in a zone type that has no repeated-node variants.
104
+ _FIXED_SHAPE: dict[ZoneType, FeCellShape] = {
105
+ ZoneType.FELINESEG: FeCellShape.BAR,
106
+ ZoneType.FETRIANGLE: FeCellShape.TRIANGLE,
107
+ ZoneType.FETETRAHEDRON: FeCellShape.TETRAHEDRON,
108
+ }
109
+
110
+ # Edges of each cell, as pairs of positions in the node list.
111
+ _EDGES: dict[ZoneType, tuple[tuple[int, int], ...]] = {
112
+ ZoneType.FELINESEG: ((0, 1),),
113
+ ZoneType.FETRIANGLE: ((0, 1), (1, 2), (2, 0)),
114
+ ZoneType.FEQUADRILATERAL: ((0, 1), (1, 2), (2, 3), (3, 0)),
115
+ ZoneType.FETETRAHEDRON: ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)),
116
+ ZoneType.FEBRICK: (
117
+ (0, 1),
118
+ (1, 2),
119
+ (2, 3),
120
+ (3, 0),
121
+ (4, 5),
122
+ (5, 6),
123
+ (6, 7),
124
+ (7, 4),
125
+ (0, 4),
126
+ (1, 5),
127
+ (2, 6),
128
+ (3, 7),
129
+ ),
130
+ }
131
+
132
+ # Brick nodes follow the Tecplot data formatting guide ordering: 0-3 run around the
133
+ # bottom face and 4-7 around the top face, with node 4 above node 0.
134
+ _BRICK_CORNERS = (
135
+ (0, 0, 0),
136
+ (1, 0, 0),
137
+ (1, 1, 0),
138
+ (0, 1, 0),
139
+ (0, 0, 1),
140
+ (1, 0, 1),
141
+ (1, 1, 1),
142
+ (0, 1, 1),
143
+ )
144
+ _BRICK_FACES = (
145
+ (0, 1, 2, 3),
146
+ (4, 5, 6, 7),
147
+ (0, 1, 5, 4),
148
+ (1, 2, 6, 5),
149
+ (2, 3, 7, 6),
150
+ (3, 0, 4, 7),
151
+ )
152
+
153
+ # Corners of a pyramid in FEMIXED node order (the pyramid base runs counterclockwise
154
+ # seen from the apex side).
155
+ _PYRAMID_CORNERS = ((0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1))
156
+
157
+ # Corners of a prism in FEMIXED node order (node 3 of the prism is above node 0).
158
+ _PRISM_CORNERS = ((0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1))
159
+
160
+ # Nodes of each face as positions in the cell's node list.
161
+ _FACE_NODES: dict[ZoneType, tuple[tuple[int, ...], ...]] = {
162
+ ZoneType.FETRIANGLE: ((0, 1), (1, 2), (2, 0)),
163
+ ZoneType.FEQUADRILATERAL: ((0, 1), (1, 2), (2, 3), (3, 0)),
164
+ ZoneType.FETETRAHEDRON: ((0, 1, 2), (0, 1, 3), (1, 2, 3), (0, 2, 3)),
165
+ ZoneType.FEBRICK: _BRICK_FACES,
166
+ }
167
+
168
+
169
+ # Zone type each collapsible zone type can be reduced to, with the cell shape of its
170
+ # cells and the node positions used to expand them again.
171
+ _COLLAPSE: dict[ZoneType, tuple[ZoneType, FeCellShape]] = {
172
+ ZoneType.FEBRICK: (ZoneType.FETETRAHEDRON, FeCellShape.TETRAHEDRON),
173
+ ZoneType.FEQUADRILATERAL: (ZoneType.FETRIANGLE, FeCellShape.TRIANGLE),
174
+ }
175
+ _EXPAND: dict[tuple[ZoneType, ZoneType], tuple[int, ...]] = {
176
+ (ZoneType.FETETRAHEDRON, ZoneType.FEBRICK): (0, 1, 2, 2, 3, 3, 3, 3),
177
+ (ZoneType.FETRIANGLE, ZoneType.FEQUADRILATERAL): (0, 1, 2, 2),
178
+ }
179
+
180
+
181
+ class _Table(NamedTuple):
182
+ """Collapse patterns of one zone type, keyed by node-equality bit mask."""
183
+
184
+ masks: npt.NDArray[np.int64] # sorted
185
+ shapes: npt.NDArray[np.int8]
186
+ orders: npt.NDArray[np.int8] # node positions of the collapsed cell, -1 if unused
187
+
188
+
189
+ # ======================================================================================
190
+ # Pattern tables
191
+ # ======================================================================================
192
+
193
+
194
+ def _label_strings(n: int) -> Iterator[tuple[int, ...]]:
195
+ """Yield every partition of *n* positions as labels in order of first appearance.
196
+
197
+ Yields:
198
+ Tuples of ``n`` labels, where each label first appears after all smaller ones.
199
+ """
200
+
201
+ def extend(prefix: tuple[int, ...], used: int) -> Iterator[tuple[int, ...]]:
202
+ if len(prefix) == n:
203
+ yield prefix
204
+ return
205
+ for label in range(used + 1):
206
+ yield from extend((*prefix, label), used + (label == used))
207
+
208
+ yield from extend((), 0)
209
+
210
+
211
+ def _polygons(
212
+ labels: tuple[int, ...], faces: tuple[tuple[int, ...], ...]
213
+ ) -> list[tuple[int, ...]] | None:
214
+ """Return the faces of a collapsed cell as polygons of node labels.
215
+
216
+ Returns:
217
+ The faces left with three or more distinct nodes, or ``None`` if a face folds
218
+ over itself (a node repeated at non-adjacent positions of the face).
219
+ """
220
+ polygons = []
221
+ for face in faces:
222
+ ring = [labels[i] for i in face]
223
+ kept = [ring[i] for i in range(len(ring)) if ring[i] != ring[i - 1]]
224
+ if len(kept) <= 2:
225
+ continue # collapsed to an edge or a point
226
+ if len(set(kept)) != len(kept):
227
+ return None
228
+ polygons.append(tuple(kept))
229
+ return polygons
230
+
231
+
232
+ def _brick_shape(labels: tuple[int, ...]) -> FeCellShape | None:
233
+ """Name the solid a collapsed brick forms.
234
+
235
+ Returns:
236
+ The shape, or ``None`` if the collapsed cell is not a closed solid or is not a
237
+ tetrahedron, pyramid, prism or hexahedron.
238
+ """
239
+ polygons = _polygons(labels, _BRICK_FACES)
240
+ if polygons is None:
241
+ return None
242
+ edge_uses: dict[frozenset[int], int] = {}
243
+ for polygon in polygons:
244
+ for i in range(len(polygon)):
245
+ edge = frozenset((polygon[i], polygon[i - 1]))
246
+ edge_uses[edge] = edge_uses.get(edge, 0) + 1
247
+ if any(uses != 2 for uses in edge_uses.values()):
248
+ return None
249
+ num_nodes = len(set(labels))
250
+ triangles = sum(len(p) == 3 for p in polygons)
251
+ quads = sum(len(p) == 4 for p in polygons)
252
+ shape = {
253
+ (4, 4, 0): FeCellShape.TETRAHEDRON,
254
+ (5, 4, 1): FeCellShape.PYRAMID,
255
+ (6, 2, 3): FeCellShape.PRISM,
256
+ (8, 0, 6): FeCellShape.HEXAHEDRON,
257
+ }.get((num_nodes, triangles, quads))
258
+ if shape is None:
259
+ return None
260
+ # Matching face counts is not enough (a sliver folded onto itself has them too). A
261
+ # real solid has the edges per node of its shape (a pyramid apex has four).
262
+ degree: dict[int, int] = {}
263
+ for edge in edge_uses:
264
+ for node in edge:
265
+ degree[node] = degree.get(node, 0) + 1
266
+ apex = [4] if shape == FeCellShape.PYRAMID else []
267
+ expected = sorted([3] * (num_nodes - len(apex)) + apex)
268
+ return shape if sorted(degree.values()) == expected else None
269
+
270
+
271
+ def _quad_shape(labels: tuple[int, ...]) -> FeCellShape | None:
272
+ """Name the polygon a collapsed quadrilateral forms.
273
+
274
+ Returns:
275
+ ``QUADRILATERAL`` or ``TRIANGLE``, or ``None`` if the cell has fewer than three
276
+ distinct nodes or repeats a node at non-adjacent positions.
277
+ """
278
+ polygons = _polygons(labels, ((0, 1, 2, 3),))
279
+ if not polygons:
280
+ return None
281
+ return FeCellShape.TRIANGLE if len(polygons[0]) == 3 else FeCellShape.QUADRILATERAL
282
+
283
+
284
+ def _simpson_volume(corners: Sequence[tuple[int, ...]]) -> Fraction:
285
+ """Return the exact volume of a trilinear hexahedron.
286
+
287
+ The Jacobian determinant is quadratic in each coordinate, so a three-point Simpson
288
+ rule integrates it exactly.
289
+
290
+ Returns:
291
+ Signed volume, positive for a right-handed brick.
292
+ """
293
+ points = (-1, 0, 1)
294
+ weights = (Fraction(1, 3), Fraction(4, 3), Fraction(1, 3))
295
+ signs = [tuple(2 * c - 1 for c in corner) for corner in _BRICK_CORNERS]
296
+ total = Fraction(0)
297
+ for (a, wa), (b, wb), (c, wc) in itertools.product(
298
+ zip(points, weights, strict=True), repeat=3
299
+ ):
300
+ J = [[Fraction(0)] * 3 for _ in range(3)] # noqa N806
301
+ for node, (sx, sy, sz) in enumerate(signs):
302
+ slopes = (
303
+ sx * (1 + sy * b) * (1 + sz * c),
304
+ sy * (1 + sx * a) * (1 + sz * c),
305
+ sz * (1 + sx * a) * (1 + sy * b),
306
+ )
307
+ for i in range(3):
308
+ for k in range(3):
309
+ J[i][k] += Fraction(slopes[i], 8) * corners[node][k]
310
+ det = (
311
+ J[0][0] * (J[1][1] * J[2][2] - J[1][2] * J[2][1])
312
+ - J[0][1] * (J[1][0] * J[2][2] - J[1][2] * J[2][0])
313
+ + J[0][2] * (J[1][0] * J[2][1] - J[1][1] * J[2][0])
314
+ )
315
+ total += wa * wb * wc * det
316
+ return total
317
+
318
+
319
+ def _first_positions(labels: tuple[int, ...]) -> list[int]:
320
+ """Return the first position of each label, in label order."""
321
+ return [labels.index(label) for label in range(max(labels) + 1)]
322
+
323
+
324
+ def _tet_order(labels: tuple[int, ...]) -> tuple[int, ...]:
325
+ """Return the brick positions that give a tetrahedron of the brick's handedness.
326
+
327
+ The nodes are taken in order of first appearance. If a unit tetrahedron put on
328
+ those nodes has the opposite sign to the collapsed brick, the last two swap.
329
+
330
+ Returns:
331
+ Four brick positions, in the order of the new node map.
332
+ """
333
+ unit = ((0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)) # volume +1/6
334
+ brick_volume = _simpson_volume([unit[label] for label in labels])
335
+ order = _first_positions(labels)
336
+ if brick_volume < 0:
337
+ order[2], order[3] = order[3], order[2]
338
+ return tuple(order)
339
+
340
+
341
+ def _pyramid_order(labels: tuple[int, ...]) -> tuple[int, ...]:
342
+ """Return the brick positions that give a pyramid of the brick's handedness.
343
+
344
+ The nodes are the base quadrilateral in ring order and then the apex. If a pyramid
345
+ put on those nodes has the opposite sign to the collapsed brick, two base nodes
346
+ swap.
347
+
348
+ Returns:
349
+ Five brick positions, in the order of the new node map.
350
+ """
351
+ polygons = _polygons(labels, _BRICK_FACES) or []
352
+ base = next(p for p in polygons if len(p) == 4)
353
+ apex = next(label for label in set(labels) if label not in base)
354
+ order = [*base, apex]
355
+ corners = [_PYRAMID_CORNERS[order.index(label)] for label in labels]
356
+ if _simpson_volume(corners) < 0:
357
+ order[1], order[3] = order[3], order[1]
358
+ return tuple(labels.index(label) for label in order)
359
+
360
+
361
+ def _prism_order(labels: tuple[int, ...]) -> tuple[int, ...]:
362
+ """Return the brick positions that give a prism of the brick's handedness.
363
+
364
+ The nodes are one triangle in ring order and then the node joined to each of them
365
+ by an edge of the other triangle. If a prism put on those nodes has the opposite
366
+ sign to the collapsed brick, the last two nodes of each triangle swap.
367
+
368
+ Returns:
369
+ Six brick positions, in the order of the new node map.
370
+ """
371
+ polygons = _polygons(labels, _BRICK_FACES) or []
372
+ bottom, top = (p for p in polygons if len(p) == 3)
373
+ above: dict[int, int] = {}
374
+ for quad in (p for p in polygons if len(p) == 4):
375
+ for i in range(4):
376
+ a, b = quad[i - 1], quad[i]
377
+ if a in bottom and b in top:
378
+ above[a] = b
379
+ elif b in bottom and a in top:
380
+ above[b] = a
381
+ order = [*bottom, *(above[label] for label in bottom)]
382
+ corners = [_PRISM_CORNERS[order.index(label)] for label in labels]
383
+ if _simpson_volume(corners) < 0:
384
+ order[1], order[2] = order[2], order[1]
385
+ order[4], order[5] = order[5], order[4]
386
+ return tuple(labels.index(label) for label in order)
387
+
388
+
389
+ @functools.cache
390
+ def _table(zone_type: ZoneType) -> _Table:
391
+ """Build the collapse patterns of ``FEBRICK`` or ``FEQUADRILATERAL``.
392
+
393
+ Returns:
394
+ Table of patterns, sorted by mask, for the zone type.
395
+ """
396
+ n = _NODES_PER_CELL[zone_type]
397
+ pairs = tuple(itertools.combinations(range(n), 2))
398
+ rows: list[tuple[int, FeCellShape, tuple[int, ...]]] = []
399
+ for labels in _label_strings(n):
400
+ is_brick = zone_type == ZoneType.FEBRICK
401
+ shape = _brick_shape(labels) if is_brick else _quad_shape(labels)
402
+ if shape is None:
403
+ continue
404
+ mask = sum(1 << k for k, (i, j) in enumerate(pairs) if labels[i] == labels[j])
405
+ if shape == FeCellShape.TETRAHEDRON:
406
+ order = _tet_order(labels)
407
+ elif shape == FeCellShape.PYRAMID:
408
+ order = _pyramid_order(labels)
409
+ elif shape == FeCellShape.PRISM:
410
+ order = _prism_order(labels)
411
+ elif shape == FeCellShape.TRIANGLE:
412
+ order = tuple(_first_positions(labels))
413
+ else: # hexahedron or quadrilateral retain all nodes
414
+ order = tuple(range(n))
415
+ rows.append((mask, shape, order))
416
+ rows.sort(key=lambda row: row[0])
417
+ orders = np.full((len(rows), n), -1, dtype=np.int8)
418
+ for r, (_, _, order) in enumerate(rows):
419
+ orders[r, : len(order)] = order
420
+ return _Table(
421
+ np.array([r[0] for r in rows], dtype=np.int64),
422
+ np.array([r[1].value for r in rows], dtype=np.int8),
423
+ orders,
424
+ )
425
+
426
+
427
+ # ======================================================================================
428
+ # Helpers
429
+ # ======================================================================================
430
+
431
+
432
+ def _as_node_map(
433
+ node_map: npt.ArrayLike, zone_type: ZoneType
434
+ ) -> npt.NDArray[np.integer]:
435
+ """Validate *node_map* for *zone_type* and shape it ``(num_cells, nodes_per_cell)``.
436
+
437
+ Returns:
438
+ The node map as a two-dimensional integer array.
439
+
440
+ Raises:
441
+ ValueError: If *zone_type* is not a classic finite-element zone type, the node
442
+ map has the wrong number of nodes per cell, or it is not an integer array.
443
+ """
444
+ if zone_type not in _NODES_PER_CELL:
445
+ raise ValueError(
446
+ f"zone_type must be a classic finite-element zone type, got {zone_type}."
447
+ )
448
+ arr = np.asarray(node_map)
449
+ if not np.issubdtype(arr.dtype, np.integer):
450
+ raise ValueError(f"node_map must hold integers, got dtype {arr.dtype}.")
451
+ nodes_per_cell = _NODES_PER_CELL[zone_type]
452
+ if arr.ndim == 1 and arr.size % nodes_per_cell == 0:
453
+ arr = arr.reshape(-1, nodes_per_cell)
454
+ if arr.ndim != 2 or arr.shape[1] != nodes_per_cell:
455
+ raise ValueError(
456
+ f"node_map for {zone_type.name} must have {nodes_per_cell} nodes per cell, "
457
+ f"got shape {arr.shape}."
458
+ )
459
+ return arr
460
+
461
+
462
+ def _equality_masks(nodes: npt.NDArray[np.integer]) -> npt.NDArray[np.int32]:
463
+ """Pack the pairwise node equalities of every cell into one integer per cell.
464
+
465
+ Returns:
466
+ Bit ``k`` is set where the ``k``-th pair of node positions holds the same index.
467
+ """
468
+ mask = np.zeros(len(nodes), dtype=np.int32)
469
+ pairs = itertools.combinations(range(nodes.shape[1]), 2)
470
+ for bit, (i, j) in enumerate(pairs):
471
+ mask |= (nodes[:, i] == nodes[:, j]).astype(np.int32) << bit
472
+ return mask
473
+
474
+
475
+ def _classify_chunk(
476
+ nodes: npt.NDArray[np.integer], zone_type: ZoneType
477
+ ) -> tuple[npt.NDArray[np.int8], npt.NDArray[np.intp]]:
478
+ """Classify the cells of *nodes*.
479
+
480
+ Returns:
481
+ The shape value of each cell (:data:`UNKNOWN_SHAPE` if not recognized) and the
482
+ index of its row in the pattern table (meaningful only where the shape is known
483
+ and the zone type has a table).
484
+ """
485
+ masks = _equality_masks(nodes)
486
+ fixed = _FIXED_SHAPE.get(zone_type)
487
+ if fixed is not None:
488
+ shapes = np.where(masks == 0, fixed.value, UNKNOWN_SHAPE).astype(np.int8)
489
+ return shapes, np.zeros(len(nodes), dtype=np.intp)
490
+ table = _table(zone_type)
491
+ rows = np.minimum(np.searchsorted(table.masks, masks), len(table.masks) - 1)
492
+ hit = table.masks[rows] == masks
493
+ shapes = np.where(hit, table.shapes[rows], UNKNOWN_SHAPE).astype(np.int8)
494
+ return shapes, rows
495
+
496
+
497
+ # ======================================================================================
498
+ # Public API
499
+ # ======================================================================================
500
+
501
+
502
+ def classify_cells(
503
+ node_map: npt.ArrayLike, zone_type: ZoneType
504
+ ) -> npt.NDArray[np.int8]:
505
+ """Identify the shape of every cell, looking through repeated node indices.
506
+
507
+ ``FEBRICK`` cells are reported as ``TETRAHEDRON``, ``PYRAMID``, ``PRISM`` or
508
+ ``HEXAHEDRON`` and ``FEQUADRILATERAL`` cells as ``TRIANGLE`` or ``QUADRILATERAL``.
509
+ The other classic zone types report their own shape, unless a cell repeats a node.
510
+ A cell that repeats nodes in any other way (a collapsed edge that leaves a solid
511
+ that is not one of these shapes, or a cell flattened to a face) is unknown.
512
+
513
+ Args:
514
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``, or the same
515
+ values flattened.
516
+ zone_type: The zone type that *node_map* belongs to.
517
+
518
+ Returns:
519
+ Array of :class:`~tecio.FeCellShape` values, one per cell, with
520
+ :data:`UNKNOWN_SHAPE` for a cell that is not recognized.
521
+
522
+ Raises:
523
+ ValueError: If *zone_type* is not a classic finite-element type or *node_map*
524
+ does not fit it.
525
+ """
526
+ nodes = _as_node_map(node_map, zone_type)
527
+ shapes = np.empty(len(nodes), dtype=np.int8)
528
+ for lo in range(0, len(nodes), _CHUNK_CELLS):
529
+ hi = lo + _CHUNK_CELLS
530
+ shapes[lo:hi] = _classify_chunk(nodes[lo:hi], zone_type)[0]
531
+ return shapes
532
+
533
+
534
+ def shape_counts(
535
+ node_map: npt.ArrayLike, zone_type: ZoneType
536
+ ) -> dict[FeCellShape | None, int]:
537
+ """Count the cells of each shape (see :func:`classify_cells`).
538
+
539
+ Args:
540
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``.
541
+ zone_type: The zone type that *node_map* belongs to.
542
+
543
+ Returns:
544
+ Mapping from shape to cell count, ordered by shape value, with ``None`` as the
545
+ key for unrecognized cells. Shapes that do not occur are left out.
546
+ """
547
+ shapes = classify_cells(node_map, zone_type)
548
+ counts = np.bincount(shapes.astype(np.intp) + 1, minlength=len(FeCellShape) + 1)
549
+ result: dict[FeCellShape | None, int] = {}
550
+ if counts[0]:
551
+ result[None] = int(counts[0])
552
+ for shape in FeCellShape:
553
+ if counts[shape.value + 1]:
554
+ result[shape] = int(counts[shape.value + 1])
555
+ return result
556
+
557
+
558
+ def degenerate_edges(
559
+ node_map: npt.ArrayLike, zone_type: ZoneType
560
+ ) -> npt.NDArray[np.bool_]:
561
+ """Flag the edges of each cell whose two end nodes are the same index.
562
+
563
+ Args:
564
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``.
565
+ zone_type: The zone type that *node_map* belongs to.
566
+
567
+ Returns:
568
+ Boolean array ``(num_cells, num_edges)``. The edges are those of the zone type:
569
+ 1 for ``FELINESEG``, 3 for ``FETRIANGLE``, 4 for ``FEQUADRILATERAL``, 6 for
570
+ ``FETETRAHEDRON`` and 12 for ``FEBRICK`` (bottom ring, top ring, then the four
571
+ vertical edges, in the order of Tecplot's node numbering).
572
+
573
+ Raises:
574
+ ValueError: If *zone_type* is not a classic finite-element type or *node_map*
575
+ does not fit it.
576
+ """
577
+ nodes = _as_node_map(node_map, zone_type)
578
+ return np.stack([nodes[:, i] == nodes[:, j] for i, j in _EDGES[zone_type]], axis=1)
579
+
580
+
581
+ def collapsed_zone_type(
582
+ node_map: npt.ArrayLike, zone_type: ZoneType
583
+ ) -> ZoneType | None:
584
+ """Return the zone type a zone can be collapsed to, if every cell allows it.
585
+
586
+ Only ``FEBRICK`` zones whose cells are all tetrahedra and ``FEQUADRILATERAL`` zones
587
+ whose cells are all triangles can be collapsed. Pyramids and prisms have no classic
588
+ zone type, so a zone that holds any is left as it is.
589
+
590
+ Args:
591
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``.
592
+ zone_type: The zone type that *node_map* belongs to.
593
+
594
+ Returns:
595
+ ``FETETRAHEDRON`` or ``FETRIANGLE``, or ``None`` if the zone cannot be collapsed
596
+ (including a zone with no cells).
597
+
598
+ Raises:
599
+ ValueError: If *zone_type* is not a classic finite-element type or *node_map*
600
+ does not fit it.
601
+ """
602
+ nodes = _as_node_map(node_map, zone_type)
603
+ if zone_type not in _COLLAPSE or len(nodes) == 0:
604
+ return None
605
+ target, shape = _COLLAPSE[zone_type]
606
+ for lo in range(0, len(nodes), _CHUNK_CELLS):
607
+ shapes = _classify_chunk(nodes[lo : lo + _CHUNK_CELLS], zone_type)[0]
608
+ if not np.all(shapes == shape.value):
609
+ return None
610
+ return target
611
+
612
+
613
+ def collapse_cells(
614
+ node_map: npt.ArrayLike, zone_type: ZoneType, target: ZoneType
615
+ ) -> npt.NDArray[np.integer]:
616
+ """Collapse every cell to a smaller zone type, keeping its handedness.
617
+
618
+ ``FEBRICK`` cells that are tetrahedra become ``FETETRAHEDRON`` cells and
619
+ ``FEQUADRILATERAL`` cells that are triangles become ``FETRIANGLE`` cells. The
620
+ repeated nodes are dropped and the rest are kept in order of first appearance, with
621
+ the last two tetrahedron nodes swapped where the order would otherwise mirror the
622
+ cell. Node indices are unchanged.
623
+
624
+ Args:
625
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``.
626
+ zone_type: The zone type that *node_map* belongs to.
627
+ target: The zone type to collapse to, ``FETETRAHEDRON`` for ``FEBRICK`` and
628
+ ``FETRIANGLE`` for ``FEQUADRILATERAL``.
629
+
630
+ Returns:
631
+ New node map with 4 (tetrahedron) or 3 (triangle) nodes per cell and the dtype
632
+ of *node_map*.
633
+
634
+ Raises:
635
+ ValueError: If *zone_type* cannot collapse to *target*, *node_map* does not fit
636
+ *zone_type*, or any cell is not a tetrahedron or triangle respectively.
637
+ """
638
+ nodes = _as_node_map(node_map, zone_type)
639
+ if zone_type not in _COLLAPSE or _COLLAPSE[zone_type][0] != target:
640
+ raise ValueError(f"{zone_type.name} cannot be collapsed to {target.name}.")
641
+ shape = _COLLAPSE[zone_type][1]
642
+ table = _table(zone_type)
643
+ width = CELL_SHAPE_NUM_NODES[shape]
644
+ out = np.empty((len(nodes), width), dtype=nodes.dtype)
645
+ for lo in range(0, len(nodes), _CHUNK_CELLS):
646
+ chunk = nodes[lo : lo + _CHUNK_CELLS]
647
+ shapes, rows = _classify_chunk(chunk, zone_type)
648
+ wrong = np.flatnonzero(shapes != shape.value)
649
+ if wrong.size:
650
+ raise ValueError(
651
+ f"cannot collapse {zone_type.name} to {target.name}: cell "
652
+ f"{lo + int(wrong[0])} is not a {shape.name.lower()}."
653
+ )
654
+ positions = table.orders[rows, :width].astype(np.intp)
655
+ out[lo : lo + len(chunk)] = np.take_along_axis(chunk, positions, axis=1)
656
+ return out
657
+
658
+
659
+ def split_cells_by_shape(
660
+ node_map: npt.ArrayLike, zone_type: ZoneType
661
+ ) -> dict[FeCellShape, tuple[npt.NDArray[np.intp], npt.NDArray[np.integer]]]:
662
+ """Separate the cells of a zone by shape, for a ``FEMIXED`` zone.
663
+
664
+ Every cell is reduced to its collapsed shape: ``FEBRICK`` cells give tetrahedra,
665
+ pyramids, prisms and hexahedra and ``FEQUADRILATERAL`` cells give triangles and
666
+ quadrilaterals. Repeated nodes are dropped, the nodes are in the order of a FEMIXED
667
+ zone section and the handedness of each cell is kept. Node indices are unchanged.
668
+
669
+ Cells are numbered through the sections in the order returned, so a cell-centered
670
+ variable of the new zone is ``values[np.concatenate(cells)]``, with *cells* the
671
+ first item of each result.
672
+
673
+ Args:
674
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``, or the same
675
+ values flattened.
676
+ zone_type: The zone type that *node_map* belongs to.
677
+
678
+ Returns:
679
+ Mapping from shape to ``(cells, node_map)``, ordered by shape value and holding
680
+ only the shapes that occur. ``cells`` is the ascending 0-based index in the
681
+ input of each cell of that shape and ``node_map`` has their nodes, with the
682
+ dtype of the input.
683
+
684
+ Raises:
685
+ ValueError: If *zone_type* is not a classic finite-element type, *node_map* does
686
+ not fit it, or any cell is not a recognized shape (see
687
+ :func:`classify_cells`).
688
+ """
689
+ nodes = _as_node_map(node_map, zone_type)
690
+ table = None if zone_type in _FIXED_SHAPE else _table(zone_type)
691
+ parts: dict[int, list[tuple[npt.NDArray[np.intp], npt.NDArray[np.integer]]]] = {}
692
+ for lo in range(0, len(nodes), _CHUNK_CELLS):
693
+ chunk = nodes[lo : lo + _CHUNK_CELLS]
694
+ shapes, rows = _classify_chunk(chunk, zone_type)
695
+ unknown = np.flatnonzero(shapes == UNKNOWN_SHAPE)
696
+ if unknown.size:
697
+ raise ValueError(f"cell {lo + int(unknown[0])} is not a recognized shape.")
698
+ for value in np.unique(shapes):
699
+ local = np.flatnonzero(shapes == value)
700
+ picked = chunk[local]
701
+ if table is not None:
702
+ width = CELL_SHAPE_NUM_NODES[FeCellShape(int(value))]
703
+ positions = table.orders[rows[local], :width].astype(np.intp)
704
+ picked = np.take_along_axis(picked, positions, axis=1)
705
+ parts.setdefault(int(value), []).append((local + lo, picked))
706
+ result: dict[FeCellShape, tuple[npt.NDArray[np.intp], npt.NDArray[np.integer]]] = {}
707
+ for value in sorted(parts):
708
+ chunks = parts[value]
709
+ if len(chunks) == 1:
710
+ result[FeCellShape(value)] = chunks[0]
711
+ else:
712
+ result[FeCellShape(value)] = (
713
+ np.concatenate([c[0] for c in chunks]),
714
+ np.concatenate([c[1] for c in chunks]),
715
+ )
716
+ return result
717
+
718
+
719
+ def expand_cells(
720
+ node_map: npt.ArrayLike, zone_type: ZoneType, target: ZoneType
721
+ ) -> npt.NDArray[np.integer]:
722
+ """Expand every cell to a larger zone type by repeating nodes.
723
+
724
+ ``FETETRAHEDRON`` cells become ``FEBRICK`` cells as ``(n0, n1, n2, n2, n3, n3, n3,
725
+ n3)`` and ``FETRIANGLE`` cells become ``FEQUADRILATERAL`` cells as ``(n0, n1, n2,
726
+ n2)``. The result keeps the handedness of the input and collapses back to it with
727
+ :func:`collapse_cells`.
728
+
729
+ Args:
730
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``.
731
+ zone_type: The zone type that *node_map* belongs to.
732
+ target: The zone type to expand to, ``FEBRICK`` for ``FETETRAHEDRON`` and
733
+ ``FEQUADRILATERAL`` for ``FETRIANGLE``.
734
+
735
+ Returns:
736
+ New node map with 8 (brick) or 4 (quadrilateral) nodes per cell and the dtype
737
+ of *node_map*.
738
+
739
+ Raises:
740
+ ValueError: If *zone_type* cannot expand to *target* or *node_map* does not fit
741
+ *zone_type*.
742
+ """
743
+ nodes = _as_node_map(node_map, zone_type)
744
+ columns = _EXPAND.get((zone_type, target))
745
+ if columns is None:
746
+ raise ValueError(f"{zone_type.name} cannot be expanded to {target.name}.")
747
+ return nodes[:, list(columns)]
748
+
749
+
750
+ # ======================================================================================
751
+ # Face neighbors
752
+ # ======================================================================================
753
+
754
+
755
+ # --------------------------------------------------------------------------------------
756
+ # Hashing functions
757
+ # --------------------------------------------------------------------------------------
758
+
759
+
760
+ _GAMMA = np.uint64(0x9E3779B97F4A7C15)
761
+ _MUL64 = (np.uint64(0xBF58476D1CE4E5B9), np.uint64(0x94D049BB133111EB))
762
+ _MUL32 = (np.uint32(0x7FEB352D), np.uint32(0x846CA68B))
763
+
764
+
765
+ def _splitmix64(x: npt.NDArray[np.uint64]) -> npt.NDArray[np.uint64]:
766
+ """Return the SplitMix64 output for each generator state in *x*.
767
+
768
+ This is one step of the generator: add the golden ratio increment to the state, then
769
+ mix. Output ``k`` of a generator seeded with ``s`` is ``splitmix64(s + k * gamma)``
770
+ with ``gamma = 0x9E3779B97F4A7C15``, so ``splitmix64(0)`` is its first output for
771
+ seed 0. Arithmetic wraps modulo 2**64 and *x* is not modified.
772
+
773
+ Args:
774
+ x: Array of ``uint64`` states.
775
+
776
+ Returns:
777
+ New ``uint64`` array of the same shape.
778
+
779
+ References:
780
+ :func:`splitmix64` is the output function of the SplitMix64 generator, written
781
+ in 2015 by Sebastiano Vigna and dedicated to the public domain
782
+ (https://prng.di.unimi.it/splitmix64.c). It is a fixed increment version of the
783
+ SplittableRandom generator of G. L. Steele Jr., D. Lea and C. H. Flood, "Fast
784
+ splittable pseudorandom number generators", OOPSLA 2014,
785
+ https://doi.org/10.1145/2714064.2660195.
786
+ """
787
+ z = x + _GAMMA
788
+ z ^= z >> np.uint64(30)
789
+ z *= _MUL64[0]
790
+ z ^= z >> np.uint64(27)
791
+ z *= _MUL64[1]
792
+ z ^= z >> np.uint64(31)
793
+ return z
794
+
795
+
796
+ def _lowbias32(x: npt.NDArray[np.uint32]) -> npt.NDArray[np.uint32]:
797
+ """Return the ``lowbias32`` hash of each value in *x*.
798
+
799
+ Zero maps to zero, so offset the input when that matters. Arithmetic wraps modulo
800
+ 2**32 and *x* is not modified.
801
+
802
+ Args:
803
+ x: Array of ``uint32`` values.
804
+
805
+ Returns:
806
+ New ``uint32`` array of the same shape.
807
+
808
+ References:
809
+ Chris Wellons, "Prospecting for Hash Functions", 2018,
810
+ https://nullprogram.com/blog/2018/07/31/ (public domain, exact bias 0.1735).
811
+ """
812
+ z = x ^ (x >> np.uint32(16))
813
+ z *= _MUL32[0]
814
+ z ^= z >> np.uint32(15)
815
+ z *= _MUL32[1]
816
+ z ^= z >> np.uint32(16)
817
+ return z
818
+
819
+
820
+ def _node_hashes(
821
+ num_nodes: int,
822
+ ) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint32]]:
823
+ """Return two independent hash values for each node index.
824
+
825
+ The 64-bit hash is :func:`~tecio._hashing.splitmix64` of the index. The 32-bit hash
826
+ is :func:`~tecio._hashing.lowbias32` of the index plus one, with the high half
827
+ folded into the low half for indices of 2**32 or more. Both are bijections for
828
+ indices below 2**32.
829
+
830
+ Returns:
831
+ A 64-bit and a 32-bit hash per node.
832
+ """
833
+ index = np.arange(num_nodes, dtype=np.uint64)
834
+ one_based = index + np.uint64(1)
835
+ one_based ^= one_based >> np.uint64(32)
836
+ return _splitmix64(index), _lowbias32(one_based.astype(np.uint32))
837
+
838
+
839
+ def _hash_faces(
840
+ nodes: npt.NDArray[np.integer],
841
+ table: tuple[tuple[int, ...], ...],
842
+ min_nodes: int,
843
+ ) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint32], npt.NDArray[np.bool_]]:
844
+ """Hash the set of nodes of every face of every cell.
845
+
846
+ A node repeated within a face counts once, so a face of a degenerate cell hashes the
847
+ same as a face with the same distinct nodes. Faces are numbered ``face * num_cells +
848
+ cell``.
849
+
850
+ Args:
851
+ nodes: Node map ``(num_cells, nodes_per_cell)``.
852
+ table: Node positions of each face of a cell.
853
+ min_nodes: Fewest distinct nodes a face needs to be a face.
854
+
855
+ Returns:
856
+ A 64-bit hash, an independent 32-bit hash, and a flag for faces with at least
857
+ *min_nodes* distinct nodes.
858
+ """
859
+ num_cells = len(nodes)
860
+ wide, narrow = _node_hashes(int(np.max(nodes)) + 1)
861
+ wide_sum = np.empty(len(table) * num_cells, dtype=np.uint64)
862
+ narrow_sum = np.empty(len(table) * num_cells, dtype=np.uint32)
863
+ valid = np.empty(len(table) * num_cells, dtype=bool)
864
+ for lo in range(0, num_cells, _CHUNK_CELLS):
865
+ hi = min(lo + _CHUNK_CELLS, num_cells)
866
+ columns = np.ascontiguousarray(nodes[lo:hi].T)
867
+ wide_node, narrow_node = wide.take(columns), narrow.take(columns)
868
+ for f, positions in enumerate(table):
869
+ out = slice(f * num_cells + lo, f * num_cells + hi)
870
+ total_wide = wide_node[positions[0]].copy()
871
+ total_narrow = narrow_node[positions[0]].copy()
872
+ distinct = np.ones(hi - lo, dtype=np.int8)
873
+ for j in range(1, len(positions)):
874
+ repeated = columns[positions[j]] == columns[positions[0]]
875
+ for k in range(1, j):
876
+ repeated |= columns[positions[j]] == columns[positions[k]]
877
+ new = ~repeated
878
+ np.add(total_wide, wide_node[positions[j]], out=total_wide, where=new)
879
+ np.add(
880
+ total_narrow, narrow_node[positions[j]], out=total_narrow, where=new
881
+ )
882
+ distinct += new
883
+ wide_sum[out] = total_wide
884
+ narrow_sum[out] = total_narrow
885
+ valid[out] = distinct >= min_nodes
886
+ return wide_sum, narrow_sum, valid
887
+
888
+
889
+ def _face_rows(
890
+ nodes: npt.NDArray[np.integer], table: npt.NDArray[np.intp], face_ids: npt.NDArray
891
+ ) -> npt.NDArray[np.integer]:
892
+ """Return the node indices of the faces with the given face-major ids."""
893
+ face, cell = np.divmod(face_ids, len(nodes))
894
+ flat = nodes.reshape(-1)
895
+ return flat.take((cell * nodes.shape[1])[:, None] + table[face])
896
+
897
+
898
+ def _pair_exact(
899
+ nodes: npt.NDArray[np.integer],
900
+ table: npt.NDArray[np.intp],
901
+ face_ids: npt.NDArray[np.intp],
902
+ ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]:
903
+ """Pair up faces with the same distinct nodes, comparing the nodes themselves.
904
+
905
+ Used for the faces whose hashes alone leave doubt: a node set shared by more than
906
+ two cells, or a hash collision.
907
+
908
+ Returns:
909
+ The two face ids of every node set that exactly two of *face_ids* have.
910
+ """
911
+ rows = _face_rows(nodes, table, face_ids)
912
+ rows.sort(axis=1)
913
+ repeated = np.zeros(rows.shape, dtype=bool)
914
+ repeated[:, 1:] = rows[:, 1:] == rows[:, :-1]
915
+ rows[repeated] = -1
916
+ rows.sort(axis=1)
917
+ order = np.lexsort(rows.T[::-1])
918
+ rows = rows[order]
919
+ starts = np.flatnonzero(np.r_[True, (rows[1:] != rows[:-1]).any(axis=1), True])
920
+ first = starts[:-1][np.diff(starts) == 2]
921
+ return face_ids[order[first]], face_ids[order[first + 1]]
922
+
923
+
924
+ def cell_face_neighbors(
925
+ node_map: npt.ArrayLike, zone_type: ZoneType
926
+ ) -> npt.NDArray[np.int64]:
927
+ """Find the cell on the other side of every face of every cell.
928
+
929
+ Two cells are neighbors across a face when they have the same nodes on that face. A
930
+ node repeated within a face counts once, so cells written as bricks with repeated
931
+ nodes (see :func:`classify_cells`) match their neighbors through the faces that
932
+ remain. Faces collapsed to an edge or a point have no neighbor, and neither does a
933
+ face shared by more than two cells. Nodes are compared by index, not by position, so
934
+ nodes at the same location with different indices are not merged.
935
+
936
+ Faces are matched by sorting a 96-bit hash of each face's node set, which makes the
937
+ cost grow as ``num_cells * log(num_cells)``. Doubt about a match (a node set shared
938
+ by more than two cells) is settled by comparing the nodes themselves.
939
+
940
+ The faces of ``FETRIANGLE`` and ``FEQUADRILATERAL`` cells are the edges from node
941
+ ``i`` to node ``i + 1``. The order of the faces of ``FETETRAHEDRON`` and ``FEBRICK``
942
+ cells is provisional: it has not yet been checked against the face numbering figures
943
+ of the Tecplot data format guide, so the neighbor across each face is certain, but
944
+ the column it is reported in is not.
945
+
946
+ Args:
947
+ node_map: Node indices with shape ``(num_cells, nodes_per_cell)``.
948
+ zone_type: One of ``FETRIANGLE``, ``FEQUADRILATERAL``, ``FETETRAHEDRON`` or
949
+ ``FEBRICK``.
950
+
951
+ Returns:
952
+ Array ``(num_cells, num_faces)`` holding the 0-based index of the neighbor of
953
+ each face, or ``-1`` where there is none.
954
+
955
+ Raises:
956
+ ValueError: If *zone_type* has no faces to match (``FELINESEG`` or a zone type
957
+ that is not finite-element), *node_map* does not fit it, or a node index is
958
+ negative.
959
+ """
960
+ nodes = _as_node_map(node_map, zone_type)
961
+ if zone_type not in _FACE_NODES:
962
+ raise ValueError(f"{zone_type.name} cells have no faces to match.")
963
+ table = np.array(_FACE_NODES[zone_type], dtype=np.intp)
964
+ num_cells, num_faces = len(nodes), len(table)
965
+ if num_cells == 0:
966
+ return np.full((0, num_faces), -1, dtype=np.int64)
967
+ if np.min(nodes) < 0:
968
+ raise ValueError("node_map holds negative node indices.")
969
+ nodes = np.ascontiguousarray(nodes)
970
+
971
+ wide, narrow, valid = _hash_faces(
972
+ nodes, _FACE_NODES[zone_type], 2 if table.shape[1] == 2 else 3
973
+ )
974
+ if valid.all():
975
+ keys = wide
976
+ order = np.argsort(keys)
977
+ ids = order
978
+ else:
979
+ usable = np.flatnonzero(valid)
980
+ keys = wide[usable]
981
+ order = np.argsort(keys)
982
+ ids = usable[order]
983
+ keys = keys[order]
984
+ del order, valid
985
+
986
+ # A run of equal hashes is a pair of faces, or a collision or a node set shared by
987
+ # many cells.
988
+ equal = keys[1:] == keys[:-1]
989
+ follows = np.zeros(len(keys), dtype=bool)
990
+ follows[1:] = equal
991
+ precedes = np.zeros(len(keys), dtype=bool)
992
+ precedes[:-1] = equal
993
+ first = precedes & ~follows
994
+ first[:-1] &= ~precedes[1:]
995
+ start = np.flatnonzero(first)
996
+ in_pair = np.zeros(len(keys), dtype=bool)
997
+ in_pair[start] = in_pair[start + 1] = True
998
+ in_run = follows | precedes
999
+ ambiguous = ids[in_run & ~in_pair]
1000
+ a, b = ids[start], ids[start + 1]
1001
+ confirmed = narrow[a] == narrow[b]
1002
+ a, b = a[confirmed], b[confirmed]
1003
+ if ambiguous.size:
1004
+ extra_a, extra_b = _pair_exact(nodes, table, ambiguous)
1005
+ a, b = np.r_[a, extra_a], np.r_[b, extra_b]
1006
+ cell_a, cell_b = a % num_cells, b % num_cells
1007
+ other = cell_a != cell_b # a cell cannot be its own neighbor
1008
+ a, b, cell_a, cell_b = a[other], b[other], cell_a[other], cell_b[other]
1009
+ neighbors = np.full(num_faces * num_cells, -1, dtype=np.int64)
1010
+ neighbors[a] = cell_b
1011
+ neighbors[b] = cell_a
1012
+ return np.ascontiguousarray(neighbors.reshape(num_faces, num_cells).T)
1013
+
1014
+
1015
+ # --------------------------------------------------------------------------------------
1016
+ # Matching zones that are stored in another order
1017
+ # --------------------------------------------------------------------------------------
1018
+
1019
+
1020
+ def _as_cell_nodes(node_map: npt.ArrayLike) -> npt.NDArray[np.integer]:
1021
+ """Validate one node map for :func:`match_cells`.
1022
+
1023
+ Returns:
1024
+ The node map as an integer array.
1025
+
1026
+ Raises:
1027
+ ValueError: If it is not a two-dimensional integer array or holds a negative
1028
+ index.
1029
+ """
1030
+ arr = np.asarray(node_map)
1031
+ if arr.ndim != 2 or not np.issubdtype(arr.dtype, np.integer):
1032
+ raise ValueError("node maps must be two-dimensional integer arrays.")
1033
+ if arr.size and int(arr.min()) < 0:
1034
+ raise ValueError("node maps hold negative node indices.")
1035
+ return arr
1036
+
1037
+
1038
+ def _hash_cells(
1039
+ nodes: npt.NDArray[np.integer],
1040
+ wide: npt.NDArray[np.uint64],
1041
+ narrow: npt.NDArray[np.uint32],
1042
+ renumber: npt.NDArray[np.intp] | None = None,
1043
+ ) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint32]]:
1044
+ """Hash each cell by summing the hashes of its nodes, in chunks of cells.
1045
+
1046
+ Node indices are renumbered first when *renumber* is given. The sums wrap, so they
1047
+ do not depend on the order of the nodes in a cell. A repeated node counts each time.
1048
+
1049
+ Returns:
1050
+ The 64-bit and the 32-bit hash of each cell.
1051
+ """
1052
+ num_cells = len(nodes)
1053
+ cell_wide = np.empty(num_cells, dtype=np.uint64)
1054
+ cell_narrow = np.empty(num_cells, dtype=np.uint32)
1055
+ for lo in range(0, num_cells, _CHUNK_CELLS):
1056
+ chunk = nodes[lo : lo + _CHUNK_CELLS]
1057
+ if renumber is not None:
1058
+ chunk = renumber[chunk]
1059
+ cell_wide[lo : lo + len(chunk)] = wide[chunk].sum(axis=1, dtype=np.uint64)
1060
+ cell_narrow[lo : lo + len(chunk)] = narrow[chunk].sum(axis=1, dtype=np.uint32)
1061
+ return cell_wide, cell_narrow
1062
+
1063
+
1064
+ def match_nodes(
1065
+ ref_coords: Sequence[npt.ArrayLike], coords: Sequence[npt.ArrayLike]
1066
+ ) -> npt.NDArray[np.intp] | None:
1067
+ """Find how the nodes of a zone are ordered relative to a reference zone.
1068
+
1069
+ The same grid can be stored with its nodes in another order, for example by SZPLT
1070
+ in large zones, or by another program that wrote the same mesh. Nodes are matched
1071
+ when all of their coordinates are exactly equal, so the coordinates must have the
1072
+ same values, not just the same locations to a tolerance, and must be unique.
1073
+
1074
+ Args:
1075
+ ref_coords: One array per coordinate (``x``, ``y``, ``z``) of the reference
1076
+ zone.
1077
+ coords: The same coordinates of the zone to match.
1078
+
1079
+ Returns:
1080
+ Array ``order`` where ``order[i]`` is the index in *coords* of the node that is
1081
+ node ``i`` of the reference, so ``coords[k][order]`` equals ``ref_coords[k]``
1082
+ and ``values[order]`` lists a nodal variable of the zone in the reference
1083
+ order. ``np.argsort(order)`` is the inverse, giving the reference index of each
1084
+ node of the zone. ``None`` if the zones do not have the same nodes, or if
1085
+ coordinates repeat, which leaves the match ambiguous.
1086
+
1087
+ Raises:
1088
+ ValueError: If a coordinate array is not one-dimensional or the coordinates of
1089
+ a zone have different lengths.
1090
+ """
1091
+ ref = [np.asarray(c) for c in ref_coords]
1092
+ got = [np.asarray(c) for c in coords]
1093
+ for arrays in (ref, got):
1094
+ if not arrays or any(c.ndim != 1 or len(c) != len(arrays[0]) for c in arrays):
1095
+ raise ValueError("coordinates must be 1-D arrays of the same length.")
1096
+ if len(ref) != len(got) or len(ref[0]) != len(got[0]):
1097
+ return None
1098
+ # lexsort treats the last key as the primary one, which does not matter here
1099
+ ref_sort = np.lexsort(ref)
1100
+ got_sort = np.lexsort(got)
1101
+ repeated = np.ones(max(len(ref_sort) - 1, 0), dtype=bool)
1102
+ for r, g in zip(ref, got, strict=True):
1103
+ r, g = r[ref_sort], g[got_sort]
1104
+ if not np.array_equal(r, g):
1105
+ return None
1106
+ repeated &= r[1:] == r[:-1]
1107
+ if repeated.any():
1108
+ return None
1109
+ order = np.empty(len(ref_sort), dtype=np.intp)
1110
+ order[ref_sort] = got_sort
1111
+ return order
1112
+
1113
+
1114
+ def match_cells(
1115
+ ref_node_maps: Sequence[npt.ArrayLike],
1116
+ node_maps: Sequence[npt.ArrayLike],
1117
+ node_order: npt.ArrayLike | None = None,
1118
+ ) -> npt.NDArray[np.intp] | None:
1119
+ """Find how the cells of a zone are ordered relative to a reference zone.
1120
+
1121
+ A cell is identified by its set of nodes, so cells match whatever the order of the
1122
+ nodes within them. Compare the node maps in the reference order afterwards when the
1123
+ order within a cell matters. Each cell is hashed by summing the per-node hash that
1124
+ :func:`cell_face_neighbors` uses to match faces, and the cells are paired by sorting
1125
+ the hashes, so the cost grows as ``num_cells * log(num_cells)``. A pair is accepted
1126
+ only when a second, 32-bit hash agrees too.
1127
+
1128
+ Args:
1129
+ ref_node_maps: The node map of each section of the reference zone, each with
1130
+ shape ``(num_cells, nodes_per_cell)`` and 0-based. Pass ``[node_map]`` for a
1131
+ classic zone.
1132
+ node_maps: The node map of each section of the zone to match, in the same
1133
+ layout.
1134
+ node_order: Order of the nodes as returned by :func:`match_nodes`. Leave out if
1135
+ both zones number their nodes alike.
1136
+
1137
+ Returns:
1138
+ Array ``order`` where ``order[i]`` is the index in the zone of the cell that is
1139
+ cell ``i`` of the reference, counting cells through the sections, so
1140
+ ``values[order]`` lists a cell-centered variable of the zone in the reference
1141
+ order. ``None`` if the zones do not have the same sections or the same cells,
1142
+ or if a section of the reference holds cells with identical nodes, which leaves
1143
+ the match ambiguous.
1144
+
1145
+ Raises:
1146
+ ValueError: If a node map is not two-dimensional or integer, holds a negative
1147
+ index, or holds an index beyond the nodes of the zone (the length of
1148
+ *node_order*, when given).
1149
+ """
1150
+ ref_maps = [_as_cell_nodes(m) for m in ref_node_maps]
1151
+ maps = [_as_cell_nodes(m) for m in node_maps]
1152
+ if len(ref_maps) != len(maps) or any(
1153
+ r.shape != m.shape for r, m in zip(ref_maps, maps, strict=True)
1154
+ ):
1155
+ return None
1156
+ if node_order is None:
1157
+ num_nodes = 1 + max(
1158
+ (int(np.max(m)) for m in (*ref_maps, *maps) if m.size), default=0
1159
+ )
1160
+ renumber = None
1161
+ else:
1162
+ node_order = np.asarray(node_order)
1163
+ num_nodes = len(node_order)
1164
+ renumber = np.empty(num_nodes, dtype=np.intp)
1165
+ renumber[node_order] = np.arange(num_nodes, dtype=np.intp)
1166
+ for m in (*ref_maps, *maps):
1167
+ if m.size and int(np.max(m)) >= num_nodes:
1168
+ raise ValueError("node maps hold indices beyond the nodes of the zone.")
1169
+ wide, narrow = _node_hashes(num_nodes)
1170
+
1171
+ orders = []
1172
+ offset = 0
1173
+ for ref_map, node_map in zip(ref_maps, maps, strict=True):
1174
+ ref_wide, ref_narrow = _hash_cells(ref_map, wide, narrow)
1175
+ got_wide, got_narrow = _hash_cells(node_map, wide, narrow, renumber)
1176
+ ref_sort = np.argsort(ref_wide)
1177
+ got_sort = np.argsort(got_wide)
1178
+ ref_wide, got_wide = ref_wide[ref_sort], got_wide[got_sort]
1179
+ if (ref_wide[1:] == ref_wide[:-1]).any() or not np.array_equal(
1180
+ ref_wide, got_wide
1181
+ ):
1182
+ return None
1183
+ if not np.array_equal(ref_narrow[ref_sort], got_narrow[got_sort]):
1184
+ return None
1185
+ cells = np.empty(len(ref_sort), dtype=np.intp)
1186
+ cells[ref_sort] = got_sort
1187
+ orders.append(cells + offset)
1188
+ offset += len(cells)
1189
+ return np.concatenate(orders) if orders else np.empty(0, dtype=np.intp)
1190
+
1191
+
1192
+ # --------------------------------------------------------------------------------------
1193
+ # Elements of face-based zones
1194
+ # --------------------------------------------------------------------------------------
1195
+
1196
+
1197
+ def faces_by_element(
1198
+ face_left: npt.ArrayLike, face_right: npt.ArrayLike, num_elements: int
1199
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
1200
+ """List the faces of every element of a face-based zone.
1201
+
1202
+ Each face names the element on its left and on its right. This regroups that into
1203
+ one list of faces per element. A side that is not an element of the zone (``-1`` for
1204
+ none, or a boundary reference below that) is skipped. Within an element the faces
1205
+ are in ascending order.
1206
+
1207
+ The cost is one stable sort of the ``2 * num_faces`` sides. No faces are matched.
1208
+
1209
+ Args:
1210
+ face_left: Element on the left of each face, shape ``(num_faces,)``.
1211
+ face_right: Element on the right of each face, same shape.
1212
+ num_elements: Number of elements of the zone.
1213
+
1214
+ Returns:
1215
+ The ``offsets`` with shape ``(num_elements + 1,)`` and the flat ``faces``. The
1216
+ faces of element ``e`` are ``faces[offsets[e]:offsets[e + 1]]``.
1217
+
1218
+ Raises:
1219
+ ValueError: If the arrays are not one dimensional and of the same length, or an
1220
+ element index is not below *num_elements*.
1221
+ """
1222
+ left = np.asarray(face_left, dtype=np.int64)
1223
+ right = np.asarray(face_right, dtype=np.int64)
1224
+ if left.ndim != 1 or left.shape != right.shape:
1225
+ raise ValueError("face_left and face_right must be 1-D arrays of one length.")
1226
+ sides = np.empty(2 * left.size, dtype=np.int64) # face f is at 2 * f and 2 * f + 1
1227
+ sides[0::2] = left
1228
+ sides[1::2] = right
1229
+ entries = np.flatnonzero(sides >= 0)
1230
+ elements = sides[entries]
1231
+ if elements.size and np.max(elements) >= num_elements:
1232
+ raise ValueError(f"An element index is not below num_elements={num_elements}.")
1233
+ order = np.argsort(elements, kind="stable")
1234
+ faces = (entries[order] >> 1).astype(np.int64, copy=False)
1235
+ offsets = np.zeros(num_elements + 1, dtype=np.int64)
1236
+ np.cumsum(np.bincount(elements, minlength=num_elements), out=offsets[1:])
1237
+ return offsets, faces
1238
+
1239
+
1240
+ def _unique_pairs(
1241
+ first: npt.NDArray[np.int64],
1242
+ second: npt.NDArray[np.int64],
1243
+ num_first: int,
1244
+ num_second: int,
1245
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
1246
+ """Return the distinct ``(first, second)`` pairs, sorted by *first* then *second*.
1247
+
1248
+ Args:
1249
+ first: Values in ``[0, num_first)``.
1250
+ second: Values in ``[0, num_second)``, the same length as *first*.
1251
+ num_first: Exclusive upper bound of *first*.
1252
+ num_second: Exclusive upper bound of *second*.
1253
+ """
1254
+ if first.size == 0:
1255
+ return first, second
1256
+ if num_first * num_second < 2**62: # one integer key per pair is the fast path
1257
+ key = np.unique(first * num_second + second)
1258
+ return np.divmod(key, num_second)
1259
+ order = np.lexsort((second, first))
1260
+ first, second = first[order], second[order]
1261
+ keep = np.ones(first.size, dtype=bool)
1262
+ keep[1:] = (first[1:] != first[:-1]) | (second[1:] != second[:-1])
1263
+ return first[keep], second[keep]
1264
+
1265
+
1266
+ def nodes_by_element(
1267
+ face_nodes: npt.ArrayLike,
1268
+ face_node_offsets: npt.ArrayLike,
1269
+ element_offsets: npt.NDArray[np.int64],
1270
+ element_faces: npt.NDArray[np.int64],
1271
+ num_nodes: int,
1272
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
1273
+ """List the distinct nodes of every element of a face-based zone.
1274
+
1275
+ An element is defined by its faces, so its nodes are the nodes of its faces with
1276
+ repeats removed. They come out in ascending order. That is a set, not a cell node
1277
+ order: a polyhedron has no natural node order.
1278
+
1279
+ Args:
1280
+ face_nodes: Flat node indices of all faces.
1281
+ face_node_offsets: Running offsets into *face_nodes*, ``(num_faces + 1,)``.
1282
+ element_offsets: Offsets from :func:`faces_by_element`.
1283
+ element_faces: Faces from :func:`faces_by_element`.
1284
+ num_nodes: Number of nodes of the zone.
1285
+
1286
+ Returns:
1287
+ The ``offsets`` with shape ``(num_elements + 1,)`` and the flat ``nodes``. The
1288
+ nodes of element ``e`` are ``nodes[offsets[e]:offsets[e + 1]]``.
1289
+
1290
+ Raises:
1291
+ ValueError: If a node index is outside ``[0, num_nodes)``.
1292
+ """
1293
+ flat = np.asarray(face_nodes, dtype=np.int64)
1294
+ starts = np.asarray(face_node_offsets, dtype=np.int64)
1295
+ num_elements = len(element_offsets) - 1
1296
+ counts = (starts[1:] - starts[:-1])[element_faces] # nodes of each listed face
1297
+ # Position in `flat` of every node of every listed face.
1298
+ take = np.arange(int(counts.sum()), dtype=np.int64)
1299
+ take += np.repeat(starts[element_faces] - (np.cumsum(counts) - counts), counts)
1300
+ nodes = flat[take]
1301
+ if nodes.size and (np.min(nodes) < 0 or np.max(nodes) >= num_nodes):
1302
+ raise ValueError(f"A node index is outside [0, {num_nodes}).")
1303
+ elements = np.repeat(
1304
+ np.arange(num_elements, dtype=np.int64), np.diff(element_offsets)
1305
+ )
1306
+ elements, nodes = _unique_pairs(
1307
+ np.repeat(elements, counts), nodes, num_elements, num_nodes
1308
+ )
1309
+ offsets = np.zeros(num_elements + 1, dtype=np.int64)
1310
+ np.cumsum(np.bincount(elements, minlength=num_elements), out=offsets[1:])
1311
+ return offsets, nodes