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,545 @@
1
+ """
2
+ Cartesian grid for fold interpolator
3
+
4
+ """
5
+
6
+ import logging
7
+
8
+ import numpy as np
9
+
10
+ from ..math.finite_difference_stencil import Operator
11
+ from . import SupportType
12
+ from ._base_support import BaseSupport
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class StructuredGrid2D(BaseSupport):
18
+ """ """
19
+
20
+ dimension = 2
21
+
22
+ def __init__(
23
+ self,
24
+ origin=None,
25
+ nsteps=None,
26
+ step_vector=None,
27
+ ):
28
+ """
29
+
30
+ Parameters
31
+ ----------
32
+ origin - 2d list or numpy array
33
+ nsteps - 2d list or numpy array of ints
34
+ step_vector - 2d list or numpy array of int
35
+ """
36
+ if origin is None:
37
+ origin = np.zeros(2)
38
+ if nsteps is None:
39
+ nsteps = np.array([10, 10])
40
+ if step_vector is None:
41
+ step_vector = np.ones(2)
42
+
43
+ self.type = SupportType.StructuredGrid2D
44
+ self.nsteps = np.ceil(np.array(nsteps)).astype(int)
45
+ self.step_vector = np.array(step_vector)
46
+ self.origin = np.array(origin)
47
+ self.maximum = origin + self.nsteps * self.step_vector
48
+
49
+ self.dim = 2
50
+ self.nsteps_cells = self.nsteps - 1
51
+ self.n_cell_x = self.nsteps[0] - 1
52
+ self.n_cell_y = self.nsteps[1] - 1
53
+ self.properties = {}
54
+
55
+ # calculate the node positions using numpy (this should probably not
56
+ # be stored as it defeats
57
+ # the purpose of a structured grid
58
+
59
+ # self.barycentre = self.cell_centres(np.arange(self.n_elements))
60
+
61
+ self.regions = {}
62
+ self.regions["everywhere"] = np.ones(self.n_nodes).astype(bool)
63
+
64
+ @property
65
+ def nodes(self):
66
+ max = self.origin + self.nsteps_cells * self.step_vector
67
+ x = np.linspace(self.origin[0], max[0], self.nsteps[0])
68
+ y = np.linspace(self.origin[1], max[1], self.nsteps[1])
69
+ xx, yy = np.meshgrid(x, y, indexing="ij")
70
+ return np.array([xx.flatten(order="F"), yy.flatten(order="F")]).T
71
+
72
+ @property
73
+ def n_nodes(self):
74
+ return self.nsteps[0] * self.nsteps[1]
75
+
76
+ def set_nelements(self, nelements) -> int:
77
+ raise NotImplementedError("Cannot set number of elements for 2D structured grid")
78
+
79
+ @property
80
+ def n_elements(self):
81
+ return self.nsteps_cells[0] * self.nsteps_cells[1]
82
+
83
+ @property
84
+ def element_size(self):
85
+ return np.prod(self.step_vector)
86
+
87
+ @property
88
+ def barycentre(self):
89
+ return self.cell_centres(np.arange(self.n_elements))
90
+
91
+ # @property
92
+ # def barycentre(self):
93
+ # return self.cell_centres(np.arange(self.n_elements))
94
+ @property
95
+ def elements(self) -> np.ndarray:
96
+ global_index = np.arange(self.n_elements)
97
+ cell_indexes = self.global_index_to_cell_index(global_index)
98
+
99
+ return self.global_node_indices(self.cell_corner_indexes(cell_indexes))
100
+
101
+ def print_geometry(self):
102
+ print(f"Origin: {self.origin[0]:f} {self.origin[1]:f} {self.origin[2]:f}")
103
+ print(
104
+ f"Cell size: {self.step_vector[0]:f} {self.step_vector[1]:f} {self.step_vector[2]:f}"
105
+ )
106
+ max = self.origin + self.nsteps_cells * self.step_vector
107
+ print(f"Max extent: {max[0]:f} {max[1]:f} {max[2]:f}")
108
+
109
+ def cell_centres(self, global_index: np.ndarray) -> np.ndarray:
110
+ """[summary]
111
+
112
+ [extended_summary]
113
+
114
+ Parameters
115
+ ----------
116
+ global_index : [type]
117
+ [description]
118
+
119
+ Returns
120
+ -------
121
+ [type]
122
+ [description]
123
+ """
124
+ cell_indexes = self.global_index_to_cell_index(global_index)
125
+ cell_centres = np.zeros((cell_indexes.shape[0], 2))
126
+
127
+ cell_centres[:, 0] = (
128
+ self.origin[None, 0]
129
+ + self.step_vector[None, 0] * 0.5
130
+ + self.step_vector[None, 0] * cell_indexes[:, 0]
131
+ )
132
+ cell_centres[:, 1] = (
133
+ self.origin[None, 1]
134
+ + self.step_vector[None, 1] * 0.5
135
+ + self.step_vector[None, 1] * cell_indexes[:, 1]
136
+ )
137
+ return cell_centres
138
+
139
+ def position_to_cell_index(self, pos: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
140
+ """[summary]
141
+
142
+ [extended_summary]
143
+
144
+ Parameters
145
+ ----------
146
+ pos : [type]
147
+ [description]
148
+
149
+ Returns
150
+ -------
151
+ [type]
152
+ [description]
153
+ """
154
+ inside = self.inside(pos)
155
+ cell_indexes = np.zeros((pos.shape[0], 2))
156
+ cell_indexes[:, 0] = pos[:, 0] - self.origin[None, 0]
157
+ cell_indexes[:, 1] = pos[:, 1] - self.origin[None, 1]
158
+ cell_indexes /= self.step_vector[None, :]
159
+ return cell_indexes.astype(int), inside
160
+
161
+ def inside(self, pos: np.ndarray) -> np.ndarray:
162
+ # check whether point is inside box
163
+ inside = np.ones(pos.shape[0]).astype(bool)
164
+ for i in range(self.dim):
165
+ inside *= pos[:, i] > self.origin[None, i]
166
+ inside *= (
167
+ pos[:, i]
168
+ < self.origin[None, i] + self.step_vector[None, i] * self.nsteps_cells[None, i]
169
+ )
170
+ return inside
171
+
172
+ def check_position(self, pos: np.ndarray) -> np.ndarray:
173
+ """[summary]
174
+
175
+ [extended_summary]
176
+
177
+ Parameters
178
+ ----------
179
+ pos : [type]
180
+ [description]
181
+
182
+ Returns
183
+ -------
184
+ [type]
185
+ [description]
186
+ """
187
+
188
+ if len(pos.shape) == 1:
189
+ pos = np.array([pos])
190
+ if len(pos.shape) != 2:
191
+ raise ValueError("Position array needs to be a list of points or a point")
192
+
193
+ return pos
194
+
195
+ def bilinear(self, local_coords: np.ndarray) -> np.ndarray:
196
+ """
197
+ returns the bilinear interpolation for the local coordinates
198
+ Parameters
199
+ ----------
200
+ x - double, array of doubles
201
+ y - double, array of doubles
202
+ z - double, array of doubles
203
+
204
+ Returns
205
+ -------
206
+ array of interpolation coefficients
207
+
208
+ """
209
+
210
+ return np.array(
211
+ [
212
+ (1 - local_coords[:, 0]) * (1 - local_coords[:, 1]),
213
+ local_coords[:, 0] * (1 - local_coords[:, 1]),
214
+ (1 - local_coords[:, 0]) * local_coords[:, 1],
215
+ local_coords[:, 0] * local_coords[:, 1],
216
+ ]
217
+ ).T
218
+
219
+ def position_to_local_coordinates(self, pos: np.ndarray) -> np.ndarray:
220
+ """
221
+ Convert from global to local coordinates within a cel
222
+ Parameters
223
+ ----------
224
+ pos - array of positions inside
225
+
226
+ Returns
227
+ -------
228
+ localx, localy, localz
229
+
230
+ """
231
+ # TODO check if inside mesh
232
+
233
+ # calculate local coordinates for positions
234
+ local_coords = np.zeros(pos.shape)
235
+ local_coords[:, 0] = (
236
+ (pos[:, 0] - self.origin[None, 0]) % self.step_vector[None, 0]
237
+ ) / self.step_vector[None, 0]
238
+ local_coords[:, 1] = (
239
+ (pos[:, 1] - self.origin[None, 1]) % self.step_vector[None, 1]
240
+ ) / self.step_vector[None, 1]
241
+
242
+ return local_coords
243
+
244
+ def position_to_dof_coefs(self, pos: np.ndarray):
245
+ """
246
+ global posotion to interpolation coefficients
247
+ Parameters
248
+ ----------
249
+ pos
250
+
251
+ Returns
252
+ -------
253
+
254
+ """
255
+ local_coords = self.position_to_local_coordinates(pos)
256
+ weights = self.bilinear(local_coords)
257
+ return weights
258
+
259
+ def neighbour_global_indexes(self, mask=None, **kwargs):
260
+ """
261
+ Get neighbour indexes
262
+
263
+ Parameters
264
+ ----------
265
+ kwargs - indexes array specifying the cells to return neighbours
266
+
267
+ Returns
268
+ -------
269
+
270
+ """
271
+ indexes = None
272
+ if "indexes" in kwargs:
273
+ indexes = kwargs["indexes"]
274
+ if "indexes" not in kwargs:
275
+ gi = np.arange(self.n_nodes)
276
+ indexes = self.global_index_to_node_index(gi)
277
+ edge_mask = (
278
+ (indexes[:, 0] > 0)
279
+ & (indexes[:, 0] < self.nsteps[0] - 1)
280
+ & (indexes[:, 1] > 0)
281
+ & (indexes[:, 1] < self.nsteps[1] - 1)
282
+ )
283
+ indexes = indexes[edge_mask, :].T
284
+ # ii = []
285
+ # jj = []
286
+ # for i in range(1, self.nsteps[0] - 1):
287
+ # for j in range(1, self.nsteps[1] - 1):
288
+ # ii.append(i)
289
+ # jj.append(j)
290
+ # indexes = np.array([ii, jj])
291
+ # indexes = np.array(indexes).T
292
+ if indexes.ndim != 2:
293
+ print(indexes.ndim)
294
+ return
295
+ # determine which neighbours to return default is diagonals included.
296
+ if mask is None:
297
+ mask = np.array([[-1, 0, 1, -1, 0, 1, -1, 0, 1], [1, 1, 1, 0, 0, 0, -1, -1, -1]])
298
+ neighbours = indexes[:, None, :] + mask[:, :, None]
299
+ return (neighbours[0, :, :] + self.nsteps[0, None, None] * neighbours[1, :, :]).astype(
300
+ np.int64
301
+ )
302
+
303
+ def cell_corner_indexes(self, cell_indexes: np.ndarray) -> np.ndarray:
304
+ """
305
+ Returns the indexes of the corners of a cell given its location xi,
306
+ yi, zi
307
+
308
+ Parameters
309
+ ----------
310
+ x_cell_index
311
+ y_cell_index
312
+ z_cell_index
313
+
314
+ Returns
315
+ -------
316
+
317
+ """
318
+ corner_indexes = np.zeros((cell_indexes.shape[0], 4, 2), dtype=np.int64)
319
+ xcorner = np.array([0, 1, 0, 1])
320
+ ycorner = np.array([0, 0, 1, 1])
321
+ corner_indexes[:, :, 0] = (
322
+ cell_indexes[:, None, 0] + corner_indexes[:, :, 0] + xcorner[None, :]
323
+ )
324
+ corner_indexes[:, :, 1] = (
325
+ cell_indexes[:, None, 1] + corner_indexes[:, :, 1] + ycorner[None, :]
326
+ )
327
+ return corner_indexes
328
+
329
+ def global_index_to_cell_index(self, global_index):
330
+ """
331
+ Convert from global indexes to xi,yi,zi
332
+
333
+ Parameters
334
+ ----------
335
+ global_index
336
+
337
+ Returns
338
+ -------
339
+
340
+ """
341
+ # determine the ijk indices for the global index.
342
+ # remainder when dividing by nx = i
343
+ # remained when dividing modulus of nx by ny is j
344
+ cell_indexes = np.zeros((global_index.shape[0], 2), dtype=np.int64)
345
+ cell_indexes[:, 0] = global_index % self.nsteps_cells[0, None]
346
+ cell_indexes[:, 1] = global_index // self.nsteps_cells[0, None] % self.nsteps_cells[1, None]
347
+ return cell_indexes
348
+
349
+ def global_index_to_node_index(self, global_index):
350
+ cell_indexes = np.zeros((global_index.shape[0], 2), dtype=np.int64)
351
+ cell_indexes[:, 0] = global_index % self.nsteps[0, None]
352
+ cell_indexes[:, 1] = global_index // self.nsteps[0, None] % self.nsteps[1, None]
353
+ return cell_indexes
354
+
355
+ def _global_indices(self, indexes: np.ndarray, nsteps: np.ndarray) -> np.ndarray:
356
+ if len(indexes.shape) == 1:
357
+ raise ValueError("Indexes must be a 2D array")
358
+ if indexes.shape[-1] != 2:
359
+ raise ValueError("Last dimension of cell indexing needs to be ijk indexing")
360
+ original_shape = indexes.shape
361
+ indexes = indexes.reshape(-1, 2)
362
+ gi = indexes[:, 0] + nsteps[0] * indexes[:, 1]
363
+ return gi.reshape(original_shape[:-1])
364
+
365
+ def global_cell_indices(self, indexes: np.ndarray) -> np.ndarray:
366
+ return self._global_indices(indexes, self.nsteps_cells)
367
+
368
+ def global_node_indices(self, indexes: np.ndarray) -> np.ndarray:
369
+ return self._global_indices(indexes, self.nsteps)
370
+
371
+ def node_indexes_to_position(self, node_indexes: np.ndarray) -> np.ndarray:
372
+
373
+ original_shape = node_indexes.shape
374
+ node_indexes = node_indexes.reshape((-1, 2))
375
+ xy = np.zeros((node_indexes.shape[0], 2), dtype=float)
376
+ xy[:, 0] = self.origin[0] + self.step_vector[0] * node_indexes[:, 0]
377
+ xy[:, 1] = self.origin[1] + self.step_vector[1] * node_indexes[:, 1]
378
+ xy = xy.reshape(original_shape)
379
+ return xy
380
+
381
+ def position_to_cell_corners(self, pos):
382
+ """Get the global indices of the vertices (corner) nodes of the cell containing each point.
383
+
384
+ Parameters
385
+ ----------
386
+ pos : np.array
387
+ (N, 2) array of xy coordinates representing the positions of N points.
388
+
389
+ Returns
390
+ -------
391
+ globalidx : np.array
392
+ (N, 4) array of global indices corresponding to the 4 corner nodes of the cell
393
+ each point lies in. If a point lies outside the support, its corresponding entry
394
+ will be set to -1.
395
+ inside : np.array
396
+ (N,) boolean array indicating whether each point is inside the support domain.
397
+ """
398
+ corner_index, inside = self.position_to_cell_index(pos)
399
+ corners = self.cell_corner_indexes(corner_index)
400
+ globalidx = self.global_node_indices(corners)
401
+ # if global index is not inside the support set to -1
402
+ globalidx[~inside] = -1
403
+ return globalidx, inside
404
+
405
+ def evaluate_value(self, evaluation_points: np.ndarray, property_array: np.ndarray):
406
+ """
407
+ Evaluate the value of of the property at the locations.
408
+ Trilinear interpolation dot corner values
409
+
410
+ Parameters
411
+ ----------
412
+ evaluation_points np array of locations
413
+ property_name string of property name
414
+
415
+ Returns
416
+ -------
417
+
418
+ """
419
+ idc, inside = self.position_to_cell_corners(evaluation_points)
420
+ v = np.zeros(idc.shape)
421
+ v[:, :] = np.nan
422
+
423
+ v[inside, :] = self.position_to_dof_coefs(evaluation_points[inside, :])
424
+ v[inside, :] *= property_array[idc[inside, :]]
425
+ return np.sum(v, axis=1)
426
+
427
+ def evaluate_gradient(self, evaluation_points, property_array):
428
+ T = np.zeros((evaluation_points.shape[0], 2, 4))
429
+ _vertices, T, elements, inside = self.get_element_gradient_for_location(evaluation_points)
430
+ # indices = np.array([self.position_to_cell_index(evaluation_points)])
431
+ # idc = self.global_indicies(indices.swapaxes(0,1))
432
+ # print(idc)
433
+ T[inside, 0, :] *= property_array[self.elements[elements[inside]]]
434
+ T[inside, 1, :] *= property_array[self.elements[elements[inside]]]
435
+ # T[inside, 2, :] *= self.properties[property_name][idc[inside, :]]
436
+ return np.array([np.sum(T[:, 0, :], axis=1), np.sum(T[:, 1, :], axis=1)]).T
437
+
438
+ def get_element_gradient_for_location(
439
+ self, pos
440
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
441
+ """
442
+ Calculates the gradient matrix at location pos
443
+ :param pos: numpy array of location Nx3
444
+ :return: Nx3x4 matrix
445
+ """
446
+ pos = np.asarray(pos)
447
+ T = np.zeros((pos.shape[0], 2, 4))
448
+ local_coords = self.position_to_local_coordinates(pos)
449
+ vertices, inside = self.position_to_cell_corners(pos)
450
+ elements, inside = self.position_to_cell_index(pos)
451
+ elements = self.global_cell_indices(elements)
452
+
453
+ T[:, 0, 0] = -(1 - local_coords[:, 1])
454
+ T[:, 0, 1] = 1 - local_coords[:, 1]
455
+ T[:, 0, 2] = -local_coords[:, 1]
456
+ T[:, 0, 3] = local_coords[:, 1]
457
+
458
+ T[:, 1, 0] = -(1 - local_coords[:, 0])
459
+ T[:, 1, 1] = -local_coords[:, 0]
460
+ T[:, 1, 2] = 1 - local_coords[:, 0]
461
+ T[:, 1, 3] = local_coords[:, 0]
462
+
463
+ return vertices, T, elements, inside
464
+
465
+ def get_element_for_location(
466
+ self, pos: np.ndarray
467
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
468
+
469
+ vertices, inside = self.position_to_cell_vertices(pos)
470
+ vertices = np.array(vertices)
471
+ # print("ver", vertices.shape)
472
+ # vertices = vertices.reshape((vertices.shape[1], 8, 3))
473
+ elements, inside = self.position_to_cell_corners(pos)
474
+ elements, inside = self.position_to_cell_index(pos)
475
+ elements = self.global_cell_indices(elements)
476
+ a = self.position_to_dof_coefs(pos)
477
+ return vertices, a, elements, inside
478
+
479
+ def position_to_cell_vertices(self, pos):
480
+ """Get the vertices of the cell a point is in
481
+
482
+ Parameters
483
+ ----------
484
+ pos : np.array
485
+ Nx3 array of xyz locations
486
+
487
+ Returns
488
+ -------
489
+ np.array((N,3),dtype=float), np.array(N,dtype=int)
490
+ vertices, inside
491
+ """
492
+ gi, inside = self.position_to_cell_corners(pos)
493
+
494
+ node_indexes = self.global_index_to_node_index(gi.flatten())
495
+ return self.node_indexes_to_position(node_indexes), inside
496
+
497
+ def onGeometryChange(self):
498
+ pass
499
+
500
+ def vtk(self, z, *, node_properties=None, cell_properties=None):
501
+ """
502
+ Create a vtk unstructured grid from the mesh
503
+ """
504
+ import pyvista as pv
505
+ from pyvista import CellType
506
+
507
+ if node_properties is None:
508
+ node_properties = {}
509
+ if cell_properties is None:
510
+ cell_properties = {}
511
+ points = np.zeros((self.n_nodes, 3))
512
+ points[:, :2] = self.nodes
513
+ points[:, 2] = z
514
+ celltype = np.full(self.n_elements, CellType.QUAD, dtype=np.uint8)
515
+ vtk_elements = self.elements[:, [0, 1, 3, 2]]
516
+ elements = np.hstack(
517
+ [np.full((vtk_elements.shape[0], 1), 4, dtype=int), vtk_elements.astype(np.int64)]
518
+ ).ravel()
519
+ grid = pv.UnstructuredGrid(elements, celltype, points)
520
+ for key, value in node_properties.items():
521
+ grid.point_data[key] = value
522
+ for key, value in cell_properties.items():
523
+ grid.cell_data[key] = value
524
+ return grid
525
+
526
+ def get_operators(self, weights: dict[str, float]) -> dict[str, tuple[np.ndarray, float]]:
527
+ """Get
528
+
529
+ Parameters
530
+ ----------
531
+ weights : Dict[str, float]
532
+ _description_
533
+
534
+ Returns
535
+ -------
536
+ Dict[str, Tuple[np.ndarray, float]]
537
+ _description_
538
+ """
539
+ # in a map we only want the xy operators
540
+ operators = {
541
+ "dxy": (Operator.Dxy_mask[1, :, :], weights["dxy"] * 2),
542
+ "dxx": (Operator.Dxx_mask[1, :, :], weights["dxx"]),
543
+ "dyy": (Operator.Dyy_mask[1, :, :], weights["dyy"]),
544
+ }
545
+ return operators