lsdyna-mesh-reader 0.1.4__cp313-cp313-win_amd64.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,15 @@
1
+ """LS-DYNA mesh reader."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from lsdyna_mesh_reader import examples
6
+ from lsdyna_mesh_reader.deck import Deck
7
+
8
+ # get current version from the package metadata
9
+ try:
10
+ __version__ = version("lsdyna_mesh_reader")
11
+ except PackageNotFoundError:
12
+ __version__ = "unknown"
13
+
14
+
15
+ __all__ = ["examples", "Deck"]
Binary file
@@ -0,0 +1,57 @@
1
+ from typing import List, Tuple
2
+
3
+ import numpy as np
4
+ from numpy.typing import NDArray
5
+
6
+ # shape typing added in 2.1, not adding it here yet
7
+ IntArray = NDArray[np.int32]
8
+ FloatArray1D = NDArray[np.float64]
9
+ FloatArray2D = NDArray[np.float64]
10
+ LongArray1D = NDArray[np.int64]
11
+ Uint8Array1D = NDArray[np.uint8]
12
+
13
+ class NodeSection:
14
+ def __init__(self) -> None: ...
15
+ @property
16
+ def nid(self) -> IntArray: ...
17
+ @property
18
+ def coordinates(self) -> FloatArray2D: ...
19
+ @property
20
+ def tc(self) -> IntArray: ...
21
+ @property
22
+ def rc(self) -> IntArray: ...
23
+ def __len__(self) -> int: ...
24
+ @property
25
+ def fpos(self) -> int: ...
26
+
27
+ class ElementSection:
28
+ def __init__(self) -> None: ...
29
+ @property
30
+ def eid(self) -> IntArray: ...
31
+ @property
32
+ def pid(self) -> IntArray: ...
33
+ @property
34
+ def node_ids(self) -> IntArray: ...
35
+ @property
36
+ def node_id_offsets(self) -> IntArray: ...
37
+ def __len__(self) -> int: ...
38
+ def to_vtk(self) -> Tuple[LongArray1D, LongArray1D, Uint8Array1D]: ...
39
+
40
+ class ElementShellSection(ElementSection): ...
41
+ class ElementSolidSection(ElementSection): ...
42
+
43
+ class _Deck:
44
+ def __init__(self, fname: str) -> None: ...
45
+ @property
46
+ def node_sections(self) -> List[NodeSection]: ...
47
+ @property
48
+ def element_solid_sections(self) -> List[ElementSolidSection]: ...
49
+ @property
50
+ def element_shell_sections(self) -> List[ElementShellSection]: ...
51
+ def read_line(self) -> int: ...
52
+ def read_element_solid_section(self) -> None: ...
53
+ def read_element_shell_section(self) -> None: ...
54
+ def read_node_section(self) -> None: ...
55
+ def read(self) -> None: ...
56
+
57
+ def overwrite_node_section(filename: str, fpos: int, nodes: FloatArray2D) -> None: ...
@@ -0,0 +1,303 @@
1
+ import os
2
+ import shutil
3
+ from pathlib import Path
4
+ from typing import TYPE_CHECKING, List, Union
5
+
6
+ import numpy as np
7
+ from numpy.typing import NDArray
8
+
9
+ from lsdyna_mesh_reader._deck import (
10
+ ElementShellSection,
11
+ ElementSolidSection,
12
+ NodeSection,
13
+ _Deck,
14
+ overwrite_node_section,
15
+ )
16
+
17
+ if TYPE_CHECKING:
18
+ try:
19
+ from pyvista.core.pointset import UnstructuredGrid
20
+ except ImportError:
21
+ pass
22
+
23
+
24
+ class Deck:
25
+ r"""LS-DYNA deck.
26
+
27
+ Parameters
28
+ ----------
29
+ filename : str | pathlib.Path
30
+ Path to the keyword file (``*.k``, ``*.key``, ``*.dyn``).
31
+
32
+ Examples
33
+ --------
34
+ >>> import lsdyna_mesh_reader
35
+ >>> from lsdyna_mesh_reader import examples
36
+ >>> deck = lsdyna_mesh_reader.Deck(examples.birdball)
37
+ LSDYNA Deck with:
38
+ Node sections: 1
39
+ Element Solid sections: 1
40
+ Element Shell sections: 1
41
+
42
+ """
43
+
44
+ def __init__(self, filename: Union[str, Path]) -> None:
45
+ """Initialize the deck object."""
46
+ filename = str(filename)
47
+ if not os.path.isfile(filename):
48
+ raise FileNotFoundError(f"Invalid file or unable to locate {filename}")
49
+ self._deck = _Deck(filename)
50
+ self._deck.read()
51
+ self._filename = filename
52
+
53
+ @property
54
+ def element_solid_sections(self) -> List[ElementSolidSection]:
55
+ """Return the element_solid sections.
56
+
57
+ Returns
58
+ -------
59
+ List[ElementSolidSection]
60
+
61
+ Examples
62
+ --------
63
+ Load an example keyword deck and output the element IDs.
64
+
65
+ >>> import lsdyna_mesh_reader
66
+ >>> from lsdyna_mesh_reader import examples
67
+ >>> deck = lsdyna_mesh_reader.Deck(examples.birdball)
68
+ >>> section = deck.element_solid_sections[0]
69
+ >>> section.eid
70
+ array([1, 2, 3, ..., 814, 815, 816], dtype=int32)
71
+
72
+ Output a list of individual elements.
73
+
74
+ >>> import numpy as np
75
+ >>> elements = np.split(section.node_ids, section.node_id_offsets[1:-1])
76
+ >>> elements[:5] # show the first 5
77
+ [array([ 1, 2, 6, 5, 17, 18, 22, 21], dtype=int32),
78
+ array([ 2, 3, 7, 6, 18, 19, 23, 22], dtype=int32),
79
+ array([ 3, 4, 8, 7, 19, 20, 24, 23], dtype=int32),
80
+ array([ 5, 6, 10, 9, 21, 22, 26, 25], dtype=int32),
81
+ array([ 6, 7, 11, 10, 22, 23, 27, 26], dtype=int32)]
82
+
83
+ """
84
+ return self._deck.element_solid_sections
85
+
86
+ @property
87
+ def element_shell_sections(self) -> List[ElementShellSection]:
88
+ """Return the element_shell sections.
89
+
90
+ Returns
91
+ -------
92
+ List[ElementShellSection]
93
+
94
+ Examples
95
+ --------
96
+ >>> import lsdyna_mesh_reader
97
+ >>> from lsdyna_mesh_reader import examples
98
+ >>> deck = lsdyna_mesh_reader.Deck(examples.birdball)
99
+ >>> section = deck.element_shell_sections[0]
100
+ >>> section.eid
101
+ array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
102
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
103
+ 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
104
+ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
105
+ 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
106
+ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
107
+ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
108
+ 92, 93, 94, 95, 96, 97, 98, 99, 100], dtype=int32)
109
+
110
+ Output a list of individual elements.
111
+
112
+ >>> import numpy as np
113
+ >>> elements = np.split(section.node_ids, section.node_id_offsets[1:-1])
114
+ >>> elements[:5] # output the first 5
115
+ [array([377, 388, 389, 378], dtype=int32),
116
+ array([378, 389, 390, 379], dtype=int32),
117
+ array([379, 390, 391, 380], dtype=int32),
118
+ array([380, 391, 392, 381], dtype=int32),
119
+ array([381, 392, 393, 382], dtype=int32)]
120
+
121
+ """
122
+ return self._deck.element_shell_sections
123
+
124
+ @property
125
+ def node_sections(self) -> List[NodeSection]:
126
+ """Return the node sections.
127
+
128
+ Returns
129
+ -------
130
+ List[NodeSection]
131
+
132
+ Examples
133
+ --------
134
+ Load an example keyword deck and output the node IDs of the first node
135
+ section.
136
+
137
+ >>> import lsdyna_mesh_reader
138
+ >>> from lsdyna_mesh_reader import examples
139
+ >>> deck = lsdyna_mesh_reader.Deck(examples.birdball)
140
+ >>> node_section = deck.node_sections[0]
141
+ >>> node_section.nid
142
+ array([ 1, 2, 3, ..., 1342, 1343, 1344], dtype=int32)
143
+
144
+ Output the node coordinates.
145
+
146
+ >>> node_section.coordinates
147
+ array([[ -2.30940104, -2.30940104, -2.30940104],
148
+ [ -2.03960061, -2.03960061, -2.03960061],
149
+ [ -1.76980031, -1.76980031, -1.76980031],
150
+ ...,
151
+ [ -4. , -10. , 0. ],
152
+ [ -2. , -10. , 0. ],
153
+ [ 0. , -10. , 0. ]])
154
+
155
+ """
156
+ return self._deck.node_sections
157
+
158
+ def to_grid(self) -> "UnstructuredGrid":
159
+ """Convert the mesh within the deck to a pyvista.UnstructuredGrid.
160
+
161
+ Returns
162
+ -------
163
+ pyvista.UnstructuredGrid
164
+
165
+ Notes
166
+ -----
167
+ This requires ``pyvista`` to be installed.
168
+
169
+ Examples
170
+ --------
171
+ Load an example keyword deck and convert it to an unstructured grid.
172
+
173
+ >>> import lsdyna_mesh_reader
174
+ >>> from lsdyna_mesh_reader import examples
175
+ >>> deck = lsdyna_mesh_reader.Deck(examples.birdball)
176
+ >>> ugrid = deck.to_grid()
177
+ UnstructuredGrid (0x70d5caaed1e0)
178
+ N Cells: 916
179
+ N Points: 1281
180
+ X Bounds: -2.000e+01, 2.220e-15
181
+ Y Bounds: -1.000e+01, 4.000e+00
182
+ Z Bounds: -2.000e+01, 4.441e-15
183
+ N Arrays: 2
184
+
185
+ Save the unstructured grid to disk.
186
+
187
+ >>> ugrid.save("grid.vtu")
188
+
189
+ Plot it.
190
+
191
+ >>> ugrid.plot(color="w", show_edges=True)
192
+
193
+ """
194
+ try:
195
+ import pyvista as pv
196
+ from pyvista import ID_TYPE, CellArray
197
+ from pyvista.core.pointset import UnstructuredGrid
198
+ from vtkmodules.util.numpy_support import numpy_to_vtk
199
+ except ImportError:
200
+ pass
201
+
202
+ if not self.node_sections:
203
+ raise RuntimeError("Missing node sections. Unable to generate UnstructuredGrid.")
204
+
205
+ node_section = self.node_sections[0]
206
+
207
+ # map between the node ids and a sequential index
208
+ id_map = np.empty(node_section.nid[-1] + 1, dtype=ID_TYPE)
209
+ id_map[node_section.nid] = np.arange(len(node_section), dtype=ID_TYPE)
210
+
211
+ element_sections = self.element_shell_sections + self.element_solid_sections
212
+
213
+ if not element_sections:
214
+ raise NotImplementedError("Deck missing element sections")
215
+
216
+ # add shell sections
217
+ offsets: List[NDArray[np.int64]] = []
218
+ celltypes: List[NDArray[np.uint8]] = []
219
+ cells: List[NDArray[np.int64]] = []
220
+ part_ids = []
221
+ for section in element_sections:
222
+ section_cells, section_offset, section_celltypes = section.to_vtk()
223
+ if offsets:
224
+ # we need to shift by the last value of the last offset
225
+ offsets.append(section_offset[1:] + offsets[-1][-1])
226
+ else:
227
+ offsets.append(section_offset)
228
+
229
+ celltypes.append(section_celltypes)
230
+ cells.append(id_map[section_cells])
231
+ part_ids.append(section.pid)
232
+
233
+ offsets_arr = np.hstack(offsets, dtype=ID_TYPE)
234
+ cells_arr = np.hstack(cells, dtype=ID_TYPE)
235
+ celltypes_arr = np.hstack(celltypes, dtype=np.uint8)
236
+
237
+ grid = UnstructuredGrid()
238
+ grid.points = pv.pyvista_ndarray(node_section.coordinates)
239
+
240
+ vtk_cells = CellArray.from_arrays(offsets_arr, cells_arr, deep=False)
241
+ vtk_cell_type = numpy_to_vtk(celltypes_arr, deep=False)
242
+ grid.SetCells(vtk_cell_type, vtk_cells)
243
+
244
+ # add part and node ids
245
+ grid.cell_data["Part ID"] = np.hstack(part_ids)
246
+ grid.point_data["Node ID"] = node_section.nid
247
+
248
+ return grid
249
+
250
+ def overwrite_node_section(
251
+ self, filename: Union[str, Path], nodes: NDArray[np.float64]
252
+ ) -> None:
253
+ """
254
+ Create a new deck file with the same content but overwritten node section.
255
+
256
+ Parameters
257
+ ----------
258
+ filename : str | pathlib.Path
259
+ Path to the new file.
260
+ nodes : np.ndarray[float]
261
+ New node coordinates to write. Number of nodes must match the
262
+ number of nodes in the node section.
263
+
264
+ Notes
265
+ -----
266
+ Overwrites the first node section.
267
+
268
+ Examples
269
+ --------
270
+ Load an existing LS-DYNA deck and write new nodes to it in a new file.
271
+
272
+ >>> import numpy as np
273
+ >>> import lsdyna_mesh_reader
274
+ >>> from lsdyna_mesh_reader import examples
275
+ >>> deck = lsdyna_mesh_reader.Deck(examples.birdball)
276
+ >>> nodes = deck.node_sections[0].coordinates
277
+ >>> new_nodes = nodes + np.random.random(nodes.shape)
278
+ >>> deck.overwrite_node_section("new_deck.k", new_nodes)
279
+
280
+ """
281
+ if not self.node_sections:
282
+ raise RuntimeError("This deck is missing a node section")
283
+ nsec = self.node_sections[0]
284
+
285
+ if nodes.ndim != 2 or nodes.shape[1] != 3:
286
+ raise ValueError(f"Expected `nodes` to contain 3D coordinates, not {nodes.shape}")
287
+ elif nodes.shape[0] != nsec.nid.size:
288
+ raise RuntimeError(
289
+ f"Number of coordinates in `nodes` ({nodes.shape[0]}) must match number of "
290
+ f"nodes in the node section ({nsec.nid.size})"
291
+ )
292
+
293
+ filename = str(filename)
294
+ shutil.copy(self._filename, filename)
295
+ overwrite_node_section(filename, nsec.fpos, nodes)
296
+
297
+ def __repr__(self) -> str:
298
+ lines = ["LSDYNA Deck with:"]
299
+ lines.append(f" Node sections: {len(self.node_sections)}")
300
+ lines.append(f" Element Solid sections: {len(self.element_solid_sections)}")
301
+ lines.append(f" Element Shell sections: {len(self.element_shell_sections)}")
302
+
303
+ return "\n".join(lines)