version GIT relicensing-7278-g091132d5eb 2026-12-02 03:10:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
sparsity_tools.cc
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
4// Copyright (C) 2008 - 2025 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Detailed license information governing the source code and contributions
9// can be found in LICENSE.md and CONTRIBUTING.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
13
15
19
20#include <algorithm>
21#include <functional>
22#include <memory>
23#include <set>
24
25#ifdef DEAL_II_WITH_MPI
26# include <deal.II/base/mpi.h>
28
31#endif
32
33#ifdef DEAL_II_WITH_METIS
34// metis.h declares its functions in an extern "C" { } block
35# include <metis.h>
36#endif
37
38#ifdef DEAL_II_TRILINOS_WITH_ZOLTAN
39# include <zoltan_cpp.h>
40#endif
41
42#include <string>
43
44
46
47namespace SparsityTools
48{
49 namespace
50 {
51 void
52 partition_metis(const SparsityPattern &sparsity_pattern,
53 const std::vector<unsigned int> &cell_weights,
54 const unsigned int n_partitions,
55 std::vector<unsigned int> &partition_indices)
56 {
57 // Make sure that METIS is actually
58 // installed and detected
59#ifndef DEAL_II_WITH_METIS
60 (void)sparsity_pattern;
61 (void)cell_weights;
62 (void)n_partitions;
63 (void)partition_indices;
65#else
66
67 // Generate the data structures for METIS. Note that this is particularly
68 // simple, since METIS wants exactly our compressed row storage format.
69 // We only have to set up a few auxiliary arrays and convert from our
70 // unsigned cell weights to signed ones.
71 idx_t n = static_cast<signed int>(sparsity_pattern.n_rows());
72
73 idx_t ncon = 1; // number of balancing constraints (should be >0)
74
75 // We can not partition n items into more than n parts. METIS will
76 // generate non-sensical output (everything is owned by a single process)
77 // and complain with a message (but won't return an error code!):
78 // ***Cannot bisect a graph with 0 vertices!
79 // ***You are trying to partition a graph into too many parts!
80 idx_t nparts =
81 std::min(n,
82 static_cast<idx_t>(
83 n_partitions)); // number of subdomains to create
84
85 // use default options for METIS
86 idx_t options[METIS_NOPTIONS];
87 METIS_SetDefaultOptions(options);
88
89 // one more nuisance: we have to copy our own data to arrays that store
90 // signed integers :-(
91 std::vector<idx_t> int_rowstart(1);
92 int_rowstart.reserve(sparsity_pattern.n_rows() + 1);
93 std::vector<idx_t> int_colnums;
94 int_colnums.reserve(sparsity_pattern.n_nonzero_elements());
95 for (SparsityPattern::size_type row = 0; row < sparsity_pattern.n_rows();
96 ++row)
97 {
98 for (SparsityPattern::iterator col = sparsity_pattern.begin(row);
99 col < sparsity_pattern.end(row);
100 ++col)
101 int_colnums.push_back(col->column());
102 int_rowstart.push_back(int_colnums.size());
103 }
104
105 std::vector<idx_t> int_partition_indices(sparsity_pattern.n_rows());
106
107 // Set up cell weighting option
108 std::vector<idx_t> int_cell_weights;
109 if (cell_weights.size() > 0)
110 {
111 Assert(cell_weights.size() == sparsity_pattern.n_rows(),
112 ExcDimensionMismatch(cell_weights.size(),
113 sparsity_pattern.n_rows()));
114 int_cell_weights.resize(cell_weights.size());
115 std::copy(cell_weights.begin(),
116 cell_weights.end(),
117 int_cell_weights.begin());
118 }
119 // Set a pointer to the optional cell weighting information.
120 // METIS expects a null pointer if there are no weights to be considered.
121 idx_t *const p_int_cell_weights =
122 (cell_weights.size() > 0 ? int_cell_weights.data() : nullptr);
123
124
125 // Make use of METIS' error code.
126 int ierr;
127
128 // Select which type of partitioning to create
129
130 // Use recursive if the number of partitions is less than or equal to 8
131 idx_t dummy; // output: # of edges cut by the resulting partition
132 if (nparts <= 8)
133 ierr = METIS_PartGraphRecursive(&n,
134 &ncon,
135 int_rowstart.data(),
136 int_colnums.data(),
137 p_int_cell_weights,
138 nullptr,
139 nullptr,
140 &nparts,
141 nullptr,
142 nullptr,
143 options,
144 &dummy,
145 int_partition_indices.data());
146
147 // Otherwise use kway
148 else
149 ierr = METIS_PartGraphKway(&n,
150 &ncon,
151 int_rowstart.data(),
152 int_colnums.data(),
153 p_int_cell_weights,
154 nullptr,
155 nullptr,
156 &nparts,
157 nullptr,
158 nullptr,
159 options,
160 &dummy,
161 int_partition_indices.data());
162
163 // If metis returns normally, an error code METIS_OK=1 is returned from
164 // the above functions (see metish.h)
165 AssertThrow(ierr == 1, ExcMETISError(ierr));
166
167 // now copy back generated indices into the output array
168 std::copy(int_partition_indices.begin(),
169 int_partition_indices.end(),
170 partition_indices.begin());
171#endif
172 }
173
174
175// Query functions unused if zoltan is not installed
176#ifdef DEAL_II_TRILINOS_WITH_ZOLTAN
177 // Query functions for partition_zoltan
178 int
179 get_number_of_objects(void *data, int *ierr)
180 {
181 SparsityPattern *graph = reinterpret_cast<SparsityPattern *>(data);
182
183 *ierr = ZOLTAN_OK;
184
185 return graph->n_rows();
186 }
187
188
189 void
190 get_object_list(void *data,
191 int /*sizeGID*/,
192 int /*sizeLID*/,
193 ZOLTAN_ID_PTR globalID,
194 ZOLTAN_ID_PTR localID,
195 int /*wgt_dim*/,
196 float * /*obj_wgts*/,
197 int *ierr)
198 {
199 SparsityPattern *graph = reinterpret_cast<SparsityPattern *>(data);
200 *ierr = ZOLTAN_OK;
201
202 Assert(globalID != nullptr, ExcInternalError());
203 Assert(localID != nullptr, ExcInternalError());
204
205 // set global degrees of freedom
206 auto n_dofs = graph->n_rows();
207
208 for (unsigned int i = 0; i < n_dofs; ++i)
209 {
210 globalID[i] = i;
211 localID[i] = i; // Same as global ids.
212 }
213 }
214
215
216 void
217 get_num_edges_list(void *data,
218 int /*sizeGID*/,
219 int /*sizeLID*/,
220 int num_obj,
221 ZOLTAN_ID_PTR globalID,
222 ZOLTAN_ID_PTR /*localID*/,
223 int *numEdges,
224 int *ierr)
225 {
226 SparsityPattern *graph = reinterpret_cast<SparsityPattern *>(data);
227
228 *ierr = ZOLTAN_OK;
229
230 Assert(numEdges != nullptr, ExcInternalError());
231
232 for (int i = 0; i < num_obj; ++i)
233 {
234 if (graph->exists(i, i)) // Check if diagonal element is present
235 numEdges[i] = graph->row_length(globalID[i]) - 1;
236 else
237 numEdges[i] = graph->row_length(globalID[i]);
238 }
239 }
240
241
242
243 void
244 get_edge_list(void *data,
245 int /*sizeGID*/,
246 int /*sizeLID*/,
247 int num_obj,
248 ZOLTAN_ID_PTR /*globalID*/,
249 ZOLTAN_ID_PTR /*localID*/,
250 int * /*num_edges*/,
251 ZOLTAN_ID_PTR nborGID,
252 int *nborProc,
253 int /*wgt_dim*/,
254 float * /*ewgts*/,
255 int *ierr)
256 {
257 SparsityPattern *graph = reinterpret_cast<SparsityPattern *>(data);
258 *ierr = ZOLTAN_OK;
259
260 ZOLTAN_ID_PTR nextNborGID = nborGID;
261 int *nextNborProc = nborProc;
262
263 // Loop through rows corresponding to indices in globalID implicitly
265 i < static_cast<SparsityPattern::size_type>(num_obj);
266 ++i)
267 {
268 // Loop through each column to find neighbours
269 for (SparsityPattern::iterator col = graph->begin(i);
270 col < graph->end(i);
271 ++col)
272 // Ignore diagonal entries. Not needed for partitioning.
273 if (i != col->column())
274 {
275 Assert(nextNborGID != nullptr, ExcInternalError());
276 Assert(nextNborProc != nullptr, ExcInternalError());
277
278 *nextNborGID++ = col->column();
279 *nextNborProc++ = 0; // All the vertices on processor 0
280 }
281 }
282 }
283#endif
284
285
286 void
287 partition_zoltan(const SparsityPattern &sparsity_pattern,
288 const std::vector<unsigned int> &cell_weights,
289 const unsigned int n_partitions,
290 std::vector<unsigned int> &partition_indices)
291 {
292 // Make sure that ZOLTAN is actually
293 // installed and detected
294#ifndef DEAL_II_TRILINOS_WITH_ZOLTAN
295 (void)sparsity_pattern;
296 (void)cell_weights;
297 (void)n_partitions;
298 (void)partition_indices;
300#else
301
302 Assert(
303 cell_weights.empty(),
305 "The cell weighting functionality for Zoltan has not yet been implemented."));
306
307 // MPI environment must have been initialized by this point.
308 std::unique_ptr<Zoltan> zz = std::make_unique<Zoltan>(MPI_COMM_SELF);
309
310 // General parameters
311 // DEBUG_LEVEL call must precede the call to LB_METHOD
312 zz->Set_Param("DEBUG_LEVEL", "0"); // set level of debug info
313 zz->Set_Param(
314 "LB_METHOD",
315 "GRAPH"); // graph based partition method (LB-load balancing)
316 zz->Set_Param("NUM_LOCAL_PARTS",
317 std::to_string(n_partitions)); // set number of partitions
318
319 // The PHG partitioner is a hypergraph partitioner that Zoltan could use
320 // for graph partitioning.
321 // If number of vertices in hyperedge divided by total vertices in
322 // hypergraph exceeds PHG_EDGE_SIZE_THRESHOLD,
323 // then the hyperedge will be omitted as such (dense) edges will likely
324 // incur high communication costs regardless of the partition.
325 // PHG_EDGE_SIZE_THRESHOLD value is raised to 0.5 from the default
326 // value of 0.25 so that the PHG partitioner doesn't throw warning saying
327 // "PHG_EDGE_SIZE_THRESHOLD is low ..." after removing all dense edges.
328 // For instance, in two dimensions if the triangulation being partitioned
329 // is two quadrilaterals sharing an edge and if PHG_EDGE_SIZE_THRESHOLD
330 // value is set to 0.25, PHG will remove all the edges throwing the
331 // above warning.
332 zz->Set_Param("PHG_EDGE_SIZE_THRESHOLD", "0.5");
333
334 // Need a non-const object equal to sparsity_pattern
335 SparsityPattern graph;
336 graph.copy_from(sparsity_pattern);
337
338 // Set query functions
339 zz->Set_Num_Obj_Fn(get_number_of_objects, &graph);
340 zz->Set_Obj_List_Fn(get_object_list, &graph);
341 zz->Set_Num_Edges_Multi_Fn(get_num_edges_list, &graph);
342 zz->Set_Edge_List_Multi_Fn(get_edge_list, &graph);
343
344 // Variables needed by partition function
345 int changes = 0;
346 int num_gid_entries = 1;
347 int num_lid_entries = 1;
348 int num_import = 0;
349 ZOLTAN_ID_PTR import_global_ids = nullptr;
350 ZOLTAN_ID_PTR import_local_ids = nullptr;
351 int *import_procs = nullptr;
352 int *import_to_part = nullptr;
353 int num_export = 0;
354 ZOLTAN_ID_PTR export_global_ids = nullptr;
355 ZOLTAN_ID_PTR export_local_ids = nullptr;
356 int *export_procs = nullptr;
357 int *export_to_part = nullptr;
358
359 // call partitioner
360 const int rc = zz->LB_Partition(changes,
361 num_gid_entries,
362 num_lid_entries,
363 num_import,
364 import_global_ids,
365 import_local_ids,
366 import_procs,
367 import_to_part,
368 num_export,
369 export_global_ids,
370 export_local_ids,
371 export_procs,
372 export_to_part);
373
374 // check for error code in partitioner
375 Assert(rc == ZOLTAN_OK, ExcInternalError());
376
377 // By default, all indices belong to part 0. After zoltan partition
378 // some are migrated to different part ID, which is stored in
379 // export_to_part array.
380 std::fill(partition_indices.begin(), partition_indices.end(), 0);
381
382 // copy from export_to_part to partition_indices, whose part_ids != 0.
383 Assert(export_to_part != nullptr, ExcInternalError());
384 for (int i = 0; i < num_export; ++i)
385 partition_indices[export_local_ids[i]] = export_to_part[i];
386#endif
387 }
388 } // namespace
389
390
391 void
392 partition(const SparsityPattern &sparsity_pattern,
393 const unsigned int n_partitions,
394 std::vector<unsigned int> &partition_indices,
395 const Partitioner partitioner)
396 {
397 std::vector<unsigned int> cell_weights;
398
399 // Call the other more general function
400 partition(sparsity_pattern,
401 cell_weights,
402 n_partitions,
403 partition_indices,
404 partitioner);
405 }
406
407
408 void
409 partition(const SparsityPattern &sparsity_pattern,
410 const std::vector<unsigned int> &cell_weights,
411 const unsigned int n_partitions,
412 std::vector<unsigned int> &partition_indices,
413 const Partitioner partitioner)
414 {
415 Assert(sparsity_pattern.n_rows() == sparsity_pattern.n_cols(),
417 Assert(sparsity_pattern.is_compressed(),
419
420 Assert(n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));
421 Assert(partition_indices.size() == sparsity_pattern.n_rows(),
422 ExcInvalidArraySize(partition_indices.size(),
423 sparsity_pattern.n_rows()));
424
425 // check for an easy return
426 if (n_partitions == 1 || (sparsity_pattern.n_rows() == 1))
427 {
428 std::fill_n(partition_indices.begin(), partition_indices.size(), 0U);
429 return;
430 }
431
432 if (partitioner == Partitioner::metis)
433 partition_metis(sparsity_pattern,
434 cell_weights,
435 n_partitions,
436 partition_indices);
437 else if (partitioner == Partitioner::zoltan)
438 partition_zoltan(sparsity_pattern,
439 cell_weights,
440 n_partitions,
441 partition_indices);
442 else
444 }
445
446
447 unsigned int
449 std::vector<unsigned int> &color_indices)
450 {
451 // Make sure that ZOLTAN is actually
452 // installed and detected
453#ifndef DEAL_II_TRILINOS_WITH_ZOLTAN
454 (void)sparsity_pattern;
455 (void)color_indices;
457 return 0;
458#else
459 // coloring algorithm is run in serial by each processor.
460 std::unique_ptr<Zoltan> zz = std::make_unique<Zoltan>(MPI_COMM_SELF);
461
462 // Coloring parameters
463 // DEBUG_LEVEL must precede all other calls
464 zz->Set_Param("DEBUG_LEVEL", "0"); // level of debug info
465 zz->Set_Param("COLORING_PROBLEM", "DISTANCE-1"); // Standard coloring
466 zz->Set_Param("NUM_GID_ENTRIES", "1"); // 1 entry represents global ID
467 zz->Set_Param("NUM_LID_ENTRIES", "1"); // 1 entry represents local ID
468 zz->Set_Param("OBJ_WEIGHT_DIM", "0"); // object weights not used
469 zz->Set_Param("RECOLORING_NUM_OF_ITERATIONS", "0");
470
471 // Zoltan::Color function requires a non-const SparsityPattern object
472 SparsityPattern graph;
473 graph.copy_from(sparsity_pattern);
474
475 // Set query functions required by coloring function
476 zz->Set_Num_Obj_Fn(get_number_of_objects, &graph);
477 zz->Set_Obj_List_Fn(get_object_list, &graph);
478 zz->Set_Num_Edges_Multi_Fn(get_num_edges_list, &graph);
479 zz->Set_Edge_List_Multi_Fn(get_edge_list, &graph);
480
481 // Variables needed by coloring function
482 int num_gid_entries = 1;
483 const int num_objects = graph.n_rows();
484
485 // Preallocate input variables. Element type fixed by ZOLTAN.
486 std::vector<ZOLTAN_ID_TYPE> global_ids(num_objects);
487 std::vector<int> color_exp(num_objects);
488
489 // Set ids for which coloring needs to be done
490 for (int i = 0; i < num_objects; ++i)
491 global_ids[i] = i;
492
493 // Call ZOLTAN coloring algorithm
494 int rc = zz->Color(num_gid_entries,
495 num_objects,
496 global_ids.data(),
497 color_exp.data());
498 // Check for error code
499 Assert(rc == ZOLTAN_OK, ExcInternalError());
500
501 // Allocate and assign color indices
502 color_indices.resize(num_objects);
503 Assert(color_exp.size() == color_indices.size(),
504 ExcDimensionMismatch(color_exp.size(), color_indices.size()));
505
506 std::copy(color_exp.begin(), color_exp.end(), color_indices.begin());
507
508 unsigned int n_colors =
509 *(std::max_element(color_indices.begin(), color_indices.end()));
510 return n_colors;
511#endif
512 }
513
514
515 namespace internal
516 {
527 const std::vector<DynamicSparsityPattern::size_type> &new_indices,
528 const std::vector<std::pair<DynamicSparsityPattern::size_type,
530 &rows_by_coordination,
531 std::size_t &next_candidate)
532 {
533 while (new_indices[rows_by_coordination[next_candidate].second] !=
535 ++next_candidate;
536
537 return rows_by_coordination[next_candidate].second;
538 }
539 } // namespace internal
540
541
542
543 void
545 const DynamicSparsityPattern &sparsity,
546 std::vector<DynamicSparsityPattern::size_type> &new_indices,
547 const std::vector<DynamicSparsityPattern::size_type> &starting_indices)
548 {
549 Assert(sparsity.n_rows() == sparsity.n_cols(),
550 ExcDimensionMismatch(sparsity.n_rows(), sparsity.n_cols()));
551 Assert(sparsity.n_rows() == new_indices.size(),
552 ExcDimensionMismatch(sparsity.n_rows(), new_indices.size()));
553 Assert(starting_indices.size() <= sparsity.n_rows(),
555 "You can't specify more starting indices than there are rows"));
556 Assert(sparsity.row_index_set().size() == 0 ||
557 sparsity.row_index_set().size() == sparsity.n_rows(),
559 "Only valid for sparsity patterns which store all rows."));
560 for (const auto starting_index : starting_indices)
561 {
562 (void)starting_index;
563 Assert(starting_index < sparsity.n_rows(),
564 ExcMessage("Invalid starting index: All starting indices need "
565 "to be between zero and the number of rows in the "
566 "sparsity pattern."));
567 }
568
569 // store the indices of the dofs renumbered in the last round. Default to
570 // starting points
571 std::vector<DynamicSparsityPattern::size_type> last_round_dofs(
572 starting_indices);
573
574 // initialize the new_indices array with invalid values
575 std::fill(new_indices.begin(),
576 new_indices.end(),
578
579 // if no starting indices were given: find dof with lowest coordination
580 // number
581 if (last_round_dofs.empty())
582 {
583 DynamicSparsityPattern::size_type starting_index = 0;
584 for (DynamicSparsityPattern::size_type row = 1; row < sparsity.n_rows();
585 ++row)
586 if (sparsity.row_length(row) < sparsity.row_length(starting_index))
587 starting_index = row;
588 last_round_dofs.push_back(starting_index);
589 }
590
591 // all rows sorted by coordination number (and row index). We only set
592 // up and use this vector when renumbering with sparsity patterns that
593 // have more than one component in the connectivity graph.
594 std::vector<std::pair<DynamicSparsityPattern::size_type,
596 rows_by_coordination;
597 std::size_t next_candidate = 0;
598
599 // store next free dof index
600 DynamicSparsityPattern::size_type next_free_number = 0;
601
602 // enumerate the first round dofs
603 for (const auto &last_round_dof : last_round_dofs)
604 new_indices[last_round_dof] = next_free_number++;
605
606 // store the indices of the dofs to be renumbered in the next round
607 std::vector<DynamicSparsityPattern::size_type> next_round_dofs;
608
609 // store for each coordination number the dofs with these coordination
610 // number
611 std::vector<std::pair<unsigned int, DynamicSparsityPattern::size_type>>
612 dofs_by_coordination;
613
614 // now do as many steps as needed to renumber all dofs
615 while (true)
616 {
617 next_round_dofs.clear();
618
619 // find all neighbors of the dofs numbered in the last round
620 for (const auto dof : last_round_dofs)
621 {
622 const unsigned int row_length = sparsity.row_length(dof);
623 for (unsigned int i = 0; i < row_length; ++i)
624 {
625 // skip dofs which are already numbered
626 const auto column = sparsity.column_number(dof, i);
627 if (new_indices[column] == numbers::invalid_size_type)
628 {
629 next_round_dofs.push_back(column);
630
631 // assign a dummy value to 'new_indices' to avoid adding
632 // the same index again; those will get the right number
633 // at the end of the outer 'while' loop
634 new_indices[column] = 0;
635 }
636 }
637 }
638
639 // check whether there are any new dofs in the list. if there are
640 // none, then we have completely numbered the current component of the
641 // graph. check if there are as yet unnumbered components of the graph
642 // that we would then have to do next
643 if (next_round_dofs.empty())
644 {
645 if (next_free_number == sparsity.n_rows())
646 // no unnumbered indices, so we can leave now
647 break;
648
649 // otherwise find a valid starting point for the next component of
650 // the graph and continue with numbering that one. we only do so
651 // if no starting indices were provided by the user (see the
652 // documentation of this function) so produce an error if we got
653 // here and starting indices were given
654 Assert(starting_indices.empty(),
655 ExcMessage("The input graph appears to have more than one "
656 "component, but as stated in the documentation "
657 "we only want to reorder such graphs if no "
658 "starting indices are given. The function was "
659 "called with starting indices, however."));
660
661 if (rows_by_coordination.empty())
662 {
663 // We have more than one component in the connectivity
664 // graph of the sparsity pattern. Set up rows_by_coordination:
665
666 rows_by_coordination.reserve(sparsity.n_rows());
668 row < sparsity.n_rows();
669 ++row)
670 rows_by_coordination.emplace_back(sparsity.row_length(row),
671 row);
672 std::sort(rows_by_coordination.begin(),
673 rows_by_coordination.end());
674 }
675
676 next_round_dofs.push_back(internal::find_unnumbered_starting_index(
677 new_indices, rows_by_coordination, next_candidate));
678 }
679
680
681 // find coordination number for each of these dofs
682 dofs_by_coordination.clear();
683 for (const types::global_dof_index next_round_dof : next_round_dofs)
684 dofs_by_coordination.emplace_back(sparsity.row_length(next_round_dof),
685 next_round_dof);
686 std::sort(dofs_by_coordination.begin(), dofs_by_coordination.end());
687
688 // assign new DoF numbers to the elements of the present front:
689 for (const auto &i : dofs_by_coordination)
690 new_indices[i.second] = next_free_number++;
691
692 // after that: use this round's dofs for the next round
693 last_round_dofs.swap(next_round_dofs);
694 }
695
696 // test for all indices numbered. this mostly tests whether the
697 // front-marching-algorithm (which Cuthill-McKee actually is) has reached
698 // all points.
699 Assert((std::find(new_indices.begin(),
700 new_indices.end(),
701 numbers::invalid_size_type) == new_indices.end()) &&
702 (next_free_number == sparsity.n_rows()),
704 }
705
706
707
708 namespace internal
709 {
710 void
712 const DynamicSparsityPattern &connectivity,
713 std::vector<DynamicSparsityPattern::size_type> &renumbering)
714 {
715 AssertDimension(connectivity.n_rows(), connectivity.n_cols());
716 AssertDimension(connectivity.n_rows(), renumbering.size());
717 Assert(connectivity.row_index_set().size() == 0 ||
718 connectivity.row_index_set().size() == connectivity.n_rows(),
720 "Only valid for sparsity patterns which store all rows."));
721
722 // The algorithm below works by partitioning the rows in the
723 // connectivity graph, called nodes, into groups. The groups are defined
724 // as those nodes in immediate neighborhood of some pivot node, which we
725 // choose by minimal adjacency below.
726
727 // We define two types of node categories for nodes not yet classified,
728 // one consisting of all nodes we've not seen at all, and one for nodes
729 // identified as neighbors (variable current_neighbors below) but not
730 // yet grouped. We use this classification in combination with an
731 // unsorted vector, which is much faster than keeping a sorted data
732 // structure (e.g. std::set)
733 constexpr types::global_dof_index unseen_node =
735 constexpr types::global_dof_index available_node = unseen_node - 1;
736 const types::global_dof_index n_nodes = connectivity.n_rows();
737 std::vector<types::global_dof_index> touched_nodes(n_nodes, unseen_node);
738
739 std::vector<unsigned int> row_lengths(n_nodes);
740 std::vector<types::global_dof_index> current_neighbors;
741 std::vector<types::global_dof_index> group_starts(1);
742 std::vector<types::global_dof_index> group_indices;
743 group_indices.reserve(n_nodes);
744
745 // First collect the number of neighbors for each node. We use this
746 // field to find the next node with the minimum number of non-touched
747 // neighbors in the field n_remaining_neighbors, so we will count down
748 // on this field. We also cache the row lengths because we need this
749 // data frequently and getting it from the sparsity pattern is more
750 // expensive.
751 for (types::global_dof_index row = 0; row < n_nodes; ++row)
752 {
753 row_lengths[row] = connectivity.row_length(row);
754 Assert(row_lengths[row] > 0, ExcInternalError());
755 }
756 std::vector<unsigned int> n_remaining_neighbors(row_lengths);
757
758 // This outer loop is typically traversed only once, unless the global
759 // graph is not connected
760 while (true)
761 {
762 // Find node with the minimal number of neighbors (typically a
763 // corner node when based on FEM meshes). If no node is left, we are
764 // done. Together with the outer while loop, this loop can possibly
765 // be of quadratic complexity in the number of disconnected
766 // partitions, i.e. up to n_nodes in the worst case,
767 // but that is not the usual use case of this loop and thus not
768 // optimized for.
769 {
770 unsigned int candidate_valence = numbers::invalid_unsigned_int;
771 types::global_dof_index candidate_index =
773 for (types::global_dof_index i = 0; i < n_nodes; ++i)
774 if (touched_nodes[i] == unseen_node)
775 if (row_lengths[i] < candidate_valence)
776 {
777 candidate_index = i;
778 candidate_valence = n_remaining_neighbors[i];
779 if (candidate_valence <= 1)
780 break;
781 }
782 if (candidate_index == numbers::invalid_dof_index)
783 break;
784
785 Assert(candidate_valence > 0, ExcInternalError());
786
787 current_neighbors = {candidate_index};
788 touched_nodes[candidate_index] = available_node;
789 }
790
791 while (true)
792 {
793 // Find node with minimum number of untouched neighbors among
794 // the next set of possible neighbors (= valence), and among the
795 // set of nodes with the minimal number of neighbors, choose the
796 // one with the largest number of touched neighbors (i.e., the
797 // largest row length).
798 //
799 // This loop is typically the most expensive part for large
800 // graphs and thus only run once. We also do some cleanup, i.e.,
801 // the indices added to a group in the previous round need to be
802 // removed at this point.
803 unsigned int candidate_valence = numbers::invalid_unsigned_int;
804 types::global_dof_index candidate_index =
806 unsigned int candidate_row_length = 0;
807 const unsigned int loop_length = current_neighbors.size();
808 unsigned int write_index = 0;
809 for (unsigned int i = 0; i < loop_length; ++i)
810 {
811 const types::global_dof_index node = current_neighbors[i];
812 Assert(touched_nodes[node] != unseen_node,
814 if (touched_nodes[node] == available_node)
815 {
816 current_neighbors[write_index] = node;
817 ++write_index;
818 if (n_remaining_neighbors[node] < candidate_valence ||
819 (n_remaining_neighbors[node] == candidate_valence &&
820 (row_lengths[node] > candidate_row_length ||
821 (row_lengths[node] == candidate_row_length &&
822 node < candidate_index))))
823 {
824 candidate_index = node;
825 candidate_valence = n_remaining_neighbors[node];
826 candidate_row_length = row_lengths[node];
827 }
828 }
829 }
830 current_neighbors.resize(write_index);
831
832 if constexpr (running_in_debug_mode())
833 {
834 for (const types::global_dof_index node : current_neighbors)
835 Assert(touched_nodes[node] == available_node,
837 }
838
839 // No more neighbors left -> terminate loop
840 if (current_neighbors.empty())
841 break;
842
843 // Add the pivot and all direct neighbors of the pivot node not
844 // yet touched to the list of new entries.
845 group_indices.push_back(candidate_index);
846 touched_nodes[candidate_index] = group_starts.size() - 1;
847 const auto end_it = connectivity.end(candidate_index);
848 for (auto it = connectivity.begin(candidate_index); it != end_it;
849 ++it)
850 if (touched_nodes[it->column()] >= available_node)
851 {
852 group_indices.push_back(it->column());
853 touched_nodes[it->column()] = group_starts.size() - 1;
854 }
855 group_starts.push_back(group_indices.size());
856
857 // Add all neighbors of the current list not yet seen to the set
858 // of possible next nodes. The added node is grouped and thus no
859 // longer a valid neighbor (here we assume symmetry of the
860 // connectivity). It will be removed from the list of neighbors
861 // by the code further up in the next iteration of the
862 // surrounding loop.
863 for (types::global_dof_index index =
864 group_starts[group_starts.size() - 2];
865 index < group_starts.back();
866 ++index)
867 {
868 auto it = connectivity.begin(group_indices[index]);
869 const auto end_row = connectivity.end(group_indices[index]);
870 for (; it != end_row; ++it)
871 {
872 if (touched_nodes[it->column()] == unseen_node)
873 {
874 current_neighbors.push_back(it->column());
875 touched_nodes[it->column()] = available_node;
876 }
877 n_remaining_neighbors[it->column()]--;
878 }
879 }
880 }
881 }
882
883 // Sanity check: for all nodes, there should not be any neighbors left
884 for (types::global_dof_index row = 0; row < n_nodes; ++row)
885 Assert(n_remaining_neighbors[row] == 0, ExcInternalError());
886
887 // If the number of groups is smaller than the number of nodes, we
888 // continue by recursively calling this method
889 const unsigned int n_groups = group_starts.size() - 1;
890 if (n_groups < n_nodes)
891 {
892 // Form the connectivity of the groups
893 DynamicSparsityPattern connectivity_next(n_groups, n_groups);
894 for (types::global_dof_index row = 0; row < n_groups; ++row)
895 for (types::global_dof_index index = group_starts[row];
896 index < group_starts[row + 1];
897 ++index)
898 {
899 auto it = connectivity.begin(group_indices[index]);
900 const auto end_it = connectivity.end(group_indices[index]);
901 for (; it != end_it; ++it)
902 connectivity_next.add(row, touched_nodes[it->column()]);
903 }
904
905 // Recursively call the reordering
906 std::vector<types::global_dof_index> renumbering_next(n_groups);
907 reorder_hierarchical(connectivity_next, renumbering_next);
908
909 // Renumber the indices group by group according to the incoming
910 // ordering for the groups
911 for (types::global_dof_index row = 0, c = 0; row < n_groups; ++row)
912 for (types::global_dof_index index =
913 group_starts[renumbering_next[row]];
914 index < group_starts[renumbering_next[row] + 1];
915 ++index, ++c)
916 renumbering[c] = group_indices[index];
917 }
918 else
919 {
920 // All groups should have size one and no more recursion is possible,
921 // so use the numbering of the groups
922 unsigned int c = 0;
923 for (const types::global_dof_index i : group_indices)
924 renumbering[c++] = i;
925 }
926 }
927 } // namespace internal
928
929 void
931 const DynamicSparsityPattern &connectivity,
932 std::vector<DynamicSparsityPattern::size_type> &renumbering)
933 {
934 // the internal renumbering keeps the numbering the wrong way around (but
935 // we cannot invert the numbering inside that method because it is used
936 // recursively), so invert it here
937 internal::reorder_hierarchical(connectivity, renumbering);
938 renumbering = Utilities::invert_permutation(renumbering);
939 }
940
941
942
943#ifdef DEAL_II_WITH_MPI
944
945 void
947 const IndexSet &locally_owned_rows,
948 const MPI_Comm mpi_comm,
949 const IndexSet &locally_relevant_rows)
950 {
951 using map_vec_t =
952 std::map<unsigned int, std::vector<DynamicSparsityPattern::size_type>>;
953
954 // 1. limit rows to non owned:
955 IndexSet requested_rows(locally_relevant_rows);
956 requested_rows.subtract_set(locally_owned_rows);
957
958 std::vector<unsigned int> index_owner =
959 Utilities::MPI::compute_index_owner(locally_owned_rows,
960 requested_rows,
961 mpi_comm);
962
963 // 2. go through requested_rows, figure out the owner and add the row to
964 // request
965 map_vec_t rows_data;
967 i < requested_rows.n_elements();
968 ++i)
969 {
971 requested_rows.nth_index_in_set(i);
972
973 rows_data[index_owner[i]].push_back(row);
974 }
975
976 // 3. get what others ask us to send
977 const auto rows_data_received =
978 Utilities::MPI::some_to_some(mpi_comm, rows_data);
979
980 // 4. now prepare data to be sent in the same format as in
981 // distribute_sparsity_pattern() below, i.e.
982 // rX,num_rX,cols_rX
983 map_vec_t send_data;
984 for (const auto &data : rows_data_received)
985 {
986 for (const auto &row : data.second)
987 {
988 const auto rlen = dsp.row_length(row);
989
990 // skip empty lines
991 if (rlen == 0)
992 continue;
993
994 // save entries
995 send_data[data.first].push_back(row); // row index
996 send_data[data.first].push_back(rlen); // number of entries
997 for (DynamicSparsityPattern::size_type c = 0; c < rlen; ++c)
998 send_data[data.first].push_back(
999 dsp.column_number(row, c)); // columns
1000 } // loop over rows
1001 } // loop over received data
1002
1003 // 5. communicate rows
1004 const auto received_data =
1005 Utilities::MPI::some_to_some(mpi_comm, send_data);
1006
1007 // 6. add result to our sparsity
1008 for (const auto &data : received_data)
1009 {
1010 const auto &recv_buf = data.second;
1011 auto ptr = recv_buf.begin();
1012 const auto end = recv_buf.end();
1013 while (ptr != end)
1014 {
1015 const auto row = *(ptr++);
1016 Assert(ptr != end, ExcInternalError());
1017
1018 const auto n_entries = *(ptr++);
1019 Assert(n_entries > 0, ExcInternalError());
1020 Assert(ptr != end, ExcInternalError());
1021
1022 // make sure we clear whatever was previously stored
1023 // in these rows. Otherwise we can't guarantee that the
1024 // data is consistent across MPI communicator.
1025 dsp.clear_row(row);
1026
1027 Assert(ptr + (n_entries - 1) != end, ExcInternalError());
1028 dsp.add_entries(row, ptr, ptr + n_entries, true);
1029 ptr += n_entries;
1030 }
1031 Assert(ptr == end, ExcInternalError());
1032 }
1033 }
1034
1035
1036
1037 void
1040 const std::vector<DynamicSparsityPattern::size_type> &rows_per_cpu,
1041 const MPI_Comm mpi_comm,
1042 const IndexSet &myrange)
1043 {
1044 const unsigned int myid = Utilities::MPI::this_mpi_process(mpi_comm);
1045 std::vector<DynamicSparsityPattern::size_type> start_index(
1046 rows_per_cpu.size() + 1);
1047 start_index[0] = 0;
1048 for (DynamicSparsityPattern::size_type i = 0; i < rows_per_cpu.size(); ++i)
1049 start_index[i + 1] = start_index[i] + rows_per_cpu[i];
1050
1051 IndexSet owned(start_index.back());
1052 owned.add_range(start_index[myid], start_index[myid] + rows_per_cpu[myid]);
1053
1054 distribute_sparsity_pattern(dsp, owned, mpi_comm, myrange);
1055 }
1056
1057
1058
1059 void
1061 const IndexSet &locally_owned_rows,
1062 const MPI_Comm mpi_comm,
1063 const IndexSet &locally_relevant_rows)
1064 {
1066 dsp.row_index_set() == locally_relevant_rows,
1067 ExcMessage(
1068 "The DynamicSparsityPattern must be initialized with an IndexSet that contains locally relevant indices."));
1069
1070 IndexSet requested_rows(locally_relevant_rows);
1071 requested_rows.subtract_set(locally_owned_rows);
1072
1073 std::vector<unsigned int> index_owner =
1074 Utilities::MPI::compute_index_owner(locally_owned_rows,
1075 requested_rows,
1076 mpi_comm);
1077
1078 using map_vec_t =
1079 std::map<unsigned int, std::vector<DynamicSparsityPattern::size_type>>;
1080
1081 map_vec_t send_data;
1082
1084 i < requested_rows.n_elements();
1085 ++i)
1086 {
1088 requested_rows.nth_index_in_set(i);
1089
1090 const auto rlen = dsp.row_length(row);
1091
1092 // skip empty lines
1093 if (rlen == 0)
1094 continue;
1095
1096 // save entries
1097 send_data[index_owner[i]].push_back(row); // row index
1098 send_data[index_owner[i]].push_back(rlen); // number of entries
1099 for (DynamicSparsityPattern::size_type c = 0; c < rlen; ++c)
1100 {
1101 // columns
1102 const auto column = dsp.column_number(row, c);
1103 send_data[index_owner[i]].push_back(column);
1104 }
1105 }
1106
1107 const auto receive_data = Utilities::MPI::some_to_some(mpi_comm, send_data);
1108
1109 // add what we received
1110 for (const auto &data : receive_data)
1111 {
1112 const auto &recv_buf = data.second;
1113 auto ptr = recv_buf.begin();
1114 const auto end = recv_buf.end();
1115 while (ptr != end)
1116 {
1117 const auto row = *(ptr++);
1118 Assert(ptr != end, ExcInternalError());
1119 const auto n_entries = *(ptr++);
1120
1121 Assert(ptr + (n_entries - 1) != end, ExcInternalError());
1122 dsp.add_entries(row, ptr, ptr + n_entries, true);
1123 ptr += n_entries;
1124 }
1125 Assert(ptr == end, ExcInternalError());
1126 }
1127 }
1128
1129
1130
1131 void
1133 const std::vector<IndexSet> &owned_set_per_cpu,
1134 const MPI_Comm mpi_comm,
1135 const IndexSet &myrange)
1136 {
1137 const unsigned int myid = Utilities::MPI::this_mpi_process(mpi_comm);
1139 owned_set_per_cpu[myid],
1140 mpi_comm,
1141 myrange);
1142 }
1143
1144
1145
1146 void
1148 const IndexSet &locally_owned_rows,
1149 const MPI_Comm mpi_comm,
1150 const IndexSet &locally_relevant_rows)
1151 {
1152 using map_vec_t =
1154 std::vector<BlockDynamicSparsityPattern::size_type>>;
1155 map_vec_t send_data;
1156
1157 IndexSet requested_rows(locally_relevant_rows);
1158 requested_rows.subtract_set(locally_owned_rows);
1159
1160 std::vector<unsigned int> index_owner =
1161 Utilities::MPI::compute_index_owner(locally_owned_rows,
1162 requested_rows,
1163 mpi_comm);
1164
1166 i < requested_rows.n_elements();
1167 ++i)
1168 {
1170 requested_rows.nth_index_in_set(i);
1171
1173
1174 // skip empty lines
1175 if (rlen == 0)
1176 continue;
1177
1178 // save entries
1179 std::vector<BlockDynamicSparsityPattern::size_type> &dst =
1180 send_data[index_owner[i]];
1181
1182 dst.push_back(rlen); // number of entries
1183 dst.push_back(row); // row index
1184 for (BlockDynamicSparsityPattern::size_type c = 0; c < rlen; ++c)
1185 {
1186 // columns
1188 dsp.column_number(row, c);
1189 dst.push_back(column);
1190 }
1191 }
1192
1193 unsigned int num_receive = 0;
1194 {
1195 std::vector<unsigned int> send_to;
1196 send_to.reserve(send_data.size());
1197 for (const auto &sparsity_line : send_data)
1198 send_to.push_back(sparsity_line.first);
1199
1200 num_receive =
1202 send_to);
1203 }
1204
1205 std::vector<MPI_Request> requests(send_data.size());
1206
1207
1208 // send data
1209
1211 Utilities::MPI::CollectiveMutex::ScopedLock lock(mutex, mpi_comm);
1212
1213 const int mpi_tag = Utilities::MPI::internal::Tags::
1215
1216 {
1217 unsigned int idx = 0;
1218 for (const auto &sparsity_line : send_data)
1219 {
1220 const int ierr = MPI_Isend(
1221 sparsity_line.second.data(),
1222 sparsity_line.second.size(),
1223 Utilities::MPI::mpi_type_id_for_type<types::global_dof_index>,
1224 sparsity_line.first,
1225 mpi_tag,
1226 mpi_comm,
1227 &requests[idx++]);
1228 AssertThrowMPI(ierr);
1229 }
1230 }
1231
1232 {
1233 // receive
1234 std::vector<BlockDynamicSparsityPattern::size_type> recv_buf;
1235 for (unsigned int index = 0; index < num_receive; ++index)
1236 {
1237 MPI_Status status;
1238 int ierr = MPI_Probe(MPI_ANY_SOURCE, mpi_tag, mpi_comm, &status);
1239 AssertThrowMPI(ierr);
1240
1241 int len;
1242 ierr = MPI_Get_count(
1243 &status,
1244 Utilities::MPI::mpi_type_id_for_type<types::global_dof_index>,
1245 &len);
1246 AssertThrowMPI(ierr);
1247
1248 recv_buf.resize(len);
1249 ierr = MPI_Recv(
1250 recv_buf.data(),
1251 len,
1252 Utilities::MPI::mpi_type_id_for_type<types::global_dof_index>,
1253 status.MPI_SOURCE,
1254 status.MPI_TAG,
1255 mpi_comm,
1256 &status);
1257 AssertThrowMPI(ierr);
1258
1259 std::vector<BlockDynamicSparsityPattern::size_type>::const_iterator
1260 ptr = recv_buf.begin();
1261 std::vector<BlockDynamicSparsityPattern::size_type>::const_iterator
1262 end = recv_buf.end();
1263 while (ptr != end)
1264 {
1266 Assert(ptr != end, ExcInternalError());
1268 for (unsigned int c = 0; c < num; ++c)
1269 {
1270 Assert(ptr != end, ExcInternalError());
1271 dsp.add(row, *ptr);
1272 ++ptr;
1273 }
1274 }
1275 Assert(ptr == end, ExcInternalError());
1276 }
1277 }
1278
1279 // complete all sends, so that we can safely destroy the buffers.
1280 if (requests.size() > 0)
1281 {
1282 const int ierr =
1283 MPI_Waitall(requests.size(), requests.data(), MPI_STATUSES_IGNORE);
1284 AssertThrowMPI(ierr);
1285 }
1286 }
1287#endif
1288} // namespace SparsityTools
1289
*  iterator end()
size_type column_number(const size_type row, const unsigned int index) const
unsigned int row_length(const size_type row) const
void add(const size_type i, const size_type j)
void add_entries(const size_type row, ForwardIterator begin, ForwardIterator end, const bool indices_are_unique_and_sorted=false)
types::global_dof_index size_type
const IndexSet & row_index_set() const
size_type row_length(const size_type row) const
size_type column_number(const size_type row, const size_type index) const
void clear_row(const size_type row)
void add(const size_type i, const size_type j)
size_type size() const
Definition index_set.h:1759
size_type n_elements() const
Definition index_set.h:1917
void subtract_set(const IndexSet &other)
Definition index_set.cc:496
void add_range(const size_type begin, const size_type end)
Definition index_set.h:1786
size_type nth_index_in_set(const size_type local_index) const
Definition index_set.h:1958
types::global_dof_index size_type
size_type n_rows() const
size_type n_cols() const
bool is_compressed() const
std::size_t n_nonzero_elements() const
bool exists(const size_type i, const size_type j) const
iterator begin() const
void copy_from(const size_type n_rows, const size_type n_cols, const ForwardIterator begin, const ForwardIterator end)
iterator end() const
unsigned int row_length(const size_type row) const
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:38
constexpr bool running_in_debug_mode()
Definition config.h:76
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:39
Point< 2 > second
Definition grid_out.cc:4640
static ::ExceptionBase & ExcMETISNotInstalled()
static ::ExceptionBase & ExcInvalidNumberOfPartitions(int arg1)
static ::ExceptionBase & ExcMETISError(int arg1)
#define Assert(cond, exc)
#define AssertDimension(dim1, dim2)
#define AssertThrowMPI(error_code)
static ::ExceptionBase & ExcInvalidArraySize(int arg1, int arg2)
static ::ExceptionBase & ExcInternalError()
static ::ExceptionBase & ExcDimensionMismatch(std::size_t arg1, std::size_t arg2)
static ::ExceptionBase & ExcNotQuadratic()
static ::ExceptionBase & ExcZOLTANNotInstalled()
static ::ExceptionBase & ExcNotCompressed()
static ::ExceptionBase & ExcMessage(std::string arg1)
#define AssertThrow(cond, exc)
std::vector< index_type > data
Definition mpi.cc:734
void reorder_hierarchical(const DynamicSparsityPattern &connectivity, std::vector< DynamicSparsityPattern::size_type > &renumbering)
DynamicSparsityPattern::size_type find_unnumbered_starting_index(const std::vector< DynamicSparsityPattern::size_type > &new_indices, const std::vector< std::pair< DynamicSparsityPattern::size_type, DynamicSparsityPattern::size_type > > &rows_by_coordination, std::size_t &next_candidate)
unsigned int color_sparsity_pattern(const SparsityPattern &sparsity_pattern, std::vector< unsigned int > &color_indices)
void partition(const SparsityPattern &sparsity_pattern, const unsigned int n_partitions, std::vector< unsigned int > &partition_indices, const Partitioner partitioner=Partitioner::metis)
void reorder_hierarchical(const DynamicSparsityPattern &sparsity, std::vector< DynamicSparsityPattern::size_type > &new_indices)
void distribute_sparsity_pattern(DynamicSparsityPattern &dsp, const IndexSet &locally_owned_rows, const MPI_Comm mpi_comm, const IndexSet &locally_relevant_rows)
void gather_sparsity_pattern(DynamicSparsityPattern &dsp, const IndexSet &locally_owned_rows, const MPI_Comm mpi_comm, const IndexSet &locally_relevant_rows)
void reorder_Cuthill_McKee(const DynamicSparsityPattern &sparsity, std::vector< DynamicSparsityPattern::size_type > &new_indices, const std::vector< DynamicSparsityPattern::size_type > &starting_indices=std::vector< DynamicSparsityPattern::size_type >())
@ sparsity_tools_distribute_sparsity_pattern
SparsityTools::sparsity_tools_distribute_sparsity_pattern()
Definition mpi_tags.h:73
std::map< unsigned int, T > some_to_some(const MPI_Comm comm, const std::map< unsigned int, T > &objects_to_send)
std::vector< unsigned int > compute_index_owner(const IndexSet &owned_indices, const IndexSet &indices_to_look_up, const MPI_Comm comm)
Definition mpi.cc:1820
unsigned int this_mpi_process(const MPI_Comm mpi_communicator)
Definition mpi.cc:118
unsigned int compute_n_point_to_point_communications(const MPI_Comm mpi_comm, const std::vector< unsigned int > &destinations)
Definition mpi.cc:371
std::vector< Integer > invert_permutation(const std::vector< Integer > &permutation)
Definition utilities.h:1670
constexpr types::global_dof_index invalid_dof_index
Definition types.h:259
constexpr types::global_dof_index invalid_size_type
Definition types.h:240
constexpr unsigned int invalid_unsigned_int
Definition types.h:228
::VectorizedArray< Number, width > min(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)