Debian Codegraph @

src/adios4dolfinx/utils.py

raw
1 # Copyright (C) 2023 Jørgen Schartum Dokken
2 #
3 # This file is part of adios4dolfinx
4 #
5 # SPDX-License-Identifier: MIT
6
7 """
8 Vectorized numpy operations used internally in adios4dolfinx
9 """
10
11 from __future__ import annotations
12
13 import typing
14
15 from mpi4py import MPI
16
17 import dolfinx
18 import numpy as np
19 import numpy.typing as npt
20 from packaging.version import Version
21
22 __all__ = [
23 "compute_local_range",
24 "index_owner",
25 "compute_dofmap_pos",
26 "unroll_dofmap",
27 "compute_insert_position",
28 "unroll_insert_position",
29 ]
30 """Layer for small backward compatibility wrappers for DOLFINx"""
31
32 valid_function_types = typing.Union[np.float32, np.float64, np.complex64, np.complex128]
33 valid_real_types = typing.Union[np.float32, np.float64]
34
35
36 def get_cmap(mesh: dolfinx.mesh.Mesh) -> dolfinx.fem.CoordinateElement:
37 """Get the basix Cmap for the mesh."""
38 if callable(mesh.geometry.cmap):
39 return mesh.geometry.cmap()
40 else:
41 return mesh.geometry.cmap
42
43
44 def element_signature(V):
45 if Version(dolfinx.__version__) > Version("0.9.0"):
46 return V.element.signature
47 else:
48 return V.element.signature()
49
50
51 def compute_insert_position(
52 data_owner: npt.NDArray[np.int32],
53 destination_ranks: npt.NDArray[np.int32],
54 out_size: npt.NDArray[np.int32],
55 ) -> npt.NDArray[np.int32]:
56 """
57 Giving a list of ranks, compute the local insert position for each rank in a list
58 sorted by destination ranks. This function is used for packing data from a
59 given process to its destination processes.
60
61 Example:
62
63 .. highlight:: python
64 .. code-block:: python
65
66 data_owner = [0, 1, 1, 0, 2, 3]
67 destination_ranks = [2,0,3,1]
68 out_size = [1, 2, 1, 2]
69 insert_position = compute_insert_position(data_owner, destination_ranks, out_size)
70
71 Insert position is then ``[1, 4, 5, 2, 0, 3]``
72 """
73 process_pos_indicator = data_owner.reshape(-1, 1) == destination_ranks
74
75 # Compute offsets for insertion based on input size
76 send_offsets = np.zeros(len(out_size) + 1, dtype=np.intc)
77 send_offsets[1:] = np.cumsum(out_size)
78 assert send_offsets[-1] == len(data_owner)
79
80 # Compute local insert index on each process
81 proc_row, proc_col = np.nonzero(process_pos_indicator)
82 cum_pos = np.cumsum(process_pos_indicator, axis=0)
83 insert_position = cum_pos[proc_row, proc_col] - 1
84
85 # Add process offset for each local index
86 insert_position += send_offsets[proc_col]
87 return insert_position
88
89
90 def unroll_insert_position(
91 insert_position: npt.NDArray[np.int32], block_size: int
92 ) -> npt.NDArray[np.int32]:
93 """
94 Unroll insert position by a block size
95
96 Example:
97
98
99 .. highlight:: python
100 .. code-block:: python
101
102 insert_position = [1, 4, 5, 2, 0, 3]
103 unrolled_ip = unroll_insert_position(insert_position, 3)
104
105 where ``unrolled_ip = [3, 4 ,5, 12, 13, 14, 15, 16, 17, 6, 7, 8, 0, 1, 2, 9, 10, 11]``
106 """
107 unrolled_ip = np.repeat(insert_position, block_size) * block_size
108 unrolled_ip += np.tile(np.arange(block_size), len(insert_position))
109 return unrolled_ip
110
111
112 def compute_local_range(comm: MPI.Intracomm, N: np.int64):
113 """
114 Divide a set of `N` objects into `M` partitions, where `M` is
115 the size of the MPI communicator `comm`.
116
117 NOTE: If N is not divisible by the number of ranks, the first `r`
118 processes gets an extra value
119
120 Returns the local range of values
121 """
122 rank = comm.rank
123 size = comm.size
124 n = N // size
125 r = N % size
126 # First r processes has one extra value
127 if rank < r:
128 return [rank * (n + 1), (rank + 1) * (n + 1)]
129 else:
130 return [rank * n + r, (rank + 1) * n + r]
131
132
133 def index_owner(
134 comm: MPI.Intracomm, indices: npt.NDArray[np.int64], N: np.int64
135 ) -> npt.NDArray[np.int32]:
136 """
137 Find which rank (local to comm) which owns an `index`, given that
138 data of size `N` has been split equally among the ranks.
139
140 NOTE: If `N` is not divisible by the number of ranks, the first `r`
141 processes gets an extra value.
142 """
143 size = comm.size
144 assert (indices < N).all()
145 n = N // size
146 r = N % size
147
148 owner = np.empty_like(indices, dtype=np.int32)
149 inc_remainder = indices < (n + 1) * r
150 owner[inc_remainder] = indices[inc_remainder] // (n + 1)
151 owner[~inc_remainder] = r + (indices[~inc_remainder] - r * (n + 1)) // n
152 return owner
153
154
155 def unroll_dofmap(dofs: npt.NDArray[np.int32], bs: int) -> npt.NDArray[np.int32]:
156 """
157 Given a two-dimensional dofmap of size `(num_cells, num_dofs_per_cell)`
158 Expand the dofmap by its block size such that the resulting array
159 is of size `(num_cells, bs*num_dofs_per_cell)`
160 """
161 num_cells, num_dofs_per_cell = dofs.shape
162 unrolled_dofmap = np.repeat(dofs, bs).reshape(num_cells, num_dofs_per_cell * bs) * bs
163 unrolled_dofmap += np.tile(np.arange(bs), num_dofs_per_cell)
164 return unrolled_dofmap
165
166
167 def compute_dofmap_pos(
168 V: dolfinx.fem.FunctionSpace,
169 ) -> tuple[npt.NDArray[np.int32], npt.NDArray[np.int32]]:
170 """
171 Compute a map from each owned dof in the dofmap to a single cell owned by the
172 process, and the relative position of the dof.
173
174 :param V: The function space
175 :returns: The tuple (`cells`, `dof_pos`) where each array is the size of the
176 number of owned dofs (unrolled for block size)
177 """
178 dofs = V.dofmap.list
179 mesh = V.mesh
180 num_owned_cells = mesh.topology.index_map(mesh.topology.dim).size_local
181 dofmap_bs = V.dofmap.bs
182 num_owned_dofs = V.dofmap.index_map.size_local * V.dofmap.index_map_bs
183
184 local_cell = np.empty(
185 num_owned_dofs, dtype=np.int32
186 ) # Local cell index for each dof owned by process
187 dof_pos = np.empty(num_owned_dofs, dtype=np.int32) # Position in dofmap for said dof
188
189 unrolled_dofmap = unroll_dofmap(dofs[:num_owned_cells, :], dofmap_bs)
190 markers = unrolled_dofmap < num_owned_dofs
191 local_indices = np.broadcast_to(np.arange(markers.shape[1]), markers.shape)
192 cell_indicator = np.broadcast_to(
193 np.arange(num_owned_cells, dtype=np.int32).reshape(-1, 1),
194 (num_owned_cells, markers.shape[1]),
195 )
196 indicator = unrolled_dofmap[markers].reshape(-1)
197 local_cell[indicator] = cell_indicator[markers].reshape(-1)
198 dof_pos[indicator] = local_indices[markers].reshape(-1)
199 return local_cell, dof_pos