1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
|
/*
Copyright 2024 OPM-OP AS
This file is part of The Open Porous Media project (OPM).
OPM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OPM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with OPM. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if HAVE_MPI // no code in this file without MPI, then skip includes.
#include <opm/common/OpmLog/OpmLog.hpp>
#include <opm/grid/common/ZoltanGraphFunctions.hpp>
#include <opm/grid/common/MetisPartition.hpp>
#include <opm/grid/utility/OpmWellType.hpp>
#include <opm/grid/cpgrid/CpGridData.hpp>
#include <opm/grid/cpgrid/Entity.hpp>
#include <algorithm>
#include <type_traits>
#endif
#if defined(HAVE_METIS) && HAVE_MPI
namespace Dune
{
namespace cpgrid
{
// We want to use METIS, but if METIS is installed as part of the ScotchMetis package, then the following options are not available.
#if !IS_SCOTCH_METIS_HEADER
void setMetisOptions(const std::map<std::string, std::string>& optionsMap, int& manuallySelectedMethod, idx_t* options) {
// Initialize all options to default values
METIS_SetDefaultOptions(options);
// A map containing the METIS option keys
// This is the list of options available for METIS Version 5.1.0 - possibly more can be added in the future
std::unordered_map<std::string, int> metisOptionKeys = {
// These options are only valid for the METIS_PartGraphKway method
{"METIS_OPTION_OBJTYPE", METIS_OPTION_OBJTYPE},
{"METIS_OPTION_MINCONN", METIS_OPTION_MINCONN},
{"METIS_OPTION_CONTIG", METIS_OPTION_CONTIG},
// The options are vaild for the METIS_PartGraphKway method and the METIS_PartGraphRecursive method
{"METIS_OPTION_CTYPE", METIS_OPTION_CTYPE},
{"METIS_OPTION_IPTYPE", METIS_OPTION_IPTYPE},
{"METIS_OPTION_RTYPE", METIS_OPTION_RTYPE},
{"METIS_OPTION_NO2HOP", METIS_OPTION_NO2HOP},
{"METIS_OPTION_NCUTS", METIS_OPTION_NCUTS},
{"METIS_OPTION_NITER", METIS_OPTION_NITER},
{"METIS_OPTION_SEED", METIS_OPTION_SEED},
{"METIS_OPTION_UFACTOR", METIS_OPTION_UFACTOR},
{"METIS_OPTION_NUMBERING", METIS_OPTION_NUMBERING},
{"METIS_OPTION_DBGLVL", METIS_OPTION_DBGLVL}
};
// A map containing the METIS option values
std::unordered_map<std::string, int> metisOptionValues = {
{"METIS_PTYPE_RB", METIS_PTYPE_RB},
{"METIS_PTYPE_KWAY", METIS_PTYPE_KWAY},
{"METIS_OBJTYPE_CUT", METIS_OBJTYPE_CUT},
{"METIS_OBJTYPE_VOL", METIS_OBJTYPE_VOL},
{"METIS_CTYPE_RM", METIS_CTYPE_RM},
{"METIS_CTYPE_SHEM", METIS_CTYPE_SHEM},
{"METIS_IPTYPE_GROW", METIS_IPTYPE_GROW},
{"METIS_IPTYPE_RANDOM", METIS_IPTYPE_RANDOM},
{"METIS_IPTYPE_EDGE", METIS_IPTYPE_EDGE},
{"METIS_IPTYPE_NODE", METIS_IPTYPE_NODE},
{"METIS_RTYPE_FM", METIS_RTYPE_FM},
{"METIS_RTYPE_GREEDY", METIS_RTYPE_GREEDY},
{"METIS_RTYPE_SEP2SIDED", METIS_RTYPE_SEP2SIDED},
{"METIS_RTYPE_SEP1SIDED", METIS_RTYPE_SEP1SIDED},
{"METIS_DBG_INFO", METIS_DBG_INFO},
{"METIS_DBG_TIME", METIS_DBG_TIME},
{"METIS_DBG_COARSEN", METIS_DBG_COARSEN},
{"METIS_DBG_REFINE", METIS_DBG_REFINE},
{"METIS_DBG_IPART", METIS_DBG_IPART},
{"METIS_DBG_MOVEINFO", METIS_DBG_MOVEINFO},
{"METIS_DBG_SEPINFO", METIS_DBG_SEPINFO},
{"METIS_DBG_CONNINFO", METIS_DBG_CONNINFO},
{"METIS_DBG_CONTIGINFO", METIS_DBG_CONTIGINFO}
};
// Option keys not valid for the METIS_PartGraphRecursive or METIS_PartGraphKway functions.
std::unordered_set<std::string> metisOptionKeysForOtherMethods = {
"METIS_OPTION_NSEPS",
"METIS_OPTION_COMPRESS",
"METIS_OPTION_CCORDER",
"METIS_OPTION_PFACTOR",
"METIS_OPTION_UFACTOR"
};
// Iterate over the input map and set the options accordingly
for (const auto& [key,value] : optionsMap) {
auto keyIt = metisOptionKeys.find(key);
if (keyIt != metisOptionKeys.end()) {
idx_t optionIndex = keyIt->second;
auto optionIt = metisOptionValues.find(value);
if (optionIt != metisOptionValues.end()) {
options[optionIndex] = optionIt->second;
Opm::OpmLog::info("Set metis option " + key + " to " + value + ".");
} else {
try {
options[optionIndex] = std::stoi(value);
Opm::OpmLog::info("Set metis option " + key + " to " + value + ".");
} catch (...) {
OPM_THROW(std::logic_error, "The value " + value + " for key " + key + " is not a valid METIS option.");
}
}
} else if (metisOptionKeysForOtherMethods.count(key) != 0) {
OPM_THROW(std::logic_error, "The METIS key " + key + " is not valid for METIS_PartGraphRecursive or METIS_PartGraphKway. "
"Please choose only options for these graph partitioning functions.");
} else if (key == "METIS_OPTION_PTYPE") {
manuallySelectedMethod = (value == "METIS_PTYPE_RB") ? 1 :
(value == "METIS_PTYPE_KWAY") ? 2 :
3;
if (manuallySelectedMethod == 3) {
OPM_THROW(std::logic_error, "Unknown value '" + value + "' for METIS option " + key);
}
} else {
OPM_THROW(std::logic_error, "Unknown METIS key: " + key);
}
}
}
#endif
std::tuple<std::vector<int>,
std::vector<std::pair<std::string, bool>>,
std::vector<std::tuple<int, int, char>>,
std::vector<std::tuple<int, int, char, int>>,
WellConnections>
metisSerialGraphPartitionGridOnRoot(const CpGrid& cpgrid,
const std::vector<OpmWellType> * wells,
const std::unordered_map<std::string, std::set<int>>& possibleFutureConnections,
const double* transmissibilities,
const Communication<MPI_Comm>& cc,
EdgeWeightMethod edgeWeightsMethod,
int root,
real_t imbalanceTol,
bool allowDistributedWells,
[[maybe_unused]] const std::map<std::string,std::string>& params)
{
#if defined(IDXTYPEWIDTH) // IDXTYPEWIDTH might be an expression, e.g. sizeof(::idx_t) * 8
if ( IDXTYPEWIDTH != 64 && edgeWeightsMethod == Dune::EdgeWeightMethod::defaultTransEdgeWgt )
OPM_THROW(std::runtime_error, "The selected partition method is METIS with default edge weights (i.e. transmissibilities).\
This combination works only for METIS with 64-bit integers, but the installed version of METIS does not use 64-bit integers.\
Either reinstall METIS with 64-bit integers or choose another edge weight method!");
#endif
std::shared_ptr<CombinedGridWellGraph> gridAndWells;
if( wells )
{
gridAndWells.reset(new CombinedGridWellGraph(cpgrid,
wells,
possibleFutureConnections,
transmissibilities,
false,
edgeWeightsMethod));
}
std::vector<int> partitionVector;
int rc = METIS_OK;
cc.barrier();
//Metis is a serial graph partitioner, we do everything only on root
if (cc.rank() == root) {
//////// First, we define all variables that *do not depend* on whether there are wells or not
// The number of vertices, every cell is a vertex in the graph.
idx_t n = cpgrid.numCells();
// This is a vector of size n that upon successful completion stores the partition vector of the graph.
// The numbering of this vector starts from either 0 or 1, depending on the value of options[METIS_OPTION_NUMBERING].
idx_t* gpart = new idx_t[n];
// Upon successful completion, this variable stores the edge-cut or the total communication volume of
// the partitioning solution. The value returned depends on the partitioning’s objective function.
idx_t objval = 0;
// The number of partitions to split the graph into, we want to distribtue over all processes, so cc.size()
idx_t nparts = cc.size();
auto& globalIdSet = cpgrid.globalIdSet();
auto& localIdSet = cpgrid.localIdSet();
idx_t* gids = new idx_t[n];
idx_t* lids = new idx_t[n];
int idx = 0;
for (auto cell = cpgrid.leafbegin<0>(), cellEnd = cpgrid.leafend<0>(); cell != cellEnd; ++cell)
{
gids[idx] = globalIdSet.id(*cell);
lids[idx++] = localIdSet.id(*cell);
}
//The number of balancing constraints, should be at least 1.
idx_t ncon = 1;
// The adjacency structure of a graph with n vertices and m edges is represented using two arrays xadj and adjncy.
// An array of size n+1 that specifies the adjacency structure of the graph. The adjacency list of vertex i is stored in adjncy[xadj[i]] to adjncy[xadj[i+1]-1].
idx_t* xadj = new idx_t[n+1];
xadj[0] = 0;
int manuallySelectedMethod = 0; // 0: choose according to number of partitions, 1: recursive, 2: kway
#if IS_SCOTCH_METIS_HEADER
Opm::OpmLog::info("Not setting specific METIS Options since you're using Scotch-METIS.");
idx_t* options = nullptr;
if (imbalanceTol >= 1.0) {
imbalanceTol -= 1.0;
Opm::OpmLog::info("Note that the imbalanceTol parameter is interpeted differently by Scotch-METIS than just by METIS! Currently, imbalanceTol >= 1.0, we subtract 1.0, such that imbalanceTol = " + std::to_string(imbalanceTol) + ".");
}
#else
// NOTE: scotchmetis interprets the imbalanceTol parameter differently
assert(imbalanceTol >= 1.0);
// This is the array of options as described in Section 5.4.
// The METIS options are not available if METIS is installed together with Scotch.
idx_t* options = new idx_t[METIS_NOPTIONS];
Dune::cpgrid::setMetisOptions(params, manuallySelectedMethod, options);
#endif
// This is an array of size ncon (in our case, of size 1) that specifies the allowed load imbalance tolerance for each constraint.
// For the ith partition and jth constraint the allowed weight is the ubvec[j]*tpwgts[i*ncon+j] fraction
// of the jth’s constraint total weight. The load imbalances must be greater than 1.0.
// A NULL value can be passed indicating that the load imbalance tolerance for each constraint should
// be 1.001 (for ncon=1) or 1.01 (for ncon>1).
real_t ubvec = imbalanceTol;
//////// Now, we define all variables that *do depend* on whether there are wells or not
if( wells )
{
for (int i = 0; i < n; i++) {
xadj[i+1] = xadj[i] + Dune::cpgrid::getNumberOfEdgesForSpecificCellForGridWithWells(*gridAndWells, lids[i]);
}
}
else
{
for (int i = 0; i < n; i++) {
xadj[i+1] = xadj[i] + Dune::cpgrid::getNumberOfEdgesForSpecificCell(cpgrid, lids[i]);
}
}
// The number of edges depends on whether there are wells or not, twoM = 2*m, where m = number of edges.
idx_t twoM = xadj[n];
// An array that contains the adjacency list of the graph.
// The xadj array is of size n + 1 whereas the adjncy array is of size 2m (because for each edge between vertices v and u we actually store both (v, u) and (u, v)).
// The adjacency list of vertex i is stored in array adjncy starting at index xadj[i] and ending at (but not
// including) index xadj[i + 1] (i.e., adjncy[xadj[i]] through and including adjncy[xadj[i + 1]-1])
// So: xadj contains the indices where we start for the respective component
idx_t* adjncy = new idx_t[twoM];
// An array that contains the weights of the edges. If all edges have the same weight, this can be set to NULL.
// The weights of the edges (if any) are stored in an additional array called adjwgt. This array contains 2m elements, and the weight of edge adjncy[j] is stored at location adjwgt[j]
idx_t* adjwgt = new idx_t[twoM];
if( wells )
{
int neighborCounter = 0;
for( int cell = 0; cell < n; cell++ )
{
fillNBORGIDAndWeightsForSpecificCellAndIncrementNeighborCounterForGridWithWells(*gridAndWells, lids[cell], gids, neighborCounter, adjncy, adjwgt);
}
}
else
{
int neighborCounter = 0;
for( int cell = 0; cell < n; cell++ )
{
fillNBORGIDForSpecificCellAndIncrementNeighborCounter(cpgrid, lids[cell], gids, neighborCounter, adjncy);
}
}
// Decide which partition method to use, both methods create k partitions, where
// METIS_PartGraphRecursive uses multilevel recursive bisection and
// METIS_PartGraphKway uses multilevel k-way partition.
// The advice is: Use METIS_PartGraphRecursive if k is small and if k is a power of two
// (n & (n - 1) == 0) is true if n > 0 and n is a power of two, this is an efficient bitwise check.
if (manuallySelectedMethod == 1 || (manuallySelectedMethod == 0 && nparts < 65 && ((nparts & (nparts - 1)) == 0))) {
if (manuallySelectedMethod == 1)
Opm::OpmLog::info("Partitioning grid using METIS_PartGraphRecursive.");
else if (nparts < 65 && ((nparts & (nparts - 1)) == 0))
Opm::OpmLog::info("Partitioning grid using METIS_PartGraphRecursive, since the number of partitions is small (<65) and a power of 2. If you want to use METIS_PartGraphKway instead, set the METIS Parameter METIS_OPTION_PTYPE = METIS_PTYPE_KWAY.");
rc = METIS_PartGraphRecursive(&n,
&ncon,
xadj,
adjncy,
nullptr, // vwgt
nullptr, // vsize,
wells ? adjwgt : nullptr,
&nparts,
nullptr, // tpwgts,
&ubvec,
options,
&objval,
gpart);
} else {
Opm::OpmLog::info("Partitioning grid using METIS_PartGraphKway.");
rc = METIS_PartGraphKway(&n,
&ncon,
xadj,
adjncy,
nullptr, // vwgt
nullptr, // vsize,
wells ? adjwgt : nullptr,
&nparts,
nullptr, // tpwgts,
&ubvec,
options,
&objval,
gpart);
}
partitionVector.assign(gpart, gpart + n);
delete[] gids;
delete[] lids;
delete[] xadj;
delete[] adjncy;
delete[] adjwgt;
delete[] options;
delete[] gpart;
}
//Broadcast the return value to all processes
cc.broadcast(&rc, 1, root);
if (rc == METIS_OK) {
// Function returned normally :)
} else if (rc == METIS_ERROR_INPUT) {
OPM_THROW(std::runtime_error, "METIS Input Error!");
} else if (rc == METIS_ERROR_MEMORY) {
OPM_THROW(std::runtime_error, "METIS could not allocate the required memory!");
} else if (rc == METIS_ERROR) {
OPM_THROW(std::runtime_error, "Some other type of METIS error!");
} else {
OPM_THROW(std::runtime_error, "Some other type of general error!");
}
return cpgrid::createListsFromParts(cpgrid, wells, possibleFutureConnections, transmissibilities, partitionVector, allowDistributedWells, gridAndWells);
}
} // namespace cpgrid
} // namespace Dune
#endif // HAVE_METIS && HAVE_MPI
|