Coverage for python/src/dolfinx_mpc/utils/mpc_utils.py: 87%
270 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-03 12:11 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-03 12:11 +0000
1# Copyright (C) 2020-2021 Jørgen S. Dokken
2#
3# This file is part of DOLFINX_MPC
4#
5# SPDX-License-Identifier: MIT
6from __future__ import annotations
8from mpi4py import MPI
9from petsc4py import PETSc
11import dolfinx.common as _common
12import dolfinx.cpp as _cpp
13import dolfinx.fem as _fem
14import dolfinx.geometry as _geometry
15import dolfinx.la as _la
16import dolfinx.log as _log
17import dolfinx.mesh as _mesh
18import numpy as np
19import ufl
20from dolfinx import default_scalar_type as _dt
22import dolfinx_mpc.cpp
24__all__ = [
25 "rotation_matrix",
26 "facet_normal_approximation",
27 "log_info",
28 "rigid_motions_nullspace",
29 "determine_closest_block",
30 "create_normal_approximation",
31 "create_point_to_point_constraint",
32]
35def rotation_matrix(axis, angle):
36 # See https://en.wikipedia.org/wiki/Rotation_matrix,
37 # Subsection: Rotation_matrix_from_axis_and_angle.
38 if np.isclose(np.inner(axis, axis), 1):
39 n_axis = axis
40 else:
41 # Normalize axis
42 n_axis = axis / np.sqrt(np.inner(axis, axis))
44 # Define cross product matrix of axis
45 axis_x = np.array([[0, -n_axis[2], n_axis[1]], [n_axis[2], 0, -n_axis[0]], [-n_axis[1], n_axis[0], 0]])
46 identity = np.cos(angle) * np.eye(3)
47 outer = (1 - np.cos(angle)) * np.outer(n_axis, n_axis)
48 return np.sin(angle) * axis_x + identity + outer
51def facet_normal_approximation(
52 V,
53 mt: _mesh.MeshTags,
54 mt_id: int,
55 tangent=False,
56 jit_options: dict = {},
57 form_compiler_options: dict = {},
58):
59 """
60 Approximate the facet normal by projecting it into the function space for a set of facets
62 Args:
63 V: The function space to project into
64 mt: The `dolfinx.mesh.MeshTagsMetaClass` containing facet markers
65 mt_id: The id for the facets in `mt` we want to represent the normal at
66 tangent: To approximate the tangent to the facet set this flag to `True`
67 jit_options: Parameters used in CFFI JIT compilation of C code generated by FFCx.
68 See https://github.com/FEniCS/dolfinx/blob/main/python/dolfinx/jit.py#L22-L37
69 for all available parameters. Takes priority over all other parameter values.
70 form_compiler_options: Parameters used in FFCx compilation of this form. Run `ffcx - -help` at
71 the commandline to see all available options. Takes priority over all
72 other parameter values, except for `scalar_type` which is determined by
73 DOLFINx.
74 """
75 timer = _common.Timer("~MPC: Facet normal projection")
76 comm = V.mesh.comm
77 n = ufl.FacetNormal(V.mesh)
78 nh = _fem.Function(V)
79 u, v = ufl.TrialFunction(V), ufl.TestFunction(V)
80 ds = ufl.ds(domain=V.mesh, subdomain_data=mt, subdomain_id=mt_id)
81 if tangent:
82 if V.mesh.geometry.dim == 1:
83 raise ValueError("Tangent not defined for 1D problem")
84 elif V.mesh.geometry.dim == 2:
85 a = ufl.inner(u, v) * ds
86 L = ufl.inner(ufl.as_vector([-n[1], n[0]]), v) * ds
87 else:
89 def tangential_proj(u, n):
90 """
91 See for instance:
92 https://link.springer.com/content/pdf/10.1023/A:1022235512626.pdf
93 """
94 return (ufl.Identity(u.ufl_shape[0]) - ufl.outer(n, n)) * u
96 c = _fem.Constant(V.mesh, [1, 1, 1])
97 a = ufl.inner(u, v) * ds
98 L = ufl.inner(tangential_proj(c, n), v) * ds
99 else:
100 a = ufl.inner(u, v) * ds
101 L = ufl.inner(n, v) * ds
103 # Find all dofs that are not boundary dofs
104 imap = V.dofmap.index_map
105 all_blocks = np.arange(imap.size_local, dtype=np.int32)
106 top_blocks = _fem.locate_dofs_topological(V, V.mesh.topology.dim - 1, mt.find(mt_id))
107 deac_blocks = all_blocks[np.isin(all_blocks, top_blocks, invert=True)]
109 # Note there should be a better way to do this
110 # Create sparsity pattern only for constraint + bc
111 bilinear_form = _fem.form(a, jit_options=jit_options, form_compiler_options=form_compiler_options)
112 pattern = _fem.create_sparsity_pattern(bilinear_form)
113 pattern.insert_diagonal(deac_blocks)
114 pattern.finalize()
115 u_0 = _fem.Function(V)
116 u_0.x.petsc_vec.set(0)
118 bc_deac = _fem.dirichletbc(u_0, deac_blocks)
119 A = _cpp.la.petsc.create_matrix(comm, pattern._cpp_object, None)
120 A.zeroEntries()
122 # Assemble the matrix with all entries
123 form_coeffs = _cpp.fem.pack_coefficients(bilinear_form._cpp_object)
124 form_consts = _cpp.fem.pack_constants(bilinear_form._cpp_object)
125 _fem.petsc.assemble_matrix(A, a=bilinear_form, constants=form_consts, coeffs=form_coeffs, bcs=[bc_deac])
126 if bilinear_form.function_spaces[0] is bilinear_form.function_spaces[1]:
127 A.assemblyBegin(PETSc.Mat.AssemblyType.FLUSH) # type: ignore
128 A.assemblyEnd(PETSc.Mat.AssemblyType.FLUSH) # type: ignore
129 dofs = np.empty(0, dtype=np.int32)
130 if bilinear_form.function_spaces[0].contains(bc_deac.function_space):
131 dofs, owned = bc_deac.dof_indices()
132 rows = np.array(dofs, dtype=np.int32)
133 _la.petsc.set_diagonal(A, rows, 1.0, PETSc.InsertMode.INSERT_VALUES) # type: ignore
134 A.assemble()
135 linear_form = _fem.form(L, jit_options=jit_options, form_compiler_options=form_compiler_options)
136 b = _fem.petsc.assemble_vector(linear_form)
138 _fem.petsc.apply_lifting(b, [bilinear_form], [[bc_deac]])
139 b.ghostUpdate(addv=PETSc.InsertMode.ADD_VALUES, mode=PETSc.ScatterMode.REVERSE) # type: ignore
140 _fem.petsc.set_bc(b, [bc_deac])
142 # Solve Linear problem
143 solver = PETSc.KSP().create(V.mesh.comm) # type: ignore
144 solver.setType("cg")
145 solver.rtol = 1e-8
146 solver.setOperators(A)
147 solver.solve(b, nh.x.petsc_vec)
148 nh.x.petsc_vec.ghostUpdate(addv=PETSc.InsertMode.INSERT, mode=PETSc.ScatterMode.FORWARD) # type: ignore
149 timer.stop()
150 solver.destroy()
151 b.destroy()
152 return nh
155def log_info(message):
156 """
157 Wrapper for logging a simple string on the zeroth communicator
158 Reverting the log level
159 """
160 old_level = _log.get_log_level()
161 if MPI.COMM_WORLD.rank == 0:
162 _log.set_log_level(_log.LogLevel.INFO)
163 _log.log(_log.LogLevel.INFO, message)
164 _log.set_log_level(old_level)
167def rigid_motions_nullspace(V: _fem.FunctionSpace):
168 """
169 Function to build nullspace for 2D/3D elasticity.
171 Args:
172 V: The function space
173 """
174 _x = _fem.Function(V)
175 # Get geometric dim
176 gdim = V.mesh.geometry.dim
177 assert gdim == 2 or gdim == 3
179 # Set dimension of nullspace
180 dim = 3 if gdim == 2 else 6
182 # Create list of vectors for null space
183 nullspace_basis = [
184 _la.vector(V.dofmap.index_map, bs=V.dofmap.index_map_bs, dtype=PETSc.ScalarType) # type: ignore
185 for i in range(dim)
186 ]
188 basis = [b.array for b in nullspace_basis]
189 dofs = [V.sub(i).dofmap.list.reshape(-1) for i in range(gdim)]
191 # Build translational null space basis
192 for i in range(gdim):
193 basis[i][dofs[i]] = 1.0
194 # Build rotational null space basis
195 x = V.tabulate_dof_coordinates()
196 dofs_block = V.dofmap.list.reshape(-1)
197 x0, x1, x2 = x[dofs_block, 0], x[dofs_block, 1], x[dofs_block, 2]
198 if gdim == 2:
199 basis[2][dofs[0]] = -x1
200 basis[2][dofs[1]] = x0
201 elif gdim == 3:
202 basis[3][dofs[0]] = -x1
203 basis[3][dofs[1]] = x0
205 basis[4][dofs[0]] = x2
206 basis[4][dofs[2]] = -x0
207 basis[5][dofs[2]] = x1
208 basis[5][dofs[1]] = -x2
209 for b in nullspace_basis:
210 b.scatter_forward()
212 _la.orthonormalize(nullspace_basis)
213 assert _la.is_orthonormal(nullspace_basis, float(np.finfo(_x.x.array.dtype).eps))
214 local_size = V.dofmap.index_map.size_local * V.dofmap.index_map_bs
215 basis_petsc = [
216 PETSc.Vec().createWithArray(x[:local_size], bsize=gdim, comm=V.mesh.comm) # type: ignore
217 for x in basis
218 ]
219 return PETSc.NullSpace().create(comm=V.mesh.comm, vectors=basis_petsc) # type: ignore
222def determine_closest_block(V, point):
223 """
224 Determine the closest dofs (in a single block) to a point and the distance
225 """
226 # Create boundingboxtree of cells connected to boundary facets
227 tdim = V.mesh.topology.dim
228 boundary_facets = _mesh.exterior_facet_indices(V.mesh.topology)
229 V.mesh.topology.create_connectivity(tdim - 1, tdim)
230 f_to_c = V.mesh.topology.connectivity(tdim - 1, tdim)
231 boundary_cells = []
232 for facet in boundary_facets:
233 boundary_cells.extend(f_to_c.links(facet))
234 cell_imap = V.mesh.topology.index_map(tdim)
235 boundary_cells = np.array(np.unique(boundary_cells), dtype=np.int32)
236 boundary_cells = boundary_cells[boundary_cells < cell_imap.size_local]
237 bb_tree = _geometry.bb_tree(V.mesh, tdim, entities=boundary_cells, padding=0.0)
238 midpoint_tree = _geometry.create_midpoint_tree(V.mesh, tdim, boundary_cells)
240 # Find facet closest
241 point = np.reshape(point, (1, 3)).astype(V.mesh.geometry.x.dtype)
242 closest_cell = _geometry.compute_closest_entity(bb_tree, midpoint_tree, V.mesh, point)[0]
244 # Set distance high if cell is not owned
245 if cell_imap.size_local < closest_cell or closest_cell == -1:
246 R = 1e5
247 else:
248 # Get cell geometry
249 p = V.mesh.geometry.x
250 V.mesh.topology.create_connectivity(tdim, tdim)
251 entities = _mesh.entities_to_geometry(V.mesh, tdim, np.array([closest_cell], dtype=np.int32), False)
252 R = np.linalg.norm(_geometry.compute_distance_gjk(point, p[entities[0]]))
254 # Find processor with cell closest to point
255 global_distances = MPI.COMM_WORLD.allgather(R)
256 owning_processor = np.argmin(global_distances)
258 dofmap = V.dofmap
259 imap = dofmap.index_map
260 ghost_owner = imap.owners
261 local_max = imap.size_local
262 # Determine which block of dofs is closest
263 min_distance = max(R, 1e5)
264 minimal_distance_block = None
265 min_dof_owner = owning_processor
266 if MPI.COMM_WORLD.rank == owning_processor:
267 x = V.tabulate_dof_coordinates()
268 cell_blocks = dofmap.cell_dofs(closest_cell)
269 for block in cell_blocks:
270 distance = np.linalg.norm(_geometry.compute_distance_gjk(point, x[block]))
271 if distance < min_distance:
272 # If cell owned by processor, but not the closest dof
273 if block < local_max:
274 min_dof_owner = MPI.COMM_WORLD.rank
275 else:
276 min_dof_owner = ghost_owner[block - local_max]
277 minimal_distance_block = block
278 min_distance = distance
279 min_dof_owner = MPI.COMM_WORLD.bcast(min_dof_owner, root=owning_processor)
280 # If dofs not owned by cell
281 if owning_processor != min_dof_owner:
282 owning_processor = min_dof_owner
284 if MPI.COMM_WORLD.rank == min_dof_owner:
285 # Re-search using the closest cell
286 x = V.tabulate_dof_coordinates()
287 cell_blocks = dofmap.cell_dofs(closest_cell)
288 for block in cell_blocks:
289 distance = np.linalg.norm(_geometry.compute_distance_gjk(point, x[block]))
290 if distance < min_distance:
291 # If cell owned by processor, but not the closest dof
292 if block < local_max:
293 min_dof_owner = MPI.COMM_WORLD.rank
294 else:
295 min_dof_owner = ghost_owner[block - local_max]
296 minimal_distance_block = block
297 min_distance = distance
298 assert min_dof_owner == owning_processor
299 return owning_processor, [minimal_distance_block]
300 else:
301 return owning_processor, []
304def create_point_to_point_constraint(V, slave_point, master_point, vector=None):
305 # Determine which processor owns the dof closest to the slave and master point
306 slave_proc, slave_block = determine_closest_block(V, slave_point)
307 master_proc, master_block = determine_closest_block(V, master_point)
308 is_master_proc = MPI.COMM_WORLD.rank == master_proc
309 is_slave_proc = MPI.COMM_WORLD.rank == slave_proc
311 block_size = V.dofmap.index_map_bs
312 imap = V.dofmap.index_map
313 # Output structures
314 slaves, masters, coeffs, owners, offsets = [], [], [], [], []
315 # Information required to handle vector as input
316 zero_indices, slave_index = None, None
317 if vector is not None:
318 zero_indices = np.argwhere(np.isclose(vector, 0)).T[0]
319 slave_index = np.argmax(np.abs(vector))
320 if is_slave_proc:
321 assert len(slave_block) == 1
322 slave_block_g = imap.local_to_global(np.asarray(slave_block, dtype=np.int32))[0]
323 if vector is None:
324 slaves = np.arange(
325 slave_block[0] * block_size,
326 slave_block[0] * block_size + block_size,
327 dtype=np.int32,
328 )
329 else:
330 assert len(vector) == block_size
331 # Check for input vector (Should be of same length as number of slaves)
332 # All entries should not be zero
333 assert not np.isin(slave_index, zero_indices)
334 # Check vector for zero contributions
335 slaves = np.array([slave_block[0] * block_size + slave_index], dtype=np.int32)
336 for i in range(block_size):
337 if i != slave_index and not np.isin(i, zero_indices):
338 masters.append(slave_block_g * block_size + i)
339 owners.append(slave_proc)
340 coeffs.append(-vector[i] / vector[slave_index])
342 global_masters = None
343 if is_master_proc:
344 assert len(master_block) == 1
345 master_block_g = imap.local_to_global(np.asarray(master_block, dtype=np.int32))[0]
346 masters_as_glob = np.arange(
347 master_block_g * block_size, master_block_g * block_size + block_size, dtype=np.int64
348 )
349 else:
350 masters_as_glob = np.array([], dtype=np.int64)
352 ghost_processors = []
353 shared_indices = dolfinx_mpc.cpp.mpc.compute_shared_indices(V._cpp_object)
355 if is_master_proc and is_slave_proc:
356 # If slaves and masters are on the same processor finalize local work
357 if vector is None:
358 masters = masters_as_glob
359 owners = np.full(len(masters), master_proc, dtype=np.int32)
360 coeffs = np.ones(len(masters), dtype=_dt)
361 offsets = np.arange(0, len(masters) + 1, dtype=np.int32)
362 else:
363 for i in range(len(masters_as_glob)):
364 if not np.isin(i, zero_indices):
365 masters.append(masters_as_glob[i])
366 owners.append(master_proc)
367 coeffs.append(vector[i] / vector[slave_index])
368 offsets = [0, len(masters)]
369 else:
370 # Send/Recv masters from other processor
371 if is_master_proc:
372 MPI.COMM_WORLD.send(masters_as_glob, dest=slave_proc, tag=10)
373 if is_slave_proc:
374 global_masters = MPI.COMM_WORLD.recv(source=master_proc, tag=10)
375 for i, master in enumerate(global_masters):
376 if not np.isin(i, zero_indices):
377 masters.append(master)
378 owners.append(master_proc)
379 if vector is None:
380 coeffs.append(1)
381 else:
382 coeffs.append(vector[i] / vector[slave_index])
383 if vector is None:
384 offsets = np.arange(0, len(slaves) + 1, dtype=np.int32)
385 else:
386 offsets = np.array([0, len(masters)], dtype=np.int32)
387 ghost_processors = shared_indices.links(slave_block[0])
389 # Broadcast processors containg slave
390 ghost_processors = MPI.COMM_WORLD.bcast(ghost_processors, root=slave_proc)
391 if is_slave_proc:
392 for proc in ghost_processors:
393 MPI.COMM_WORLD.send(slave_block_g * block_size + slaves % block_size, dest=proc, tag=20 + proc)
394 MPI.COMM_WORLD.send(coeffs, dest=proc, tag=30 + proc)
395 MPI.COMM_WORLD.send(owners, dest=proc, tag=40 + proc)
396 MPI.COMM_WORLD.send(masters, dest=proc, tag=50 + proc)
397 MPI.COMM_WORLD.send(offsets, dest=proc, tag=60 + proc)
399 # Receive data for ghost slaves
400 ghost_slaves, ghost_masters, ghost_coeffs, ghost_owners, ghost_offsets = [], [], [], [], []
401 if np.isin(MPI.COMM_WORLD.rank, ghost_processors):
402 # Convert recieved slaves to the corresponding ghost index
403 recv_slaves = MPI.COMM_WORLD.recv(source=slave_proc, tag=20 + MPI.COMM_WORLD.rank)
404 ghost_coeffs = MPI.COMM_WORLD.recv(source=slave_proc, tag=30 + MPI.COMM_WORLD.rank)
405 ghost_owners = MPI.COMM_WORLD.recv(source=slave_proc, tag=40 + MPI.COMM_WORLD.rank)
406 ghost_masters = MPI.COMM_WORLD.recv(source=slave_proc, tag=50 + MPI.COMM_WORLD.rank)
407 ghost_offsets = MPI.COMM_WORLD.recv(source=slave_proc, tag=60 + MPI.COMM_WORLD.rank)
409 # Unroll ghost blocks
410 ghosts = imap.ghosts
411 ghost_dofs = [g * block_size + i for g in ghosts for i in range(block_size)]
413 ghost_slaves = np.zeros(len(recv_slaves), dtype=np.int32)
414 local_size = imap.size_local
415 for i, slave in enumerate(recv_slaves):
416 idx = np.argwhere(ghost_dofs == slave)[0, 0]
417 ghost_slaves[i] = local_size * block_size + idx
418 slaves = np.asarray(np.append(slaves, ghost_slaves), dtype=np.int32)
419 masters = np.asarray(np.append(masters, ghost_masters), dtype=np.int64)
420 coeffs = np.asarray(np.append(coeffs, ghost_coeffs), dtype=_dt)
421 owners = np.asarray(np.append(owners, ghost_owners), dtype=np.int32)
422 offsets = np.asarray(np.append(offsets, ghost_offsets), dtype=np.int32)
423 return slaves, masters, coeffs, owners, offsets
426def create_normal_approximation(V: _fem.FunctionSpace, mt: _cpp.mesh.MeshTags_int32, value: int):
427 """
428 Creates a normal approximation for the dofs in the closure of the attached entities.
429 Where a dof is attached to multiple entities, an average is computed.
431 Args:
432 V: The function space
433 mt: The meshtag containing the indices
434 value: Value for the entities in the mesh tag to compute normal on
436 Returns:
437 nh: The normal vector
438 """
439 nh = _fem.Function(V)
440 n_cpp = dolfinx_mpc.cpp.mpc.create_normal_approximation(V._cpp_object, mt.dim, mt.find(value))
441 nh._cpp_object = n_cpp
442 return nh