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,374 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ from . import SupportType
6
+ from ._3d_structured_tetra import TetMesh
7
+ from ._3d_unstructured_tetra import UnStructuredTetMesh
8
+
9
+
10
+ class P2UnstructuredTetMesh(UnStructuredTetMesh):
11
+ def __init__(
12
+ self,
13
+ nodes: np.ndarray | None = None,
14
+ elements: np.ndarray | None = None,
15
+ neighbours: np.ndarray | None = None,
16
+ aabb_nsteps=None,
17
+ origin: np.ndarray | None = None,
18
+ step_vector: np.ndarray | None = None,
19
+ nsteps_cells: np.ndarray | None = None,
20
+ ):
21
+ if nodes is None or elements is None or neighbours is None:
22
+ if origin is None or step_vector is None or nsteps_cells is None:
23
+ raise ValueError(
24
+ "P2UnstructuredTetMesh requires either explicit nodes/elements/"
25
+ "neighbours arrays, or origin/step_vector/nsteps_cells to build a "
26
+ "quadratic tetrahedral mesh over a bounding box"
27
+ )
28
+ nodes, elements, neighbours = self._build_from_bbox(origin, step_vector, nsteps_cells)
29
+ UnStructuredTetMesh.__init__(self, nodes, elements, neighbours, aabb_nsteps)
30
+ self.type = SupportType.P2UnstructuredTetMesh
31
+ if self.elements.shape[1] != 10:
32
+ raise ValueError(f"P2 tetrahedron must have 10 nodes, has {self.elements.shape[1]}")
33
+ self.hessian = np.array(
34
+ [
35
+ [
36
+ [4, 4, 0, 0, 0, 0, -8, 0, 0, 0],
37
+ [4, 0, 0, 0, 0, 0, -4, 4, 0, -4],
38
+ [4, 0, 0, 0, 0, -4, -4, 0, 4, 0],
39
+ ],
40
+ [
41
+ [4, 0, 0, 0, 0, 0, -4, 4, 0, -4],
42
+ [4, 0, 4, 0, 0, 0, 0, 0, 0, -8],
43
+ [4, 0, 0, 0, 4, -4, 0, 0, 0, -4],
44
+ ],
45
+ [
46
+ [4, 0, 0, 0, 0, -4, -4, 0, 4, 0],
47
+ [4, 0, 0, 0, 4, -4, 0, 0, 0, -4],
48
+ [4, 0, 0, 4, 0, -8, 0, 0, 0, 0],
49
+ ],
50
+ ]
51
+ )
52
+
53
+ @staticmethod
54
+ def _build_from_bbox(origin: np.ndarray, step_vector: np.ndarray, nsteps_cells: np.ndarray):
55
+ """Build a quadratic (10-node) tetrahedral mesh over a structured grid.
56
+
57
+ Tessellates the grid into linear tets and adds a deduplicated midpoint node for each edge.
58
+ """
59
+ p1 = TetMesh(origin=origin, nsteps_cells=nsteps_cells, step_vector=step_vector)
60
+ p1_nodes = p1.nodes
61
+ p1_elements = p1.elements
62
+ p1_neighbours = p1.neighbours
63
+
64
+ local_edges = np.array([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]])
65
+ local_index_for_edge = [6, 9, 5, 7, 8, 4]
66
+
67
+ n_elements = p1_elements.shape[0]
68
+ edge_nodes = p1_elements[:, local_edges]
69
+ edge_nodes_sorted = np.sort(edge_nodes, axis=2)
70
+ flat_edges = edge_nodes_sorted.reshape(-1, 2)
71
+
72
+ unique_edges, inverse = np.unique(flat_edges, axis=0, return_inverse=True)
73
+ midpoint_nodes = (p1_nodes[unique_edges[:, 0]] + p1_nodes[unique_edges[:, 1]]) / 2.0
74
+
75
+ all_nodes = np.vstack([p1_nodes, midpoint_nodes])
76
+ edge_node_index = p1_nodes.shape[0] + inverse.reshape(n_elements, 6)
77
+
78
+ p2_elements = np.zeros((n_elements, 10), dtype=p1_elements.dtype)
79
+ p2_elements[:, :4] = p1_elements
80
+ for edge_i, local_idx in enumerate(local_index_for_edge):
81
+ p2_elements[:, local_idx] = edge_node_index[:, edge_i]
82
+
83
+ return all_nodes, p2_elements, p1_neighbours
84
+
85
+ def get_quadrature_points(self, npts: int = 3):
86
+ """Calculate the quadrature points for the triangle using 3 points
87
+ these points are at the barycentric coordinates of (1/6,1/6), (1/6,2/3), (2/3,1/6)
88
+ All points are weighted equally at 1/6
89
+
90
+ Parameters
91
+ ----------
92
+ npts : int, optional
93
+ _description_, by default 3
94
+
95
+ Returns
96
+ -------
97
+ _type_
98
+ _description_
99
+ """
100
+ if npts == 3:
101
+ vertices = self.nodes[self.shared_elements]
102
+ cp = np.zeros((vertices.shape[0], 3, 3))
103
+ reference_points = np.array([[1 / 6, 2 / 3, 1 / 6], [1 / 6, 1 / 6, 2 / 3]])
104
+
105
+ cp[:, 0, :] = (
106
+ vertices[:, 0, :] * (1 - reference_points[0, 0] - reference_points[1, 0])
107
+ + vertices[:, 1, :] * (reference_points[0, 0])
108
+ + vertices[:, 2, :] * (reference_points[1, 0])
109
+ )
110
+ cp[:, 1, :] = (
111
+ vertices[:, 0, :] * (1 - reference_points[0, 1] - reference_points[1, 1])
112
+ + vertices[:, 1, :] * (reference_points[0, 1])
113
+ + vertices[:, 2, :] * (reference_points[1, 1])
114
+ )
115
+ cp[:, 2, :] = (
116
+ vertices[:, 0, :] * (1 - reference_points[0, 2] - reference_points[1, 2])
117
+ + vertices[:, 1, :] * (reference_points[0, 2])
118
+ + vertices[:, 2, :] * (reference_points[1, 2])
119
+ )
120
+ weights = np.zeros((vertices.shape[0], 3))
121
+ weights[:, :] = 1 / 6
122
+ return cp, weights
123
+ if npts == 1:
124
+ vertices = self.nodes[self.shared_elements]
125
+ cp = np.zeros((vertices.shape[0], 1, 3))
126
+ reference_points = np.array([[1 / 3], [1 / 3]])
127
+
128
+ cp[:, 0, :] = (
129
+ vertices[:, 0, :] * (1 - reference_points[0, 0] - reference_points[1, 0])
130
+ + vertices[:, 1, :] * (reference_points[0, 0])
131
+ + vertices[:, 2, :] * (reference_points[1, 0])
132
+ )
133
+ weights = np.zeros((vertices.shape[0], 1))
134
+ weights[:, :] = 1 / 2
135
+ return cp, weights
136
+
137
+ def evaluate_shape_d2(self, indexes: np.ndarray) -> np.ndarray:
138
+ """Evaluate second derivatives of shape functions in s and t
139
+
140
+ Parameters
141
+ ----------
142
+ indexes : np.ndarray
143
+ array of indexes
144
+
145
+ Returns
146
+ -------
147
+ np.array
148
+ array of second derivative shape function
149
+ """
150
+ vertices = self.nodes[self.elements[indexes], :]
151
+
152
+ jac = np.array(
153
+ [
154
+ [
155
+ (vertices[:, 1, 0] - vertices[:, 0, 0]),
156
+ (vertices[:, 1, 1] - vertices[:, 0, 1]),
157
+ (vertices[:, 1, 2] - vertices[:, 0, 2]),
158
+ ],
159
+ [
160
+ (vertices[:, 2, 0] - vertices[:, 0, 0]),
161
+ (vertices[:, 2, 1] - vertices[:, 0, 1]),
162
+ (vertices[:, 2, 2] - vertices[:, 0, 2]),
163
+ ],
164
+ [
165
+ (vertices[:, 3, 0] - vertices[:, 0, 0]),
166
+ (vertices[:, 3, 1] - vertices[:, 0, 1]),
167
+ (vertices[:, 3, 2] - vertices[:, 0, 2]),
168
+ ],
169
+ ]
170
+ )
171
+ jac = jac.swapaxes(0, 2)
172
+ jac = jac.swapaxes(1, 2)
173
+ jac = np.linalg.inv(jac)
174
+ # calculate derivative by summation
175
+ d2 = np.zeros((vertices.shape[0], 6, self.elements.shape[1]))
176
+ ii = 0
177
+ for i in range(3):
178
+ for j in range(i, 3):
179
+ for k in range(3):
180
+ for l in range(3):
181
+ d2[:, ii, :] += (
182
+ jac[:, i, k, None] * jac[:, j, l, None] * self.hessian[None, k, l, :]
183
+ )
184
+ ii += 1
185
+ return d2
186
+
187
+ def evaluate_shape_derivatives(
188
+ self, locations: np.ndarray, elements: np.ndarray = None
189
+ ) -> np.ndarray:
190
+ """
191
+ Compute dN/ds (1st row), dN/dt(2nd row)
192
+
193
+ Parameters
194
+ ----------
195
+ locations : np.array
196
+ location (n,3) array
197
+ elements : np.array, optional
198
+ indexes to calculate shape function for. Used when evaluating quad points
199
+ on faces as two tetra hold the point by default None
200
+ When it is none, the index is calculated from the location
201
+
202
+ Returns
203
+ -------
204
+ np.array
205
+ array of shape paramters
206
+ """
207
+ locations = np.array(locations)
208
+ if elements is None:
209
+ verts, c, elements, _inside = self.get_element_for_location(locations)
210
+ else:
211
+ M = np.ones((elements.shape[0], 4, 4))
212
+ M[:, :, 1:] = self.nodes[self.elements[elements], :][:, :4, :]
213
+ points_ = np.ones((locations.shape[0], 4))
214
+ points_[:, 1:] = locations
215
+ minv = np.linalg.inv(M)
216
+ c = np.einsum("lij,li->lj", minv, points_)
217
+ verts = self.nodes[self.elements[elements][:, :4]]
218
+ jac = np.array(
219
+ [
220
+ [
221
+ (verts[:, 1, 0] - verts[:, 0, 0]),
222
+ (verts[:, 1, 1] - verts[:, 0, 1]),
223
+ (verts[:, 1, 2] - verts[:, 0, 2]),
224
+ ],
225
+ [
226
+ (verts[:, 2, 0] - verts[:, 0, 0]),
227
+ (verts[:, 2, 1] - verts[:, 0, 1]),
228
+ (verts[:, 2, 2] - verts[:, 0, 2]),
229
+ ],
230
+ [
231
+ (verts[:, 3, 0] - verts[:, 0, 0]),
232
+ (verts[:, 3, 1] - verts[:, 0, 1]),
233
+ (verts[:, 3, 2] - verts[:, 0, 2]),
234
+ ],
235
+ ]
236
+ )
237
+ r = c[:, 1]
238
+ s = c[:, 2]
239
+ t = c[:, 3]
240
+ jac = np.swapaxes(jac, 0, 2)
241
+ # dN containts the derivatives of the shape functions
242
+ dN = np.zeros((elements.shape[0], 3, 10))
243
+
244
+ dN[:, 0, 0] = 4 * r + 4 * s + 4 * t - 3
245
+ dN[:, 0, 1] = 4 * r - 1
246
+ dN[:, 0, 2] = 0
247
+ dN[:, 0, 3] = 0
248
+ dN[:, 0, 4] = 0
249
+ dN[:, 0, 5] = -4 * t
250
+ dN[:, 0, 6] = -8 * r - 4 * s - 4 * t + 4
251
+ dN[:, 0, 7] = 4 * s
252
+ dN[:, 0, 8] = 4 * t
253
+ dN[:, 0, 9] = -4 * s
254
+
255
+ dN[:, 1, 0] = 4 * r + 4 * s + 4 * t - 3
256
+ dN[:, 1, 1] = 0
257
+ dN[:, 1, 2] = 4 * s - 1
258
+ dN[:, 1, 3] = 0
259
+ dN[:, 1, 4] = 4 * t
260
+ dN[:, 1, 5] = -4 * t
261
+ dN[:, 1, 6] = -4 * r
262
+ dN[:, 1, 7] = 4 * r
263
+ dN[:, 1, 8] = -0
264
+ dN[:, 1, 9] = -4 * r - 8 * s - 4 * t + 4
265
+
266
+ dN[:, 2, 0] = 4 * r + 4 * s + 4 * t - 3
267
+ dN[:, 2, 1] = 0
268
+ dN[:, 2, 2] = 0
269
+ dN[:, 2, 3] = 4 * t - 1
270
+ dN[:, 2, 4] = 4 * s
271
+ dN[:, 2, 5] = -4 * r - 4 * s - 8 * t + 4
272
+ dN[:, 2, 6] = -4 * r
273
+ dN[:, 2, 7] = 0
274
+ dN[:, 2, 8] = 4 * r
275
+ dN[:, 2, 9] = -4 * s
276
+
277
+ # find the derivatives in x and y by calculating the dot product between the jacobian^-1 and the
278
+ # derivative matrix
279
+ # d_n = np.einsum('ijk,ijl->ilk',np.linalg.inv(jac),dN)
280
+ d_n = np.linalg.inv(jac)
281
+ # d_n = d_n.swapaxes(1,2)
282
+ d_n = d_n.swapaxes(1, 2)
283
+ d_n = d_n @ dN
284
+ # d_n = np.dot(np.linalg.inv(jac),dN)
285
+ return d_n, elements
286
+
287
+ def evaluate_shape(self, locations: np.ndarray):
288
+ locations = np.array(locations)
289
+ _verts, c, elements, inside = self.get_element_for_location(locations)
290
+ # order of bary coord is (1-s-t,s,t)
291
+ N = np.zeros((c.shape[0], 10)) # evaluate shape functions at barycentric coordinates
292
+
293
+ for i in range(c.shape[1]):
294
+ N[:, i] = (2 * c[:, i] - 1) * c[:, i]
295
+
296
+ N[:, 4] = 4 * c[:, 3] * c[:, 2]
297
+ N[:, 5] = 4 * c[:, 0] * c[:, 3]
298
+ N[:, 6] = 4 * c[:, 0] * c[:, 1]
299
+ N[:, 7] = 4 * c[:, 1] * c[:, 2]
300
+ N[:, 8] = 4 * c[:, 1] * c[:, 3]
301
+ N[:, 9] = 4 * c[:, 0] * c[:, 2]
302
+ # inside = np.all(c>0,axis=1)
303
+ return N, elements, inside
304
+
305
+ def evaluate_d2(self, pos: np.ndarray, prop: np.ndarray) -> np.ndarray:
306
+ """
307
+ Evaluate the second derivative of the interpolant
308
+ d2x, dxdy, d2y, dxdz dydz d2dz
309
+
310
+ Parameters
311
+ ----------
312
+ pos - numpy array
313
+ locations
314
+ prop - numpy array
315
+ property values at nodes
316
+
317
+ Returns
318
+ -------
319
+
320
+ """
321
+ _c, tri, inside = self.evaluate_shape(pos)
322
+ d2 = self.evaluate_shape_d2(tri)
323
+ values = np.zeros((pos.shape[0], d2.shape[1]))
324
+ values[:] = np.nan
325
+
326
+ for i in range(d2.shape[1]):
327
+ values[inside, i] = np.sum(
328
+ d2[inside, i, :] * prop[self.elements[tri[inside], :]],
329
+ axis=1,
330
+ )
331
+
332
+ return values
333
+
334
+ def evaluate_value(self, pos: np.ndarray, property_array: np.ndarray) -> np.ndarray:
335
+ """
336
+ Evaluate value of interpolant
337
+
338
+ Parameters
339
+ ----------
340
+ pos - numpy array
341
+ locations
342
+ prop - string
343
+ property name
344
+
345
+ Returns
346
+ -------
347
+
348
+ """
349
+ if len(pos.shape) != 2 or pos.shape[1] != 3:
350
+ raise ValueError(f"pos must be a numpy array of shape (n,3), shape is {pos.shape}")
351
+ if property_array.shape[0] != self.n_nodes:
352
+ raise ValueError("property array must have same length as nodes")
353
+ values = np.zeros(pos.shape[0])
354
+ values[:] = np.nan
355
+ N, tetras, inside = self.evaluate_shape(pos)
356
+ values[inside] = np.sum(
357
+ N[inside, :] * property_array[self.elements[tetras][inside, :]], axis=1
358
+ )
359
+ return values
360
+
361
+ def evaluate_gradient(self, pos: np.ndarray, property_array: np.ndarray) -> np.ndarray:
362
+ if len(pos.shape) != 2 or pos.shape[1] != 3:
363
+ raise ValueError(f"pos must be a numpy array of shape (n,3), shape is {pos.shape}")
364
+ if property_array.shape[0] != self.n_nodes:
365
+ raise ValueError("property array must have same length as nodes")
366
+ values = np.zeros(pos.shape)
367
+ values[:] = np.nan
368
+ element_gradients, tetra = self.evaluate_shape_derivatives(pos[:, :3])
369
+ inside = tetra >= 0
370
+ values[inside, :] = (
371
+ element_gradients[:, :, :] * property_array[self.elements[tetra[inside], None, :]]
372
+ ).sum(2)
373
+
374
+ return values
@@ -0,0 +1,315 @@
1
+ """
2
+ Rectilinear grid support for finite difference interpolation.
3
+
4
+ A rectilinear grid has the same topology as a structured grid, but allows
5
+ varying cell sizes along each axis. Node positions along each axis are
6
+ specified explicitly as monotonically increasing 1-D arrays.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+
13
+ from ..logging import get_logger as getLogger
14
+ from . import SupportType
15
+ from ._3d_structured_grid import StructuredGrid
16
+
17
+ logger = getLogger(__name__)
18
+
19
+
20
+ class RectilinearGrid(StructuredGrid):
21
+ """A rectilinear (non-uniformly spaced) 3-D structured grid.
22
+
23
+ Unlike :class:`StructuredGrid`, the spacing between nodes may differ from
24
+ cell to cell. Node positions are given as three 1-D arrays *xnodes*,
25
+ *ynodes*, *znodes* (strictly increasing).
26
+
27
+ Parameters
28
+ ----------
29
+ xnodes, ynodes, znodes : array-like
30
+ Node positions along each axis (must be strictly increasing).
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ xnodes: np.ndarray,
36
+ ynodes: np.ndarray,
37
+ znodes: np.ndarray,
38
+ ):
39
+ xnodes = np.asarray(xnodes, dtype=float)
40
+ ynodes = np.asarray(ynodes, dtype=float)
41
+ znodes = np.asarray(znodes, dtype=float)
42
+
43
+ if xnodes.ndim != 1 or ynodes.ndim != 1 or znodes.ndim != 1:
44
+ raise ValueError("Node arrays must be 1-D.")
45
+
46
+ self._xnodes = xnodes
47
+ self._ynodes = ynodes
48
+ self._znodes = znodes
49
+
50
+ nsteps = np.array([len(xnodes) - 1, len(ynodes) - 1, len(znodes) - 1], dtype=int)
51
+ origin = np.array([xnodes[0], ynodes[0], znodes[0]])
52
+ with np.errstate(divide="ignore", invalid="ignore"):
53
+ extent = np.array(
54
+ [xnodes[-1] - xnodes[0], ynodes[-1] - ynodes[0], znodes[-1] - znodes[0]]
55
+ )
56
+ step_vector = np.where(nsteps > 0, extent / nsteps, 1.0)
57
+
58
+ from ._3d_base_structured import BaseStructuredSupport
59
+
60
+ BaseStructuredSupport.__init__(self, origin=origin, nsteps=nsteps, step_vector=step_vector)
61
+ self.type = SupportType.RectilinearGrid
62
+ self.regions = {}
63
+ self.regions["everywhere"] = np.ones(self.n_nodes).astype(bool)
64
+
65
+ # ------------------------------------------------------------------
66
+ # Node-array accessors
67
+ # ------------------------------------------------------------------
68
+
69
+ @property
70
+ def xnodes(self) -> np.ndarray:
71
+ return self._xnodes
72
+
73
+ @property
74
+ def ynodes(self) -> np.ndarray:
75
+ return self._ynodes
76
+
77
+ @property
78
+ def znodes(self) -> np.ndarray:
79
+ return self._znodes
80
+
81
+ def onGeometryChange(self):
82
+ if self.interpolator is not None:
83
+ self.interpolator.reset()
84
+
85
+ # ------------------------------------------------------------------
86
+ # Override geometry properties
87
+ # ------------------------------------------------------------------
88
+
89
+ @property
90
+ def nodes(self) -> np.ndarray:
91
+ """Return all node positions as an (n_nodes, 3) array (Fortran order)."""
92
+ xx, yy, zz = np.meshgrid(self._xnodes, self._ynodes, self._znodes, indexing="ij")
93
+ return np.column_stack([xx.ravel(order="F"), yy.ravel(order="F"), zz.ravel(order="F")])
94
+
95
+ @property
96
+ def maximum(self) -> np.ndarray:
97
+ return np.array([self._xnodes[-1], self._ynodes[-1], self._znodes[-1]])
98
+
99
+ @property
100
+ def barycentre(self) -> np.ndarray:
101
+ return self.cell_centres(np.arange(self.n_elements))
102
+
103
+ def cell_centres(self, global_index: np.ndarray) -> np.ndarray:
104
+ global_index = np.asarray(global_index)
105
+ cell_idx = self.global_index_to_cell_index(global_index)
106
+ cx = 0.5 * (self._xnodes[cell_idx[:, 0]] + self._xnodes[cell_idx[:, 0] + 1])
107
+ cy = 0.5 * (self._ynodes[cell_idx[:, 1]] + self._ynodes[cell_idx[:, 1] + 1])
108
+ cz = 0.5 * (self._znodes[cell_idx[:, 2]] + self._znodes[cell_idx[:, 2] + 1])
109
+ return np.column_stack([cx, cy, cz])
110
+
111
+ # ------------------------------------------------------------------
112
+ # Geometry: position to cell index
113
+ # ------------------------------------------------------------------
114
+
115
+ def inside(self, pos: np.ndarray) -> np.ndarray:
116
+ return np.all((pos > self.origin[None, :]) & (pos < self.maximum[None, :]), axis=1)
117
+
118
+ def position_to_cell_index(self, pos: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
119
+ """Return (i,j,k) cell indices and an *inside* boolean mask."""
120
+ pos = self.check_position(pos)
121
+ inside = self.inside(pos)
122
+
123
+ cell_idx = np.zeros((pos.shape[0], 3), dtype=int)
124
+ for dim, nodes in enumerate((self._xnodes, self._ynodes, self._znodes)):
125
+ idx = np.searchsorted(nodes, pos[:, dim], side="right") - 1
126
+ n_cells = len(nodes) - 1
127
+ idx = np.clip(idx, 0, n_cells - 1)
128
+ cell_idx[:, dim] = idx
129
+
130
+ return cell_idx, inside
131
+
132
+ def node_indexes_to_position(self, node_indexes: np.ndarray) -> np.ndarray:
133
+ original_shape = node_indexes.shape
134
+ ni = node_indexes.reshape((-1, 3))
135
+ xyz = np.zeros((ni.shape[0], 3), dtype=float)
136
+ xyz[:, 0] = self._xnodes[np.clip(ni[:, 0], 0, len(self._xnodes) - 1)]
137
+ xyz[:, 1] = self._ynodes[np.clip(ni[:, 1], 0, len(self._ynodes) - 1)]
138
+ xyz[:, 2] = self._znodes[np.clip(ni[:, 2], 0, len(self._znodes) - 1)]
139
+ return xyz.reshape(original_shape)
140
+
141
+ # ------------------------------------------------------------------
142
+ # Local coordinates within a cell (0 -> 1 per axis)
143
+ # ------------------------------------------------------------------
144
+
145
+ def position_to_local_coordinates(self, pos: np.ndarray) -> np.ndarray:
146
+ pos = np.asarray(pos)
147
+ cell_idx, _ = self.position_to_cell_index(pos)
148
+ local = np.zeros(pos.shape)
149
+ for dim, nodes in enumerate((self._xnodes, self._ynodes, self._znodes)):
150
+ x0 = nodes[cell_idx[:, dim]]
151
+ x1 = nodes[np.minimum(cell_idx[:, dim] + 1, len(nodes) - 1)]
152
+ h = x1 - x0
153
+ h = np.where(h == 0, 1.0, h)
154
+ local[:, dim] = (pos[:, dim] - x0) / h
155
+ return local
156
+
157
+ # ------------------------------------------------------------------
158
+ # Gradient of shape functions
159
+ # ------------------------------------------------------------------
160
+
161
+ def get_element_gradient_for_location(
162
+ self, pos: np.ndarray
163
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
164
+ """Return (vertices, T, elements, inside) with T of shape (N, 3, 8).
165
+
166
+ T correctly accounts for local cell size so that
167
+ T[:, d, :] * node_values approximates df/dx_d at *pos*.
168
+ """
169
+ pos = np.asarray(pos)
170
+ T = np.zeros((pos.shape[0], 3, 8))
171
+ local_coords = self.position_to_local_coordinates(pos)
172
+ vertices, inside = self.position_to_cell_vertices(pos)
173
+ elements, inside = self.position_to_cell_index(pos)
174
+ elements_global = self.global_cell_indices(elements)
175
+
176
+ c = local_coords
177
+
178
+ T[:, 0, 0] = (1 - c[:, 2]) * (c[:, 1] - 1)
179
+ T[:, 0, 1] = (1 - c[:, 1]) * (1 - c[:, 2])
180
+ T[:, 0, 2] = -c[:, 1] * (1 - c[:, 2])
181
+ T[:, 0, 4] = -(1 - c[:, 1]) * c[:, 2]
182
+ T[:, 0, 5] = (1 - c[:, 1]) * c[:, 2]
183
+ T[:, 0, 6] = -c[:, 1] * c[:, 2]
184
+ T[:, 0, 3] = c[:, 1] * (1 - c[:, 2])
185
+ T[:, 0, 7] = c[:, 1] * c[:, 2]
186
+
187
+ T[:, 1, 0] = (c[:, 0] - 1) * (1 - c[:, 2])
188
+ T[:, 1, 1] = -c[:, 0] * (1 - c[:, 2])
189
+ T[:, 1, 2] = (1 - c[:, 0]) * (1 - c[:, 2])
190
+ T[:, 1, 4] = -(1 - c[:, 0]) * c[:, 2]
191
+ T[:, 1, 5] = -c[:, 0] * c[:, 2]
192
+ T[:, 1, 6] = (1 - c[:, 0]) * c[:, 2]
193
+ T[:, 1, 3] = c[:, 0] * (1 - c[:, 2])
194
+ T[:, 1, 7] = c[:, 0] * c[:, 2]
195
+
196
+ T[:, 2, 0] = -(1 - c[:, 0]) * (1 - c[:, 1])
197
+ T[:, 2, 1] = -c[:, 0] * (1 - c[:, 1])
198
+ T[:, 2, 2] = -(1 - c[:, 0]) * c[:, 1]
199
+ T[:, 2, 4] = (1 - c[:, 0]) * (1 - c[:, 1])
200
+ T[:, 2, 5] = c[:, 0] * (1 - c[:, 1])
201
+ T[:, 2, 6] = (1 - c[:, 0]) * c[:, 1]
202
+ T[:, 2, 3] = -c[:, 0] * c[:, 1]
203
+ T[:, 2, 7] = c[:, 0] * c[:, 1]
204
+
205
+ # Chain rule: dN/dx = dN/d(local) / h
206
+ for dim, nodes in enumerate((self._xnodes, self._ynodes, self._znodes)):
207
+ h = nodes[elements[:, dim] + 1] - nodes[elements[:, dim]]
208
+ h = np.where(h == 0, 1.0, h)
209
+ T[:, dim, :] /= h[:, None]
210
+
211
+ return vertices, T, elements_global, inside
212
+
213
+ # ------------------------------------------------------------------
214
+ # FD regularisation operators
215
+ # ------------------------------------------------------------------
216
+
217
+ def get_operators(self, weights: dict[str, float]) -> dict[str, tuple]:
218
+ """Return rectilinear FD operators.
219
+
220
+ The mask is ``None`` to signal to the FD interpolator that it should
221
+ call :meth:`build_scaled_operator_rows` instead of the fixed stencil.
222
+ """
223
+ return {
224
+ "dxx": (None, weights["dxx"]),
225
+ "dyy": (None, weights["dyy"]),
226
+ "dzz": (None, weights["dzz"]),
227
+ "dxy": (None, weights["dxy"] / 4),
228
+ "dyz": (None, weights["dyz"] / 4),
229
+ "dxz": (None, weights["dxz"] / 4),
230
+ }
231
+
232
+ def build_scaled_operator_rows(
233
+ self, axis: int, cross_axis: int = -1
234
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
235
+ """Build per-node FD stencil rows scaled for non-uniform spacing.
236
+
237
+ Parameters
238
+ ----------
239
+ axis : int
240
+ Primary axis (0=x, 1=y, 2=z).
241
+ cross_axis : int
242
+ If >= 0 and != axis, build d^2/(d_axis d_cross_axis).
243
+ Otherwise, build d^2/d_axis^2.
244
+
245
+ Returns
246
+ -------
247
+ A_values : (n_interior, n_stencil_pts)
248
+ col_global_idx : (n_interior, n_stencil_pts)
249
+ row_node_idx : (n_interior,)
250
+ """
251
+ nodes_list = (self._xnodes, self._ynodes, self._znodes)
252
+ nsteps = self.nsteps # number of *nodes* per axis
253
+
254
+ gi_all = np.arange(self.n_nodes)
255
+ ijk = self.global_index_to_node_index(gi_all) # (n_nodes, 3)
256
+
257
+ interior_mask = np.ones(self.n_nodes, dtype=bool)
258
+ pure = cross_axis < 0 or cross_axis == axis
259
+ if pure:
260
+ interior_mask &= (ijk[:, axis] > 0) & (ijk[:, axis] < nsteps[axis] - 1)
261
+ else:
262
+ for ax in (axis, cross_axis):
263
+ interior_mask &= (ijk[:, ax] > 0) & (ijk[:, ax] < nsteps[ax] - 1)
264
+
265
+ interior_ijk = ijk[interior_mask]
266
+ n_interior = interior_ijk.shape[0]
267
+ row_node_idx = self.global_node_indices(interior_ijk)
268
+
269
+ if pure:
270
+ # Non-uniform second derivative:
271
+ # f''(x_i) ~= 2[f_{i-1}/(hL*(hL+hR)) - f_i/(hL*hR) + f_{i+1}/(hR*(hL+hR))]
272
+ nodes_ax = nodes_list[axis]
273
+ i = interior_ijk[:, axis]
274
+ hL = nodes_ax[i] - nodes_ax[i - 1]
275
+ hR = nodes_ax[i + 1] - nodes_ax[i]
276
+
277
+ coef_m = 2.0 / (hL * (hL + hR))
278
+ coef_p = 2.0 / (hR * (hL + hR))
279
+ coef_c = -(coef_m + coef_p)
280
+
281
+ A_values = np.column_stack([coef_m, coef_c, coef_p])
282
+
283
+ col_ijk = np.zeros((n_interior, 3, 3), dtype=int)
284
+ col_ijk[:, :, :] = interior_ijk[:, None, :]
285
+ col_ijk[:, 0, axis] -= 1
286
+ col_ijk[:, 2, axis] += 1
287
+ col_global_idx = self.global_node_indices(col_ijk.reshape(-1, 3)).reshape(n_interior, 3)
288
+
289
+ else:
290
+ # Mixed second derivative:
291
+ # d^2f/dxdy ~= [f(i+1,j+1) - f(i+1,j-1) - f(i-1,j+1) + f(i-1,j-1)]
292
+ # / ((hxL+hxR) * (hyL+hyR))
293
+ nodes_ax = nodes_list[axis]
294
+ nodes_cx = nodes_list[cross_axis]
295
+ ia = interior_ijk[:, axis]
296
+ ic = interior_ijk[:, cross_axis]
297
+ hx = nodes_ax[ia + 1] - nodes_ax[ia - 1]
298
+ hy = nodes_cx[ic + 1] - nodes_cx[ic - 1]
299
+
300
+ denom = hx * hy
301
+ signs = np.array([1.0, -1.0, -1.0, 1.0])
302
+ A_values = signs[None, :] / denom[:, None]
303
+
304
+ da = [1, 1, -1, -1]
305
+ dc = [1, -1, 1, -1]
306
+ col_ijk_4 = np.zeros((n_interior, 4, 3), dtype=int)
307
+ for k, (da_k, dc_k) in enumerate(zip(da, dc)):
308
+ col_ijk_4[:, k, :] = interior_ijk
309
+ col_ijk_4[:, k, axis] += da_k
310
+ col_ijk_4[:, k, cross_axis] += dc_k
311
+ col_global_idx = self.global_node_indices(col_ijk_4.reshape(-1, 3)).reshape(
312
+ n_interior, 4
313
+ )
314
+
315
+ return A_values, col_global_idx, row_node_idx