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,764 @@
1
+ """
2
+ Tetmesh based on cartesian grid for piecewise linear interpolation
3
+ """
4
+
5
+ import numpy as np
6
+ from scipy.sparse import coo_matrix, tril
7
+
8
+ from loop_common.logging import get_logger as getLogger
9
+
10
+ from . import SupportType
11
+ from ._3d_base_structured import BaseStructuredSupport
12
+
13
+ logger = getLogger(__name__)
14
+
15
+
16
+ class TetMesh(BaseStructuredSupport):
17
+ """ """
18
+
19
+ def __init__(self, origin=None, nsteps_cells=None, step_vector=None, nsteps=None):
20
+ if origin is None:
21
+ origin = np.zeros(3)
22
+ if step_vector is None:
23
+ step_vector = np.ones(3)
24
+ if nsteps_cells is None:
25
+ nsteps_cells = np.ones(3) * 10 if nsteps is None else np.array(nsteps)
26
+ BaseStructuredSupport.__init__(self, origin, nsteps_cells, step_vector)
27
+ self.type = SupportType.TetMesh
28
+ self.tetra_mask_even = np.array(
29
+ [[7, 1, 2, 4], [6, 2, 4, 7], [5, 1, 4, 7], [0, 1, 2, 4], [3, 1, 2, 7]]
30
+ )
31
+
32
+ self.tetra_mask = np.array(
33
+ [[0, 6, 5, 3], [7, 3, 5, 6], [4, 0, 5, 6], [2, 0, 3, 6], [1, 0, 3, 5]]
34
+ )
35
+ self.shared_element_relationships = np.zeros(
36
+ (self.neighbours[self.neighbours >= 0].flatten().shape[0], 2), dtype=int
37
+ )
38
+ self.shared_elements = np.zeros(
39
+ (self.neighbours[self.neighbours >= 0].flatten().shape[0], 3), dtype=int
40
+ )
41
+ self.cg = None
42
+ self._elements = None
43
+
44
+ self._init_face_table()
45
+
46
+ def onGeometryChange(self):
47
+ self._elements = None
48
+ self.shared_element_relationships = np.zeros(
49
+ (self.neighbours[self.neighbours >= 0].flatten().shape[0], 2), dtype=int
50
+ )
51
+ self.shared_elements = np.zeros(
52
+ (self.neighbours[self.neighbours >= 0].flatten().shape[0], 3), dtype=int
53
+ )
54
+ self._init_face_table()
55
+ if self.interpolator is not None:
56
+ self.interpolator.reset()
57
+
58
+ @property
59
+ def neighbours(self):
60
+ return self.get_neighbours()
61
+
62
+ @property
63
+ def ntetra(self) -> int:
64
+ return np.prod(self.nsteps_cells) * 5
65
+
66
+ @property
67
+ def n_elements(self) -> int:
68
+ return self.ntetra
69
+
70
+ @property
71
+ def n_cells(self) -> int:
72
+ return np.prod(self.nsteps_cells)
73
+
74
+ @property
75
+ def elements(self):
76
+ if self._elements is None:
77
+ self._elements = self.get_elements()
78
+ return self._elements
79
+
80
+ @property
81
+ def element_size(self):
82
+ """Calculate the volume of a tetrahedron using the 4 corners
83
+ volume = abs(det(A))/6 where A is the jacobian of the corners
84
+
85
+ Returns
86
+ -------
87
+ _type_
88
+ _description_
89
+ """
90
+ vecs = (
91
+ self.nodes[self.elements[:, :4], :][:, 1:, :]
92
+ - self.nodes[self.elements[:, :4], :][:, 0, None, :]
93
+ )
94
+
95
+ return np.abs(np.linalg.det(vecs)) / 6
96
+
97
+ @property
98
+ def element_scale(self):
99
+ size = self.element_size
100
+ size -= np.min(size)
101
+ size /= np.max(size)
102
+ size += 1.0
103
+ return size
104
+
105
+ @property
106
+ def barycentre(self) -> np.ndarray:
107
+ """
108
+ Return the barycentres of all tetrahedrons or of specified tetras using
109
+ global index
110
+
111
+ Returns
112
+ -------
113
+ barycentres : numpy array
114
+ barycentres of all tetrahedrons
115
+ """
116
+ tetra = self.elements
117
+ barycentre = np.sum(self.nodes[tetra][:, :, :], axis=1) / 4.0
118
+ return barycentre
119
+
120
+ def _init_face_table(self):
121
+ """
122
+ Fill table containing elements that share a face, and another
123
+ table that contains the nodes for a face.
124
+ """
125
+ # need to identify the shared nodes for pairs of elements
126
+ # we do this by creating a sparse matrix that has N rows (number of elements)
127
+ # and M columns (number of nodes).
128
+ # We then fill the location where a node is in an element with true
129
+ # Then we create a table for the pairs of elements in the mesh
130
+ # we have the neighbour relationships, which are the 4 neighbours for each element
131
+ # create a new table that shows the element index repeated four times
132
+ # flatten both of these arrays so we effectively have a table with pairs of neighbours
133
+ # disgard the negative neighbours because these are border neighbours
134
+ rows = np.tile(np.arange(self.n_elements)[:, None], (1, 4))
135
+ elements = self.elements
136
+ neighbours = self.get_neighbours()
137
+ # add array of bool to the location where there are elements for each node
138
+
139
+ # use this to determine shared faces
140
+
141
+ element_nodes = coo_matrix(
142
+ (np.ones(elements.shape[0] * 4), (rows.ravel(), elements.ravel())),
143
+ shape=(self.n_elements, self.n_nodes),
144
+ dtype=bool,
145
+ ).tocsr()
146
+ n1 = np.tile(np.arange(neighbours.shape[0], dtype=int)[:, None], (1, 4))
147
+ n1 = n1.flatten()
148
+ n2 = neighbours.flatten()
149
+ n1 = n1[n2 >= 0]
150
+ n2 = n2[n2 >= 0]
151
+ el_rel = np.zeros((self.neighbours.flatten().shape[0], 2), dtype=int)
152
+ el_rel[:] = -1
153
+ el_rel[np.arange(n1.shape[0]), 0] = n1
154
+ el_rel[np.arange(n1.shape[0]), 1] = n2
155
+ el_rel = el_rel[el_rel[:, 0] >= 0, :]
156
+
157
+ # el_rel2 = np.zeros((self.neighbours.flatten().shape[0], 2), dtype=int)
158
+ self.shared_element_relationships[:] = -1
159
+ el_pairs = coo_matrix((np.ones(el_rel.shape[0]), (el_rel[:, 0], el_rel[:, 1]))).tocsr()
160
+ i, j = tril(el_pairs).nonzero()
161
+
162
+ self.shared_element_relationships[: len(i), 0] = i
163
+ self.shared_element_relationships[: len(i), 1] = j
164
+
165
+ self.shared_element_relationships = self.shared_element_relationships[
166
+ self.shared_element_relationships[:, 0] >= 0, :
167
+ ]
168
+
169
+ faces = element_nodes[self.shared_element_relationships[:, 0], :].multiply(
170
+ element_nodes[self.shared_element_relationships[:, 1], :]
171
+ )
172
+ shared_faces = faces[np.array(np.sum(faces, axis=1) == 3).flatten(), :]
173
+ row, col = shared_faces.nonzero()
174
+ row = row[row.argsort()]
175
+ col = col[row.argsort()]
176
+ shared_face_index = np.zeros((shared_faces.shape[0], 3), dtype=int)
177
+ shared_face_index[:] = -1
178
+ shared_face_index[row.reshape(-1, 3)[:, 0], :] = col.reshape(-1, 3)
179
+
180
+ self.shared_elements[np.arange(self.shared_element_relationships.shape[0]), :] = (
181
+ shared_face_index
182
+ )
183
+ # resize
184
+ self.shared_elements = self.shared_elements[: len(self.shared_element_relationships), :]
185
+
186
+ @property
187
+ def shared_element_norm(self):
188
+ """
189
+ Get the normal to all of the shared elements
190
+ """
191
+ elements = self.shared_elements
192
+ v1 = self.nodes[elements[:, 1], :] - self.nodes[elements[:, 0], :]
193
+ v2 = self.nodes[elements[:, 2], :] - self.nodes[elements[:, 0], :]
194
+ return np.cross(v1, v2, axisa=1, axisb=1)
195
+
196
+ @property
197
+ def shared_element_size(self):
198
+ """
199
+ Get the area of the share triangle
200
+ """
201
+ norm = self.shared_element_norm
202
+ return 0.5 * np.linalg.norm(norm, axis=1)
203
+
204
+ @property
205
+ def shared_element_scale(self):
206
+ return self.shared_element_size / np.mean(self.shared_element_size)
207
+
208
+ def evaluate_value(self, pos: np.ndarray, property_array: np.ndarray) -> np.ndarray:
209
+ """
210
+ Evaluate value of interpolant
211
+
212
+ Parameters
213
+ ----------
214
+ pos - numpy array
215
+ locations
216
+ prop - string
217
+ property name
218
+
219
+ Returns
220
+ -------
221
+
222
+ """
223
+ values = np.zeros(pos.shape[0])
224
+ values[:] = np.nan
225
+ _vertices, c, tetras, inside = self.get_element_for_location(pos)
226
+ values[inside] = np.sum(
227
+ c[inside, :] * property_array[self.elements[tetras[inside]]], axis=1
228
+ )
229
+ return values
230
+
231
+ def evaluate_gradient(self, pos: np.ndarray, property_array: np.ndarray) -> np.ndarray:
232
+ """
233
+ Evaluate the gradient of an interpolant at the locations
234
+
235
+ Parameters
236
+ ----------
237
+ pos - numpy array
238
+ locations
239
+ prop - string
240
+ property to evaluate
241
+
242
+
243
+ Returns
244
+ -------
245
+
246
+ """
247
+ values = np.zeros(pos.shape)
248
+ values[:] = np.nan
249
+ (
250
+ _vertices,
251
+ element_gradients,
252
+ tetras,
253
+ inside,
254
+ ) = self.get_element_gradient_for_location(pos)
255
+ # grads = np.zeros(tetras.shape)
256
+ values[inside, :] = (
257
+ element_gradients[inside, :, :]
258
+ * property_array[self.elements[tetras[inside]][:, None, :]]
259
+ ).sum(2)
260
+ # length = np.sum(values[inside, :], axis=1)
261
+ # values[inside,:] /= length[:,None]
262
+ return values
263
+
264
+ def inside(self, pos: np.ndarray):
265
+ inside = np.ones(pos.shape[0]).astype(bool)
266
+ for i in range(3):
267
+ inside *= pos[:, i] > self.origin[None, i]
268
+ inside *= (
269
+ pos[:, i]
270
+ < self.origin[None, i] + self.step_vector[None, i] * self.nsteps_cells[None, i]
271
+ )
272
+ return inside
273
+
274
+ def get_element_for_location(self, pos: np.ndarray):
275
+ """
276
+ Determine the tetrahedron from a numpy array of points
277
+
278
+ Parameters
279
+ ----------
280
+ pos : np.array
281
+
282
+
283
+
284
+ Returns
285
+ -------
286
+
287
+ """
288
+ pos = np.array(pos)
289
+ pos = pos[:, : self.dimension]
290
+ inside = self.inside(pos)
291
+ # initialise array for tetrahedron vertices
292
+ vertices = np.zeros((pos.shape[0], 5, 4, 3))
293
+ vertices[:] = np.nan
294
+ # get cell indexes
295
+ cell_indexes, inside = self.position_to_cell_index(pos)
296
+ # determine if using +ve or -ve mask
297
+ even_mask = np.sum(cell_indexes, axis=1) % 2 == 0
298
+ # get cell corners
299
+ corner_indexes = self.cell_corner_indexes(cell_indexes) # global_index_to_node_index(gi)
300
+ # convert to node locations
301
+ nodes = self.node_indexes_to_position(corner_indexes)
302
+
303
+ vertices[even_mask, :, :, :] = nodes[even_mask, :, :][:, self.tetra_mask_even, :]
304
+ vertices[~even_mask, :, :, :] = nodes[~even_mask, :, :][:, self.tetra_mask, :]
305
+ # changing order to points, tetra, nodes, coord
306
+ # vertices = vertices.swapaxes(0, 2)
307
+ # vertices = vertices.swapaxes(1, 2)
308
+ # use scalar triple product to calculate barycentric coords
309
+
310
+ vap = pos[:, None, :] - vertices[:, :, 0, :]
311
+ vbp = pos[:, None, :] - vertices[:, :, 1, :]
312
+ # # vcp = p - points[:, 2, :]
313
+ # # vdp = p - points[:, 3, :]
314
+ vab = vertices[:, :, 1, :] - vertices[:, :, 0, :]
315
+ vac = vertices[:, :, 2, :] - vertices[:, :, 0, :]
316
+ vad = vertices[:, :, 3, :] - vertices[:, :, 0, :]
317
+ vbc = vertices[:, :, 2, :] - vertices[:, :, 1, :]
318
+ vbd = vertices[:, :, 3, :] - vertices[:, :, 1, :]
319
+ va = np.einsum("ikj, ikj->ik", vbp, np.cross(vbd, vbc, axisa=2, axisb=2)) / 6.0
320
+ vb = np.einsum("ikj, ikj->ik", vap, np.cross(vac, vad, axisa=2, axisb=2)) / 6.0
321
+ vc = np.einsum("ikj, ikj->ik", vap, np.cross(vad, vab, axisa=2, axisb=2)) / 6.0
322
+ vd = np.einsum("ikj, ikj->ik", vap, np.cross(vab, vac, axisa=2, axisb=2)) / 6.0
323
+ v = np.einsum("ikj, ikj->ik", vab, np.cross(vac, vad, axisa=2, axisb=2)) / 6.0
324
+ c = np.zeros((va.shape[0], va.shape[1], 4))
325
+ c[:, :, 0] = va / v
326
+ c[:, :, 1] = vb / v
327
+ c[:, :, 2] = vc / v
328
+ c[:, :, 3] = vd / v
329
+
330
+ # if all coords are +ve then point is inside cell
331
+ mask = np.all(c >= 0, axis=2)
332
+ i, j = np.where(mask)
333
+ ## find any cases where the point belongs to two cells
334
+ ## just use the second cell
335
+ pairs = dict(zip(i, j))
336
+ mask[:] = False
337
+ mask[list(pairs.keys()), list(pairs.values())] = True
338
+
339
+ inside = np.logical_and(inside, np.any(mask, axis=1))
340
+ # get cell corners
341
+ # create mask to see which cells are even
342
+ even_mask = np.sum(cell_indexes, axis=1) % 2 == 0
343
+ # create global node index list
344
+ gi = self.global_node_indices(corner_indexes)
345
+ # gi = xi + yi * self.nsteps[0] + zi * self.nsteps[0] * self.nsteps[1]
346
+ # container for tetras
347
+ tetras = np.zeros((corner_indexes.shape[0], 5, 4)).astype(int)
348
+ tetras[even_mask, :, :] = gi[even_mask, :][:, self.tetra_mask_even]
349
+ tetras[~even_mask, :, :] = gi[~even_mask, :][:, self.tetra_mask]
350
+ inside = np.logical_and(inside, self.inside(pos))
351
+ vertices_return = np.zeros((pos.shape[0], 4, 3))
352
+ vertices_return[:] = np.nan
353
+ # set all masks not inside to False
354
+ mask[~inside, :] = False
355
+ vertices_return[inside, :, :] = vertices[mask, :, :] # [mask,:,:]#[inside,:,:]
356
+ c_return = np.zeros((pos.shape[0], 4))
357
+ c_return[:] = np.nan
358
+ c_return[inside] = c[mask]
359
+ tetra_return = np.zeros(pos.shape[0]).astype(int)
360
+ tetra_return[:] = -1
361
+ local_tetra_index = np.tile(np.arange(0, 5)[None, :], (mask.shape[0], 1))
362
+ local_tetra_index = local_tetra_index[mask]
363
+ tetra_global_index = self.tetra_global_index(cell_indexes[inside, :], local_tetra_index)
364
+ tetra_return[inside] = tetra_global_index
365
+ return vertices_return, c_return, tetra_return, inside
366
+
367
+ def evaluate_shape(self, locations):
368
+ """
369
+ Convenience function returning barycentric coords
370
+
371
+ """
372
+ locations = np.array(locations)
373
+ _verts, c, elements, inside = self.get_element_for_location(locations)
374
+ return c, elements, inside
375
+
376
+ def get_elements(self):
377
+ """
378
+ Get a numpy array of all of the elements in the mesh
379
+
380
+ Returns
381
+ -------
382
+ numpy array elements
383
+
384
+ """
385
+ x = np.arange(0, self.nsteps_cells[0])
386
+ y = np.arange(0, self.nsteps_cells[1])
387
+ z = np.arange(0, self.nsteps_cells[2])
388
+ ## reverse x and z so that indexing is
389
+ zz, yy, xx = np.meshgrid(z, y, x, indexing="ij")
390
+ cell_indexes = np.array([xx.flatten(), yy.flatten(), zz.flatten()]).T
391
+ # get cell corners
392
+ cell_corners = self.cell_corner_indexes(cell_indexes)
393
+ even_mask = np.sum(cell_indexes, axis=1) % 2 == 0
394
+ gi = self.global_node_indices(cell_corners)
395
+ tetras = np.zeros((cell_corners.shape[0], 5, 4)).astype("int64")
396
+ tetras[even_mask, :, :] = gi[even_mask, :][:, self.tetra_mask_even]
397
+ tetras[~even_mask, :, :] = gi[~even_mask, :][:, self.tetra_mask]
398
+
399
+ return tetras.reshape((tetras.shape[0] * tetras.shape[1], tetras.shape[2]))
400
+
401
+ def tetra_global_index(self, indices, tetra_index):
402
+ """
403
+ Get the global index of a tetra from the cell index and the local tetra index
404
+
405
+ Parameters
406
+ ----------
407
+ indices
408
+ tetra_index
409
+
410
+ Returns
411
+ -------
412
+
413
+ """
414
+ return (
415
+ tetra_index
416
+ + indices[:, 0] * 5
417
+ + self.nsteps_cells[0] * indices[:, 1] * 5
418
+ + self.nsteps_cells[0] * self.nsteps_cells[1] * indices[:, 2] * 5
419
+ )
420
+
421
+ def get_element_gradients(self, elements=None):
422
+ """
423
+ Get the gradients of all tetras
424
+
425
+ Parameters
426
+ ----------
427
+ elements
428
+
429
+ Returns
430
+ -------
431
+
432
+ """
433
+ if elements is None:
434
+ elements = np.arange(0, self.ntetra)
435
+ x = np.arange(0, self.nsteps_cells[0])
436
+ y = np.arange(0, self.nsteps_cells[1])
437
+ z = np.arange(0, self.nsteps_cells[2])
438
+
439
+ zz, yy, xx = np.meshgrid(z, y, x, indexing="ij")
440
+ cell_indexes = np.array([xx.flatten(), yy.flatten(), zz.flatten()]).T
441
+ # c_xi = c_xi.flatten(order="F")
442
+ # c_yi = c_yi.flatten(order="F")
443
+ # c_zi = c_zi.flatten(order="F")
444
+ even_mask = np.sum(cell_indexes, axis=1) % 2 == 0
445
+ # get cell corners
446
+ corner_indexes = self.cell_corner_indexes(cell_indexes) # global_index_to_node_index(gi)
447
+ # convert to node locations
448
+ nodes = self.node_indexes_to_position(corner_indexes)
449
+
450
+ points = np.zeros((self.n_cells, 5, 4, 3))
451
+ points[even_mask, :, :, :] = nodes[even_mask, :, :][:, self.tetra_mask_even, :]
452
+ points[~even_mask, :, :, :] = nodes[~even_mask, :, :][:, self.tetra_mask, :]
453
+
454
+ # changing order to points, tetra, nodes, coord
455
+ # points = points.swapaxes(0, 2)
456
+ # points = points.swapaxes(1, 2)
457
+
458
+ ps = points.reshape(points.shape[0] * points.shape[1], points.shape[2], points.shape[3])
459
+
460
+ m = np.array(
461
+ [
462
+ [
463
+ (ps[:, 1, 0] - ps[:, 0, 0]),
464
+ (ps[:, 1, 1] - ps[:, 0, 1]),
465
+ (ps[:, 1, 2] - ps[:, 0, 2]),
466
+ ],
467
+ [
468
+ (ps[:, 2, 0] - ps[:, 0, 0]),
469
+ (ps[:, 2, 1] - ps[:, 0, 1]),
470
+ (ps[:, 2, 2] - ps[:, 0, 2]),
471
+ ],
472
+ [
473
+ (ps[:, 3, 0] - ps[:, 0, 0]),
474
+ (ps[:, 3, 1] - ps[:, 0, 1]),
475
+ (ps[:, 3, 2] - ps[:, 0, 2]),
476
+ ],
477
+ ]
478
+ )
479
+ I = np.array([[-1.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 1.0, 0.0], [-1.0, 0.0, 0.0, 1.0]])
480
+ m = np.swapaxes(m, 0, 2)
481
+ element_gradients = np.linalg.inv(m)
482
+
483
+ element_gradients = element_gradients.swapaxes(1, 2)
484
+ element_gradients = element_gradients @ I
485
+
486
+ return element_gradients[elements, :, :]
487
+
488
+ def evaluate_shape_derivatives(self, pos, elements=None):
489
+ inside = None
490
+ if elements is not None:
491
+ inside = np.ones(elements.shape[0], dtype=bool)
492
+ if elements is None:
493
+ _verts, _c, elements, inside = self.get_element_for_location(pos)
494
+ # np.arange(0, self.n_elements, dtype=int)
495
+
496
+ return (
497
+ self.get_element_gradients(elements),
498
+ elements,
499
+ inside,
500
+ )
501
+
502
+ def get_element_gradient_for_location(self, pos: np.ndarray):
503
+ """
504
+ Get the gradient of the tetra for a location
505
+
506
+ Parameters
507
+ ----------
508
+ pos
509
+
510
+ Returns
511
+ -------
512
+
513
+ """
514
+ vertices, _bc, tetras, inside = self.get_element_for_location(pos)
515
+ ps = vertices
516
+ m = np.array(
517
+ [
518
+ [
519
+ (ps[:, 1, 0] - ps[:, 0, 0]),
520
+ (ps[:, 1, 1] - ps[:, 0, 1]),
521
+ (ps[:, 1, 2] - ps[:, 0, 2]),
522
+ ],
523
+ [
524
+ (ps[:, 2, 0] - ps[:, 0, 0]),
525
+ (ps[:, 2, 1] - ps[:, 0, 1]),
526
+ (ps[:, 2, 2] - ps[:, 0, 2]),
527
+ ],
528
+ [
529
+ (ps[:, 3, 0] - ps[:, 0, 0]),
530
+ (ps[:, 3, 1] - ps[:, 0, 1]),
531
+ (ps[:, 3, 2] - ps[:, 0, 2]),
532
+ ],
533
+ ]
534
+ )
535
+ # m[~inside,:,:] = np.nan
536
+ I = np.array([[-1.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 1.0, 0.0], [-1.0, 0.0, 0.0, 1.0]])
537
+ m = np.swapaxes(m, 0, 2)
538
+ element_gradients = np.zeros_like(m)
539
+ element_gradients[:] = np.nan
540
+ element_gradients[inside, :, :] = np.linalg.inv(m[inside, :, :])
541
+ # element_gradients = np.linalg.inv(m)
542
+
543
+ element_gradients = element_gradients.swapaxes(1, 2)
544
+ element_gradients = element_gradients @ I
545
+ return vertices, element_gradients, tetras, inside
546
+
547
+ def global_node_indicies(self, indexes: np.ndarray):
548
+ """
549
+ Convert from node indexes to global node index
550
+
551
+ Parameters
552
+ ----------
553
+ indexes
554
+
555
+ Returns
556
+ -------
557
+
558
+ """
559
+ indexes = np.array(indexes).swapaxes(0, 2)
560
+ return (
561
+ indexes[:, :, 0]
562
+ + self.nsteps[None, None, 0] * indexes[:, :, 1]
563
+ + self.nsteps[None, None, 0] * self.nsteps[None, None, 1] * indexes[:, :, 2]
564
+ )
565
+
566
+ def global_cell_indicies(self, indexes: np.ndarray):
567
+ """
568
+ Convert from cell indexes to global cell index
569
+
570
+ Parameters
571
+ ----------
572
+ indexes
573
+
574
+ Returns
575
+ -------
576
+
577
+ """
578
+ indexes = np.array(indexes).swapaxes(0, 2)
579
+ return (
580
+ indexes[:, :, 0]
581
+ + self.nsteps_cells[None, None, 0] * indexes[:, :, 1]
582
+ + self.nsteps_cells[None, None, 0] * self.nsteps_cells[None, None, 1] * indexes[:, :, 2]
583
+ )
584
+
585
+ def global_index_to_node_index(self, global_index: np.ndarray):
586
+ """
587
+ Convert from global indexes to xi,yi,zi
588
+
589
+ Parameters
590
+ ----------
591
+ global_index
592
+
593
+ Returns
594
+ -------
595
+
596
+ """
597
+ # determine the ijk indices for the global index.
598
+ # remainder when dividing by nx = i
599
+ # remained when dividing modulus of nx by ny is j
600
+ x_index = global_index % self.nsteps[0, None]
601
+ y_index = global_index // self.nsteps[0, None] % self.nsteps[1, None]
602
+ z_index = global_index // self.nsteps[0, None] // self.nsteps[1, None]
603
+ return x_index, y_index, z_index
604
+
605
+ def global_index_to_cell_index(self, global_index):
606
+ """
607
+ Convert from global indexes to xi,yi,zi
608
+
609
+ Parameters
610
+ ----------
611
+ global_index
612
+
613
+ Returns
614
+ -------
615
+
616
+ """
617
+ # determine the ijk indices for the global index.
618
+ # remainder when dividing by nx = i
619
+ # remained when dividing modulus of nx by ny is j
620
+
621
+ x_index = global_index % self.nsteps_cells[0, None]
622
+ y_index = global_index // self.nsteps_cells[0, None] % self.nsteps_cells[1, None]
623
+ z_index = global_index // self.nsteps_cells[0, None] // self.nsteps_cells[1, None]
624
+ return x_index, y_index, z_index
625
+
626
+ def get_neighbours(self) -> np.ndarray:
627
+ """
628
+ This function goes through all of the elements in the mesh and assembles a numpy array
629
+ with the neighbours for each element
630
+
631
+ Returns
632
+ -------
633
+
634
+ """
635
+ # elements = self.get_elements()
636
+ # neighbours = np.zeros((self.ntetra,4)).astype('int64')
637
+ # neighbours[:] = -1
638
+ # tetra_neighbours(elements,neighbours)
639
+ # return neighbours
640
+ tetra_index = np.arange(0, self.ntetra)
641
+ neighbours = np.zeros((self.ntetra, 4)).astype("int64")
642
+ neighbours[:] = -9999
643
+ neighbours[tetra_index % 5 == 0, :] = (
644
+ tetra_index[tetra_index % 5 == 0, None] + np.arange(1, 5)[None, :]
645
+ ) # first tetra is the centre one so all of its neighbours are in the same cell
646
+ neighbours[tetra_index % 5 != 0, 0] = np.tile(
647
+ tetra_index[tetra_index % 5 == 0], (4, 1)
648
+ ).flatten(
649
+ order="F"
650
+ ) # add first tetra to other neighbours
651
+
652
+ # now create masks for the different tetra indexes
653
+ one_mask = tetra_index % 5 == 1
654
+ two_mask = tetra_index % 5 == 2
655
+ three_mask = tetra_index % 5 == 3
656
+ four_mask = tetra_index % 5 == 4
657
+
658
+ # create masks for whether cell is odd or even
659
+ odd_mask = np.sum(self.global_index_to_cell_index(tetra_index // 5), axis=0) % 2 == 1
660
+ odd_mask = odd_mask.astype(bool)
661
+
662
+ # apply masks to
663
+ masks = []
664
+ masks.append(
665
+ [
666
+ np.logical_and(one_mask, odd_mask),
667
+ np.array([[1, 0, 0, 1], [0, 1, 0, 2], [0, 0, 1, 4]]),
668
+ ]
669
+ )
670
+ masks.append(
671
+ [
672
+ np.logical_and(two_mask, odd_mask),
673
+ np.array([[-1, 0, 0, 2], [0, -1, 0, 1], [0, 0, 1, 3]]),
674
+ ]
675
+ )
676
+ masks.append(
677
+ [
678
+ np.logical_and(three_mask, odd_mask),
679
+ np.array([[-1, 0, 0, 4], [0, 1, 0, 3], [0, 0, -1, 1]]),
680
+ ]
681
+ )
682
+ masks.append(
683
+ [
684
+ np.logical_and(four_mask, odd_mask),
685
+ np.array([[1, 0, 0, 3], [0, -1, 0, 4], [0, 0, -1, 2]]),
686
+ ]
687
+ )
688
+
689
+ masks.append(
690
+ [
691
+ np.logical_and(one_mask, ~odd_mask),
692
+ np.array([[-1, 0, 0, 1], [0, 1, 0, 2], [0, 0, 1, 3]]),
693
+ ]
694
+ )
695
+ masks.append(
696
+ [
697
+ np.logical_and(two_mask, ~odd_mask),
698
+ np.array([[1, 0, 0, 2], [0, -1, 0, 1], [0, 0, 1, 4]]),
699
+ ]
700
+ )
701
+ masks.append(
702
+ [
703
+ np.logical_and(three_mask, ~odd_mask),
704
+ np.array([[-1, 0, 0, 4], [0, -1, 0, 3], [0, 0, -1, 2]]),
705
+ ]
706
+ )
707
+ masks.append(
708
+ [
709
+ np.logical_and(four_mask, ~odd_mask),
710
+ np.array([[1, 0, 0, 3], [0, 1, 0, 4], [0, 0, -1, 1]]),
711
+ ]
712
+ )
713
+
714
+ for m in masks:
715
+ logic = m[0]
716
+ mask = m[1]
717
+ c_xi, c_yi, c_zi = self.global_index_to_cell_index(tetra_index[logic] // 5)
718
+ # mask = np.array([[1,0,0,4],[0,0,-1,2],[0,1,0,3],[0,0,0,0]])
719
+ neigh_cell = np.zeros((c_xi.shape[0], 3, 3)).astype(int)
720
+ neigh_cell[:, :, 0] = c_xi[:, None] + mask[:, 0]
721
+ neigh_cell[:, :, 1] = c_yi[:, None] + mask[:, 1]
722
+ neigh_cell[:, :, 2] = c_zi[:, None] + mask[:, 2]
723
+ inside = neigh_cell[:, :, 0] >= 0
724
+ inside = np.logical_and(inside, neigh_cell[:, :, 1] >= 0)
725
+ inside = np.logical_and(inside, neigh_cell[:, :, 2] >= 0)
726
+ inside = np.logical_and(inside, neigh_cell[:, :, 0] < self.nsteps_cells[0])
727
+ inside = np.logical_and(inside, neigh_cell[:, :, 1] < self.nsteps_cells[1])
728
+ inside = np.logical_and(inside, neigh_cell[:, :, 2] < self.nsteps_cells[2])
729
+
730
+ global_neighbour_idx = np.zeros((c_xi.shape[0], 4)).astype(int)
731
+ global_neighbour_idx[:] = -1
732
+ global_neighbour_idx = (
733
+ neigh_cell[:, :, 0]
734
+ + neigh_cell[:, :, 1] * self.nsteps_cells[0]
735
+ + neigh_cell[:, :, 2] * self.nsteps_cells[0] * self.nsteps_cells[1]
736
+ ) * 5 + mask[:, 3]
737
+ global_neighbour_idx[~inside] = -1
738
+ neighbours[logic, 1:] = global_neighbour_idx
739
+
740
+ return neighbours
741
+
742
+ def vtk(self, node_properties=None, cell_properties=None):
743
+ try:
744
+ import pyvista as pv
745
+ except ImportError:
746
+ raise ImportError("pyvista is required for vtk support")
747
+
748
+ if node_properties is None:
749
+ node_properties = {}
750
+ if cell_properties is None:
751
+ cell_properties = {}
752
+ from pyvista import CellType
753
+
754
+ celltype = np.full(self.elements.shape[0], CellType.TETRA, dtype=np.uint8)
755
+ elements = np.hstack(
756
+ [np.zeros(self.elements.shape[0], dtype=int)[:, None] + 4, self.elements]
757
+ )
758
+ elements = elements.flatten()
759
+ grid = pv.UnstructuredGrid(elements, celltype, self.nodes)
760
+ for prop in node_properties:
761
+ grid[prop] = node_properties[prop]
762
+ for prop in cell_properties:
763
+ grid.cell_arrays[prop] = cell_properties[prop]
764
+ return grid