loop-common 0.0.1__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 (50) hide show
  1. loop_common/__init__.py +6 -0
  2. loop_common/base.py +98 -0
  3. loop_common/geometry/__init__.py +19 -0
  4. loop_common/geometry/_aabb.py +37 -0
  5. loop_common/geometry/_bounding_box.py +792 -0
  6. loop_common/geometry/_face_table.py +42 -0
  7. loop_common/geometry/_point.py +238 -0
  8. loop_common/geometry/_structured_grid.py +114 -0
  9. loop_common/geometry/_structured_grid_2d.py +146 -0
  10. loop_common/geometry/_structured_grid_3d.py +243 -0
  11. loop_common/geometry/_surface.py +288 -0
  12. loop_common/geometry/_unstructured_mesh.py +208 -0
  13. loop_common/interfaces/__init__.py +0 -0
  14. loop_common/interfaces/representation.py +45 -0
  15. loop_common/io/__init__.py +0 -0
  16. loop_common/logging/__init__.py +14 -0
  17. loop_common/logging/logger.py +123 -0
  18. loop_common/logging/sinks.py +221 -0
  19. loop_common/logging/timing.py +113 -0
  20. loop_common/math/__init__.py +5 -0
  21. loop_common/math/_maths.py +441 -0
  22. loop_common/math/_transformation.py +178 -0
  23. loop_common/math/finite_difference_stencil.py +38 -0
  24. loop_common/observations/__init__.py +3 -0
  25. loop_common/observations/lineset.py +41 -0
  26. loop_common/observations/orientation.py +122 -0
  27. loop_common/observations/pointset.py +8 -0
  28. loop_common/observer.py +284 -0
  29. loop_common/supports/_2d_base_unstructured.py +361 -0
  30. loop_common/supports/_2d_p1_unstructured.py +131 -0
  31. loop_common/supports/_2d_p2_unstructured.py +349 -0
  32. loop_common/supports/_2d_structured_grid.py +545 -0
  33. loop_common/supports/_3d_base_structured.py +546 -0
  34. loop_common/supports/_3d_p2_tetra.py +374 -0
  35. loop_common/supports/_3d_rectilinear_grid.py +315 -0
  36. loop_common/supports/_3d_structured_grid.py +510 -0
  37. loop_common/supports/_3d_structured_tetra.py +764 -0
  38. loop_common/supports/_3d_unstructured_tetra.py +656 -0
  39. loop_common/supports/__init__.py +69 -0
  40. loop_common/supports/_aabb.py +77 -0
  41. loop_common/supports/_base_support.py +118 -0
  42. loop_common/supports/_face_table.py +70 -0
  43. loop_common/supports/_p2_structured_tetra.py +627 -0
  44. loop_common/supports/_support_factory.py +78 -0
  45. loop_common/utils.py +74 -0
  46. loop_common-0.0.1.dist-info/METADATA +35 -0
  47. loop_common-0.0.1.dist-info/RECORD +50 -0
  48. loop_common-0.0.1.dist-info/WHEEL +5 -0
  49. loop_common-0.0.1.dist-info/licenses/LICENSE +21 -0
  50. loop_common-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,243 @@
1
+ """Pure 3D regular grid geometry: origin/nsteps/step_vector indexing."""
2
+
3
+
4
+ import numpy as np
5
+
6
+ from loop_common.logging import get_logger as getLogger
7
+ from loop_common.utils import LoopException
8
+
9
+ logger = getLogger(__name__)
10
+
11
+
12
+ class StructuredGrid3DGeometry:
13
+ """A 3D regular grid defined by an origin, step vector and number of steps."""
14
+
15
+ dimension = 3
16
+
17
+ def __init__(self, origin=None, nsteps=None, step_vector=None, rotation_xy=None):
18
+ if origin is None:
19
+ origin = np.zeros(3)
20
+ if nsteps is None:
21
+ nsteps = np.array([10, 10, 10])
22
+ if step_vector is None:
23
+ step_vector = np.ones(3)
24
+ origin = np.array(origin)
25
+ nsteps = np.array(nsteps)
26
+ step_vector = np.array(step_vector)
27
+ if np.any(step_vector == 0):
28
+ logger.warning(f"Step vector {step_vector} has zero values")
29
+ if np.any(nsteps == 0):
30
+ raise LoopException("nsteps cannot be zero")
31
+ if np.any(nsteps < 0):
32
+ raise LoopException("nsteps cannot be negative")
33
+ self._nsteps = np.array(nsteps, dtype=int)
34
+ self._step_vector = np.array(step_vector)
35
+ self._origin = np.array(origin)
36
+ self._rotation_xy = np.zeros((3, 3))
37
+ self._rotation_xy[0, 0] = 1
38
+ self._rotation_xy[1, 1] = 1
39
+ self._rotation_xy[2, 2] = 1
40
+ self.rotation_xy = rotation_xy
41
+
42
+ @property
43
+ def volume(self):
44
+ return np.prod(self.maximum - self.origin)
45
+
46
+ def set_nelements(self, nelements) -> int:
47
+ box_vol = self.volume
48
+ ele_vol = box_vol / nelements
49
+ step_vector = np.zeros(3)
50
+ step_vector[:] = ele_vol ** (1.0 / 3.0)
51
+ nsteps = np.ceil((self.maximum - self.origin) / step_vector).astype(int)
52
+ self.nsteps = nsteps
53
+ return self.n_elements
54
+
55
+ def to_dict(self):
56
+ return {
57
+ "origin": self.origin,
58
+ "nsteps": self.nsteps,
59
+ "step_vector": self.step_vector,
60
+ "rotation_xy": self.rotation_xy,
61
+ }
62
+
63
+ @property
64
+ def nsteps(self):
65
+ return self._nsteps
66
+
67
+ @nsteps.setter
68
+ def nsteps(self, nsteps):
69
+ change_factor = nsteps / self.nsteps
70
+ self._step_vector /= change_factor
71
+ self._nsteps = nsteps
72
+
73
+ @property
74
+ def nsteps_cells(self):
75
+ return self.nsteps - 1
76
+
77
+ @property
78
+ def rotation_xy(self):
79
+ return self._rotation_xy
80
+
81
+ @rotation_xy.setter
82
+ def rotation_xy(self, rotation_xy):
83
+ if rotation_xy is None:
84
+ return
85
+ if isinstance(rotation_xy, (float, int)):
86
+ rotation_xy = np.array([[np.cos(np.deg2rad(rotation_xy)), -np.sin(np.deg2rad(rotation_xy)), 0], [np.sin(np.deg2rad(rotation_xy)), np.cos(np.deg2rad(rotation_xy)), 0], [0, 0, 1]])
87
+ rotation_xy = np.array(rotation_xy)
88
+ if rotation_xy.shape != (3, 3):
89
+ raise ValueError(f"Rotation matrix should be 3x3, not {rotation_xy.shape}")
90
+ self._rotation_xy = rotation_xy
91
+
92
+ @property
93
+ def step_vector(self):
94
+ return self._step_vector
95
+
96
+ @step_vector.setter
97
+ def step_vector(self, step_vector):
98
+ change_factor = step_vector / self._step_vector
99
+ newsteps = self._nsteps / change_factor
100
+ self._nsteps = np.ceil(newsteps).astype(int)
101
+ self._step_vector = step_vector
102
+
103
+ @property
104
+ def origin(self):
105
+ return self._origin
106
+
107
+ @origin.setter
108
+ def origin(self, origin):
109
+ origin = np.array(origin)
110
+ length = self.maximum - origin
111
+ length /= self.step_vector
112
+ self._nsteps = np.ceil(length).astype(np.int64)
113
+ self._nsteps[self._nsteps == 0] = 3
114
+ if np.any(~(self._nsteps > 0)):
115
+ logger.error(f"Cannot resize the grid. The proposed number of steps is {self._nsteps}, these must be all > 0")
116
+ raise ValueError("Cannot resize the grid.")
117
+ self._origin = origin
118
+
119
+ @property
120
+ def maximum(self):
121
+ return self.origin + self.nsteps_cells * self.step_vector
122
+
123
+ @maximum.setter
124
+ def maximum(self, maximum):
125
+ maximum = np.array(maximum, dtype=float)
126
+ length = maximum - self.origin
127
+ length /= self.step_vector
128
+ self._nsteps = np.ceil(length).astype(np.int64)
129
+ self._nsteps[self._nsteps == 0] = 3
130
+ if np.any(~(self._nsteps > 0)):
131
+ logger.error(f"Cannot resize the grid. The proposed number of steps is {self._nsteps}, these must be all > 0")
132
+ raise ValueError("Cannot resize the grid.")
133
+
134
+ @property
135
+ def n_nodes(self):
136
+ return np.prod(self.nsteps)
137
+
138
+ @property
139
+ def n_elements(self):
140
+ return np.prod(self.nsteps_cells)
141
+
142
+ @property
143
+ def elements(self):
144
+ global_index = np.arange(self.n_elements)
145
+ cell_indexes = self.global_index_to_cell_index(global_index)
146
+ return self.global_node_indices(self.cell_corner_indexes(cell_indexes))
147
+
148
+ def __str__(self):
149
+ return (
150
+ "LoopStructural grid geometry: \n"
151
+ f"Origin: {self.origin[0]} {self.origin[1]} {self.origin[2]} \n"
152
+ f"Maximum: {self.maximum[0]} {self.maximum[1]} {self.maximum[2]} \n"
153
+ f"Step Vector: {self.step_vector[0]} {self.step_vector[1]} {self.step_vector[2]} \n"
154
+ f"Number of Steps: {self.nsteps[0]} {self.nsteps[1]} {self.nsteps[2]} \n"
155
+ f"Degrees of freedon {self.n_nodes}"
156
+ )
157
+
158
+ @property
159
+ def nodes(self):
160
+ max = self.origin + self.nsteps_cells * self.step_vector
161
+ if np.any(np.isnan(self.nsteps)):
162
+ raise ValueError("Cannot resize mesh nsteps is NaN")
163
+ if np.any(np.isnan(self.origin)):
164
+ raise ValueError("Cannot resize mesh origin is NaN")
165
+ x = np.linspace(self.origin[0], max[0], self.nsteps[0])
166
+ y = np.linspace(self.origin[1], max[1], self.nsteps[1])
167
+ z = np.linspace(self.origin[2], max[2], self.nsteps[2])
168
+ xx, yy, zz = np.meshgrid(x, y, z, indexing="ij")
169
+ return np.array([xx.flatten(order="F"), yy.flatten(order="F"), zz.flatten(order="F")]).T
170
+
171
+ def rotate(self, pos):
172
+ return np.einsum("ijk,ik->ij", self.rotation_xy[None, :, :], pos)
173
+
174
+ def position_to_cell_index(self, pos: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
175
+ inside = self.inside(pos)
176
+ pos = self.check_position(pos)
177
+ cell_indexes = np.zeros((pos.shape[0], 3), dtype=int)
178
+ cell_indexes[:, 0] = (pos[:, 0] - self.origin[0]) / self.step_vector[0]
179
+ cell_indexes[:, 1] = (pos[:, 1] - self.origin[1]) / self.step_vector[1]
180
+ cell_indexes[:, 2] = (pos[:, 2] - self.origin[2]) / self.step_vector[2]
181
+ return cell_indexes.astype(int), inside
182
+
183
+ def inside(self, pos: np.ndarray) -> np.ndarray:
184
+ inside = np.ones(pos.shape[0]).astype(bool)
185
+ for i in range(3):
186
+ inside *= pos[:, i] > self.origin[i]
187
+ inside *= pos[:, i] < self.maximum[i]
188
+ return inside
189
+
190
+ def check_position(self, pos: np.ndarray) -> np.ndarray:
191
+ if len(pos.shape) == 1:
192
+ pos = np.array([pos])
193
+ if len(pos.shape) != 2:
194
+ raise ValueError("Position array needs to be a list of points or a point")
195
+ return pos
196
+
197
+ def neighbour_global_indexes(self, mask=None, **kwargs):
198
+ indexes = None
199
+ if "indexes" in kwargs:
200
+ indexes = kwargs["indexes"]
201
+ if "indexes" not in kwargs:
202
+ gi = np.arange(self.n_nodes)
203
+ indexes = self.global_index_to_node_index(gi)
204
+ edge_mask = (
205
+ (indexes[:, 0] > 0) & (indexes[:, 0] < self.nsteps[0] - 1)
206
+ & (indexes[:, 1] > 0) & (indexes[:, 1] < self.nsteps[1] - 1)
207
+ & (indexes[:, 2] > 0) & (indexes[:, 2] < self.nsteps[2] - 1)
208
+ )
209
+ indexes = indexes[edge_mask, :].T
210
+ if indexes.ndim != 2:
211
+ logger.error("indexes.ndim = %s, expected 2", indexes.ndim)
212
+ return
213
+ if mask is None:
214
+ mask = np.array([[-1, 0, 1, -1, 0, 1, -1, 0, 1], [1, 1, 1, 0, 0, 0, -1, -1, -1]])
215
+ neighbours = indexes[:, None, :] + mask[:, :, None]
216
+ return (neighbours[0, :, :] + self.nsteps[0, None, None] * neighbours[1, :, :]).astype(np.int64)
217
+
218
+ def cell_corner_indexes(self, cell_indexes: np.ndarray) -> np.ndarray:
219
+ corner_indexes = np.zeros((cell_indexes.shape[0], 8, 3), dtype=np.int64)
220
+ xcorner = np.array([0, 1, 0, 1, 0, 1, 0, 1])
221
+ ycorner = np.array([0, 0, 1, 1, 0, 0, 1, 1])
222
+ zcorner = np.array([0, 0, 0, 0, 1, 1, 1, 1])
223
+ corner_indexes[:, :, 0] = cell_indexes[:, None, 0] + corner_indexes[:, :, 0] + xcorner[None, :]
224
+ corner_indexes[:, :, 1] = cell_indexes[:, None, 1] + corner_indexes[:, :, 1] + ycorner[None, :]
225
+ corner_indexes[:, :, 2] = cell_indexes[:, None, 2] + corner_indexes[:, :, 2] + zcorner[None, :]
226
+ return corner_indexes
227
+
228
+ def global_index_to_cell_index(self, global_index):
229
+ cell_indexes = np.zeros((global_index.shape[0], 3), dtype=np.int64)
230
+ cell_indexes[:, 0] = global_index % self.nsteps_cells[0, None]
231
+ cell_indexes[:, 1] = (global_index // self.nsteps_cells[0, None]) % self.nsteps_cells[1, None]
232
+ cell_indexes[:, 2] = (global_index // (self.nsteps_cells[0, None] * self.nsteps_cells[1, None])) % self.nsteps_cells[2, None]
233
+ return cell_indexes
234
+
235
+ def global_index_to_node_index(self, global_index):
236
+ cell_indexes = np.zeros((global_index.shape[0], 3), dtype=np.int64)
237
+ cell_indexes[:, 0] = global_index % self.nsteps[0, None]
238
+ cell_indexes[:, 1] = (global_index // self.nsteps[0, None]) % self.nsteps[1, None]
239
+ cell_indexes[:, 2] = (global_index // (self.nsteps[0, None] * self.nsteps[1, None])) % self.nsteps[2, None]
240
+ return cell_indexes
241
+
242
+ def global_node_indices(self, node_indexes):
243
+ return node_indexes
@@ -0,0 +1,288 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from dataclasses import dataclass, field
5
+
6
+ import numpy as np
7
+ import pyvista as pv
8
+
9
+ from loop_common.logging import get_logger as getLogger
10
+
11
+ logger = getLogger(__name__)
12
+
13
+
14
+ @dataclass
15
+ class Surface:
16
+ vertices: np.ndarray = field(default_factory=lambda: np.array([[0, 0, 0]]))
17
+ triangles: np.ndarray = field(default_factory=lambda: np.array([[0, 0, 0]]))
18
+ colour: str | np.ndarray | None = field(default_factory=lambda: None)
19
+ normals: np.ndarray | None = None
20
+ name: str = "surface"
21
+ values: np.ndarray | None = None
22
+ properties: dict | None = None
23
+ cell_properties: dict | None = None
24
+
25
+ def __post_init__(self):
26
+ if self.vertices.ndim != 2 or self.vertices.shape[1] != 3:
27
+ raise ValueError("vertices must be a Nx3 numpy array")
28
+ if self.triangles.ndim != 2 or self.triangles.shape[1] != 3:
29
+ raise ValueError("triangles must be a Mx3 numpy array")
30
+ if self.normals is not None and (self.normals.shape[1] != 3 or (
31
+ self.normals.shape[0] != self.vertices.shape[0]
32
+ and self.normals.shape[0] != self.triangles.shape[0]
33
+ )):
34
+ raise ValueError(
35
+ "normals must be a Nx3 numpy array where N is the number of vertices or triangles"
36
+ )
37
+ if self.values is not None and self.values.shape[0] != self.vertices.shape[0]:
38
+ raise ValueError("values must be a N numpy array where N is the number of vertices")
39
+ if self.properties is not None:
40
+ for k, v in self.properties.items():
41
+ if len(v) != self.vertices.shape[0]:
42
+ raise ValueError(
43
+ f"property {k} must be a list or array of length {self.vertices.shape[0]}"
44
+ )
45
+ if self.cell_properties is not None:
46
+ for k, v in self.cell_properties.items():
47
+ if len(v) != self.triangles.shape[0]:
48
+ raise ValueError(
49
+ f"cell property {k} must be a list or array of length {self.triangles.shape[0]}"
50
+ )
51
+ if np.isnan(self.vertices).any():
52
+ self.remove_nan_vertices()
53
+
54
+ def remove_nan_vertices(self):
55
+ """Remove vertices with NaN values from the surface. Also removes any triangles that reference these vertices.
56
+ This modifies the vertices and triangles in place. Any associated properties are also updated.
57
+ """
58
+ vertex_index = np.arange(0, self.vertices.shape[0])
59
+ not_nan_indexes = np.where(~np.isnan(self.vertices).any(axis=1))[0]
60
+ new_vertex_map = np.zeros(self.vertices.shape[0], dtype=int) - 1
61
+ new_vertex_map[not_nan_indexes] = np.arange(0, not_nan_indexes.shape[0])
62
+ nan_indexes = np.setdiff1d(vertex_index, not_nan_indexes)
63
+ triangles_with_nan = np.any(np.isin(self.triangles, nan_indexes), axis=1)
64
+ nan_triangle_indexes = np.where(triangles_with_nan)[0]
65
+ new_triangles = np.delete(self.triangles, nan_triangle_indexes, axis=0)
66
+ vertices = self.vertices[not_nan_indexes]
67
+ self.triangles = new_vertex_map[new_triangles]
68
+ self.vertices = vertices
69
+ if self.normals is not None:
70
+ self.normals = self.normals[not_nan_indexes]
71
+ if self.values is not None:
72
+ self.values = self.values[not_nan_indexes]
73
+ if self.properties is not None:
74
+ for k, v in self.properties.items():
75
+ self.properties[k] = np.array(v)[not_nan_indexes]
76
+ if self.cell_properties is not None:
77
+ for k, v in self.cell_properties.items():
78
+ self.cell_properties[k] = np.array(v)[~triangles_with_nan]
79
+
80
+ @property
81
+ def triangle_area(self):
82
+ """_summary_
83
+
84
+ Returns
85
+ -------
86
+ _type_
87
+ _description_
88
+
89
+
90
+ Notes
91
+ -----
92
+
93
+ Area of triangle for a 3d triangle with vertices at points A, B, C is given by
94
+ det([A-C, B-C])**.5
95
+ """
96
+ tri_points = self.vertices[self.triangles, :]
97
+ mat = np.array(
98
+ [
99
+ [
100
+ tri_points[:, 0, 0] - tri_points[:, 2, 0],
101
+ tri_points[:, 0, 1] - tri_points[:, 2, 1],
102
+ tri_points[:, 0, 2] - tri_points[:, 2, 2],
103
+ ],
104
+ [
105
+ tri_points[:, 1, 0] - tri_points[:, 2, 0],
106
+ tri_points[:, 1, 1] - tri_points[:, 2, 1],
107
+ tri_points[:, 1, 2] - tri_points[:, 2, 2],
108
+ ],
109
+ ]
110
+ )
111
+ matdotmatT = np.einsum("ijm,mjk->mik", mat, mat.T)
112
+ area = np.sqrt(np.linalg.det(matdotmatT))
113
+ return area
114
+
115
+ @property
116
+ def triangle_normal(self) -> np.ndarray:
117
+ """_summary_
118
+
119
+ Returns
120
+ -------
121
+ np.ndarray
122
+ numpy array of normals N,3 where N is the number of triangles
123
+
124
+
125
+ Notes
126
+ -----
127
+
128
+ The normal of a triangle is given by the cross product of two vectors in the plane of the triangle
129
+ """
130
+ tri_points = self.vertices[self.triangles, :]
131
+ normals = np.cross(
132
+ tri_points[:, 0, :] - tri_points[:, 2, :], tri_points[:, 1, :] - tri_points[:, 2, :]
133
+ )
134
+ normals = normals / np.linalg.norm(normals, axis=1)[:, np.newaxis]
135
+ return normals
136
+
137
+ def vtk(self):
138
+ import pyvista as pv
139
+
140
+ surface = pv.PolyData.from_regular_faces(self.vertices, self.triangles)
141
+ if self.values is not None:
142
+ surface["values"] = self.values
143
+ if self.properties is not None:
144
+ for k, v in self.properties.items():
145
+ surface.point_data[k] = np.array(v)
146
+ if self.cell_properties is not None:
147
+ for k, v in self.cell_properties.items():
148
+ surface.cell_data[k] = np.array(v)
149
+ return surface
150
+
151
+ def plot(self, pyvista_kwargs=None):
152
+ """Calls pyvista plot on the vtk object
153
+
154
+ Parameters
155
+ ----------
156
+ pyvista_kwargs : dict, optional
157
+ kwargs passed to pyvista.DataSet.plot(), by default {}
158
+ """
159
+ if pyvista_kwargs is None:
160
+ pyvista_kwargs = {}
161
+ try:
162
+ self.vtk().plot(**pyvista_kwargs)
163
+ return
164
+ except ImportError:
165
+ logger.error("pyvista is required for vtk")
166
+
167
+ def to_dict(self, flatten=False):
168
+ triangles = self.triangles
169
+ vertices = self.vertices
170
+ if flatten:
171
+ vertices = self.vertices.flatten()
172
+ triangles = (
173
+ np.hstack([np.ones((self.triangles.shape[0], 1)) * 3, self.triangles])
174
+ .astype(int)
175
+ .flatten()
176
+ )
177
+ return {
178
+ "vertices": vertices.tolist(),
179
+ "triangles": triangles.tolist(),
180
+ "normals": self.normals.tolist() if self.normals is not None else None,
181
+ "properties": (
182
+ {k: p.tolist() for k, p in self.properties.items()} if self.properties else None
183
+ ),
184
+ "cell_properties": (
185
+ {k: p.tolist() for k, p in self.cell_properties.items()}
186
+ if self.cell_properties
187
+ else None
188
+ ),
189
+ "name": self.name,
190
+ "values": self.values.tolist() if self.values is not None else None,
191
+ }
192
+
193
+ @classmethod
194
+ def from_dict(cls, d, flatten=False):
195
+ vertices = np.array(d["vertices"])
196
+ triangles = np.array(d["triangles"])
197
+ if flatten:
198
+ vertices = vertices.reshape((-1, 3))
199
+ triangles = triangles.reshape((-1, 4))[:, 1:]
200
+ return cls(
201
+ vertices,
202
+ triangles,
203
+ np.array(d["normals"]),
204
+ d["name"],
205
+ np.array(d["values"]),
206
+ d.get("properties", None),
207
+ d.get("cell_properties", None),
208
+ )
209
+
210
+ @classmethod
211
+ def from_vtk(cls, vtk_surface: pv.PolyData | str):
212
+ if isinstance(vtk_surface, str):
213
+ import pyvista as pv
214
+
215
+ vtk_surface = pv.read(vtk_surface)
216
+ vertices = vtk_surface.points
217
+ triangles = vtk_surface.faces.reshape((-1, 4))[:, 1:]
218
+ normals = vtk_surface.point_normals if "point_normals" in vtk_surface.point_data else None
219
+ properties = {k: vtk_surface.point_data[k] for k in vtk_surface.point_data}
220
+ cell_properties = {k: vtk_surface.cell_data[k] for k in vtk_surface.cell_data}
221
+ return cls(vertices, triangles, normals, properties=properties, cell_properties=cell_properties)
222
+
223
+ @classmethod
224
+ def from_obj(cls, obj_file: str):
225
+ import meshio
226
+
227
+ mesh = meshio.read(obj_file)
228
+ vertices = mesh.points
229
+ triangles = mesh.cells_dict.get("triangle", None)
230
+ normals = mesh.point_data.get("normals", None)
231
+ properties = {k: v for k, v in mesh.point_data.items() if k != "normals"}
232
+ cell_properties = {k: v for k, v in mesh.cell_data_dict.items() if k != "triangle"}
233
+ return cls(vertices, triangles, normals, properties=properties, cell_properties=cell_properties)
234
+
235
+ def save(self, filename, *, group="Loop", replace_spaces=True, ext=None):
236
+ filename = filename.replace(" ", "_") if replace_spaces else filename
237
+ if isinstance(filename, (io.StringIO, io.BytesIO)):
238
+ if ext is None:
239
+ raise ValueError("Please provide an extension for StringIO")
240
+ ext = ext.lower()
241
+ else:
242
+ filename = str(filename)
243
+ if ext is None:
244
+ ext = filename.split(".")[-1].lower()
245
+ if ext == "json":
246
+ import json
247
+
248
+ with open(filename, "w") as f:
249
+ json.dump(self.to_dict(), f)
250
+ elif ext == "vtk":
251
+ self.vtk().save(filename)
252
+ elif ext == "obj":
253
+ import meshio
254
+
255
+ meshio.write_points_cells(
256
+ filename,
257
+ self.vertices,
258
+ [("triangle", self.triangles)],
259
+ point_data={"normals": self.normals},
260
+ )
261
+ elif ext == "ts" or ext == "gocad":
262
+ from LoopStructural.export.exporters import _write_feat_surfs_gocad
263
+
264
+ _write_feat_surfs_gocad(self, filename)
265
+ elif ext == "geoh5":
266
+ from LoopStructural.export.geoh5 import add_surface_to_geoh5
267
+
268
+ add_surface_to_geoh5(filename, self, groupname=group)
269
+
270
+ elif ext == "pkl":
271
+ import pickle
272
+
273
+ with open(filename, "wb") as f:
274
+ pickle.dump(self, f)
275
+ elif ext == "csv":
276
+ import pandas as pd
277
+
278
+ df = pd.DataFrame(self.vertices, columns=["x", "y", "z"])
279
+ if self.properties:
280
+ for k, v in self.properties.items():
281
+ df[k] = v
282
+ df.to_csv(filename, index=False)
283
+ elif ext == "omf":
284
+ from LoopStructural.export.omf_wrapper import add_surface_to_omf
285
+
286
+ add_surface_to_omf(self, filename)
287
+ else:
288
+ raise ValueError(f"Extension {ext} not supported")