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,656 @@
1
+ """
2
+ Tetmesh based on cartesian grid for piecewise linear interpolation
3
+ """
4
+
5
+
6
+ import numpy as np
7
+ from scipy.sparse import coo_matrix, csr_matrix, tril
8
+
9
+ from loop_common.logging import get_logger as getLogger
10
+
11
+ from . import SupportType
12
+ from ._3d_structured_grid import StructuredGrid
13
+ from ._base_support import BaseSupport
14
+
15
+ logger = getLogger(__name__)
16
+
17
+
18
+ def _cross(a: np.ndarray, b: np.ndarray) -> np.ndarray:
19
+ """Cross product for stacks of 3-vectors, ~10x faster than np.cross
20
+ for this shape because it skips np.cross's generic axis handling.
21
+ """
22
+ return np.stack(
23
+ (
24
+ a[:, 1] * b[:, 2] - a[:, 2] * b[:, 1],
25
+ a[:, 2] * b[:, 0] - a[:, 0] * b[:, 2],
26
+ a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0],
27
+ ),
28
+ axis=1,
29
+ )
30
+
31
+
32
+ class UnStructuredTetMesh(BaseSupport):
33
+ """ """
34
+
35
+ dimension = 3
36
+
37
+ def __init__(
38
+ self,
39
+ nodes: np.ndarray,
40
+ elements: np.ndarray,
41
+ neighbours: np.ndarray,
42
+ aabb_nsteps=None,
43
+ ):
44
+ """An unstructured mesh defined by nodes, elements and neighbours
45
+ An axis aligned bounding box (AABB) grid is used to speed up finding
46
+ which tetra a point is in: each grid cell is sized from the tetra's
47
+ bounding box extent (see _initialise_aabb) so it only needs to test
48
+ a handful of candidate tetra per query point.
49
+
50
+ Parameters
51
+ ----------
52
+ nodes : array or array like
53
+ container of vertex locations
54
+ elements : array or array like, dtype cast to long
55
+ container of tetra indicies
56
+ neighbours : array or array like, dtype cast to long
57
+ array containing element neighbours
58
+ aabb_nsteps : list, optional
59
+ force nsteps for aabb, by default None
60
+ """
61
+ self.type = SupportType.UnStructuredTetMesh
62
+ self._nodes = np.array(nodes)
63
+ if self._nodes.shape[1] != 3:
64
+ raise ValueError("Nodes must be 3D")
65
+ self.neighbours = np.array(neighbours, dtype=np.int64)
66
+ if self.neighbours.shape[1] != 4:
67
+ raise ValueError("Neighbours array is too big")
68
+ self._elements = np.array(elements, dtype=np.int64)
69
+ if self.elements.shape[0] != self.neighbours.shape[0]:
70
+ raise ValueError("Number of elements and neighbours do not match")
71
+ self._barycentre = np.sum(self.nodes[self.elements[:, :4]][:, :, :], axis=1) / 4.0
72
+ self.minimum = np.min(self.nodes, axis=0)
73
+ self.maximum = np.max(self.nodes, axis=0)
74
+ length = self.maximum - self.minimum
75
+ self.minimum -= length * 0.1
76
+ self.maximum += length * 0.1
77
+ # cache each tetra's bounding box; reused here to size the aabb grid
78
+ # and again in _initialise_aabb to bucket tetra into grid cells.
79
+ tetra_nodes = self.nodes[self.elements[:, :4]]
80
+ self._tetra_bbox_min = np.min(tetra_nodes, axis=1)
81
+ self._tetra_bbox_max = np.max(tetra_nodes, axis=1)
82
+ if aabb_nsteps is None:
83
+ # Size grid cells from the tetrahedra's *bounding box* extent, not
84
+ # their volume: a thin/skewed tetrahedron's AABB can be many times
85
+ # larger than its volume would suggest, so a volume-based estimate
86
+ # undersizes cells and each tetra ends up straddling many cells.
87
+ # Cells about half the typical (median) tetra AABB edge keep the
88
+ # per-cell candidate count low (a handful of tetra per cell)
89
+ # without letting the sparse table blow up in size.
90
+ bbox_extent = self._tetra_bbox_max - self._tetra_bbox_min
91
+ median_extent = np.median(bbox_extent, axis=0)
92
+ median_extent = np.maximum(median_extent, np.max(length) * 1e-6)
93
+ step_vector = median_extent * 0.5
94
+ # number of steps is the length of the box / step vector
95
+ aabb_nsteps = np.ceil((self.maximum - self.minimum) / step_vector).astype(int)
96
+ # make sure there is at least one cell in every dimension
97
+ aabb_nsteps[aabb_nsteps < 2] = 2
98
+ aabb_nsteps = np.array(aabb_nsteps, dtype=int)
99
+ step_vector = (self.maximum - self.minimum) / (aabb_nsteps - 1)
100
+ self.aabb_grid = StructuredGrid(self.minimum, nsteps=aabb_nsteps, step_vector=step_vector)
101
+ # make a big table to store which tetra are in which element.
102
+ # if this takes up too much memory it could be simplified by using sparse matrices or dict but
103
+ # at the expense of speed
104
+ self.aabb_table = csr_matrix((self.aabb_grid.n_elements, len(self.elements)), dtype=bool)
105
+ self.shared_element_relationships = np.zeros(
106
+ (self.neighbours[self.neighbours >= 0].flatten().shape[0], 2), dtype=int
107
+ )
108
+ self.shared_elements = np.zeros(
109
+ (self.neighbours[self.neighbours >= 0].flatten().shape[0], 3), dtype=int
110
+ )
111
+ self._init_face_table()
112
+ self._initialise_aabb()
113
+
114
+ def set_nelements(self, nelements):
115
+ raise NotImplementedError("Cannot set number of elements for unstructured mesh")
116
+
117
+ @property
118
+ def nodes(self):
119
+ return self._nodes
120
+
121
+ @property
122
+ def elements(self):
123
+ return self._elements
124
+
125
+ @property
126
+ def barycentre(self):
127
+ return self._barycentre
128
+
129
+ @property
130
+ def n_nodes(self):
131
+ return self.nodes.shape[0]
132
+
133
+ def onGeometryChange(self):
134
+ pass
135
+
136
+ def _init_face_table(self):
137
+ """
138
+ Fill table containing elements that share a face, and another
139
+ table that contains the nodes for a face.
140
+ """
141
+ # need to identify the shared nodes for pairs of elements
142
+ # we do this by creating a sparse matrix that has N rows (number of elements)
143
+ # and M columns (number of nodes).
144
+ # We then fill the location where a node is in an element with true
145
+ # Then we create a table for the pairs of elements in the mesh
146
+ # we have the neighbour relationships, which are the 4 neighbours for each element
147
+ # create a new table that shows the element index repeated four times
148
+ # flatten both of these arrays so we effectively have a table with pairs of neighbours
149
+ # disgard the negative neighbours because these are border neighbours
150
+ rows = np.tile(np.arange(self.n_elements)[:, None], (1, 4))
151
+ elements = self.get_elements()
152
+ neighbours = self.get_neighbours()
153
+ # add array of bool to the location where there are elements for each node
154
+
155
+ # use this to determine shared faces
156
+
157
+ element_nodes = coo_matrix(
158
+ (np.ones(elements.shape[0] * 4), (rows.ravel(), elements[:, :4].ravel())),
159
+ shape=(self.n_elements, self.n_nodes),
160
+ dtype=bool,
161
+ ).tocsr()
162
+ n1 = np.tile(np.arange(neighbours.shape[0], dtype=int)[:, None], (1, 4))
163
+ n1 = n1.flatten()
164
+ n2 = neighbours.flatten()
165
+ n1 = n1[n2 >= 0]
166
+ n2 = n2[n2 >= 0]
167
+ el_rel = np.zeros((self.neighbours.flatten().shape[0], 2), dtype=int)
168
+ el_rel[:] = -1
169
+ el_rel[np.arange(n1.shape[0]), 0] = n1
170
+ el_rel[np.arange(n1.shape[0]), 1] = n2
171
+ el_rel = el_rel[el_rel[:, 0] >= 0, :]
172
+
173
+ # el_rel2 = np.zeros((self.neighbours.flatten().shape[0], 2), dtype=int)
174
+ self.shared_element_relationships[:] = -1
175
+ el_pairs = coo_matrix((np.ones(el_rel.shape[0]), (el_rel[:, 0], el_rel[:, 1]))).tocsr()
176
+ i, j = tril(el_pairs).nonzero()
177
+ self.shared_element_relationships[: len(i), 0] = i
178
+ self.shared_element_relationships[: len(i), 1] = j
179
+
180
+ self.shared_element_relationships = self.shared_element_relationships[
181
+ self.shared_element_relationships[:, 0] >= 0, :
182
+ ]
183
+
184
+ faces = element_nodes[self.shared_element_relationships[:, 0], :].multiply(
185
+ element_nodes[self.shared_element_relationships[:, 1], :]
186
+ )
187
+ shared_faces = faces[np.array(np.sum(faces, axis=1) == 3).flatten(), :]
188
+ row, col = shared_faces.nonzero()
189
+ row = row[row.argsort()]
190
+ col = col[row.argsort()]
191
+ shared_face_index = np.zeros((shared_faces.shape[0], 3), dtype=int)
192
+ shared_face_index[:] = -1
193
+ shared_face_index[row.reshape(-1, 3)[:, 0], :] = col.reshape(-1, 3)
194
+
195
+ self.shared_elements[np.arange(self.shared_element_relationships.shape[0]), :] = (
196
+ shared_face_index
197
+ )
198
+ # resize
199
+ self.shared_elements = self.shared_elements[: len(self.shared_element_relationships), :]
200
+ # flag = np.zeros(self.elements.shape[0])
201
+ # face_index = 0
202
+ # for i, t in enumerate(self.elements):
203
+ # flag[i] = True
204
+ # for n in self.neighbours[i]:
205
+ # if n < 0:
206
+ # continue
207
+ # if flag[n]:
208
+ # continue
209
+ # face_node_index = 0
210
+ # self.shared_element_relationships[face_index, 0] = i
211
+ # self.shared_element_relationships[face_index, 1] = n
212
+ # for v in t:
213
+ # if v in self.elements[n, :4]:
214
+ # self.shared_elements[face_index, face_node_index] = v
215
+ # face_node_index += 1
216
+
217
+ # face_index += 1
218
+ # self.shared_elements = self.shared_elements[:face_index, :]
219
+ # self.shared_element_relationships = self.shared_element_relationships[
220
+ # :face_index, :
221
+ # ]
222
+
223
+ def _initialise_aabb(self):
224
+ """Builds a sparse mapping from AABB grid cells to the tetrahedra whose
225
+ axis-aligned bounding box overlaps that cell.
226
+
227
+ Rather than testing every (cell, tetra) pair -- which costs
228
+ O(n_cells * n_elements) time and memory and does not scale to large
229
+ meshes -- each tetra's bounding box is converted directly into the
230
+ (small) range of grid cells it spans, and only those (cell, tetra)
231
+ pairs are recorded. Cells are sized (in __init__) at about half the
232
+ median tetra bounding-box edge, so most tetra touch only a handful of
233
+ cells and the resulting table stays close to O(n_elements) in size,
234
+ rather than O(n_cells * n_elements).
235
+ """
236
+ bbox_min = self._tetra_bbox_min
237
+ bbox_max = self._tetra_bbox_max
238
+
239
+ origin = self.aabb_grid.origin
240
+ step = self.aabb_grid.step_vector
241
+ nsteps_cells = self.aabb_grid.nsteps_cells
242
+
243
+ cell_min = np.floor((bbox_min - origin[None, :]) / step[None, :]).astype(np.int64)
244
+ cell_max = np.floor((bbox_max - origin[None, :]) / step[None, :]).astype(np.int64)
245
+ for d in range(3):
246
+ cell_min[:, d] = np.clip(cell_min[:, d], 0, nsteps_cells[d] - 1)
247
+ cell_max[:, d] = np.clip(cell_max[:, d], 0, nsteps_cells[d] - 1)
248
+
249
+ # number of grid cells each tetra's bounding box spans per axis (>=1)
250
+ span = cell_max - cell_min + 1
251
+ counts = span[:, 0] * span[:, 1] * span[:, 2]
252
+ total = int(counts.sum())
253
+
254
+ tetra_id = np.repeat(np.arange(self.n_elements), counts)
255
+ block_start = np.repeat(np.concatenate(([0], np.cumsum(counts)[:-1])), counts)
256
+ local_idx = np.arange(total) - block_start
257
+
258
+ ny_rep = np.repeat(span[:, 1], counts)
259
+ nz_rep = np.repeat(span[:, 2], counts)
260
+ k_off = local_idx % nz_rep
261
+ j_off = (local_idx // nz_rep) % ny_rep
262
+ i_off = local_idx // (nz_rep * ny_rep)
263
+
264
+ i = np.repeat(cell_min[:, 0], counts) + i_off
265
+ j = np.repeat(cell_min[:, 1], counts) + j_off
266
+ k = np.repeat(cell_min[:, 2], counts) + k_off
267
+
268
+ global_cell = i + nsteps_cells[0] * j + nsteps_cells[0] * nsteps_cells[1] * k
269
+
270
+ self.aabb_table = csr_matrix(
271
+ (np.ones(total, dtype=bool), (global_cell, tetra_id)),
272
+ shape=(self.aabb_grid.n_elements, self.n_elements),
273
+ dtype=bool,
274
+ )
275
+
276
+ @property
277
+ def ntetra(self):
278
+ return self.elements.shape[0]
279
+
280
+ @property
281
+ def n_elements(self):
282
+ return self.ntetra
283
+
284
+ @property
285
+ def n_cells(self):
286
+ return None
287
+
288
+ @property
289
+ def shared_element_norm(self):
290
+ """
291
+ Get the normal to all of the shared elements
292
+ """
293
+ elements = self.shared_elements
294
+ v1 = self.nodes[elements[:, 1], :] - self.nodes[elements[:, 0], :]
295
+ v2 = self.nodes[elements[:, 2], :] - self.nodes[elements[:, 0], :]
296
+ return np.cross(v1, v2, axisa=1, axisb=1)
297
+
298
+ @property
299
+ def shared_element_size(self):
300
+ """
301
+ Get the area of the share triangle
302
+ """
303
+ norm = self.shared_element_norm
304
+ return 0.5 * np.linalg.norm(norm, axis=1)
305
+
306
+ @property
307
+ def element_size(self):
308
+ """Calculate the volume of a tetrahedron using the 4 corners
309
+ volume = abs(det(A))/6 where A is the jacobian of the corners
310
+
311
+ Returns
312
+ -------
313
+ _type_
314
+ _description_
315
+ """
316
+ vecs = (
317
+ self.nodes[self.elements[:, :4], :][:, 1:, :]
318
+ - self.nodes[self.elements[:, :4], :][:, 0, None, :]
319
+ )
320
+ return np.abs(np.linalg.det(vecs)) / 6
321
+
322
+ def evaluate_shape_derivatives(self, locations, elements=None):
323
+ """
324
+ Get the gradients of all tetras
325
+
326
+ Parameters
327
+ ----------
328
+ elements
329
+
330
+ Returns
331
+ -------
332
+
333
+ """
334
+ inside = None
335
+ if elements is not None:
336
+ inside = np.zeros(self.n_elements, dtype=bool)
337
+ inside[elements] = True
338
+ if elements is None:
339
+ _verts, _c, elements, inside = self.get_element_for_location(locations)
340
+ # elements = np.arange(0, self.n_elements, dtype=int)
341
+ ps = self.nodes[self.elements, :]
342
+ m = np.array(
343
+ [
344
+ [
345
+ (ps[:, 1, 0] - ps[:, 0, 0]),
346
+ (ps[:, 1, 1] - ps[:, 0, 1]),
347
+ (ps[:, 1, 2] - ps[:, 0, 2]),
348
+ ],
349
+ [
350
+ (ps[:, 2, 0] - ps[:, 0, 0]),
351
+ (ps[:, 2, 1] - ps[:, 0, 1]),
352
+ (ps[:, 2, 2] - ps[:, 0, 2]),
353
+ ],
354
+ [
355
+ (ps[:, 3, 0] - ps[:, 0, 0]),
356
+ (ps[:, 3, 1] - ps[:, 0, 1]),
357
+ (ps[:, 3, 2] - ps[:, 0, 2]),
358
+ ],
359
+ ]
360
+ )
361
+ 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]])
362
+ m = np.swapaxes(m, 0, 2)
363
+ element_gradients = np.linalg.inv(m)
364
+
365
+ element_gradients = element_gradients.swapaxes(1, 2)
366
+ element_gradients = element_gradients @ I
367
+
368
+ return element_gradients[elements, :, :], elements, inside
369
+
370
+ def evaluate_shape(self, locations):
371
+ """
372
+ Convenience function returning barycentric coords
373
+
374
+ """
375
+ locations = np.array(locations)
376
+ _verts, c, elements, inside = self.get_element_for_location(locations)
377
+ return c, elements, inside
378
+
379
+ def evaluate_value(self, pos, property_array):
380
+ """
381
+ Evaluate value of interpolant
382
+
383
+ Parameters
384
+ ----------
385
+ pos - numpy array
386
+ locations
387
+ prop - string
388
+ property name
389
+
390
+ Returns
391
+ -------
392
+
393
+ """
394
+ values = np.zeros(pos.shape[0])
395
+ values[:] = np.nan
396
+ _vertices, c, tetras, inside = self.get_element_for_location(pos)
397
+ values[inside] = np.sum(
398
+ c[inside, :] * property_array[self.elements[tetras[inside], :]], axis=1
399
+ )
400
+ return values
401
+
402
+ def evaluate_gradient(self, pos, property_array):
403
+ """
404
+ Evaluate the gradient of an interpolant at the locations
405
+
406
+ Parameters
407
+ ----------
408
+ pos - numpy array
409
+ locations
410
+ prop - string
411
+ property to evaluate
412
+
413
+
414
+ Returns
415
+ -------
416
+
417
+ """
418
+ values = np.zeros(pos.shape)
419
+ values[:] = np.nan
420
+ (
421
+ _vertices,
422
+ element_gradients,
423
+ tetras,
424
+ inside,
425
+ ) = self.get_element_gradient_for_location(pos)
426
+ # grads = np.zeros(tetras.shape)
427
+ values[inside, :] = (
428
+ element_gradients[inside, :, :] * property_array[self.elements[tetras][inside, None, :]]
429
+ ).sum(2)
430
+ # length = np.sum(values[inside, :], axis=1)
431
+ # values[inside,:] /= length[:,None]
432
+ return values
433
+
434
+ def inside(self, pos):
435
+ if pos.shape[1] > 3:
436
+ logger.warning(f"Converting {pos.shape[1]} to 3d using first 3 columns")
437
+ pos = pos[:, :3]
438
+
439
+ inside = np.ones(pos.shape[0]).astype(bool)
440
+ for i in range(3):
441
+ inside *= pos[:, i] > self.origin[None, i]
442
+ inside *= (
443
+ pos[:, i]
444
+ < self.origin[None, i] + self.step_vector[None, i] * self.nsteps_cells[None, i]
445
+ )
446
+ return inside
447
+
448
+ def get_elements(self):
449
+ return self.elements
450
+
451
+ def get_element_for_location(self, points: np.ndarray) -> tuple:
452
+ """
453
+ Determine the tetrahedron from a numpy array of points
454
+
455
+ Parameters
456
+ ----------
457
+ pos : np.array
458
+
459
+
460
+
461
+ Returns
462
+ -------
463
+
464
+ """
465
+ points = np.asarray(points)
466
+ npoints = points.shape[0]
467
+ verts = np.zeros((npoints, 4, 3))
468
+ bc = np.zeros((npoints, 4))
469
+ tetras = np.full(npoints, -1, dtype="int64")
470
+ inside = np.zeros(npoints, dtype=bool)
471
+ npts_step = int(1e4)
472
+ # process points in blocks to bound the size of the candidate table
473
+ for start in range(0, npoints, npts_step):
474
+ end = min(start + npts_step, npoints)
475
+ block = points[start:end, :]
476
+
477
+ cell_index, block_inside = self.aabb_grid.position_to_cell_index(block)
478
+ # block_inside indicates which points fall within the aabb grid bounds
479
+ block_inside_idx = np.flatnonzero(block_inside)
480
+ if block_inside_idx.size == 0:
481
+ continue
482
+ global_index = (
483
+ cell_index[block_inside_idx, 0]
484
+ + self.aabb_grid.nsteps_cells[0] * cell_index[block_inside_idx, 1]
485
+ + self.aabb_grid.nsteps_cells[0]
486
+ * self.aabb_grid.nsteps_cells[1]
487
+ * cell_index[block_inside_idx, 2]
488
+ )
489
+
490
+ tetra_indices = self.aabb_table[global_index, :].tocoo()
491
+ # tetra_indices.row indexes into block_inside_idx (the compacted
492
+ # set of in-bounds points), map it back to indices within block
493
+ point_idx = block_inside_idx[tetra_indices.row]
494
+ col = tetra_indices.col
495
+ # using returned indexes calculate barycentric coords to determine which tetra the points are in
496
+ vertices = self.nodes[self.elements[col, :4]]
497
+ pos = block[point_idx, :]
498
+ vap = pos[:, :] - vertices[:, 0, :]
499
+ vbp = pos[:, :] - vertices[:, 1, :]
500
+ # # vcp = p - points[:, 2, :]
501
+ # # vdp = p - points[:, 3, :]
502
+ vab = vertices[:, 1, :] - vertices[:, 0, :]
503
+ vac = vertices[:, 2, :] - vertices[:, 0, :]
504
+ vad = vertices[:, 3, :] - vertices[:, 0, :]
505
+ vbc = vertices[:, 2, :] - vertices[:, 1, :]
506
+ vbd = vertices[:, 3, :] - vertices[:, 1, :]
507
+
508
+ va = np.einsum("ij, ij->i", vbp, _cross(vbd, vbc)) / 6.0
509
+ vb = np.einsum("ij, ij->i", vap, _cross(vac, vad)) / 6.0
510
+ vc = np.einsum("ij, ij->i", vap, _cross(vad, vab)) / 6.0
511
+ vd = np.einsum("ij, ij->i", vap, _cross(vab, vac)) / 6.0
512
+ v = np.einsum("ij, ij->i", vab, _cross(vac, vad)) / 6.0
513
+ c = np.zeros((va.shape[0], 4))
514
+ c[:, 0] = va / v
515
+ c[:, 1] = vb / v
516
+ c[:, 2] = vc / v
517
+ c[:, 3] = vd / v
518
+ mask = np.all(c >= 0, axis=1)
519
+
520
+ found_point_idx = point_idx[mask]
521
+ verts[start + found_point_idx, :, :] = vertices[mask, :, :]
522
+ bc[start + found_point_idx, :] = c[mask, :]
523
+ tetras[start + found_point_idx] = col[mask]
524
+ inside[start + found_point_idx] = True
525
+
526
+ return verts, bc, tetras, inside
527
+
528
+ def get_element_gradients(self, elements=None):
529
+ """
530
+ Get the gradients of all tetras
531
+
532
+ Parameters
533
+ ----------
534
+ elements
535
+
536
+ Returns
537
+ -------
538
+
539
+ """
540
+ # points = np.zeros((5, 4, self.n_cells, 3))
541
+ # points[:, :, even_mask, :] = nodes[:, even_mask, :][self.tetra_mask_even, :, :]
542
+ # points[:, :, ~even_mask, :] = nodes[:, ~even_mask, :][self.tetra_mask, :, :]
543
+
544
+ # # changing order to points, tetra, nodes, coord
545
+ # points = points.swapaxes(0, 2)
546
+ # points = points.swapaxes(1, 2)
547
+ if elements is None:
548
+ elements = np.arange(0, self.n_elements, dtype=int)
549
+ ps = self.nodes[
550
+ self.elements, :
551
+ ] # points.reshape(points.shape[0] * points.shape[1], points.shape[2], points.shape[3])
552
+ # vertices = self.nodes[self.elements[col,:]]
553
+ m = np.array(
554
+ [
555
+ [
556
+ (ps[:, 1, 0] - ps[:, 0, 0]),
557
+ (ps[:, 1, 1] - ps[:, 0, 1]),
558
+ (ps[:, 1, 2] - ps[:, 0, 2]),
559
+ ],
560
+ [
561
+ (ps[:, 2, 0] - ps[:, 0, 0]),
562
+ (ps[:, 2, 1] - ps[:, 0, 1]),
563
+ (ps[:, 2, 2] - ps[:, 0, 2]),
564
+ ],
565
+ [
566
+ (ps[:, 3, 0] - ps[:, 0, 0]),
567
+ (ps[:, 3, 1] - ps[:, 0, 1]),
568
+ (ps[:, 3, 2] - ps[:, 0, 2]),
569
+ ],
570
+ ]
571
+ )
572
+ 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]])
573
+ m = np.swapaxes(m, 0, 2)
574
+ element_gradients = np.linalg.inv(m)
575
+
576
+ element_gradients = element_gradients.swapaxes(1, 2)
577
+ element_gradients = element_gradients @ I
578
+
579
+ return element_gradients[elements, :, :]
580
+
581
+ def get_element_gradient_for_location(self, pos):
582
+ """
583
+ Get the gradient of the tetra for a location
584
+
585
+ Parameters
586
+ ----------
587
+ pos
588
+
589
+ Returns
590
+ -------
591
+
592
+ """
593
+ vertices, _bc, tetras, inside = self.get_element_for_location(pos)
594
+ ps = vertices
595
+ m = np.array(
596
+ [
597
+ [
598
+ (ps[:, 1, 0] - ps[:, 0, 0]),
599
+ (ps[:, 1, 1] - ps[:, 0, 1]),
600
+ (ps[:, 1, 2] - ps[:, 0, 2]),
601
+ ],
602
+ [
603
+ (ps[:, 2, 0] - ps[:, 0, 0]),
604
+ (ps[:, 2, 1] - ps[:, 0, 1]),
605
+ (ps[:, 2, 2] - ps[:, 0, 2]),
606
+ ],
607
+ [
608
+ (ps[:, 3, 0] - ps[:, 0, 0]),
609
+ (ps[:, 3, 1] - ps[:, 0, 1]),
610
+ (ps[:, 3, 2] - ps[:, 0, 2]),
611
+ ],
612
+ ]
613
+ )
614
+ 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]])
615
+ m = np.swapaxes(m, 0, 2)
616
+ element_gradients = np.linalg.inv(m)
617
+
618
+ element_gradients = element_gradients.swapaxes(1, 2)
619
+ element_gradients = element_gradients @ I
620
+ return vertices, element_gradients, tetras, inside
621
+
622
+ def get_neighbours(self):
623
+ """
624
+ This function goes through all of the elements in the mesh and assembles a numpy array
625
+ with the neighbours for each element
626
+
627
+ Returns
628
+ -------
629
+
630
+ """
631
+ return self.neighbours
632
+
633
+ def vtk(self, node_properties=None, cell_properties=None):
634
+ try:
635
+ import pyvista as pv
636
+ except ImportError:
637
+ raise ImportError("pyvista is required for vtk support")
638
+
639
+ if node_properties is None:
640
+ node_properties = {}
641
+ if cell_properties is None:
642
+ cell_properties = {}
643
+ from pyvista import CellType
644
+
645
+ celltype = np.full(self.elements.shape[0], CellType.TETRA, dtype=np.uint8)
646
+ elements = np.hstack(
647
+ [np.zeros(self.elements.shape[0], dtype=int)[:, None] + 4, self.elements]
648
+ )
649
+ elements = elements.flatten()
650
+ grid = pv.UnstructuredGrid(elements, celltype, self.nodes)
651
+ for key, value in node_properties.items():
652
+ grid[key] = value
653
+ for key, value in cell_properties.items():
654
+ grid.cell_arrays[key] = value
655
+
656
+ return grid