Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/comm_helpers.py: 98%

206 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 12:02 +0000

1""" 

2Helpers for sending and receiving values for checkpointing 

3""" 

4 

5from __future__ import annotations 

6 

7from typing import Callable, TypeVar 

8 

9from mpi4py import MPI 

10 

11import numpy as np 

12import numpy.typing as npt 

13 

14from .utils import ( 

15 compute_insert_position, 

16 compute_local_range, 

17 index_owner, 

18 valid_function_types, 

19) 

20 

21__all__ = [ 

22 "send_dofmap_and_recv_values", 

23 "send_and_recv_cell_perm", 

24 "send_dofs_and_recv_values", 

25 "neighbourhood_ranks", 

26 "exchange_to_owners", 

27 "send_to_input_order", 

28 "numpy_to_mpi", 

29 "all_to_all", 

30 "run_on_root", 

31 "run_on_root_and_share", 

32 "run_on_all", 

33 "gather_rows", 

34 "gather_concatenate", 

35] 

36 

37T = TypeVar("T") 

38Local = TypeVar("Local") 

39Shared = TypeVar("Shared") 

40 

41numpy_to_mpi = { 

42 np.float64: MPI.DOUBLE, 

43 np.float32: MPI.FLOAT, 

44 np.complex64: MPI.COMPLEX, 

45 np.complex128: MPI.DOUBLE_COMPLEX, 

46 np.int64: MPI.INT64_T, 

47 np.int32: MPI.INT32_T, 

48 np.uint32: MPI.UINT32_T, 

49} 

50 

51 

52def all_to_all(comm, send_data, recv_data): 

53 """ 

54 Exchange a single item with each neighbor in a distributed graph communicator. 

55 

56 Note: 

57 The count is passed explicitly, and is 1 on every process. MPI-4.1 9.6.2 requires 

58 the type signature of ``sendcount``/``sendtype`` at a process to equal that of 

59 ``recvcount``/``recvtype`` at *any other* process in the communicator, not just at 

60 its neighbors, so the count must be identical on every process whatever its degree. 

61 Left implicit, mpi4py derives it as ``buffer size // degree`` and falls back to the 

62 whole buffer when the degree is zero, making it rank-local: 1 where the degree is 

63 nonzero, 0 where it is zero. Such a call is erroneous; Open MPI rejects it with 

64 ``MPI_ERR_TRUNCATE`` while MPICH happens to accept it. See 

65 https://github.com/open-mpi/ompi/issues/14452 for the discussion. 

66 

67 ``all_to_allv`` is not affected: the vector variant is only required to match 

68 pairwise along each edge, so per-process counts may legitimately differ there. 

69 """ 

70 dtype = numpy_to_mpi[send_data.dtype.type] 

71 assert recv_data.dtype == send_data.dtype, ( 

72 f"Data types do not match, {recv_data.dtype} != {send_data.dtype}" 

73 ) 

74 indegree, outdegree, _ = comm.Get_dist_neighbors_count() 

75 assert (d_size := send_data.size) == outdegree, ( 

76 f"Number of send data {d_size} does not match number of destinations {outdegree}" 

77 ) 

78 assert (d_size := recv_data.size) == indegree, ( 

79 f"Number of recv data {d_size} does not match number of sources {indegree}" 

80 ) 

81 comm.Neighbor_alltoall([send_data, 1, dtype], [recv_data, 1, dtype]) 

82 

83 

84def send_dofmap_and_recv_values( 

85 comm: MPI.Comm, 

86 source_ranks: npt.NDArray[np.int32], 

87 dest_ranks: npt.NDArray[np.int32], 

88 output_owners: npt.NDArray[np.int32], 

89 dest_size: npt.NDArray[np.int32], 

90 input_cells: npt.NDArray[np.int64], 

91 dofmap_pos: npt.NDArray[np.int32], 

92 num_cells_global: int | np.int64, 

93 values: npt.NDArray[valid_function_types], 

94 dofmap_offsets: npt.NDArray[np.int32], 

95) -> npt.NDArray[valid_function_types]: 

96 """ 

97 Given a set of positions in input dofmap, give the global input index of this dofmap entry 

98 in input file. 

99 

100 Args: 

101 comm: The MPI communicator to create the Neighbourhood-communicator from 

102 source_ranks: Ranks that will send dofmap indices to current process 

103 dest_ranks: Ranks that will receive dofmap indices from current process 

104 output_owners: The owners of each dofmap entry on this process. The unique set of 

105 these entries should be the same as the dest_ranks. 

106 dest_size: The number of entries sent to each owner 

107 input_cells: A cell associated with the degree of freedom sent (global index). 

108 dofmap_pos: The local position in the dofmap. I.e. 

109 `dof = dofmap.links(input_cells)[dofmap_pos]` 

110 num_cells_global: Number of global cells 

111 values: Values currently held by this process. These are 

112 ordered (num_cells_local, num_dofs_per_cell), flattened row-major. 

113 dofmap_offsets: Local dofmap offsets to access the correct `values`. 

114 

115 Returns: 

116 Values corresponding to the dofs owned by this process. 

117 """ 

118 insert_position = compute_insert_position(output_owners, dest_ranks, dest_size) 

119 

120 # Pack the cells and dofmap position for all dofs this process is distributing 

121 out_cells = np.zeros(len(output_owners), dtype=np.int64) 

122 out_cells[insert_position] = input_cells 

123 out_pos = np.zeros(len(output_owners), dtype=np.int32) 

124 out_pos[insert_position] = dofmap_pos 

125 

126 # Compute map from the data index sent to each process and the local 

127 # number on the current process 

128 proc_to_dof = np.zeros_like(input_cells, dtype=np.int32) 

129 proc_to_dof[insert_position] = np.arange(len(input_cells), dtype=np.int32) 

130 del insert_position 

131 

132 # Send sizes to create data structures for receiving from NeighAlltoAllv 

133 recv_size = np.zeros(len(source_ranks), dtype=np.int32) 

134 assert isinstance(comm, MPI.Intracomm) 

135 mesh_to_data_comm = comm.Create_dist_graph_adjacent( 

136 source_ranks.tolist(), dest_ranks.tolist(), reorder=False 

137 ) 

138 all_to_all(mesh_to_data_comm, dest_size, recv_size) 

139 

140 # Prepare data-structures for receiving 

141 total_incoming = sum(recv_size) 

142 inc_cells = np.zeros(total_incoming, dtype=np.int64) 

143 inc_pos = np.zeros(total_incoming, dtype=np.intc) 

144 

145 # Compute incoming offset 

146 inc_offsets = np.zeros(len(recv_size) + 1, dtype=np.intc) 

147 inc_offsets[1:] = np.cumsum(recv_size) 

148 

149 # Send data 

150 s_msg = [out_cells, dest_size, MPI.INT64_T] 

151 r_msg = [inc_cells, recv_size, MPI.INT64_T] 

152 mesh_to_data_comm.Neighbor_alltoallv(s_msg, r_msg) 

153 

154 s_msg = [out_pos, dest_size, MPI.INT32_T] 

155 r_msg = [inc_pos, recv_size, MPI.INT32_T] 

156 mesh_to_data_comm.Neighbor_alltoallv(s_msg, r_msg) 

157 mesh_to_data_comm.Free() 

158 

159 local_input_range = compute_local_range(comm, num_cells_global) 

160 values_to_distribute = np.zeros_like(inc_pos, dtype=values.dtype) 

161 

162 # Map values based on input cells and dofmap 

163 local_cells = inc_cells - local_input_range[0] 

164 values_to_distribute = values[dofmap_offsets[local_cells] + inc_pos] 

165 

166 # Send input dofs back to owning process 

167 data_to_mesh_comm = comm.Create_dist_graph_adjacent( 

168 dest_ranks.tolist(), source_ranks.tolist(), reorder=False 

169 ) 

170 

171 incoming_global_dofs = np.zeros(sum(dest_size), dtype=values.dtype) 

172 s_msg = [values_to_distribute, recv_size, numpy_to_mpi[values.dtype.type]] 

173 r_msg = [incoming_global_dofs, dest_size, numpy_to_mpi[values.dtype.type]] 

174 data_to_mesh_comm.Neighbor_alltoallv(s_msg, r_msg) 

175 

176 # Sort incoming global dofs as they were inputted 

177 assert len(incoming_global_dofs) == len(input_cells) 

178 sorted_global_dofs = np.zeros_like(incoming_global_dofs, dtype=values.dtype) 

179 sorted_global_dofs[proc_to_dof] = incoming_global_dofs 

180 

181 data_to_mesh_comm.Free() 

182 return sorted_global_dofs 

183 

184 

185def send_and_recv_cell_perm( 

186 cells: npt.NDArray[np.int64], 

187 perms: npt.NDArray[np.uint32], 

188 cell_owners: npt.NDArray[np.int32], 

189 comm: MPI.Comm, 

190) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.uint32]]: 

191 """ 

192 Send global cell index and permutation to corresponding entry in `dest_ranks`. 

193 

194 Args: 

195 cells: The global input index of the cell 

196 perms: The corresponding cell permutation of the cell 

197 cell_owners: The rank to send the i-th entry of cells and perms to 

198 comm: Rank of comm to generate neighbourhood communicator from 

199 """ 

200 dest_ranks, _dest_size = np.unique(cell_owners, return_counts=True) 

201 dest_size = _dest_size.astype(np.int32) 

202 del _dest_size 

203 assert isinstance(comm, MPI.Intracomm) 

204 mesh_to_data = comm.Create_dist_graph( 

205 [comm.rank], [len(dest_ranks)], dest_ranks.tolist(), reorder=False 

206 ) 

207 source, dest, _ = mesh_to_data.Get_dist_neighbors() 

208 assert np.allclose(dest, dest_ranks) 

209 insert_position = compute_insert_position(cell_owners, dest_ranks.astype(np.int32), dest_size) 

210 

211 # Pack cells and permutations for sending 

212 out_cells = np.zeros_like(cells, dtype=np.int64) 

213 out_perm = np.zeros_like(perms, dtype=np.uint32) 

214 out_cells[insert_position] = cells 

215 out_perm[insert_position] = perms 

216 del insert_position 

217 

218 # Send sizes to create data structures for receiving from NeighAlltoAllv 

219 recv_size = np.zeros_like(source, dtype=np.int32) 

220 all_to_all(mesh_to_data, dest_size, recv_size) 

221 

222 # Prepare data-structures for receiving 

223 total_incoming = sum(recv_size) 

224 inc_cells = np.zeros(total_incoming, dtype=np.int64) 

225 inc_perm = np.zeros(total_incoming, dtype=np.uint32) 

226 

227 # Compute incoming offset 

228 inc_offsets = np.zeros(len(recv_size) + 1, dtype=np.intc) 

229 inc_offsets[1:] = np.cumsum(recv_size) 

230 

231 # Send data 

232 s_msg = [out_cells, dest_size, MPI.INT64_T] 

233 r_msg = [inc_cells, recv_size, MPI.INT64_T] 

234 mesh_to_data.Neighbor_alltoallv(s_msg, r_msg) 

235 

236 s_msg = [out_perm, dest_size, MPI.UINT32_T] 

237 r_msg = [inc_perm, recv_size, MPI.UINT32_T] 

238 mesh_to_data.Neighbor_alltoallv(s_msg, r_msg) 

239 mesh_to_data.Free() 

240 return inc_cells, inc_perm 

241 

242 

243def send_dofs_and_recv_values( 

244 input_dofmap: npt.NDArray[np.int64], 

245 dofmap_owners: npt.NDArray[np.int32], 

246 comm: MPI.Comm, 

247 input_array: npt.NDArray[valid_function_types], 

248 array_start: int, 

249): 

250 """ 

251 Send a set of dofs (global index) to the process holding the DOF values to retrieve them. 

252 

253 Args: 

254 input_dofmap: List of dofs (global index) that this process wants values for 

255 dofmap_owners: The process currently holding the values this process want to get. 

256 comm: MPI communicator 

257 input_array: Values for dofs 

258 array_start: The global starting index of `input_array`. 

259 """ 

260 dest_ranks, _dest_size = np.unique(dofmap_owners, return_counts=True) 

261 dest_size = _dest_size.astype(np.int32) 

262 del _dest_size 

263 

264 assert isinstance(comm, MPI.Intracomm) 

265 dofmap_to_values = comm.Create_dist_graph( 

266 [comm.rank], [len(dest_ranks)], dest_ranks.tolist(), reorder=False 

267 ) 

268 

269 source, dest, _ = dofmap_to_values.Get_dist_neighbors() 

270 assert np.allclose(dest_ranks, dest) 

271 # Compute amount of data to send to each process 

272 

273 insert_position = compute_insert_position(dofmap_owners, dest_ranks, dest_size) 

274 

275 # Pack dofs for sending 

276 out_dofs = np.zeros(len(dofmap_owners), dtype=np.int64) 

277 out_dofs[insert_position] = input_dofmap 

278 

279 # Compute map from the data index sent to each process and the local number on 

280 # the current process 

281 proc_to_local = np.zeros_like(input_dofmap, dtype=np.int32) 

282 proc_to_local[insert_position] = np.arange(len(input_dofmap), dtype=np.int32) 

283 del insert_position 

284 

285 # Send sizes to create data structures for receiving from NeighAlltoAllv 

286 recv_size = np.zeros_like(source, dtype=np.int32) 

287 all_to_all(dofmap_to_values, dest_size, recv_size) 

288 

289 # Send input dofs to processes holding input array 

290 inc_dofs = np.zeros(sum(recv_size), dtype=np.int64) 

291 s_msg = [out_dofs, dest_size, MPI.INT64_T] 

292 r_msg = [inc_dofs, recv_size, MPI.INT64_T] 

293 dofmap_to_values.Neighbor_alltoallv(s_msg, r_msg) 

294 dofmap_to_values.Free() 

295 

296 # Send back appropriate input values 

297 if len(input_array) > 0: 

298 sending_values = input_array[inc_dofs - array_start] 

299 else: 

300 sending_values = np.zeros(0, dtype=input_array.dtype) 

301 

302 values_to_dofmap = comm.Create_dist_graph_adjacent(dest, source, reorder=False) 

303 inc_values = np.zeros_like(out_dofs, dtype=input_array.dtype) 

304 s_msg_rev = [sending_values, recv_size, numpy_to_mpi[input_array.dtype.type]] 

305 r_msg_rev = [inc_values, dest_size, numpy_to_mpi[input_array.dtype.type]] 

306 values_to_dofmap.Neighbor_alltoallv(s_msg_rev, r_msg_rev) 

307 values_to_dofmap.Free() 

308 

309 # Sort inputs according to local dof number (input process) 

310 values = np.empty_like(inc_values, dtype=input_array.dtype) 

311 values[proc_to_local] = inc_values 

312 return values 

313 

314 

315def neighbourhood_ranks( 

316 comm: MPI.Intracomm, destinations: npt.NDArray[np.int32] 

317) -> tuple[npt.NDArray[np.int32], npt.NDArray[np.int32]]: 

318 """Find the ranks this process exchanges data with. 

319 

320 A process knows which ranks it must send to, but not which ranks will send 

321 to it. Building a distributed graph over the whole communicator and reading 

322 its neighbours back discovers the incoming side without an all-to-all. 

323 

324 Both lists are sorted ascending so that every process packs and unpacks 

325 neighbour blocks in the same order. 

326 

327 Args: 

328 comm: The MPI communicator 

329 destinations: Ranks this process sends to (duplicates allowed) 

330 

331 Returns: 

332 ``(sources, destinations)``, each sorted and without duplicates. 

333 """ 

334 dest = np.unique(np.asarray(destinations, dtype=np.int32)) 

335 graph = comm.Create_dist_graph([comm.rank], [len(dest)], dest.tolist(), reorder=False) 

336 sources, _, _ = graph.Get_dist_neighbors() 

337 graph.Free() 

338 return np.unique(np.asarray(sources, dtype=np.int32)), dest 

339 

340 

341def exchange_to_owners( 

342 comm: MPI.Intracomm, 

343 owners: npt.NDArray[np.int32], 

344 arrays: list[npt.NDArray], 

345) -> tuple[ 

346 list[npt.NDArray], 

347 npt.NDArray[np.int32], 

348 npt.NDArray[np.int32], 

349 npt.NDArray[np.int32], 

350 npt.NDArray[np.int32], 

351]: 

352 """Send each entry of ``arrays`` to the rank naming it in ``owners``. 

353 

354 Entry ``i`` of every array in ``arrays`` travels together to ``owners[i]``. 

355 Data is packed grouped by destination rank in ascending rank order and is 

356 received grouped by source rank in ascending rank order, preserving the 

357 sender's relative order within each group. Both properties matter to callers 

358 that must pair a reply with the request that produced it. 

359 

360 Args: 

361 comm: The MPI communicator 

362 owners: Destination rank of each entry; ``-1`` is not allowed 

363 arrays: Arrays to send, each of length ``len(owners)``. The leading axis 

364 is the one distributed; trailing axes travel as a block. 

365 

366 Returns: 

367 ``(received, sources, send_counts, recv_counts, insert_position)`` where 

368 ``received`` holds the incoming counterpart of each entry of ``arrays``, 

369 ``sources`` the ascending source ranks, ``send_counts`` and 

370 ``recv_counts`` the number of entries exchanged with each destination and 

371 source, and ``insert_position`` the index each local entry was packed at 

372 (so a reply can be unpacked back into local order). 

373 """ 

374 owners = np.asarray(owners, dtype=np.int32) 

375 sources, destinations = neighbourhood_ranks(comm, owners) 

376 

377 send_counts = np.zeros(len(destinations), dtype=np.int32) 

378 if len(owners) > 0: 

379 present, counts = np.unique(owners, return_counts=True) 

380 send_counts[np.searchsorted(destinations, present)] = counts 

381 insert_position = compute_insert_position(owners, destinations, send_counts) 

382 

383 recv_counts = np.zeros(len(sources), dtype=np.int32) 

384 forward = comm.Create_dist_graph_adjacent( 

385 sources.tolist(), destinations.tolist(), reorder=False 

386 ) 

387 all_to_all(forward, send_counts, recv_counts) 

388 

389 received = [] 

390 for array in arrays: 

391 array = np.asarray(array) 

392 block = int(np.prod(array.shape[1:], dtype=np.int64)) if array.ndim > 1 else 1 

393 packed = np.zeros(array.shape, dtype=array.dtype) 

394 packed[insert_position] = array 

395 out = np.zeros((int(recv_counts.sum()), *array.shape[1:]), dtype=array.dtype) 

396 # Canonical type, so that e.g. ``longlong`` (as used by DOLFINx index arrays) 

397 # maps like ``int64`` 

398 mpi_type = numpy_to_mpi[np.dtype(array.dtype.str).type] 

399 forward.Neighbor_alltoallv( 

400 [packed.reshape(-1), send_counts * block, mpi_type], 

401 [out.reshape(-1), recv_counts * block, mpi_type], 

402 ) 

403 received.append(out) 

404 forward.Free() 

405 return received, sources, send_counts, recv_counts, insert_position 

406 

407 

408def send_to_input_order( 

409 comm: MPI.Intracomm, 

410 input_indices: npt.NDArray[np.int64], 

411 values: list[npt.NDArray], 

412 num_global: int, 

413) -> tuple[list[npt.NDArray], tuple[int, int]]: 

414 """Send values to the process holding their input index, so that each process 

415 gets a contiguous chunk of the input ordering. 

416 

417 Collective: the input indices are checked on all ranks, so that an invalid 

418 numbering raises an error on every rank instead of leaving some waiting. 

419 

420 Args: 

421 comm: The MPI communicator 

422 input_indices: Input index of each owned entity on this process. Over all 

423 processes, they must number the entities ``0, ..., num_global - 1``, each 

424 exactly once. 

425 values: Arrays with a value of each owned entity, each of shape 

426 ``(len(input_indices), ...)``. They are sent together. 

427 num_global: Global number of entities 

428 

429 Returns: 

430 The values of the entities in this process' chunk, in input order, one array 

431 per entry of ``values``, and the range of the chunk 

432 

433 Raises: 

434 ValueError: If the input indices do not number the entities, e.g. for a 

435 submesh, whose input indices refer to its parent mesh. 

436 """ 

437 error = ValueError( 

438 f"The input indices do not number the {num_global} entities, so the data cannot be " 

439 "written in the input ordering. This is the case for a submesh, whose input " 

440 "indices refer to its parent mesh." 

441 ) 

442 input_indices = np.asarray(input_indices, dtype=np.int64) 

443 in_range = bool(np.all((input_indices >= 0) & (input_indices < num_global))) 

444 if not comm.allreduce(in_range, op=MPI.LAND): 

445 raise error 

446 

447 owners = index_owner(comm, input_indices, num_global) 

448 (recv_indices, *recv_values), *_ = exchange_to_owners(comm, owners, [input_indices, *values]) 

449 local_range = compute_local_range(comm, num_global) 

450 num_local = int(local_range[1] - local_range[0]) 

451 # In range on every rank, but an index may still appear twice and another not at all 

452 local = recv_indices - local_range[0] 

453 complete = len(local) == num_local and len(np.unique(local)) == num_local 

454 if not comm.allreduce(complete, op=MPI.LAND): 

455 raise error 

456 

457 data = [] 

458 for received in recv_values: 

459 ordered = np.empty_like(received) 

460 ordered[local] = received 

461 data.append(ordered) 

462 return data, (int(local_range[0]), int(local_range[1])) 

463 

464 

465def run_on_root(comm: MPI.Comm, fn: Callable[[], T]) -> T | None: 

466 """Run a function on rank 0 and raise any error it raises on all ranks. 

467 

468 Returns: 

469 The result of ``fn`` on rank 0, ``None`` on the other ranks 

470 """ 

471 result, error = None, None 

472 if comm.rank == 0: 

473 try: 

474 result = fn() 

475 except Exception as e: 

476 error = e 

477 error = comm.bcast(error, root=0) 

478 if error is not None: 

479 raise error 

480 return result 

481 

482 

483def run_on_root_and_share( 

484 comm: MPI.Comm, fn: Callable[[], tuple[Local, Shared]] 

485) -> tuple[Local | None, Shared]: 

486 """Run a function on rank 0, raise any error it raises on all ranks, and share part of 

487 its result with all ranks. 

488 

489 Args: 

490 comm: MPI communicator 

491 fn: Function returning data kept on rank 0, and data shared with all ranks 

492 

493 Returns: 

494 The first output of ``fn`` on rank 0 (``None`` on the other ranks), and its second 

495 output on all ranks 

496 """ 

497 result = run_on_root(comm, fn) 

498 local, shared = result if result is not None else (None, None) 

499 return local, comm.bcast(shared, root=0) 

500 

501 

502def run_on_all(comm: MPI.Comm, fn: Callable[[], T]) -> T: 

503 """Run a function on all ranks and raise an error raised on any rank on all ranks, 

504 so that no rank is left waiting in a later collective call.""" 

505 result, error = None, None 

506 try: 

507 result = fn() 

508 except Exception as e: 

509 error = e 

510 errors = [e for e in comm.allgather(error) if e is not None] 

511 if errors: 

512 raise errors[0] 

513 return result # type: ignore[return-value] 

514 

515 

516def gather_rows( 

517 comm: MPI.Comm, local: npt.NDArray, local_range: tuple[int, int] | list[int], num_global: int 

518) -> npt.NDArray | None: 

519 """Gather rows distributed in contiguous chunks to rank 0. 

520 

521 Returns: 

522 All ``num_global`` rows on rank 0, ``None`` on the other ranks 

523 """ 

524 chunks = comm.gather((int(local_range[0]), np.asarray(local)), root=0) 

525 if comm.rank != 0: 

526 return None 

527 assert chunks is not None 

528 first = chunks[0][1] 

529 rows = np.empty((num_global, *first.shape[1:]), dtype=first.dtype) 

530 for start, chunk in chunks: 

531 rows[start : start + len(chunk)] = chunk 

532 return rows 

533 

534 

535def gather_concatenate(comm: MPI.Comm, local: npt.NDArray) -> npt.NDArray | None: 

536 """Concatenate an array over all ranks on rank 0, in rank order.""" 

537 chunks = comm.gather(local, root=0) 

538 return None if chunks is None else np.concatenate(chunks)