FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
parti_scotch.cpp
1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
5
6#include <kernel/adjacency/graph.hpp>
7#include <kernel/geometry/parti_scotch.hpp>
8#include <kernel/util/dist.hpp>
9#include <kernel/util/math.hpp>
10#include <numeric>
11
12#if defined(FEAT_HAVE_SCOTCH) || defined(DOXYGEN)
13
14#include <scotch.h>
15#include <ptscotch.h>
16
17namespace FEAT::Geometry
18{
21 {
22 SCOTCH_Dgraph* inner;
23 std::vector<SCOTCH_Num> vertloctab;
24 std::vector<SCOTCH_Num> edgeloctab;
25 std::vector<SCOTCH_Num> veloloctab;
26
27 explicit ScotchGraph(const Dist::Comm& comm) : inner(SCOTCH_dgraphAlloc())
28 {
29 XASSERT(SCOTCH_dgraphInit(inner, comm.mpi_comm()) == 0);
30 }
31
32 ScotchGraph(ScotchGraph&) = delete;
33 ScotchGraph(ScotchGraph&&) = default;
34
35 ScotchGraph& operator=(const ScotchGraph&) = delete;
36 ScotchGraph& operator=(ScotchGraph&&) = default;
37
39 {
40 SCOTCH_dgraphExit(inner);
41 SCOTCH_dgraphFree(inner);
42 }
43 };
44
45 namespace
46 {
47 // Convert FEAT graph to SCOTCH graph
48 [[nodiscard]] bool
49 graph_to_scotch(ScotchGraph& scotch, const Adjacency::Graph& graph, Index first_elem, const std::vector<Real>& weights)
50 {
51 // NOTE: On SCOTCH naming:
52 // glb - global, i.e. across all ranks
53 // loc - local, i.e. on this rank
54 // gst - ghost
55
56 // Base value for all array indexing
57 // 0 for C, 1 for Fortran
58 static constexpr SCOTCH_Num baseval(0);
59
60 // Array of start indices in edgeloctab and edgegsttab of vertex adjacency sub-arrays
61 scotch.vertloctab.clear();
62
63 // Array holding the adjacency array of every local vertex
64 scotch.edgeloctab.clear();
65
66 {
67 const Index* dom_ptr = graph.get_domain_ptr();
68 const Index* img_idx = graph.get_image_idx();
69 for(Index i(0); i < graph.get_num_nodes_domain(); ++i)
70 {
71 scotch.vertloctab.push_back(SCOTCH_Num(scotch.edgeloctab.size()));
72 for(Index k(dom_ptr[i]); k < dom_ptr[i+1]; ++k)
73 {
74 if(img_idx[k] != first_elem + i)
75 {
76 scotch.edgeloctab.push_back(SCOTCH_Num(img_idx[k]));
77 }
78 }
79 }
80 scotch.vertloctab.push_back(SCOTCH_Num(scotch.edgeloctab.size()));
81 }
82
83 // Array of after-last indices in edgeloctab and edgegsttab of vertex adjacency sub-arrays.
84 // Because our edgeloctab is stored contiguously, we do not have to allocate memory for this,
85 // and can instead reuse vertloctab with an offset of one.
86 SCOTCH_Num* const vendloctab = scotch.vertloctab.data() + 1;
87
88 // Number of local vertices borne by this process
89 const auto vertlocnbr = SCOTCH_Num(graph.get_num_nodes_domain());
90
91 XASSERT(vertlocnbr == SCOTCH_Num(scotch.vertloctab.size() - 1));
92
93 // Maximum number of local vertices to be created on this process.
94 // Must be set to vertlocnbr for graphs without holes in their global
95 // numbering.
96 const SCOTCH_Num vertlocmax = vertlocnbr;
97
98 // Local number of arcs (directed edges), including arcs to local vertices as well as to ghost vertices.
99 const auto edgelocnbr = SCOTCH_Num(scotch.edgeloctab.size());
100
101 XASSERT(scotch.vertloctab.back() == edgelocnbr);
102
103 // Lower bounded by the minimum size of teh edge array required to encompass all used adjacency values;
104 // it can be set to edgelocnbr if the edge array is compact (which our edge array is)
105 const SCOTCH_Num edgelocsiz = edgelocnbr;
106
107 XASSERT(scotch.vertloctab.front() == baseval);
108
109 // Local vertex load array, holding integer load associated with every vertex
110 scotch.veloloctab.clear();
111
112 // set up weights if desired
113 if(!weights.empty())
114 {
115 XASSERT(weights.size() == std::size_t(vertlocnbr));
116
117 scotch.veloloctab.resize(std::size_t(vertlocnbr));
118
119 // SCOTCH expects integer weights, but we have float weights, so we first have to compute
120 // the total sum of all weights and then choose a scaling factor so that the sum of the
121 // scaled weights is a large integer not greater than 10^9; then we can simply multiply
122 // the weights by that scaling factor and convert to integers.
123
124 // compute the total sum of all weights
125 Real wsum = std::accumulate(weights.begin(), weights.end(), Real(0));
126 XASSERTM(wsum > 1e-3, "weight sum appears to be zero");
127
128 // compute integer weights for METIS
129 Real scale = 1E+9 / wsum;
130 for(std::size_t i(0); i < std::size_t(vertlocnbr); ++i)
131 {
132 scotch.veloloctab[i] = SCOTCH_Num(scale * weights[i]);
133 }
134 }
135
136 // Optional array of local vertex labels
137 SCOTCH_Num* const vlblloctab = nullptr;
138
139 // Optional array holding the local and ghost indices of neighbors of local vertices.
140 SCOTCH_Num* const edgegsttab = nullptr;
141
142 // Optional array holding the integer load associated with every arc.
143 // Matching arcs should always have identical loads. (You hear that, ParMETIS?)
144 SCOTCH_Num* const edloloctab = nullptr;
145
146 // NOTE: For PT-SCOTCH to operate properly, either all the arrays of a kind must
147 // be set to null on all processes, or else all of them must be non null.
148
149 return SCOTCH_dgraphBuild(
150 scotch.inner,
151 baseval,
152 vertlocnbr,
153 vertlocmax,
154 scotch.vertloctab.data(),
155 vendloctab,
156 scotch.veloloctab.empty() ? nullptr : scotch.veloloctab.data(),
157 vlblloctab,
158 edgelocnbr,
159 edgelocsiz,
160 scotch.edgeloctab.data(),
161 edgegsttab,
162 edloloctab) == 0;
163 }
164 } // namespace
165
166 void PartiScotch::_create_subgraph(const Adjacency::Graph& faces_at_elem, const Index num_parts)
167 {
168 // set number of desired partitions and total number of elements
169 this->_num_parts = num_parts;
170 this->_global_num_elements = faces_at_elem.get_num_nodes_domain();
171
172 // first of all, determine how many processes we want to use for Zoltan
173 int num_procs = Math::max(1, int(faces_at_elem.get_num_nodes_domain() / _min_elems));
174 if(_max_work_procs > 0)
175 {
176 Math::mini(num_procs, _max_work_procs);
177 }
178 Math::mini(num_procs, int(num_parts));
179 Math::mini(num_procs, _comm.size());
180
181 // do we need to create a sub-communicator for ParMETIS?
182 if(num_procs < _comm.size())
183 {
185 }
186 else
187 {
189 }
190
191 // get my rank and size
192 const int z_rank = _work_comm.rank();
193 const int z_size = _work_comm.size();
194
195 // make sure that the number of desired parts is not smaller than the size of the communicator
196 XASSERTM(Index(z_size) <= num_parts, "thou shall not create less partitions than thou hast ranks");
197
198 // does this process not participate in the sub-communicator?
199 if(z_size == 0)
200 {
201 this->_first_elem = this->_local_num_elements = Index(0);
202 return;
203 }
204
205 // get number of elements and faces
206 const Index num_elems = faces_at_elem.get_num_nodes_domain();
207 const Index num_faces = faces_at_elem.get_num_nodes_image();
208
209 // determine the first and the last element of this rank
210 Index first_elem = (Index(z_rank) * num_elems) / Index(z_size);
211 Index end_elem = (Index(z_rank + 1) * num_elems) / Index(z_size);
212 Index my_num_elems = end_elem - first_elem;
213
214 const Index* dom_ptr = faces_at_elem.get_domain_ptr();
215 const Index* img_idx = faces_at_elem.get_image_idx();
216
217 // create a sub-graph for this rank
218 const Index first_ptr = dom_ptr[first_elem];
219 const Index my_num_idx = dom_ptr[end_elem] - first_ptr;
220 Adjacency::Graph faces_at_my_elem(my_num_elems, num_faces, my_num_idx);
221
222 Index* my_dom_ptr = faces_at_my_elem.get_domain_ptr();
223 Index* my_img_idx = faces_at_my_elem.get_image_idx();
224 for(Index i(0); i <= my_num_elems; ++i)
225 {
226 my_dom_ptr[i] = dom_ptr[first_elem + i] - first_ptr;
227 }
228 for(Index i(0); i < my_num_idx; ++i)
229 {
230 my_img_idx[i] = img_idx[first_ptr + i];
231 }
232
233 // transpose graph for this rank
234 Adjacency::Graph elems_at_faces(Adjacency::RenderType::transpose, faces_at_elem);
235
236 // combine graph into our sub-hypergraph
237 this->_first_elem = first_elem;
238 this->_local_num_elements = my_num_elems;
239 this->_subgraph = Adjacency::Graph(Adjacency::RenderType::injectify_sorted, faces_at_my_elem, elems_at_faces);
240 this->_parts.resize(std::size_t(my_num_elems));
241 }
242
243 bool PartiScotch::_execute(const std::vector<Real>& weights)
244 {
245 // If the size of the sub-communicator is zero, then this process does not participate
246 // in the actual partitioning process and it only needs to participate in the broadcast
247 if(this->_work_comm.size() == 0)
248 {
249 return this->_broadcast_coloring(true);
250 }
251
252 // Create SCOTCH graph
253 ScotchGraph scotch_graph(_work_comm);
254 if(!graph_to_scotch(scotch_graph, _subgraph, _first_elem, weights))
255 {
256 return this->_broadcast_coloring(false);
257 }
258
259 // Check graph
260 if(SCOTCH_dgraphCheck(scotch_graph.inner) != 0)
261 {
262 return this->_broadcast_coloring(false);
263 }
264
265 // Create strategy for partitioning
266 SCOTCH_Strat partitioning_strategy;
267
268 if(SCOTCH_stratInit(&partitioning_strategy) != 0)
269 {
270 return this->_broadcast_coloring(false);
271 }
272
273 // NOTE: Initialized strategy object will be filled with default strategy once
274 // passed to any other operation.
275
276 // Partition distributed graph
277 std::vector<SCOTCH_Num> partloctab(_subgraph.get_num_nodes_domain());
278 if(SCOTCH_dgraphPart(scotch_graph.inner, SCOTCH_Num(_num_parts), &partitioning_strategy, partloctab.data()) != 0)
279 {
280 SCOTCH_stratFree(&partitioning_strategy);
281 return this->_broadcast_coloring(false);
282 }
283
284 SCOTCH_stratFree(&partitioning_strategy);
285
286 for(Index i(0); i < _local_num_elements; ++i)
287 {
288 _parts[std::size_t(i)] = Index(partloctab[std::size_t(i)]);
289 }
290
291 // Broadcast coloring if gathering was ok
292 return this->_broadcast_coloring(this->_gather_coloring());
293 }
294
295 // NOTE: Copied from the ParMETIS partitioner
296 bool PartiScotch::_gather_coloring()
297 {
298 // get my rank and size
299 const int scotch_rank = _work_comm.rank();
300 const auto scotch_size = Index(_work_comm.size());
301
302 // determine maximum export size
303 Index max_local_elems(0);
304 _work_comm.allreduce(&this->_local_num_elements, &max_local_elems, 1u, Dist::op_max);
305 max_local_elems += 1; // for actual size
306
307 // allocate send buffer
308 auto send_buf = std::vector<Index>(std::size_t(max_local_elems));
309 send_buf[0] = _local_num_elements;
310 for(Index i(0); i < _local_num_elements; ++i)
311 {
312 send_buf[std::size_t(i + 1)] = _parts[std::size_t(i)];
313 }
314
315 // allocate receive buffer and gather coloring at rank 0
316 std::vector<Index> recv_buf(scotch_rank == 0 ? std::size_t(max_local_elems * scotch_size) : std::size_t(0));
317 _work_comm.gather(send_buf.data(), max_local_elems, recv_buf.data(), max_local_elems, 0);
318
319 // all non-root ranks are done here
320 if(scotch_rank > 0)
321 {
322 return true;
323 }
324
325 // allocate coloring on root
326 this->_coloring = Adjacency::Coloring(this->_global_num_elements, this->_num_parts);
327 Index* col = this->_coloring.get_coloring();
328
329 // build coloring vector
330 for(Index i(0), k(0); i < scotch_size; ++i)
331 {
332 const Index off = i * max_local_elems;
333 const Index n = recv_buf[std::size_t(off)];
334 for(Index j(1); j <= n; ++j, ++k)
335 {
336 col[k] = recv_buf[std::size_t(off + j)];
337 }
338 }
339
340 // make sure we have at least 1 element per color/partition
341 std::vector<int> color_counts(std::size_t(this->_num_parts), 0);
342 for(Index i(0); i < this->_global_num_elements; ++i)
343 {
344 XASSERT(col[i] < this->_num_parts);
345 ++color_counts[std::size_t(col[i])];
346 }
347 for(Index i(0); i < this->_num_parts; ++i)
348 {
349 if(color_counts[std::size_t(i)] == 0)
350 {
351 return false;
352 }
353 }
354
355 return true;
356 }
357
358 // NOTE: Copied from the ParMETIS partitioner
359 bool PartiScotch::_broadcast_coloring(bool ok)
360 {
361 int was_ok(ok ? 0 : 1);
362 int was_all_ok(0);
363
364 this->_comm.allreduce(&was_ok, &was_all_ok, std::size_t(1), Dist::op_sum);
365 if(was_all_ok > 0)
366 {
367 return false;
368 }
369
370 if(this->_comm.rank() > 0)
371 {
372 this->_coloring = Adjacency::Coloring(this->_global_num_elements, this->_num_parts);
373 }
374
375 this->_comm.bcast(this->_coloring.get_coloring(), this->_global_num_elements, 0);
376 return true;
377 }
378} // namespace FEAT::Geometry
379
380#else
381
382// dummy function to suppress linker warnings
383void scotch_not_linked() {}
384
385#endif
#define XASSERT(expr)
Assertion macro definition.
Definition: assertion.hpp:262
#define XASSERTM(expr, msg)
Assertion macro definition with custom message.
Definition: assertion.hpp:263
Index * get_coloring()
Returns the coloring array.
Definition: coloring.hpp:168
Adjacency Graph implementation.
Definition: graph.hpp:34
Index * get_domain_ptr()
Returns the domain pointer array.
Definition: graph.hpp:359
Index * get_image_idx()
Returns the image node index array.
Definition: graph.hpp:374
Communicator class.
Definition: dist.hpp:1657
void bcast(void *buffer, std::size_t count, const Datatype &datatype, int root) const
Blocking broadcast.
Definition: dist.cpp:544
Comm comm_create_range_incl(int count, int first=0, int stride=1) const
Creates a new sub-communicator from a strided range of ranks.
Definition: dist.cpp:475
void allreduce(const void *sendbuf, void *recvbuf, std::size_t count, const Datatype &datatype, const Operation &op) const
Blocking All-Reduce.
Definition: dist.cpp:658
int size() const
Returns the size of this communicator.
Definition: dist.hpp:1814
void gather(const void *sendbuf, std::size_t sendcount, const Datatype &sendtype, void *recvbuf, std::size_t recvcount, const Datatype &recvtype, int root) const
Blocking gather.
Definition: dist.cpp:556
const MPI_Comm & mpi_comm() const
Definition: dist.hpp:1747
Comm comm_dup() const
Creates a copy of this communicator.
Definition: dist.cpp:462
int rank() const
Returns the rank of this process in this communicator.
Definition: dist.hpp:1802
Index _min_elems
Mininum number of elements on each rank.
Index _local_num_elements
Local number of elements.
Dist::Comm _work_comm
Communicator for performing partitioning.
Adjacency::Coloring _coloring
Elements-at-rank coloring.
Adjacency::Graph _subgraph
Subgraph for this rank.
Index _first_elem
First element of this process.
int _max_work_procs
Maximum number of ranks to use for partitioning
Index _global_num_elements
Global number of elements.
std::vector< Index > _parts
Element partitioning.
Index _num_parts
Desired number of partitions.
const Dist::Comm & _comm
Main communicator.
@ injectify_sorted
Render-Injectified mode, sort image indices.
@ transpose
Render-Transpose mode.
const Operation op_max(MPI_MAX)
Operation wrapper for MPI_MAX.
Definition: dist.hpp:573
const Operation op_sum(MPI_SUM)
Operation wrapper for MPI_SUM.
Definition: dist.hpp:571
Geometry namespace.
void mini(T_ &xmin, T_ x)
Updates the minimum of a set of values.
Definition: math.hpp:154
T_ max(T_ a, T_ b)
Returns the maximum of two values.
Definition: math.hpp:137
double Real
Real data type.
std::uint64_t Index
Index data type.
RAII-wrapper for Scotch graphs.