XdmfPartitioner.cpp 32.5 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"
39
#include "XdmfGridCollection.hpp"
40
#include "XdmfGridCollectionType.hpp"
41
#include "XdmfHeavyDataWriter.hpp"
42
#include "XdmfMap.hpp"
43
#include "XdmfPartitioner.hpp"
44
#include "XdmfSet.hpp"
45
#include "XdmfSetType.hpp"
46
#include "XdmfTopology.hpp"
47
#include "XdmfTopologyType.hpp"
48
#include "XdmfUnstructuredGrid.hpp"
49

50
shared_ptr<XdmfPartitioner>
51
XdmfPartitioner::New()
52
{
53
  shared_ptr<XdmfPartitioner> p(new XdmfPartitioner());
54
  return p;
55
56
}

57
58
59
60
61
62
63
64
XdmfPartitioner::XdmfPartitioner()
{
}

XdmfPartitioner::~XdmfPartitioner()
{
}

65
66
void
XdmfPartitioner::ignore(const shared_ptr<const XdmfSet> set)
67
68
69
70
{
  mIgnoredSets.insert(set);
}

71
72
shared_ptr<XdmfGridCollection>
XdmfPartitioner::partition(const shared_ptr<XdmfUnstructuredGrid> gridToPartition,
73
                           const unsigned int numberOfPartitions,
74
                           const MetisScheme metisScheme,
75
                           const shared_ptr<XdmfHeavyDataWriter> heavyDataWriter) const
76
{
77
78
79
80
81

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

82
  // Make sure geometry and topology are non null
83
  if(!(gridToPartition->getGeometry() && gridToPartition->getTopology()))
84
    XdmfError::message(XdmfError::FATAL,
85
86
                       "Current grid's geometry or topology is null in "
                       "XdmfPartitioner::partition");
87

88
  const shared_ptr<XdmfGeometry> geometry =
89
    gridToPartition->getGeometry();
90
  const shared_ptr<const XdmfGeometryType> geometryType =
91
    geometry->getType();
92
  const shared_ptr<XdmfTopology> topology =
93
    gridToPartition->getTopology();
94
  const shared_ptr<const XdmfTopologyType> topologyType =
95
96
    topology->getType();

97
  const unsigned int nodesPerElement = topologyType->getNodesPerElement();
98
99
100
101
102
103
104
105

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

  int numElements = topology->getNumberElements();
106
  int numNodes = geometry->getNumberPoints();
107

108
109
110
  // allocate metisConnectivity arrays
  idx_t * metisConnectivityEptr = new idx_t[numElements + 1];
  idx_t * metisConnectivityEind = new idx_t[nodesPerElement * numElements];
111

112
113
114
  metisConnectivityEptr[0] = 0;

  unsigned int metisConnectivityEptrValue = 0;
115
  unsigned int connectivityOffset = 0;
116
  idx_t * metisConnectivityPtr = metisConnectivityEind;
117
  for(int i=0; i<numElements; ++i) {
118
119
    metisConnectivityEptrValue += nodesPerElement;
    metisConnectivityEptr[i + 1] = metisConnectivityEptrValue;
120
121
122
123
124
125
126
    topology->getValues(connectivityOffset,
                        metisConnectivityPtr,
                        nodesPerElement);
    connectivityOffset += topologyType->getNodesPerElement();
    metisConnectivityPtr += nodesPerElement;
  }

127
128
129
130
131
132
133
134
135
136
  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];
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
  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 {
168
    XdmfError::message(XdmfError::FATAL,
169
                       "Invalid metis partitioning scheme selected in "
170
                       "XdmfPartitioner::partition");
171

172
  }
173

174
175
  delete [] metisConnectivityEptr;
  delete [] metisConnectivityEind;
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
  delete [] nodesPartition;

  // For each partition, map global to local node id
  std::vector<std::map<unsigned int, unsigned int> > globalToLocalNodeIdMap;
  // For each partition, list global element id.
  std::vector<std::vector<unsigned int> > globalElementIds;
  for(unsigned int i=0; i<numberOfPartitions; ++i) {
    std::map<unsigned int, unsigned int> nodeMap;
    globalToLocalNodeIdMap.push_back(nodeMap);
    std::vector<unsigned int> elementIds;
    globalElementIds.push_back(elementIds);
  }

  // Fill in globalNodeId for each partition
  unsigned int totalIndex = 0;
  for (int i=0; i<numElements; ++i) {
    unsigned int partitionId = elementsPartition[i];
    for (unsigned int j=0; j<topologyType->getNodesPerElement(); ++j) {
      unsigned int globalNodeId = topology->getValue<unsigned int>(totalIndex);
      if (globalToLocalNodeIdMap[partitionId].count(globalNodeId) == 0) {
        // Have not seen this node, need to add to map
        unsigned int size = globalToLocalNodeIdMap[partitionId].size();
        globalToLocalNodeIdMap[partitionId][globalNodeId] = size;
      }
      totalIndex++;
    }
    globalElementIds[partitionId].push_back(i);
  }
  delete [] elementsPartition;

  bool generateGlobalNodeIds = !gridToPartition->getAttribute("GlobalNodeId");

208
  shared_ptr<XdmfGridCollection> partitionedGrids =
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    XdmfGridCollection::New();
  partitionedGrids->setType(XdmfGridCollectionType::Spatial());

  bool releaseGeometry = false;
  if(!geometry->isInitialized()) {
    geometry->read();
    releaseGeometry = true;
  }

  // Split geometry and topology into proper partitions
  for(unsigned int i=0; i<numberOfPartitions; ++i) {
    std::map<unsigned int, unsigned int> & currNodeMap =
      globalToLocalNodeIdMap[i];
    std::vector<unsigned int> & currElemIds = globalElementIds[i];

    if(currElemIds.size() > 0) {
      std::stringstream name;
      name << gridToPartition->getName() << "_" << i;

228
      const shared_ptr<XdmfUnstructuredGrid> partitioned =
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
        XdmfUnstructuredGrid::New();
      partitioned->setName(name.str());
      partitionedGrids->insert(partitioned);

      // Fill in geometry for this partition
      partitioned->getGeometry()->setType(geometryType);
      unsigned int numDimensions = geometryType->getDimensions();
      partitioned->getGeometry()->initialize(geometry->getArrayType(),
                                             currNodeMap.size() * numDimensions);

      for(std::map<unsigned int, unsigned int>::const_iterator iter =
            currNodeMap.begin();
          iter != currNodeMap.end();
          ++iter) {
        partitioned->getGeometry()->insert(iter->second * numDimensions,
                                           geometry,
                                           iter->first * numDimensions,
                                           numDimensions);
      }

      if(heavyDataWriter) {
        partitioned->getGeometry()->accept(heavyDataWriter);
        partitioned->getGeometry()->release();
      }

      // Fill in topology for this partition
      partitioned->getTopology()->setType(topologyType);
      partitioned->getTopology()->initialize(topology->getArrayType(),
                                             currElemIds.size() * topologyType->getNodesPerElement());
      unsigned int index = 0;
      for(std::vector<unsigned int>::const_iterator iter = currElemIds.begin();
          iter != currElemIds.end();
          ++iter) {
        // Translate these global node ids to local node ids
        for(unsigned int j=0; j<topologyType->getNodesPerElement(); ++j) {
          unsigned int globalNodeId =
            currNodeMap[topology->getValue<unsigned int>(*iter * topologyType->getNodesPerElement() + j)];
          partitioned->getTopology()->insert(index, &globalNodeId, 1);
          index++;
        }
      }

      if(heavyDataWriter) {
        partitioned->getTopology()->accept(heavyDataWriter);
        partitioned->getTopology()->release();
      }

      if (generateGlobalNodeIds) {
277
        shared_ptr<XdmfAttribute> globalNodeIds = XdmfAttribute::New();
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
        globalNodeIds->setName("GlobalNodeId");
        globalNodeIds->setType(XdmfAttributeType::GlobalId());
        globalNodeIds->setCenter(XdmfAttributeCenter::Node());
        globalNodeIds->initialize<unsigned int>(currNodeMap.size());
        for(std::map<unsigned int, unsigned int>::const_iterator iter =
              currNodeMap.begin();
            iter != currNodeMap.end();
            ++iter) {
          globalNodeIds->insert(iter->second, &iter->first, 1);
        }
        partitioned->insert(globalNodeIds);

        if(heavyDataWriter) {
          globalNodeIds->accept(heavyDataWriter);
          globalNodeIds->release();
        }
      }
    }
  }

  if(releaseGeometry) {
    gridToPartition->getGeometry()->release();
  }
  if(releaseTopology) {
    gridToPartition->getTopology()->release();
  }

  // Split attributes into proper partitions
  for(unsigned int i=0; i<gridToPartition->getNumberAttributes(); ++i) {
307

308
    const shared_ptr<XdmfAttribute> currAttribute =
309
310
311
312
313
314
315
316
317
318
319
320
      gridToPartition->getAttribute(i);
    bool releaseAttribute = false;
    if(!currAttribute->isInitialized()) {
      currAttribute->read();
      releaseAttribute = true;
    }
    unsigned int partitionId = 0;
    for(unsigned int j=0; j<numberOfPartitions; ++j) {
      std::map<unsigned int, unsigned int> & currNodeMap =
        globalToLocalNodeIdMap[j];
      std::vector<unsigned int> & currElemIds = globalElementIds[j];
      if(currElemIds.size() > 0) {
321
        const shared_ptr<XdmfUnstructuredGrid> partitioned =
322
323
          partitionedGrids->getUnstructuredGrid(partitionId);
        partitionId++;
324
        shared_ptr<XdmfAttribute> createdAttribute =
325
          shared_ptr<XdmfAttribute>();
326
327
328
329
        if(currAttribute->getCenter() == XdmfAttributeCenter::Grid()) {
          // Insert into each partition
          createdAttribute = currAttribute;
        }
330
        else if(currAttribute->getCenter() == XdmfAttributeCenter::Cell()) {
331
332
333
334
335
          createdAttribute = XdmfAttribute::New();
          createdAttribute->setName(currAttribute->getName());
          createdAttribute->setCenter(currAttribute->getCenter());
          createdAttribute->setType(currAttribute->getType());
          unsigned int index = 0;
336
          const unsigned int numberComponents =
337
	    currAttribute->getSize() / topology->getNumberElements();
338
          createdAttribute->initialize(currAttribute->getArrayType(),
339
                                       currElemIds.size() * numberComponents);
340
341
342
343
344
345
          for(std::vector<unsigned int>::const_iterator iter =
                currElemIds.begin();
              iter != currElemIds.end();
              ++iter) {
            createdAttribute->insert(index,
                                     currAttribute,
346
347
348
                                     *iter * numberComponents,
                                     numberComponents);
            index += numberComponents;
349
350
351
352
353
354
355
          }
        }
        else if(currAttribute->getCenter() == XdmfAttributeCenter::Node()) {
          createdAttribute = XdmfAttribute::New();
          createdAttribute->setName(currAttribute->getName());
          createdAttribute->setCenter(currAttribute->getCenter());
          createdAttribute->setType(currAttribute->getType());
356
          createdAttribute->initialize(currAttribute->getArrayType(),
357
				       currNodeMap.size());
358
	  const unsigned int numberComponents =
359
	    currAttribute->getSize() / geometry->getNumberPoints();
360
361
362
363
          for(std::map<unsigned int, unsigned int>::const_iterator iter =
                currNodeMap.begin();
              iter != currNodeMap.end();
              ++iter) {
364
            createdAttribute->insert(iter->second * numberComponents,
365
                                     currAttribute,
366
367
                                     iter->first * numberComponents,
                                     numberComponents);
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
          }
        }
        if(createdAttribute) {
          partitioned->insert(createdAttribute);
          if(heavyDataWriter) {
            if(!createdAttribute->isInitialized()) {
              createdAttribute->read();
            }
            createdAttribute->accept(heavyDataWriter);
            createdAttribute->release();
          }
        }
      }
    }
    if(releaseAttribute) {
      currAttribute->release();
    }
  }

  // Split sets into proper partitions
  for(unsigned int i=0; i<gridToPartition->getNumberSets(); ++i) {
389
    shared_ptr<XdmfSet> currSet = gridToPartition->getSet(i);
390
391
392
393
394
395
396
397
    if(mIgnoredSets.find(currSet) == mIgnoredSets.end()) {
      bool releaseSet = false;
      if(!currSet->isInitialized()) {
        currSet->read();
        releaseSet = true;
      }
      unsigned int partitionId = 0;
      for(unsigned int j=0; j<numberOfPartitions; ++j) {
398
        const std::map<unsigned int, unsigned int> & currNodeMap =
399
          globalToLocalNodeIdMap[j];
400
        const std::vector<unsigned int> & currElemIds = globalElementIds[j];
401
        if(currElemIds.size() > 0) {
402
          shared_ptr<XdmfUnstructuredGrid> partitioned =
403
404
            partitionedGrids->getUnstructuredGrid(partitionId);
          partitionId++;
405
406

          shared_ptr<XdmfSet> partitionedSet = XdmfSet::New();
407
          std::vector<unsigned int> partitionedSetIndex;
408

409
          if(currSet->getType() == XdmfSetType::Cell()) {
410
411
412
413
414
415
416
417
418
419
            for(unsigned int k=0; k<currSet->getSize(); ++k) {
              std::vector<unsigned int>::const_iterator val =
                std::find(currElemIds.begin(),
                          currElemIds.end(),
                          currSet->getValue<unsigned int>(k));
              if(val != currElemIds.end()) {
                unsigned int valToPush = val - currElemIds.begin();
                partitionedSet->pushBack(valToPush);
                partitionedSetIndex.push_back(k);
              }
420
421
            }
          }
422
423
424
425
426
427
428
429
          else if(currSet->getType() == XdmfSetType::Node()) {
            for(unsigned int k=0; k<currSet->getSize(); ++k) {
              std::map<unsigned int, unsigned int>::const_iterator val =
                currNodeMap.find(currSet->getValue<unsigned int>(k));
              if(val != currNodeMap.end()) {
                partitionedSet->pushBack(val->second);
                partitionedSetIndex.push_back(k);
              }
430
431
            }
          }
432

433
          // Only insert set if contains values
434
435
436
          if(partitionedSet->getSize() > 0) {

            for(unsigned int k=0; k<currSet->getNumberAttributes(); ++k) {
437
              const shared_ptr<XdmfAttribute> currAttribute =
438
                currSet->getAttribute(k);
439
440
441
442
443
444
445
              bool releaseAttribute = false;
              if(!currAttribute->isInitialized()) {
                currAttribute->read();
                releaseAttribute = true;
              }
              if(currAttribute->getCenter() == XdmfAttributeCenter::Node() ||
                 currAttribute->getCenter() == XdmfAttributeCenter::Cell()) {
446
                const unsigned int numberComponents =
447
                  currAttribute->getSize() / currSet->getSize();
448

449
                const shared_ptr<XdmfAttribute> partitionedAttribute =
450
451
452
453
454
                  XdmfAttribute::New();
                partitionedAttribute->setCenter(currAttribute->getCenter());
                partitionedAttribute->setName(currAttribute->getName());
                partitionedAttribute->setType(currAttribute->getType());
                partitionedAttribute->initialize(currAttribute->getArrayType(),
455
                                                 partitionedSetIndex.size() * numberComponents);
456
                for(unsigned int l=0; l<partitionedSetIndex.size(); ++l) {
457
                  partitionedAttribute->insert(l * numberComponents,
458
                                               currAttribute,
459
460
                                               partitionedSetIndex[l] * numberComponents,
                                               numberComponents);
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
                }
                partitionedSet->insert(partitionedAttribute);
                if(heavyDataWriter) {
                  partitionedAttribute->accept(heavyDataWriter);
                  partitionedAttribute->release();
                }
              }
            }
            partitioned->insert(partitionedSet);
            partitionedSet->setName(currSet->getName());
            partitionedSet->setType(currSet->getType());
            if(heavyDataWriter) {
              partitionedSet->accept(heavyDataWriter);
              partitionedSet->release();
            }
476
477
478
          }
        }
      }
479
480
481
      if(releaseSet) {
        currSet->release();
      }
482
483
484
485
    }
  }

  // Add XdmfMap to map boundary nodes between partitions
486
  std::vector<shared_ptr<XdmfAttribute> > globalNodeIds;
487
488
489
  for(unsigned int i=0;
      i<partitionedGrids->getNumberUnstructuredGrids();
      ++i) {
490
    shared_ptr<XdmfAttribute> globalNodeId =
491
      partitionedGrids->getUnstructuredGrid(i)->getAttribute("GlobalNodeId");
492
493
494
495
    if(!globalNodeId->isInitialized()) {
      globalNodeId->read();
    }
    globalNodeIds.push_back(globalNodeId);
496
497
  }

498
  std::vector<shared_ptr<XdmfMap> > maps = XdmfMap::New(globalNodeIds);
499
500
501
  for(unsigned int i=0;
      i<partitionedGrids->getNumberUnstructuredGrids();
      ++i) {
502
    shared_ptr<XdmfMap> map = maps[i];
503
504
    map->setName("Subdomain Boundary");
    partitionedGrids->getUnstructuredGrid(i)->insert(map);
505
506
507
508
509
510
511
512
    if(heavyDataWriter) {
      globalNodeIds[i]->release();
      map->accept(heavyDataWriter);
      map->release();
    }
  }

  return partitionedGrids;
513
514
}

515
516
517
518
shared_ptr<XdmfUnstructuredGrid>
XdmfPartitioner::unpartition(const shared_ptr<XdmfGridCollection> gridToUnPartition) const
{

519
  const shared_ptr<XdmfUnstructuredGrid> returnValue =
520
    XdmfUnstructuredGrid::New();
521
  const shared_ptr<XdmfTopology> returnValueTopology =
522
523
524
525
    returnValue->getTopology();
  const shared_ptr<XdmfGeometry> returnValueGeometry =
    returnValue->getGeometry();

526
  const unsigned int numberUnstructuredGrids =
527
    gridToUnPartition->getNumberUnstructuredGrids();
528

529
530
531
532
  unsigned int elementOffset = 0;

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

533
    const shared_ptr<XdmfUnstructuredGrid> grid =
534
535
      gridToUnPartition->getUnstructuredGrid(i);

536
    const shared_ptr<XdmfAttribute> globalNodeIds =
537
538
539
      grid->getAttribute("GlobalNodeId");

    if(!globalNodeIds) {
540
      XdmfError::message(XdmfError::FATAL,
541
542
543
544
545
546
547
548
549
550
551
552
                         "Cannot find GlobalNodeId attribute in "
                         "XdmfPartitioner::unpartition");
    }

    bool releaseGlobalNodeIds = false;
    if(!globalNodeIds->isInitialized()) {
      globalNodeIds->read();
      releaseGlobalNodeIds = true;
    }

    // handle topology
    const shared_ptr<XdmfTopology> topology = grid->getTopology();
553

554
555
556
557
558
    if(i==0) {
      returnValueTopology->setType(topology->getType());
      returnValueTopology->initialize(topology->getArrayType());
    }

559
    returnValueTopology->reserve(returnValueTopology->getSize() +
560
561
562
563
564
565
566
567
568
569
                                 topology->getSize());

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

    for(unsigned int j=0; j<topology->getSize(); ++j) {
      const unsigned int localNodeId = topology->getValue<unsigned int>(j);
570
      const unsigned int globalNodeId =
571
572
573
574
575
576
577
        globalNodeIds->getValue<unsigned int>(localNodeId);
      returnValueTopology->pushBack(globalNodeId);
    }

    if(releaseTopology) {
      topology->release();
    }
578

579
580
    // handle geometry
    const shared_ptr<XdmfGeometry> geometry = grid->getGeometry();
581
    const shared_ptr<const XdmfGeometryType> geometryType =
582
583
      geometry->getType();
    const unsigned int geometryDimension = geometryType->getDimensions();
584

585
586
587
588
589
590
591
592
593
594
595
596
    if(i==0) {
      returnValueGeometry->setType(geometryType);
      returnValueGeometry->initialize(geometry->getArrayType());
    }

    bool releaseGeometry = false;
    if(!geometry->isInitialized()) {
      geometry->read();
      releaseGeometry = true;
    }

    for(unsigned int j=0; j<globalNodeIds->getSize(); ++j) {
597
      const unsigned int globalNodeId =
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
        globalNodeIds->getValue<unsigned int>(j);
      returnValueGeometry->insert(globalNodeId * geometryDimension,
                                  geometry,
                                  j * geometryDimension,
                                  geometryDimension);
    }

    if(releaseGeometry) {
      geometry->release();
    }

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

      const shared_ptr<XdmfAttribute> attribute = grid->getAttribute(j);
613
      const shared_ptr<const XdmfAttributeCenter> attributeCenter =
614
        attribute->getCenter();
615

616
617
618
619
620
621
622
      bool releaseAttribute = false;
      if(!attribute->isInitialized()) {
        attribute->read();
        releaseAttribute = true;
      }

      shared_ptr<XdmfAttribute> returnValueAttribute;
623

624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
      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());
      }


      if(attributeCenter == XdmfAttributeCenter::Grid()) {
        returnValueAttribute->insert(0,
                                     attribute,
                                     0,
641
                                     attribute->getSize());
642
643
644
645
646
647
648
649
      }
      else if(attributeCenter == XdmfAttributeCenter::Cell()) {
        returnValueAttribute->insert(returnValueAttribute->getSize(),
                                     attribute,
                                     0,
                                     attribute->getSize());
      }
      else if(attributeCenter == XdmfAttributeCenter::Node()) {
650
651

        const unsigned int numberComponents =
652
          attribute->getSize() / geometry->getNumberPoints();
653

654
        for(unsigned int k=0; k<globalNodeIds->getSize(); ++k) {
655
          const unsigned int globalNodeId =
656
657
658
659
660
661
            globalNodeIds->getValue<unsigned int>(k);
          returnValueAttribute->insert(globalNodeId * numberComponents,
                                       attribute,
                                       k * numberComponents,
                                       numberComponents);
        }
662

663
      }
664

665
666
667
668
669
670
671
672
673
674
675
      if(releaseAttribute) {
        attribute->release();
      }

    }

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

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

677
678
679
680
681
682
683
684
685
686
687
688
689
      bool releaseSet = false;
      if(!set->isInitialized()) {
        set->read();
        releaseSet = true;
      }

      shared_ptr<XdmfSet> returnValueSet = returnValue->getSet(set->getName());
      if(!returnValueSet) {
        returnValueSet = XdmfSet::New();
        returnValueSet->setName(set->getName());
        returnValueSet->setType(setType);
        returnValue->insert(returnValueSet);
      }
690

691
692
693
694
695
696
697
698
699
      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);
        }
      }
      else if(setType == XdmfSetType::Node()) {
        for(unsigned int k=0; k<set->getSize(); ++k){
          const unsigned int localNodeId = set->getValue<unsigned int>(k);
700
          const unsigned int globalNodeId =
701
702
703
704
705
706
707
            globalNodeIds->getValue<unsigned int>(localNodeId);
          returnValueSet->pushBack(globalNodeId);
        }
      }

      for(unsigned int k=0; k<set->getNumberAttributes(); ++k) {
        const shared_ptr<XdmfAttribute> attribute = set->getAttribute(k);
708
        const shared_ptr<const XdmfAttributeCenter> attributeCenter =
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
          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);
        }

        if(attributeCenter == XdmfAttributeCenter::Cell() ||
           attributeCenter == XdmfAttributeCenter::Node()) {
          returnValueAttribute->insert(returnValueAttribute->getSize(),
                                       attribute,
                                       0,
                                       attribute->getSize());
        }
730

731
      }
732

733
    }
734

735
736
737
738
739
    elementOffset += topology->getNumberElements();

    if(releaseGlobalNodeIds) {
      globalNodeIds->release();
    }
740

741
742
743
744
745
746
  }

  return returnValue;

}

747
748
#else

749
#include <cstdio>
750
#include <iostream>
751
752
753
754
#include <sstream>
#include "XdmfDomain.hpp"
#include "XdmfGridCollection.hpp"
#include "XdmfHDF5Writer.hpp"
755
#include "XdmfPartitioner.hpp"
756
757
#include "XdmfReader.hpp"
#include "XdmfWriter.hpp"
758

759
760
761
762
763
764
765
766
767
768
namespace {

  //
  // print usage
  //
  inline void
  printUsage(const char * programName)
  {

    std::cerr << "usage: " << programName << " "
769
              << "[-s metis_scheme] [-r] [-u]"
770
771
              << "<input file> <number of partitions> [output file]"
              << std::endl;
772
773
774
775
    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;

776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
    //
    //
    //
    return;

  }

  //
  // process command line
  //
  void
  processCommandLine(std::string                  & inputFileName,
                     std::string                  & outputFileName,
		     unsigned int                 & numPartitions,
                     XdmfPartitioner::MetisScheme & metisScheme,
791
                     bool                         & unpartition,
792
793
794
795
796
797
		     int                            ac,
                     char                         * av[])
  {

    int c;
    bool errorFlag = false;
798

799
    while( (c=getopt(ac, av, "s:ur")) != -1 )
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
    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;
    }
815
816
817
    case 'u':
      unpartition = true;
      break;
818
819
820
821
822
823
824
825
826
827
828
829
    case '?':
      errorFlag = true;
      break;
    }

    if (optind >= ac)
      errorFlag = true;
    else {
      inputFileName = av[optind];
      ++optind;
    }

830
831
832
833
834
835
836
    if(!unpartition) {
      if (optind >= ac)
        errorFlag = true;
      else {
        numPartitions = atoi(av[optind]);
        ++optind;
      }
837
838
839
840
841
842
    }

    if (optind < ac) {
      outputFileName = av[optind];
      ++optind;
    }
843

844
845
846
847
848
849
850
851
852
853
854
855
    //
    // check errorFlag
    //
    if (errorFlag == true) {
      printUsage(av[0]);
      std::exit(EXIT_FAILURE);
    }

  }

}

856
857
/**
 * XdmfPartitioner is a command line utility for partitioning Xdmf grids.
858
859
 * The XdmfPartitioner uses the metis library to partition Triangular,
 * Quadrilateral, Tetrahedral, and Hexahedral XdmfGridUnstructureds.
860
861
 *
 * Usage:
862
863
 *     XdmfPartitioner <path-of-file-to-partition> <num-partitions>
 *                     (Optional: <path-to-output-file>)
864
865
 *
 */
866
int main(int argc, char* argv[])
867
{
868

869
  std::string inputFileName = "";
870
871
  std::string outputFileName = "";
  unsigned int numPartitions;
872
  XdmfPartitioner::MetisScheme metisScheme = XdmfPartitioner::DUAL_GRAPH;
873
  bool unpartition = false;
874
875
876
877
878

  processCommandLine(inputFileName,
		     outputFileName,
		     numPartitions,
		     metisScheme,
879
                     unpartition,
880
881
		     argc,
		     argv);
882

883
884
885
  std::cout << inputFileName << std::endl;

  FILE * refFile = fopen(inputFileName.c_str(), "r");
886
887
888
889
890
891
892
893
894
  if (refFile) {
    // Success
    fclose(refFile);
  }
  else {
    std::cout << "Cannot open file: " << argv[1] << std::endl;
    return 1;
  }

895
896
897
898
899
900
  std::string meshName;
  if(outputFileName.compare("") == 0) {
    meshName = inputFileName;
  }
  else {
    meshName = outputFileName;
901
902
903
  }

  if(meshName.find_last_of("/\\") != std::string::npos) {
904
    meshName = meshName.substr(meshName.find_last_of("/\\") + 1,
905
906
907
908
909
910
911
                               meshName.length());
  }

  if (meshName.rfind(".") != std::string::npos) {
    meshName = meshName.substr(0, meshName.rfind("."));
  }

912
  if(outputFileName.compare("") == 0) {
913
914
915
916
917
918
919
920
    std::stringstream newMeshName;
    if(unpartition) {
      newMeshName << meshName << "_unpartitioned";
    }
    else {
      newMeshName << meshName << "_p" << numPartitions;
    }
    meshName = newMeshName.str();
921
922
  }

923
924
  shared_ptr<XdmfReader> reader = XdmfReader::New();
  shared_ptr<XdmfDomain> domain =
925
    shared_dynamic_cast<XdmfDomain>(reader->read(inputFileName));
926

927
928
929
930
931
932
933
  if(unpartition) {
    if(domain->getNumberGridCollections() == 0) {
      std::cout << "No grid collections to unpartition" << std::endl;
      return 1;
    }
  }
  else {
934
935
    if(domain->getNumberUnstructuredGrids() == 0 &&
       domain->getNumberGridCollections() == 0) {
936
937
938
      std::cout << "No grids to partition" << std::endl;
      return 1;
    }
939
940
941
942
  }

  std::stringstream heavyFileName;
  heavyFileName << meshName << ".h5";
943
  shared_ptr<XdmfHDF5Writer> heavyDataWriter =
944
945
    XdmfHDF5Writer::New(heavyFileName.str());

946
947
  shared_ptr<XdmfDomain> newDomain = XdmfDomain::New();

948
  shared_ptr<XdmfPartitioner> partitioner = XdmfPartitioner::New();
949

950
951
952
953
954
955
  if(unpartition) {
    shared_ptr<XdmfUnstructuredGrid> toWrite =
      partitioner->unpartition(domain->getGridCollection(0));
    newDomain->insert(toWrite);
  }
  else {
956
957
958
959
960
961
962
    shared_ptr<XdmfUnstructuredGrid> gridToPartition;
    if(domain->getNumberUnstructuredGrids() == 0) {
      gridToPartition = partitioner->unpartition(domain->getGridCollection(0));
    }
    else {
      gridToPartition = domain->getUnstructuredGrid(0);
    }
963
    shared_ptr<XdmfGridCollection> toWrite =
964
      partitioner->partition(gridToPartition,
965
966
967
968
969
                             numPartitions,
                             metisScheme,
                             heavyDataWriter);
    newDomain->insert(toWrite);
  }
970
971
972

  std::stringstream xmlFileName;
  xmlFileName << meshName << ".xmf";
973
974
  shared_ptr<XdmfWriter> writer = XdmfWriter::New(xmlFileName.str(),
                                                  heavyDataWriter);
975
976
977
  newDomain->accept(writer);

  std::cout << "Wrote: " << xmlFileName.str() << std::endl;
978
}
979

980
#endif // BUILD_EXE