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

50
51
#include "XdmfArrayType.hpp"

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

59
60
61
62
63
64
65
66
XdmfPartitioner::XdmfPartitioner()
{
}

XdmfPartitioner::~XdmfPartitioner()
{
}

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

73
74
shared_ptr<XdmfGridCollection>
XdmfPartitioner::partition(const shared_ptr<XdmfUnstructuredGrid> gridToPartition,
75
                           const unsigned int numberOfPartitions,
76
                           const MetisScheme metisScheme,
77
                           const shared_ptr<XdmfHeavyDataWriter> heavyDataWriter) const
78
{
79
  // Make sure geometry and topology are non null
80
  if(!(gridToPartition->getGeometry() && gridToPartition->getTopology()))
81
82
83
    XdmfError::message(XdmfError::FATAL, 
                       "Current grid's geometry or topology is null in "
                       "XdmfPartitioner::partition");
84

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

94
  unsigned int nodesPerElement = 0;
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

  if(topologyType == XdmfTopologyType::Triangle() ||
     topologyType == XdmfTopologyType::Triangle_6()) {
    nodesPerElement = 3;
  }
  else if(topologyType == XdmfTopologyType::Quadrilateral() ||
          topologyType == XdmfTopologyType::Quadrilateral_8()) {
    nodesPerElement = 4;
  }
  else if(topologyType == XdmfTopologyType::Tetrahedron() ||
          topologyType == XdmfTopologyType::Tetrahedron_10()) {
    nodesPerElement = 4;
  }
  else if(topologyType == XdmfTopologyType::Hexahedron() ||
          topologyType == XdmfTopologyType::Hexahedron_20() ||
          topologyType == XdmfTopologyType::Hexahedron_24() ||
          topologyType == XdmfTopologyType::Hexahedron_27() ||
112
          topologyType == XdmfTopologyType::Hexahedron_64() ||
113
114
115
116
117
118
119
          topologyType == XdmfTopologyType::Hexahedron_125() ||
          topologyType == XdmfTopologyType::Hexahedron_216() ||
          topologyType == XdmfTopologyType::Hexahedron_343() ||
          topologyType == XdmfTopologyType::Hexahedron_512() ||
          topologyType == XdmfTopologyType::Hexahedron_729() ||
          topologyType == XdmfTopologyType::Hexahedron_1000() ||
          topologyType == XdmfTopologyType::Hexahedron_1331()) {
120
121
122
    nodesPerElement = 8;
  }
  else {
123
124
125
126
    XdmfError::message(XdmfError::FATAL, 
                       "Topology type is not 'Triangle', 'Quadrilateral', "
                       "'Tetrahedron', 'Hexahedron' in "
                       "XdmfPartition::partition");
127
128
129
130
131
132
133
134
135
  }

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

  int numElements = topology->getNumberElements();
136
137
138
139
140
141
142
143
  
  // allocate metisConnectivity arrays
  idx_t * metisConnectivityEptr = new idx_t[numElements + 1];
  idx_t * metisConnectivityEind = new idx_t[nodesPerElement * numElements];
  
  metisConnectivityEptr[0] = 0;

  unsigned int metisConnectivityEptrValue = 0;
144
  unsigned int connectivityOffset = 0;
145
  idx_t * metisConnectivityPtr = metisConnectivityEind;
146
  for(int i=0; i<numElements; ++i) {
147
148
    metisConnectivityEptrValue += nodesPerElement;
    metisConnectivityEptr[i + 1] = metisConnectivityEptrValue;
149
150
151
152
153
154
155
156
157
158
159
    topology->getValues(connectivityOffset,
                        metisConnectivityPtr,
                        nodesPerElement);
    connectivityOffset += topologyType->getNodesPerElement();
    metisConnectivityPtr += nodesPerElement;
  }

  int numNodes = geometry->getNumberPoints();

  // Need to remap connectivity for nonlinear elements so that metis handles
  // it properly.
160
  std::map<idx_t, idx_t> xdmfIdToMetisId;
161
162
163
  if(nodesPerElement != topologyType->getNodesPerElement()) {
    unsigned int index = 0;
    for (unsigned int i=0; i<numElements * nodesPerElement; ++i) {
164
165
      std::map<idx_t, idx_t>::const_iterator val =
        xdmfIdToMetisId.find(metisConnectivityEind[i]);
166
      if (val != xdmfIdToMetisId.end()) {
167
        metisConnectivityEind[i] = val->second;
168
169
170
      }
      else {
        // Haven't seen this id before, map to index and set to new id
171
172
        xdmfIdToMetisId[metisConnectivityEind[i]] = index;
        metisConnectivityEind[i] = index;
173
174
175
176
177
178
        index++;
      }
    }
    numNodes = index;
  }

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
  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];
  
  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 {
    XdmfError::message(XdmfError::FATAL, 
                       "Invalid metis partitioning scheme selected in"
                       "XdmfPartitioner::partition");
223

224
  }
225

226
227
  delete [] metisConnectivityEptr;
  delete [] metisConnectivityEind;
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
  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");

260
  shared_ptr<XdmfGridCollection> partitionedGrids =
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    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;

280
      shared_ptr<XdmfUnstructuredGrid> partitioned =
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
        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) {
329
        shared_ptr<XdmfAttribute> globalNodeIds = XdmfAttribute::New();
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
        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) {
359
    shared_ptr<XdmfAttribute> currAttribute =
360
361
362
363
364
365
366
367
368
369
370
371
      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) {
372
        shared_ptr<XdmfUnstructuredGrid> partitioned =
373
374
          partitionedGrids->getUnstructuredGrid(partitionId);
        partitionId++;
375
376
        shared_ptr<XdmfAttribute> createdAttribute =
          shared_ptr<XdmfAttribute>();
377
378
379
380
381
382
383
384
385
386
387
388
        if(currAttribute->getCenter() == XdmfAttributeCenter::Grid()) {
          // Insert into each partition
          createdAttribute = currAttribute;
        }
        else if(currAttribute->getCenter() == XdmfAttributeCenter::Cell() ||
                currAttribute->getCenter() == XdmfAttributeCenter::Face() ||
                currAttribute->getCenter() == XdmfAttributeCenter::Edge()) {
          createdAttribute = XdmfAttribute::New();
          createdAttribute->setName(currAttribute->getName());
          createdAttribute->setCenter(currAttribute->getCenter());
          createdAttribute->setType(currAttribute->getType());
          unsigned int index = 0;
389
390
          const unsigned int numberComponents = 
	    currAttribute->getSize() / topology->getNumberElements();
391
          createdAttribute->initialize(currAttribute->getArrayType(),
392
                                       currElemIds.size() * numberComponents);
393
394
395
396
397
398
          for(std::vector<unsigned int>::const_iterator iter =
                currElemIds.begin();
              iter != currElemIds.end();
              ++iter) {
            createdAttribute->insert(index,
                                     currAttribute,
399
400
401
                                     *iter * numberComponents,
                                     numberComponents);
            index += numberComponents;
402
403
404
405
406
407
408
          }
        }
        else if(currAttribute->getCenter() == XdmfAttributeCenter::Node()) {
          createdAttribute = XdmfAttribute::New();
          createdAttribute->setName(currAttribute->getName());
          createdAttribute->setCenter(currAttribute->getCenter());
          createdAttribute->setType(currAttribute->getType());
409
410
411
412
          createdAttribute->initialize(currAttribute->getArrayType(), 
				       currNodeMap.size());
	  const unsigned int numberComponents = 
	    currAttribute->getSize() / geometry->getNumberPoints();
413
414
415
416
          for(std::map<unsigned int, unsigned int>::const_iterator iter =
                currNodeMap.begin();
              iter != currNodeMap.end();
              ++iter) {
417
            createdAttribute->insert(iter->second * numberComponents,
418
                                     currAttribute,
419
420
                                     iter->first * numberComponents,
                                     numberComponents);
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
          }
        }
        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) {
442
    shared_ptr<XdmfSet> currSet = gridToPartition->getSet(i);
443
444
445
446
447
448
449
450
451
452
453
454
    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) {
        std::map<unsigned int, unsigned int> & currNodeMap =
          globalToLocalNodeIdMap[j];
        std::vector<unsigned int> & currElemIds = globalElementIds[j];
        if(currElemIds.size() > 0) {
455
          shared_ptr<XdmfUnstructuredGrid> partitioned =
456
457
            partitionedGrids->getUnstructuredGrid(partitionId);
          partitionId++;
458
459

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

462
463
464
465
466
467
468
469
470
471
472
473
474
          if(currSet->getType() == XdmfSetType::Cell() ||
             currSet->getType() == XdmfSetType::Face() ||
             currSet->getType() == XdmfSetType::Edge()) {
            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);
              }
475
476
            }
          }
477
478
479
480
481
482
483
484
          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);
              }
485
486
            }
          }
487

488
489
490
          if(partitionedSet->getSize() > 0) {

            for(unsigned int k=0; k<currSet->getNumberAttributes(); ++k) {
491
              const shared_ptr<XdmfAttribute> currAttribute =
492
493
494
495
496
497
498
                currSet->getAttribute(k);
              if(currAttribute->getCenter() == XdmfAttributeCenter::Node()) {
                bool releaseAttribute = false;
                if(!currAttribute->isInitialized()) {
                  currAttribute->read();
                  releaseAttribute = true;
                }
499
                const shared_ptr<XdmfAttribute> partitionedAttribute =
500
501
502
503
504
505
506
                  XdmfAttribute::New();
                partitionedAttribute->setCenter(currAttribute->getCenter());
                partitionedAttribute->setName(currAttribute->getName());
                partitionedAttribute->setType(currAttribute->getType());
                partitionedAttribute->initialize(currAttribute->getArrayType(),
                                                 partitionedSetIndex.size());
                for(unsigned int l=0; l<partitionedSetIndex.size(); ++l) {
507
                  partitionedAttribute->insert(l,
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
                                               currAttribute,
                                               partitionedSetIndex[l]);
                }
                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();
            }
526
527
528
          }
        }
      }
529
530
531
      if(releaseSet) {
        currSet->release();
      }
532
533
534
535
    }
  }

  // Add XdmfMap to map boundary nodes between partitions
536
  std::vector<shared_ptr<XdmfAttribute> > globalNodeIds;
537
538
539
  for(unsigned int i=0;
      i<partitionedGrids->getNumberUnstructuredGrids();
      ++i) {
540
    shared_ptr<XdmfAttribute> globalNodeId =
541
      partitionedGrids->getUnstructuredGrid(i)->getAttribute("GlobalNodeId");
542
543
544
545
    if(!globalNodeId->isInitialized()) {
      globalNodeId->read();
    }
    globalNodeIds.push_back(globalNodeId);
546
547
  }

548
  std::vector<shared_ptr<XdmfMap> > maps = XdmfMap::New(globalNodeIds);
549
550
551
  for(unsigned int i=0;
      i<partitionedGrids->getNumberUnstructuredGrids();
      ++i) {
552
    shared_ptr<XdmfMap> map = maps[i];
553
554
    map->setName("Subdomain Boundary");
    partitionedGrids->getUnstructuredGrid(i)->insert(map);
555
556
557
558
559
560
561
562
    if(heavyDataWriter) {
      globalNodeIds[i]->release();
      map->accept(heavyDataWriter);
      map->release();
    }
  }

  return partitionedGrids;
563
564
}

565
566
#else

567
#include <iostream>
568
569
570
571
#include <sstream>
#include "XdmfDomain.hpp"
#include "XdmfGridCollection.hpp"
#include "XdmfHDF5Writer.hpp"
572
#include "XdmfPartitioner.hpp"
573
574
#include "XdmfReader.hpp"
#include "XdmfWriter.hpp"
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
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
namespace {

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

    std::cerr << "usage: " << programName << " "
              << "[-s metis_scheme] "
              << "<input file> <number of partitions> [output file]"
              << std::endl;
    std::cerr << "metis_scheme: 1 - Dual Graph" << std::endl;
    std::cerr << "metis_scheme: 2 - Node Graph" << std::endl;
 
    //
    //
    //
    return;

  }

  //
  // process command line
  //
  void
  processCommandLine(std::string                  & inputFileName,
                     std::string                  & outputFileName,
		     unsigned int                 & numPartitions,
                     XdmfPartitioner::MetisScheme & metisScheme,
		     int                            ac,
                     char                         * av[])
  {

    int c;
    bool errorFlag = false;
    
    while( (c=getopt(ac, av, "s:")) != -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 '?':
      errorFlag = true;
      break;
    }

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

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

    if (optind < ac) {
      outputFileName = av[optind];
      ++optind;
    }
   
    //
    // check errorFlag
    //
    if (errorFlag == true) {
      printUsage(av[0]);
      std::exit(EXIT_FAILURE);
    }

  }

}

666
667
/**
 * XdmfPartitioner is a command line utility for partitioning Xdmf grids.
668
669
 * The XdmfPartitioner uses the metis library to partition Triangular,
 * Quadrilateral, Tetrahedral, and Hexahedral XdmfGridUnstructureds.
670
671
 *
 * Usage:
672
673
 *     XdmfPartitioner <path-of-file-to-partition> <num-partitions>
 *                     (Optional: <path-to-output-file>)
674
675
 *
 */
676
int main(int argc, char* argv[])
677
{
678

679
680
681
682
683
684
685
686
687
688
689
  std::string inputFileName;
  std::string outputFileName = "";
  unsigned int numPartitions;
  XdmfPartitioner::MetisScheme metisScheme;

  processCommandLine(inputFileName,
		     outputFileName,
		     numPartitions,
		     metisScheme,
		     argc,
		     argv);
690

691
692
693
  std::cout << inputFileName << std::endl;

  FILE * refFile = fopen(inputFileName.c_str(), "r");
694
695
696
697
698
699
700
701
702
  if (refFile) {
    // Success
    fclose(refFile);
  }
  else {
    std::cout << "Cannot open file: " << argv[1] << std::endl;
    return 1;
  }

703
704
705
706
707
708
  std::string meshName;
  if(outputFileName.compare("") == 0) {
    meshName = inputFileName;
  }
  else {
    meshName = outputFileName;
709
710
711
  }

  if(meshName.find_last_of("/\\") != std::string::npos) {
712
    meshName = meshName.substr(meshName.find_last_of("/\\") + 1,
713
714
715
716
717
718
719
                               meshName.length());
  }

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

720
721
722
723
  if(outputFileName.compare("") == 0) {
    std::stringstream partitionedMeshName;
    partitionedMeshName << meshName << "_p" << numPartitions;
    meshName = partitionedMeshName.str();
724
725
  }

726
727
  shared_ptr<XdmfReader> reader = XdmfReader::New();
  shared_ptr<XdmfDomain> domain =
728
    shared_dynamic_cast<XdmfDomain>(reader->read(inputFileName));
729
730
731
732
733
734
735
736

  if(domain->getNumberUnstructuredGrids() <= 0) {
    std::cout << "No grids to partition" << std::endl;
    return 1;
  }

  std::stringstream heavyFileName;
  heavyFileName << meshName << ".h5";
737
  shared_ptr<XdmfHDF5Writer> heavyDataWriter =
738
739
    XdmfHDF5Writer::New(heavyFileName.str());

740
741
  shared_ptr<XdmfPartitioner> partitioner = XdmfPartitioner::New();
  shared_ptr<XdmfGridCollection> toWrite =
742
743
    partitioner->partition(domain->getUnstructuredGrid(0),
                           numPartitions,
744
                           metisScheme,
745
746
                           heavyDataWriter);

747
  shared_ptr<XdmfDomain> newDomain = XdmfDomain::New();
748
749
750
751
  newDomain->insert(toWrite);

  std::stringstream xmlFileName;
  xmlFileName << meshName << ".xmf";
752
753
  shared_ptr<XdmfWriter> writer = XdmfWriter::New(xmlFileName.str(),
                                                  heavyDataWriter);
754
755
756
  newDomain->accept(writer);

  std::cout << "Wrote: " << xmlFileName.str() << std::endl;
757
}
758

759
#endif // BUILD_EXE