XdmfPartitioner.cpp 47.4 KB
Newer Older
Kenneth Leiter's avatar
Kenneth Leiter committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfPartitioner.cpp                                                 */
/*                                                                           */
/*  Author:                                                                  */
/*     Kenneth Leiter                                                        */
/*     kenneth.leiter@arl.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2011 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/

24 25 26 27
#ifndef BUILD_EXE

extern "C"
{
28
#include <metis.h>
29 30
}

31
#include <iostream>
32
#include <sstream>
33
#include "XdmfAttribute.hpp"
34 35
#include "XdmfAttributeCenter.hpp"
#include "XdmfAttributeType.hpp"
36
#include "XdmfError.hpp"
37
#include "XdmfGeometry.hpp"
38
#include "XdmfGeometryType.hpp"
Kenneth Leiter's avatar
Kenneth Leiter committed
39
#include "XdmfGraph.hpp"
40
#include "XdmfGridCollection.hpp"
41
#include "XdmfGridCollectionType.hpp"
42
#include "XdmfHeavyDataWriter.hpp"
43
#include "XdmfMap.hpp"
44
#include "XdmfPartitioner.hpp"
45
#include "XdmfSet.hpp"
46
#include "XdmfSetType.hpp"
47
#include "XdmfTopology.hpp"
48
#include "XdmfTopologyType.hpp"
49
#include "XdmfUnstructuredGrid.hpp"
50

Kenneth Leiter's avatar
Kenneth Leiter committed
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
//
// local methods
//
namespace {

  shared_ptr<XdmfGraph>
  addSymmetricEntries(const shared_ptr<XdmfGraph> graph)
  {
    const shared_ptr<XdmfArray> rowPointer = graph->getRowPointer();
    const shared_ptr<XdmfArray> columnIndex = graph->getColumnIndex();
    const unsigned int numberRows = graph->getNumberRows();

    std::set<std::pair<unsigned int, unsigned int> > entrySet;
    for(unsigned int i=0; i<numberRows; ++i) {
      for(unsigned int j=rowPointer->getValue<unsigned int>(i);
          j<rowPointer->getValue<unsigned int>(i+1);
          ++j) {
        const unsigned int k = columnIndex->getValue<unsigned int>(j);
        entrySet.insert(std::make_pair(i, k));
        entrySet.insert(std::make_pair(k, i));
      }
    }

    shared_ptr<XdmfGraph> toReturn = XdmfGraph::New(numberRows);
    shared_ptr<XdmfArray> toReturnRowPointer = toReturn->getRowPointer();
    shared_ptr<XdmfArray> toReturnColumnIndex = toReturn->getColumnIndex();
    shared_ptr<XdmfArray> toReturnValues = toReturn->getValues();

    unsigned int currentRow = 1;
    for(std::set<std::pair<unsigned int, unsigned int> >::const_iterator
          iter = entrySet.begin();
        iter != entrySet.end();
        ++iter) {
      const std::pair<unsigned int, unsigned int> & entry = *iter;
      const unsigned int row = entry.first;
      const unsigned int column = entry.second;
      for(unsigned int j = currentRow; j<row; ++j) {
        toReturnRowPointer->insert<unsigned int>(j,
                                                 toReturnColumnIndex->getSize());
      }

      currentRow = row + 1;
      toReturnColumnIndex->pushBack<unsigned int>(column);
      toReturnValues->pushBack<double>(1.0);
      toReturnRowPointer->insert(row+1,
                                 toReturnColumnIndex->getSize());
    }

    return toReturn;

  }

}

105
shared_ptr<XdmfPartitioner>
106
XdmfPartitioner::New()
107
{
108
  shared_ptr<XdmfPartitioner> p(new XdmfPartitioner());
109
  return p;
110 111
}

112 113 114 115 116 117 118 119
XdmfPartitioner::XdmfPartitioner()
{
}

XdmfPartitioner::~XdmfPartitioner()
{
}

120 121
void
XdmfPartitioner::ignore(const shared_ptr<const XdmfSet> set)
122 123 124 125
{
  mIgnoredSets.insert(set);
}

Kenneth Leiter's avatar
Kenneth Leiter committed
126 127 128 129 130 131 132
void
XdmfPartitioner::partition(const shared_ptr<XdmfGraph> graphToPartition,
                           const unsigned int numberOfPartitions) const
{

  // Make sure row pointer and column index are non null
  if(!(graphToPartition->getRowPointer() &&
133 134 135 136 137 138 139 140 141 142
       graphToPartition->getColumnIndex())) {
    try {
      XdmfError::message(XdmfError::FATAL,
                         "Current graph's row pointer or column index is null "
                         "in XdmfPartitioner::partition");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
 
  graphToPartition->removeAttribute("Partition");

  shared_ptr<XdmfAttribute> attribute = XdmfAttribute::New();
  attribute->setName("Partition");
  attribute->setCenter(XdmfAttributeCenter::Node());
  attribute->setType(XdmfAttributeType::Scalar());
  graphToPartition->insert(attribute);

  idx_t numberVertices = graphToPartition->getNumberNodes();
  
  // Handle case where we partition onto 1 processor. Metis for some reason
  // handles this incorrectly (indices are 1 instead of zero even though 
  // correct numbering option is supplied to metis)
  if(numberOfPartitions == 1) {
    attribute->resize<idx_t>(numberVertices, 0);
    return;
  }
Kenneth Leiter's avatar
Kenneth Leiter committed
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

  shared_ptr<XdmfArray> rowPointer = graphToPartition->getRowPointer();
  shared_ptr<XdmfArray> columnIndex = graphToPartition->getColumnIndex();

  idx_t numberConstraints = 1;

  bool releaseRowPointer = false;
  if(!rowPointer->isInitialized()) {
    rowPointer->read();
    releaseRowPointer = true;
  }
  bool releaseColumnIndex = false;
  if(!columnIndex->isInitialized()) {
    columnIndex->read();
    releaseColumnIndex = true;
  }

  shared_ptr<XdmfGraph> graph = graphToPartition;

  // Check whether graph is directed, if so we need to make it undirected
  // in order to partition with metis. From metis FAQ:
  //
  // The partitioning routines in METIS can only partition undirected graphs
  // (i.e., graphs in which for each edge (v,u) there is also an edge (u,v)).
  // For partitioning purposes, the directionality of an edge does not play
  // any role because if edge (u,v) is cut so will the edge (v,u). For this
  // reason, a directed graph can be easily partitioned by METIS by first
  // converting it into the corresponding undirected graph. That is, create
  // a graph for each directed edge (u,v) also contains the (v,u) edge as
  // well.
  const unsigned int numberRows = graphToPartition->getNumberRows();
  for(unsigned int i=0; i<numberRows; ++i) {
    for(unsigned int j=rowPointer->getValue<unsigned int>(i);
        j<rowPointer->getValue<unsigned int>(i+1);
        ++j) {
      const unsigned int k = columnIndex->getValue<unsigned int>(j);
      bool symmetric = false;
      for(unsigned int l=rowPointer->getValue<unsigned int>(k);
          l<rowPointer->getValue<unsigned int>(k+1);
          ++l) {
        const unsigned int m = columnIndex->getValue<unsigned int>(l);
        if(i == m) {
          symmetric = true;
          break;
        }
      }
      if(!symmetric) {
        graph = addSymmetricEntries(graphToPartition);
        if(releaseRowPointer) {
          rowPointer->release();
        }
        if(releaseColumnIndex) {
          columnIndex->release();
        }
        rowPointer = graph->getRowPointer();
        columnIndex = graph->getColumnIndex();
        break;
      }
    }
  }

  // copy into metis data structures
  idx_t * xadj = new idx_t[rowPointer->getSize()];
  rowPointer->getValues(0,
                        xadj,
                        rowPointer->getSize());
  if(releaseRowPointer) {
    rowPointer->release();
  }
  idx_t * adjncy = new idx_t[columnIndex->getSize()];
  columnIndex->getValues(0,
                         adjncy,
                         columnIndex->getSize());
  if(releaseColumnIndex) {
    columnIndex->release();
  }

  idx_t * vwgt = NULL; // equal vertex weights
  idx_t * vsize = NULL; // equal vertex sizes
  idx_t * adjwgt = NULL; // equal edge weights
  idx_t numParts = numberOfPartitions;
  real_t * tpwgts = NULL; // equal constraints and partition weights
  real_t * ubvec = NULL; // default load imbalance tolerance
  idx_t * options = NULL; // default options
  idx_t objval;
  idx_t * part = new idx_t[numberVertices];

  METIS_PartGraphRecursive(&numberVertices,
                           &numberConstraints,
                           xadj,
                           adjncy,
                           vwgt,
                           vsize,
                           adjwgt,
                           &numParts,
                           tpwgts,
                           ubvec,
                           options,
                           &objval,
                           part);

  delete [] xadj;
  delete [] adjncy;

  attribute->insert(0,
                    part,
                    numberVertices);

  delete [] part;

  return;
}


275 276
shared_ptr<XdmfGridCollection>
XdmfPartitioner::partition(const shared_ptr<XdmfUnstructuredGrid> gridToPartition,
277
                           const unsigned int numberOfPartitions,
278
                           const MetisScheme metisScheme,
279
                           const shared_ptr<XdmfHeavyDataWriter> heavyDataWriter) const
280
{
281 282 283 284 285

  if(heavyDataWriter) {
    heavyDataWriter->openFile();
  }

286
  // Make sure geometry and topology are non null
287 288 289 290 291 292 293 294 295 296
  if(!(gridToPartition->getGeometry() && gridToPartition->getTopology())) {
    try {
      XdmfError::message(XdmfError::FATAL,
                         "Current grid's geometry or topology is null in "
                         "XdmfPartitioner::partition");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
297

298
  const shared_ptr<XdmfGeometry> geometry =
299
    gridToPartition->getGeometry();
300
  const shared_ptr<const XdmfGeometryType> geometryType =
301
    geometry->getType();
302
  const unsigned int geometryDimensions = geometryType->getDimensions();
303
  const shared_ptr<XdmfTopology> topology =
304
    gridToPartition->getTopology();
305
  const shared_ptr<const XdmfTopologyType> topologyType =
306 307
    topology->getType();

308
  const unsigned int nodesPerElement = topologyType->getNodesPerElement();
309 310 311 312 313 314 315

  bool releaseTopology = false;
  if(!topology->isInitialized()) {
    topology->read();
    releaseTopology = true;
  }

Kenneth Leiter's avatar
Kenneth Leiter committed
316 317
  idx_t numElements = topology->getNumberElements();
  idx_t numNodes = geometry->getNumberPoints();
318

319 320 321
  // allocate metisConnectivity arrays
  idx_t * metisConnectivityEptr = new idx_t[numElements + 1];
  idx_t * metisConnectivityEind = new idx_t[nodesPerElement * numElements];
322

323 324 325
  metisConnectivityEptr[0] = 0;

  unsigned int metisConnectivityEptrValue = 0;
326
  unsigned int connectivityOffset = 0;
327
  idx_t * metisConnectivityPtr = metisConnectivityEind;
328
  for(int i=0; i<numElements; ++i) {
329 330
    metisConnectivityEptrValue += nodesPerElement;
    metisConnectivityEptr[i + 1] = metisConnectivityEptrValue;
331 332 333 334 335 336 337
    topology->getValues(connectivityOffset,
                        metisConnectivityPtr,
                        nodesPerElement);
    connectivityOffset += topologyType->getNodesPerElement();
    metisConnectivityPtr += nodesPerElement;
  }

338 339 340 341 342 343 344 345 346 347
  idx_t * vwgt = NULL; // equal weight
  idx_t * vsize = NULL; // equal size
  idx_t ncommon = 1; // FIXME
  idx_t nparts = numberOfPartitions;
  real_t * tpwgts = NULL;
  idx_t * options = NULL;
  idx_t objval;

  idx_t * elementsPartition = new idx_t[numElements];
  idx_t * nodesPartition = new idx_t[numNodes];
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
  if(metisScheme == DUAL_GRAPH) {
    METIS_PartMeshDual(&numElements,
                       &numNodes,
                       metisConnectivityEptr,
                       metisConnectivityEind,
                       vwgt,
                       vsize,
                       &ncommon,
                       &nparts,
                       tpwgts,
                       options,
                       &objval,
                       elementsPartition,
                       nodesPartition);
  }
  else if(metisScheme == NODAL_GRAPH) {
    METIS_PartMeshNodal(&numElements,
                        &numNodes,
                        metisConnectivityEptr,
                        metisConnectivityEind,
                        vwgt,
                        vsize,
                        &nparts,
                        tpwgts,
                        options,
                        &objval,
                        elementsPartition,
                        nodesPartition);
  }
  else {
379 380 381 382 383 384 385 386
    try {
      XdmfError::message(XdmfError::FATAL,
                         "Invalid metis partitioning scheme selected in "
                         "XdmfPartitioner::partition");
    }
    catch (XdmfError e) {
      throw e;
    }
387
  }
388

389 390
  delete [] metisConnectivityEptr;
  delete [] metisConnectivityEind;
391 392
  delete [] nodesPartition;

393 394 395 396 397 398 399 400 401 402 403 404 405
  // map of global node ids to pair of partition id and local node id
  std::vector<std::map<unsigned int, unsigned int> > 
    nodeIdMap(numNodes);
  // map of global element ids to pair of partition id and local element id
  std::vector<std::pair<unsigned int, unsigned int> > 
    elementIdMap(numElements);
  
  // keep count of number of nodes and element per partition, needed to
  // generate local node and element ids
  std::vector<unsigned int> localNodeCounts(numberOfPartitions, 0);
  std::vector<unsigned int> localElementCounts(numberOfPartitions, 0);
  
  // fill maps
406
  unsigned int totalIndex = 0;
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
  for(int i=0; i<numElements; ++i) {
    const unsigned int partitionId = elementsPartition[i];
    for(unsigned int j=0; j<nodesPerElement; ++j) {
      const unsigned int globalNodeId = 
        topology->getValue<unsigned int>(totalIndex++);
      std::map<unsigned int, unsigned int> & localNodeIds = 
        nodeIdMap[globalNodeId];
      std::map<unsigned int, unsigned int>::const_iterator iter = 
        localNodeIds.find(partitionId);
      if(iter == localNodeIds.end()) {
        localNodeIds[partitionId] = localNodeCounts[partitionId];
        localNodeCounts[partitionId]++;
      }
      else {
        localNodeIds[partitionId] = iter->second;
422 423
      }
    }
424 425 426
    elementIdMap[i] = std::make_pair(partitionId,
                                     localElementCounts[partitionId]);
    localElementCounts[partitionId]++;
427 428 429
  }
  delete [] elementsPartition;

430 431
  // create returned partitioned grid
  shared_ptr<XdmfGridCollection> partitionedGrid =
432
    XdmfGridCollection::New();
433
  partitionedGrid->setType(XdmfGridCollectionType::Spatial());
434

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  // add unstructured grids to partitionedGrid and initialize topology
  // and geometry in each
  for(unsigned int i=0; i<numberOfPartitions; ++i) {
    const unsigned int localElementCount = localElementCounts[i];
    const unsigned int localNodeCount = localNodeCounts[i];
    std::stringstream name;
    name << gridToPartition->getName() << "_" << i;
    const shared_ptr<XdmfUnstructuredGrid> grid = 
      XdmfUnstructuredGrid::New();
    grid->setName(name.str());
    partitionedGrid->insert(grid);
    shared_ptr<XdmfGeometry> localGeometry = grid->getGeometry();
    localGeometry->setType(geometryType);
    localGeometry->initialize(geometry->getArrayType(),
                              localNodeCount * geometryDimensions);
    shared_ptr<XdmfTopology> localTopology = grid->getTopology();
    localTopology->setType(topologyType);
    localTopology->initialize(topology->getArrayType(),
                              localElementCount * nodesPerElement);
  }
  
456 457 458 459 460 461
  bool releaseGeometry = false;
  if(!geometry->isInitialized()) {
    geometry->read();
    releaseGeometry = true;
  }

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
  // fill geometry for each partition
  for(int i=0; i<numNodes; ++i) {
    const std::map<unsigned int, unsigned int> & localNodeIds = nodeIdMap[i];
    for(std::map<unsigned int, unsigned int>::const_iterator iter = 
          localNodeIds.begin(); iter != localNodeIds.end(); ++iter) {
      const unsigned int partitionId = iter->first;
      const unsigned int localNodeId = iter->second;
      const shared_ptr<XdmfUnstructuredGrid> grid = 
        partitionedGrid->getUnstructuredGrid(partitionId);
      const shared_ptr<XdmfGeometry> localGeometry = grid->getGeometry();
      localGeometry->insert(localNodeId * geometryDimensions,
                            geometry,
                            i * geometryDimensions,
                            geometryDimensions);
    }
  }
478

479 480 481
  if(releaseGeometry) {
    geometry->release();
  }
482

483 484 485 486 487 488 489 490 491
  // write geometries to disk if possible
  if(heavyDataWriter) {
    for(unsigned int i=0; i<numberOfPartitions; ++i) {
      const shared_ptr<XdmfUnstructuredGrid> grid = 
        partitionedGrid->getUnstructuredGrid(i);
      const shared_ptr<XdmfGeometry> localGeometry = grid->getGeometry();
      if(localGeometry->getSize() > 0) {
        localGeometry->accept(heavyDataWriter);
        localGeometry->release();
492 493 494 495
      }
    }
  }

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
  // fill topology for each partition
  for(int i=0; i<numElements; ++i) {
    const std::pair<unsigned int, unsigned int> & partitionElementPair = 
      elementIdMap[i];
    const unsigned int partitionId = partitionElementPair.first;
    const unsigned int localElementId = partitionElementPair.second;
    const shared_ptr<XdmfUnstructuredGrid> grid = 
      partitionedGrid->getUnstructuredGrid(partitionId);
    const shared_ptr<XdmfTopology> localTopology = grid->getTopology();
    for(unsigned int j=0; j<nodesPerElement; ++j) {
      const unsigned int globalNodeId =
        topology->getValue<unsigned int>(i*nodesPerElement + j);
      const unsigned int localNodeId = nodeIdMap[globalNodeId][partitionId];
      localTopology->insert(localElementId*nodesPerElement + j, localNodeId);
    }
511
  }
512

513
  if(releaseTopology) {
514
    topology->release();
515 516
  }

517 518 519 520 521 522 523 524 525 526 527 528
  // write topology to disk if possible
  if(heavyDataWriter) {
    for(unsigned int i=0; i<numberOfPartitions; ++i) {
      const shared_ptr<XdmfUnstructuredGrid> grid = 
        partitionedGrid->getUnstructuredGrid(i);
      const shared_ptr<XdmfTopology> localTopology = grid->getTopology();
      if(localTopology->getSize() > 0) {
        localTopology->accept(heavyDataWriter);
        localTopology->release();
      }
    }
  }
529

530 531 532 533
  // split attributes
  const unsigned int numberAttributes = gridToPartition->getNumberAttributes();
  for(unsigned int i=0; i<numberAttributes; ++i) {
    const shared_ptr<XdmfAttribute> attribute = 
534 535
      gridToPartition->getAttribute(i);
    bool releaseAttribute = false;
536 537
    if(!attribute->isInitialized()) {
      attribute->read();
538 539
      releaseAttribute = true;
    }
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    const shared_ptr<const XdmfAttributeCenter> attributeCenter = 
      attribute->getCenter();
    std::vector<shared_ptr<XdmfAttribute> > localAttributes;
    localAttributes.reserve(numberOfPartitions);
    if(attributeCenter == XdmfAttributeCenter::Grid()) {
      // insert into each partition
      for(unsigned int j=0; j<numberOfPartitions; ++j) {
        partitionedGrid->getUnstructuredGrid(j)->insert(attribute);
      }
      localAttributes.push_back(attribute);
    }
    else if(attributeCenter == XdmfAttributeCenter::Cell()) {
      const unsigned int numberComponents = attribute->getSize() / numElements;
      for(unsigned int j=0; j<numberOfPartitions; ++j) {
        const shared_ptr<XdmfAttribute> localAttribute = XdmfAttribute::New();
        localAttribute->setName(attribute->getName());
        localAttribute->setCenter(attribute->getCenter());
        localAttribute->setType(attribute->getType());
        localAttribute->initialize(attribute->getArrayType(),
                                   localElementCounts[j] * numberComponents);
        partitionedGrid->getUnstructuredGrid(j)->insert(localAttribute);
        localAttributes.push_back(localAttribute);
      }
      for(int j=0; j<numElements; ++j) {
        const std::pair<unsigned int, unsigned int> & partitionElementPair = 
          elementIdMap[j];
        const unsigned int partitionId = partitionElementPair.first;
        const unsigned int localElementId = partitionElementPair.second;
        const shared_ptr<XdmfAttribute> localAttribute = 
          localAttributes[partitionId];
        localAttribute->insert(localElementId * numberComponents,
                               attribute,
                               j * numberComponents,
                               numberComponents);
      }
    }
    else if(attributeCenter == XdmfAttributeCenter::Node()) {
      const unsigned int numberComponents = attribute->getSize() / numNodes;
      for(unsigned int j=0; j<numberOfPartitions; ++j) {
        const shared_ptr<XdmfAttribute> localAttribute = XdmfAttribute::New();
        localAttribute->setName(attribute->getName());
        localAttribute->setCenter(attribute->getCenter());
        localAttribute->setType(attribute->getType());
        localAttribute->initialize(attribute->getArrayType(),
                                   localNodeCounts[j] * numberComponents);
        partitionedGrid->getUnstructuredGrid(j)->insert(localAttribute);
        localAttributes.push_back(localAttribute);
      }
      for(int j=0; j<numNodes; ++j) {
        const std::map<unsigned int, unsigned int> & localNodeIds = 
          nodeIdMap[j];
        for(std::map<unsigned int, unsigned int>::const_iterator iter = 
              localNodeIds.begin(); iter != localNodeIds.end(); ++iter) {
          const unsigned int partitionId = iter->first;
          const unsigned int localNodeId = iter->second;        
          const shared_ptr<XdmfAttribute> localAttribute = 
            localAttributes[partitionId];
          localAttribute->insert(localNodeId * numberComponents,
                                 attribute,
                                 j * numberComponents,
                                 numberComponents);
601
        }
602 603 604 605 606 607 608 609 610
      }
    }
    
    if(heavyDataWriter) {
      for(std::vector<shared_ptr<XdmfAttribute> >::const_iterator iter =
            localAttributes.begin(); iter != localAttributes.end(); ++iter) {
        const shared_ptr<XdmfAttribute> localAttribute = *iter;
        if(!localAttribute->isInitialized()) {
          localAttribute->read();
611
        }
612 613 614
        if(localAttribute->getSize() > 0) {
          localAttribute->accept(heavyDataWriter);
          localAttribute->release();
615 616 617
        }
      }
    }
618

619
    if(releaseAttribute) {
620 621
      attribute->release();
    }    
622 623
  }

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
  // create globalnodeid if required
  bool generateGlobalNodeIds = !gridToPartition->getAttribute("GlobalNodeId");
  std::vector<shared_ptr<XdmfAttribute> > globalNodeIds;
  globalNodeIds.reserve(numberOfPartitions);
  if(generateGlobalNodeIds) {
    for(unsigned int i=0; i<numberOfPartitions; ++i) {
      const shared_ptr<XdmfAttribute> globalNodeId = XdmfAttribute::New();
      globalNodeId->setName("GlobalNodeId");
      globalNodeId->setCenter(XdmfAttributeCenter::Node());
      globalNodeId->setType(XdmfAttributeType::GlobalId());
      globalNodeId->initialize(XdmfArrayType::UInt32(),
                               localNodeCounts[i]);
      partitionedGrid->getUnstructuredGrid(i)->insert(globalNodeId);
      globalNodeIds.push_back(globalNodeId);
    }
    for(int i=0; i<numNodes; ++i) {
      const std::map<unsigned int, unsigned int> & localNodeIds = 
        nodeIdMap[i];
      for(std::map<unsigned int, unsigned int>::const_iterator iter = 
            localNodeIds.begin(); iter != localNodeIds.end(); ++iter) {
        const unsigned int partitionId = iter->first;
        const unsigned int localNodeId = iter->second;        
        const shared_ptr<XdmfAttribute> globalNodeId = 
          globalNodeIds[partitionId];
        globalNodeId->insert<unsigned int>(localNodeId,
                                           i);
      }
    }
    if(heavyDataWriter) {
      for(std::vector<shared_ptr<XdmfAttribute> >::const_iterator iter =
            globalNodeIds.begin(); iter != globalNodeIds.end(); ++iter) {
        const shared_ptr<XdmfAttribute> globalNodeId = *iter;
        if(globalNodeId->getSize() > 0) {
          globalNodeId->accept(heavyDataWriter);
          globalNodeId->release();
        }
      }
    }
  }
  else {
    for(unsigned int i=0; i<numberOfPartitions; ++i) {
      const shared_ptr<XdmfUnstructuredGrid> grid = 
        partitionedGrid->getUnstructuredGrid(i);
        globalNodeIds.push_back(grid->getAttribute("GlobalNodeId"));
    }
  }
 
  // split sets
  const unsigned int numberSets = gridToPartition->getNumberSets();
  for(unsigned int i=0; i<numberSets; ++i) {
    const shared_ptr<XdmfSet> set = gridToPartition->getSet(i);
    if(mIgnoredSets.find(set) == mIgnoredSets.end()) {
676
      bool releaseSet = false;
677 678
      if(!set->isInitialized()) {
        set->read();
679 680
        releaseSet = true;
      }
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
      const shared_ptr<const XdmfSetType> setType = set->getType();
      const unsigned int setSize = set->getSize();
      std::vector<shared_ptr<XdmfSet> > localSets;
      localSets.reserve(numberOfPartitions);
      if(setType == XdmfSetType::Cell()) {
        for(unsigned int j=0; j<numberOfPartitions; ++j) {
          const shared_ptr<XdmfSet> localSet = XdmfSet::New();
          localSets.push_back(localSet);
        }
        for(unsigned int j=0; j<setSize; ++j) {
           const unsigned int globalElementId = set->getValue<unsigned int>(j);
          const std::pair<unsigned int, unsigned int> & partitionElementPair = 
            elementIdMap[globalElementId];
          const unsigned int partitionId = partitionElementPair.first;
          const unsigned int localElementId = partitionElementPair.second;
          const shared_ptr<XdmfSet> localSet = localSets[partitionId];
          localSet->pushBack<unsigned int>(localElementId);
        }
      }
      else if(setType == XdmfSetType::Node()) {
        for(unsigned int j=0; j<numberOfPartitions; ++j) {
          const shared_ptr<XdmfSet> localSet = XdmfSet::New();
          localSets.push_back(localSet);
        }
        for(unsigned int j=0; j<setSize; ++j) {
          const unsigned int globalNodeId = set->getValue<unsigned int>(j);
          const std::map<unsigned int, unsigned int> & localNodeIds = 
            nodeIdMap[globalNodeId];
          for(std::map<unsigned int, unsigned int>::const_iterator iter = 
                localNodeIds.begin(); iter != localNodeIds.end(); ++iter) {
            const unsigned int partitionId = iter->first;
            const unsigned int localNodeId = iter->second;        
            const shared_ptr<XdmfSet> localSet = localSets[partitionId];
            localSet->pushBack<unsigned int>(localNodeId);
715
          }
716 717 718 719 720 721 722 723 724 725 726 727 728
        }
      }

      for(std::vector<shared_ptr<XdmfSet> >::size_type j=0; 
          j<localSets.size(); ++j) {
        const shared_ptr<XdmfSet> localSet = localSets[j];
        if(localSet->getSize() > 0) {
          partitionedGrid->getUnstructuredGrid(j)->insert(localSet);
          localSet->setName(set->getName());
          localSet->setType(set->getType());
          if(heavyDataWriter) {
            localSet->accept(heavyDataWriter);
            localSet->release();
729
          }
730 731 732 733 734 735 736 737 738 739 740
        }
      }

      const unsigned int numberAttributes = set->getNumberAttributes();
      for(unsigned int j=0; j<numberAttributes; ++j) {
        const shared_ptr<XdmfAttribute> attribute = set->getAttribute(j);  
        bool releaseAttribute = false;
        if(!attribute->isInitialized()) {
          attribute->read();
          releaseAttribute = true;
        }
741

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
        const shared_ptr<const XdmfAttributeCenter> attributeCenter = 
          attribute->getCenter();
        const unsigned int attributeSize = attribute->getSize();
        const unsigned int numberComponents = attributeSize / setSize;        
        std::vector<shared_ptr<XdmfAttribute> > localAttributes;
        localAttributes.reserve(numberOfPartitions);
        if(attributeCenter == XdmfAttributeCenter::Cell()) {
          for(unsigned int k=0; k<numberOfPartitions; ++k) {
            const shared_ptr<XdmfSet> localSet = localSets[k];
            const shared_ptr<XdmfAttribute> localAttribute = 
              XdmfAttribute::New();
            localAttribute->reserve(numberComponents * localSet->getSize());
            localAttributes.push_back(localAttribute);
          }
          for(unsigned int k=0; k<setSize; ++k) {
            const unsigned int globalElementId = 
              set->getValue<unsigned int>(k);
            const std::pair<unsigned int, unsigned int> & 
              partitionElementPair = elementIdMap[globalElementId];
            const unsigned int partitionId = partitionElementPair.first;
            const shared_ptr<XdmfAttribute> localAttribute = 
              localAttributes[partitionId];
            localAttribute->insert(localAttribute->getSize(),
                                   attribute,
                                   k * numberComponents,
                                   numberComponents);
          }
        }
        else if(attributeCenter == XdmfAttributeCenter::Node()) {
          for(unsigned int k=0; k<numberOfPartitions; ++k) {
            const shared_ptr<XdmfSet> localSet = localSets[k];
            const shared_ptr<XdmfAttribute> localAttribute = 
              XdmfAttribute::New();
            localAttribute->reserve(numberComponents * localSet->getSize());
            localAttributes.push_back(localAttribute);
          }
          for(unsigned int k=0; k<setSize; ++k) {
            const unsigned int globalNodeId = set->getValue<unsigned int>(k);
            const std::map<unsigned int, unsigned int> & localNodeIds = 
              nodeIdMap[globalNodeId];
            for(std::map<unsigned int, unsigned int>::const_iterator iter = 
                  localNodeIds.begin(); iter != localNodeIds.end(); ++iter) {
              const unsigned int partitionId = iter->first;
              const shared_ptr<XdmfAttribute> localAttribute = 
                localAttributes[partitionId];
              localAttribute->insert(localAttribute->getSize(),
                                     attribute,
                                     k * numberComponents,
                                     numberComponents);
791
            }
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
          }
        }

        if(releaseAttribute) {
          attribute->release();
        }

        for(std::vector<shared_ptr<XdmfAttribute> >::size_type k=0; 
            k<localAttributes.size(); ++k) {
          const shared_ptr<XdmfAttribute> localAttribute = localAttributes[k];
          if(localAttribute->getSize() > 0) {
            localSets[k]->insert(localAttribute);
            localAttribute->setName(attribute->getName());
            localAttribute->setCenter(attribute->getCenter());
            localAttribute->setType(attribute->getType());
807
            if(heavyDataWriter) {
808 809
              localAttribute->accept(heavyDataWriter);
              localAttribute->release();
810
            }
811
          }
812
        }    
813
      }
814
      
815
      if(releaseSet) {
816
        set->release();
817
      }
818 819
    }
  }
820 821
    
  // add XdmfMap to map boundary nodes between partitions
822
  std::vector<shared_ptr<XdmfMap> > maps = XdmfMap::New(globalNodeIds);
823
  for(unsigned int i=0; i<numberOfPartitions; ++i) {
824
    shared_ptr<XdmfMap> map = maps[i];
825
    map->setName("Subdomain Boundary");
826
    partitionedGrid->getUnstructuredGrid(i)->insert(map);
827 828 829 830 831 832
    if(heavyDataWriter) {
      map->accept(heavyDataWriter);
      map->release();
    }
  }

833
  return partitionedGrid;
834 835
}

836 837 838
shared_ptr<XdmfUnstructuredGrid>
XdmfPartitioner::unpartition(const shared_ptr<XdmfGridCollection> gridToUnPartition) const
{
839
  
840
  const shared_ptr<XdmfUnstructuredGrid> returnValue =
841 842 843 844 845
      XdmfUnstructuredGrid::New();
    const shared_ptr<XdmfTopology> returnValueTopology =
      returnValue->getTopology();
    const shared_ptr<XdmfGeometry> returnValueGeometry =
      returnValue->getGeometry();
846

847 848
    const unsigned int numberUnstructuredGrids =
      gridToUnPartition->getNumberUnstructuredGrids();
849

850
    unsigned int elementOffset = 0;
851

852
    for(unsigned int i=0; i<numberUnstructuredGrids; ++i) {
853

854 855
      const shared_ptr<XdmfUnstructuredGrid> grid =
        gridToUnPartition->getUnstructuredGrid(i);
856

857 858
      const shared_ptr<XdmfAttribute> globalNodeIds =
        grid->getAttribute("GlobalNodeId");
859

860 861 862 863 864 865 866 867 868
      if(!globalNodeIds) {
        try {
          XdmfError::message(XdmfError::FATAL,
                             "Cannot find GlobalNodeId attribute in "
                             "XdmfPartitioner::unpartition");
        }
        catch (XdmfError e) {
          throw e;
        }
869
      }
870

871 872 873 874 875
      bool releaseGlobalNodeIds = false;
      if(!globalNodeIds->isInitialized()) {
        globalNodeIds->read();
        releaseGlobalNodeIds = true;
      }
876

877 878
      // handle topology
      const shared_ptr<XdmfTopology> topology = grid->getTopology();
879

880 881 882 883
      if(i==0) {
        returnValueTopology->setType(topology->getType());
        returnValueTopology->initialize(topology->getArrayType());
      }
884

885 886
      returnValueTopology->reserve(returnValueTopology->getSize() +
                                   topology->getSize());
887

888 889 890 891 892
      bool releaseTopology = false;
      if(!topology->isInitialized()) {
        topology->read();
        releaseTopology = true;
      }
893

894 895 896 897 898 899
      for(unsigned int j=0; j<topology->getSize(); ++j) {
        const unsigned int localNodeId = topology->getValue<unsigned int>(j);
        const unsigned int globalNodeId =
          globalNodeIds->getValue<unsigned int>(localNodeId);
        returnValueTopology->pushBack(globalNodeId);
      }
900

901 902 903
      if(releaseTopology) {
        topology->release();
      }
904

905 906 907 908 909
      // handle geometry
      const shared_ptr<XdmfGeometry> geometry = grid->getGeometry();
      const shared_ptr<const XdmfGeometryType> geometryType =
        geometry->getType();
      const unsigned int geometryDimension = geometryType->getDimensions();
910

911 912 913 914
      if(i==0) {
        returnValueGeometry->setType(geometryType);
        returnValueGeometry->initialize(geometry->getArrayType());
      }
915

916 917 918 919 920
      bool releaseGeometry = false;
      if(!geometry->isInitialized()) {
        geometry->read();
        releaseGeometry = true;
      }
921

922 923 924 925 926 927 928 929
      for(unsigned int j=0; j<globalNodeIds->getSize(); ++j) {
        const unsigned int globalNodeId =
          globalNodeIds->getValue<unsigned int>(j);
        returnValueGeometry->insert(globalNodeId * geometryDimension,
                                    geometry,
                                    j * geometryDimension,
                                    geometryDimension);
      }
930

931 932 933
      if(releaseGeometry) {
        geometry->release();
      }
934

935 936
      // handle attributes
      for(unsigned int j=0; j<grid->getNumberAttributes(); ++j) {
937

938 939 940
        const shared_ptr<XdmfAttribute> attribute = grid->getAttribute(j);
        const shared_ptr<const XdmfAttributeCenter> attributeCenter =
          attribute->getCenter();
941

942 943 944 945 946
        bool releaseAttribute = false;
        if(!attribute->isInitialized()) {
          attribute->read();
          releaseAttribute = true;
        }
947

948
        shared_ptr<XdmfAttribute> returnValueAttribute;
949

950 951 952 953 954 955 956 957 958 959 960
        if(i==0) {
          returnValueAttribute = XdmfAttribute::New();
          returnValueAttribute->setName(attribute->getName());
          returnValueAttribute->setCenter(attributeCenter);
          returnValueAttribute->setType(attribute->getType());
          returnValueAttribute->initialize(attribute->getArrayType());
          returnValue->insert(returnValueAttribute);
        }
        else {
          returnValueAttribute = returnValue->getAttribute(attribute->getName());
        }
961 962


963 964 965 966 967 968 969 970 971 972 973 974 975
        if(attributeCenter == XdmfAttributeCenter::Grid()) {
          returnValueAttribute->insert(0,
                                       attribute,
                                       0,
                                       attribute->getSize());
        }
        else if(attributeCenter == XdmfAttributeCenter::Cell()) {
          returnValueAttribute->insert(returnValueAttribute->getSize(),
                                       attribute,
                                       0,
                                       attribute->getSize());
        }
        else if(attributeCenter == XdmfAttributeCenter::Node()) {
976

977 978 979 980 981 982 983 984 985 986 987
          const unsigned int numberComponents =
            attribute->getSize() / geometry->getNumberPoints();

          for(unsigned int k=0; k<globalNodeIds->getSize(); ++k) {
            const unsigned int globalNodeId =
              globalNodeIds->getValue<unsigned int>(k);
            returnValueAttribute->insert(globalNodeId * numberComponents,
                                         attribute,
                                         k * numberComponents,
                                         numberComponents);
          }
988

989
        }
990

991 992 993
        if(releaseAttribute) {
          attribute->release();
        }
994

995 996
      }

997 998
      // handle sets
      for(unsigned int j=0; j<grid->getNumberSets(); ++j) {
999

1000 1001
        const shared_ptr<XdmfSet> set = grid->getSet(j);
        const shared_ptr<const XdmfSetType> setType = set->getType();
1002

1003 1004 1005 1006 1007
        bool releaseSet = false;
        if(!set->isInitialized()) {
          set->read();
          releaseSet = true;
        }
1008

1009 1010 1011 1012 1013 1014 1015
        shared_ptr<XdmfSet> returnValueSet = returnValue->getSet(set->getName());
        if(!returnValueSet) {
          returnValueSet = XdmfSet::New();
          returnValueSet->setName(set->getName());
          returnValueSet->setType(setType);
          returnValue->insert(returnValueSet);
        }
1016

1017 1018 1019 1020 1021
        if(setType == XdmfSetType::Cell()) {
          for(unsigned int k=0; k<set->getSize(); ++k) {
            const unsigned int localCellId = set->getValue<unsigned int>(k);
            returnValueSet->pushBack(localCellId + elementOffset);
          }
1022
        }
1023 1024 1025 1026 1027 1028 1029
        else if(setType == XdmfSetType::Node()) {
          for(unsigned int k=0; k<set->getSize(); ++k){
            const unsigned int localNodeId = set->getValue<unsigned int>(k);
            const unsigned int globalNodeId =
              globalNodeIds->getValue<unsigned int>(localNodeId);
            returnValueSet->pushBack(globalNodeId);
          }
1030 1031
        }

1032 1033
        for(unsigned int k=0; k<set->getNumberAttributes(); ++k) {
          const shared_ptr<XdmfAttribute> attribute = set->getAttribute(k);
1034 1035 1036 1037 1038 1039 1040

          bool releaseAttribute = false;
          if(!attribute->isInitialized()) {
            attribute->read();
            releaseAttribute = true;
          }

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
          const shared_ptr<const XdmfAttributeCenter> attributeCenter =
            attribute->getCenter();
          const shared_ptr<const XdmfAttributeType> attributeType =
            attribute->getType();

          shared_ptr<XdmfAttribute> returnValueAttribute =
            returnValueSet->getAttribute(attribute->getName());
          if(!returnValueAttribute) {
            returnValueAttribute = XdmfAttribute::New();
            returnValueAttribute->setName(attribute->getName());
            returnValueAttribute->setCenter(attributeCenter);
            returnValueAttribute->setType(attributeType);
            returnValueSet->insert(returnValueAttribute);
          }
1055

1056 1057 1058 1059 1060 1061 1062
          if(attributeCenter == XdmfAttributeCenter::Cell() ||
             attributeCenter == XdmfAttributeCenter::Node()) {
            returnValueAttribute->insert(returnValueAttribute->getSize(),
                                         attribute,
                                         0,
                                         attribute->getSize());
          }
1063

1064 1065 1066 1067
          if(releaseAttribute) {
            attribute->release();
          }

1068
        }
1069

1070
      }
1071

1072
      elementOffset += topology->getNumberElements();
1073

1074 1075 1076
      if(releaseGlobalNodeIds) {
        globalNodeIds->release();
      }
1077 1078

    }
1079

1080
    return returnValue;
1081

1082
  }
1083

1084 1085
#else

1086
#include <cstdio>
1087
#include <iostream>
1088 1089
#include <sstream>
#include "XdmfDomain.hpp"
Kenneth Leiter's avatar
Kenneth Leiter committed
1090
#include "XdmfGraph.hpp"
1091
#include "XdmfGridCollection.hpp"
1092
#include "XdmfGridCollectionType.hpp"
1093
#include "XdmfHDF5Writer.hpp"
1094
#include "XdmfPartitioner.hpp"
1095
#include "XdmfReader.hpp"
1096
#include "XdmfUnstructuredGrid.hpp"
1097
#include "XdmfWriter.hpp"
1098

1099
  namespace {
1100

1101
    //
1102
    // print usage
1103
    //
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
    inline void
    printUsage(const char * programName)
    {

      std::cerr << "usage: " << programName << " "
                << "[-s metis_scheme] [-r] [-u]"
                << "<input file> <number of partitions> [output file]"
                << std::endl;
      std::cerr << "\t-s metis_scheme: 1 - Dual Graph" << std::endl;
      std::cerr << "\t-s metis_scheme: 2 - Node Graph" << std::endl;
      std::cerr << "\t-u unpartition file" << std::endl;

      //
      //
      //
      return;
1120 1121 1122

    }

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    //
    // process command line
    //
    void
    processCommandLine(std::string                  & inputFileName,
                       std::string                  & outputFileName,
                       unsigned int                 & numberOfPartitions,
                       XdmfPartitioner::MetisScheme & metisScheme,
                       bool                         & unpartition,
                       int                            ac,
                       char                         * av[])
    {

      int c;
      bool errorFlag = false;

      while( (c=getopt(ac, av, "s:ur")) != -1 )
        switch(c){

        case 's': {
          const int value = std::atoi(optarg);
          if(value == 1) {
            metisScheme = XdmfPartitioner::DUAL_GRAPH;
          }
          else if(value == 2) {
            metisScheme = XdmfPartitioner::NODAL_GRAPH;
          }
          else {
            errorFlag = true;
          }
          break;
        }
        case 'u':
          unpartition = true;
          break;
        case '?':
          errorFlag = true;
          break;
        }
1162

1163 1164 1165
      if (optind >= ac)
        errorFlag = true;
      else {
1166
        inputFileName = av[optind];
1167 1168
        ++optind;
      }
1169

1170 1171 1172 1173 1174 1175 1176 1177
      if(!unpartition) {
        if (optind >= ac)
          errorFlag = true;
        else {
          numberOfPartitions = atoi(av[optind]);
          ++optind;
        }
      }