Debian Codegraph @

src/meshzoo/_helpers.py

raw
1 import numpy as np
2
3
4 def create_edges(cells_nodes):
5 """Setup edge-node and edge-cell relations. Adapted from voropy."""
6 # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of
7 # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge
8 # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3, n)`, where `n` is
9 # the number of cells. Make sure that the k-th edge is opposite of the k-th
10 # point in the triangle.
11 local_idx = np.array([[1, 2], [2, 0], [0, 1]]).T
12 # Map idx back to the nodes. This is useful if quantities which are in
13 # idx shape need to be added up into nodes (e.g., equation system rhs).
14 nds = cells_nodes.T
15 idx_hierarchy = nds[local_idx]
16
17 s = idx_hierarchy.shape
18 a = np.sort(idx_hierarchy.reshape(s[0], s[1] * s[2]).T)
19
20 b = np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))
21 _, idx, inv, cts = np.unique(
22 b, return_index=True, return_inverse=True, return_counts=True
23 )
24
25 # No edge has more than 2 cells. This assertion fails, for example, if
26 # cells are listed twice.
27 assert all(cts < 3)
28
29 edge_nodes = a[idx]
30 cells_edges = inv.reshape(3, -1).T
31
32 return edge_nodes, cells_edges
33
34
35 def show2d(*args, **kwargs):
36 import matplotlib.pyplot as plt
37
38 plot2d(*args, **kwargs)
39 plt.show()
40
41
42 def save2d(filename, *args, **kwargs):
43 import matplotlib.pyplot as plt
44
45 plot2d(*args, **kwargs)
46 plt.savefig(filename, transparent=True, bbox_inches="tight")
47
48
49 def plot2d(
50 points,
51 cells,
52 show_axes=False,
53 # ParaView's default colors
54 fill: str = "#c8c5bd",
55 stroke: str = "#000080",
56 ):
57 """Plot a 2D mesh using matplotlib."""
58 import matplotlib.pyplot as plt
59
60 fig = plt.figure()
61 ax = fig.gca()
62 plt.axis("equal")
63 if not show_axes:
64 ax.set_axis_off()
65
66 assert points.shape[1] == 2
67
68 xmin = np.amin(points[:, 0])
69 xmax = np.amax(points[:, 0])
70 ymin = np.amin(points[:, 1])
71 ymax = np.amax(points[:, 1])
72
73 width = xmax - xmin
74 xmin -= 0.1 * width
75 xmax += 0.1 * width
76
77 height = ymax - ymin
78 ymin -= 0.1 * height
79 ymax += 0.1 * height
80
81 ax.set_xlim(xmin, xmax)
82 ax.set_ylim(ymin, ymax)
83
84 for cell in cells:
85 import matplotlib.patches
86
87 poly = matplotlib.patches.Polygon(points[cell], ec=stroke, fc=fill)
88 ax.add_patch(poly)
89
90 # import matplotlib.tri
91 # tri = matplotlib.tri.Triangulation(points[:,0], points[:,1], triangles=cells)
92 # ax.triplot(tri, '-', lw=1, color="k")
93 return fig
94
95
96 def _compose_from_faces(corners, faces, n, edge_adjust=None, face_adjust=None):
97 # create corner nodes
98 vertices = [corners]
99 vertex_count = len(corners)
100 corner_nodes = np.arange(len(corners))
101
102 # create edges
103 edges = set()
104 for face in faces:
105 edges.add(tuple(sorted([face[0], face[1]])))
106 edges.add(tuple(sorted([face[1], face[2]])))
107 edges.add(tuple(sorted([face[2], face[0]])))
108
109 edges = list(edges)
110
111 # create edge nodes:
112 edge_nodes = {}
113 t = np.linspace(1 / n, 1.0, n - 1, endpoint=False)
114 corners = vertices[0]
115 k = corners.shape[0]
116 for edge in edges:
117 i0, i1 = edge
118 new_vertices = np.outer(1 - t, corners[i0]) + np.outer(t, corners[i1])
119 if edge_adjust:
120 new_vertices = edge_adjust(edge, new_vertices)
121 vertices.append(new_vertices)
122 vertex_count += len(vertices[-1])
123 edge_nodes[edge] = np.arange(k, k + len(t))
124 k += len(t)
125
126 # This is the same code as appearing for cell in a single triangle. On each face,
127 # those indices are translated into the actual indices.
128 triangle_cells = []
129 k = 0
130 for i in range(n):
131 j = np.arange(n - i)
132 triangle_cells.append(np.column_stack([k + j, k + j + 1, k + n - i + j + 1]))
133 j = j[:-1]
134 triangle_cells.append(
135 np.column_stack([k + j + 1, k + n - i + j + 2, k + n - i + j + 1])
136 )
137 k += n - i + 1
138 triangle_cells = np.vstack(triangle_cells)
139
140 cells = []
141 for face in faces:
142 corners = face
143 edges = [(face[0], face[1]), (face[1], face[2]), (face[2], face[0])]
144 is_edge_reverted = [False, False, False]
145 for k, edge in enumerate(edges):
146 if edge[0] > edge[1]:
147 edges[k] = (edge[1], edge[0])
148 is_edge_reverted[k] = True
149
150 # First create the interior points in barycentric coordinates
151 if n == 1:
152 num_new_vertices = 0
153 else:
154 bary = (
155 np.hstack(
156 [[np.full(n - i - 1, i), np.arange(1, n - i)] for i in range(1, n)]
157 )
158 / n
159 )
160 bary = np.array([1.0 - bary[0] - bary[1], bary[1], bary[0]])
161 corner_verts = np.array([vertices[0][i] for i in corners])
162 vertices_cart = np.dot(corner_verts.T, bary).T
163
164 if face_adjust:
165 vertices_cart = face_adjust(face, bary, vertices_cart, corner_verts)
166
167 vertices.append(vertices_cart)
168 num_new_vertices = len(vertices[-1])
169
170 # translation table
171 num_nodes_per_triangle = (n + 1) * (n + 2) // 2
172 tt = np.empty(num_nodes_per_triangle, dtype=int)
173
174 # first the corners
175 tt[0] = corner_nodes[corners[0]]
176 tt[n] = corner_nodes[corners[1]]
177 tt[num_nodes_per_triangle - 1] = corner_nodes[corners[2]]
178 # then the edges.
179 # edge 0
180 tt[1:n] = edge_nodes[edges[0]]
181 if is_edge_reverted[0]:
182 tt[1:n] = tt[1:n][::-1]
183 #
184 # edge 1
185 idx = 2 * n
186 for k in range(n - 1):
187 if is_edge_reverted[1]:
188 tt[idx] = edge_nodes[edges[1]][n - 2 - k]
189 else:
190 tt[idx] = edge_nodes[edges[1]][k]
191 idx += n - k - 1
192 #
193 # edge 2
194 idx = n + 1
195 for k in range(n - 1):
196 if is_edge_reverted[2]:
197 tt[idx] = edge_nodes[edges[2]][k]
198 else:
199 tt[idx] = edge_nodes[edges[2]][n - 2 - k]
200 idx += n - k
201
202 # now the remaining interior nodes
203 idx = n + 2
204 j = vertex_count
205 for k in range(n - 2):
206 for _ in range(n - k - 2):
207 tt[idx] = j
208 j += 1
209 idx += 1
210 idx += 2
211
212 cells += [tt[triangle_cells]]
213 vertex_count += num_new_vertices
214
215 vertices = np.concatenate(vertices)
216 cells = np.concatenate(cells)
217
218 return vertices, cells
219
220
221 def insert_midpoints_edges(points, cells, cell_type):
222 """Collect all unique edges, calculate and return points including
223 midpoints on edges as well as the extended cells array."""
224
225 number_of_points = {"triangle": 3, "tetra": 4, "quad": 4, "hexahedron": 8}
226
227 if cells.shape[1] != number_of_points[cell_type]:
228 raise ValueError("Mismatch of cell type and shape of cells array.")
229
230 if cell_type == "triangle":
231 # k-th edge between cell points no. (ij[k])
232 ij = [[0, 1], [1, 2], [2, 0]]
233
234 elif cell_type == "tetra":
235 # k-th edge between cell points no. (ij[k])
236 ij = [[0, 1], [1, 2], [2, 0], [3, 0], [3, 1], [3, 2]]
237
238 elif cell_type == "quad":
239 # k-th edge between cell points no. (ij[k])
240 ij = [[0, 1], [1, 2], [2, 3], [3, 0]]
241
242 elif cell_type == "hexahedron":
243 # k-th edge between cell points no. (ij[k])
244 ij = [
245 [0, 1],
246 [1, 2],
247 [2, 3],
248 [3, 0],
249 [4, 5],
250 [5, 6],
251 [6, 7],
252 [7, 4],
253 [0, 4],
254 [1, 5],
255 [2, 6],
256 [3, 7],
257 ]
258
259 else:
260 raise TypeError("Cell type not implemented.")
261
262 # obtain edges from cells (contains duplicates)
263 edges = cells[:, ij]
264
265 # sort points of edges
266 edges_sorted = np.sort(edges.reshape(-1, 2), axis=1)
267
268 # obtain unique edges and inverse mapping
269 edges_unique, inverse = np.unique(
270 edges_sorted,
271 return_index=False,
272 return_inverse=True,
273 return_counts=False,
274 axis=0,
275 )
276
277 # calculate midpoints on edges as mean of edge-based pairs of points
278 midpoints_on_edges = np.mean(points[edges_unique.T], axis=0)
279
280 # create the additional cells array
281 # add offset to point index for midpoints on edges
282 cells_edges = inverse.reshape(len(cells), -1) + len(points)
283
284 # vertical stack of points and horizontal stack of edges
285 points_new = np.vstack((points, midpoints_on_edges))
286 cells_new = np.hstack((cells, cells_edges))
287
288 return points_new, cells_new