Zoltan2  Version of the Day
Zoltan2_PartitioningProblem.hpp
Go to the documentation of this file.
1 // @HEADER
2 //
3 // ***********************************************************************
4 //
5 // Zoltan2: A package of combinatorial algorithms for scientific computing
6 // Copyright 2012 Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact Karen Devine (kddevin@sandia.gov)
39 // Erik Boman (egboman@sandia.gov)
40 // Siva Rajamanickam (srajama@sandia.gov)
41 //
42 // ***********************************************************************
43 //
44 // @HEADER
45 
50 #ifndef _ZOLTAN2_PARTITIONINGPROBLEM_HPP_
51 #define _ZOLTAN2_PARTITIONINGPROBLEM_HPP_
52 
53 #include <Zoltan2_Problem.hpp>
57 #include <Zoltan2_GraphModel.hpp>
61 #include <Zoltan2_TaskMapping.hpp>
62 
63 #include <unistd.h>
64 
65 #ifdef HAVE_ZOLTAN2_OVIS
66 #include <ovis.h>
67 #endif
68 
69 namespace Zoltan2{
70 
90 template<typename Adapter>
91 class PartitioningProblem : public Problem<Adapter>
92 {
93 public:
94 
95  typedef typename Adapter::scalar_t scalar_t;
96  typedef typename Adapter::gid_t gid_t;
97  typedef typename Adapter::gno_t gno_t;
98  typedef typename Adapter::lno_t lno_t;
99  typedef typename Adapter::user_t user_t;
100  typedef typename Adapter::base_adapter_t base_adapter_t;
101 
102 #ifdef HAVE_ZOLTAN2_MPI
103  typedef Teuchos::OpaqueWrapper<MPI_Comm> mpiWrapper_t;
104 #endif
105 
109 
110 #ifdef HAVE_ZOLTAN2_MPI
111 
114  PartitioningProblem(Adapter *A, Teuchos::ParameterList *p, MPI_Comm comm);
115 
116 #endif
117 
119  PartitioningProblem(Adapter *A, Teuchos::ParameterList *p) ;
120 
122  //
123  // \param updateInputData If true this indicates that either
124  // this is the first attempt at solution, or that we
125  // are computing a new solution and the input data has
126  // changed since the previous solution was computed.
127  // By input data we mean coordinates, topology, or weights.
128  // If false, this indicates that we are computing a
129  // new solution using the same input data was used for
130  // the previous solution, even though the parameters
131  // may have been changed.
132  //
133  // For the sake of performance, we ask the caller to set \c updateInputData
134  // to false if he/she is computing a new solution using the same input data,
135  // but different problem parameters, than that which was used to compute
136  // the most recent solution.
137 
138  void solve(bool updateInputData=true );
139 
141  //
142  // \return a reference to the solution to the most recent solve().
143 
145  return *(solution_.getRawPtr());
146  };
147 
156  const scalar_t getImbalance(int dim=0) const {
157  scalar_t imb = 0;
158  if (!metrics_.is_null())
159  metrics_->getWeightImbalance(imb, dim);
160 
161  return imb;
162  }
163 
168  ArrayRCP<const MetricValues<scalar_t> > getMetrics() const {
169  if (metrics_.is_null()){
170  ArrayRCP<const MetricValues<scalar_t> > emptyMetrics;
171  return emptyMetrics;
172  }
173  else
174  return metrics_->getMetrics();
175  }
176 
182  void printMetrics(ostream &os) const {
183  if (metrics_.is_null())
184  os << "No metrics available." << endl;
185  else
186  metrics_->printMetrics(os);
187  };
188 
227  void setPartSizes(int len, partId_t *partIds, scalar_t *partSizes,
228  bool makeCopy=true)
229  {
230  setPartSizesForCritiera(0, len, partIds, partSizes, makeCopy);
231  }
232 
267  void setPartSizesForCritiera(int criteria, int len, partId_t *partIds,
268  scalar_t *partSizes, bool makeCopy=true) ;
269 /*
270  void setMachine(MachineRepresentation<typename Adapter::base_adapter_t::scalar_t> *machine);
271 */
274  void resetParameters(ParameterList *params)
275  {
276  Problem<Adapter>::resetParameters(params); // creates new environment
277  if (timer_.getRawPtr() != NULL)
278  this->env_->setTimer(timer_);
279  }
280 
285  const RCP<const Environment> & getEnvironment() const
286  {
287  return this->envConst_;
288  }
289 
290 private:
291  void initializeProblem();
292 
293  void createPartitioningProblem(bool newData);
294 
295  RCP<PartitioningSolution<Adapter> > solution_;
296 
297  RCP<MachineRepresentation <typename Adapter::base_adapter_t::scalar_t> > machine_;
298 
299  RCP<Comm<int> > problemComm_;
300  RCP<const Comm<int> > problemCommConst_;
301 
302 #ifdef HAVE_ZOLTAN2_MPI
303  MPI_Comm mpiComm_;
304 #endif
305 
306  InputAdapterType inputType_;
307  ModelType modelType_;
308  modelFlag_t graphFlags_;
309  modelFlag_t idFlags_;
310  modelFlag_t coordFlags_;
311  std::string algorithm_;
312 
313  int numberOfWeights_;
314 
315  // Suppose Array<partId_t> partIds = partIds_[w]. If partIds.size() > 0
316  // then the user supplied part sizes for weight index "w", and the sizes
317  // corresponding to the Ids in partIds are partSizes[w].
318  //
319  // If numberOfWeights_ >= 0, then there is an Id and Sizes array for
320  // for each weight. Otherwise the user did not supply object weights,
321  // but they can still specify part sizes.
322  // So numberOfCriteria_ is numberOfWeights_ or one, whichever is greater.
323 
324  ArrayRCP<ArrayRCP<partId_t> > partIds_;
325  ArrayRCP<ArrayRCP<scalar_t> > partSizes_;
326  int numberOfCriteria_;
327 
328  // Number of parts to be computed at each level in hierarchical partitioning.
329 
330  ArrayRCP<int> levelNumberParts_;
331  bool hierarchical_;
332 
333  // Create a Timer if the user asked for timing stats.
334 
335  RCP<TimerManager> timer_;
336 
337  // Did the user request metrics?
338 
339  bool metricsRequested_;
340  RCP<const PartitioningSolutionQuality<Adapter> > metrics_;
341 };
343 
344 #ifdef HAVE_ZOLTAN2_MPI
345 template <typename Adapter>
347  ParameterList *p, MPI_Comm comm):
348  Problem<Adapter>(A,p,comm), solution_(),
349  problemComm_(), problemCommConst_(),
350  inputType_(InvalidAdapterType), modelType_(InvalidModel),
351  graphFlags_(), idFlags_(), coordFlags_(), algorithm_(),
352  numberOfWeights_(), partIds_(), partSizes_(),
353  numberOfCriteria_(), levelNumberParts_(), hierarchical_(false),
354  timer_(), metricsRequested_(false), metrics_()
355 {
356 
357  initializeProblem();
358 }
359 #endif
360 /*
361 template <typename Adapter>
362 void PartitioningProblem<Adapter>::setMachine(MachineRepresentation<typename Adapter::base_adapter_t::scalar_t> *machine){
363  this->machine_ = RCP<MachineRepresentation<typename Adapter::base_adapter_t::scalar_t> > (machine, false);
364 }
365 */
366 template <typename Adapter>
368  ParameterList *p):
369  Problem<Adapter>(A,p), solution_(),
370  problemComm_(), problemCommConst_(),
371  inputType_(InvalidAdapterType), modelType_(InvalidModel),
372  graphFlags_(), idFlags_(), coordFlags_(), algorithm_(),
373  numberOfWeights_(),
374  partIds_(), partSizes_(), numberOfCriteria_(),
375  levelNumberParts_(), hierarchical_(false), timer_(),
376  metricsRequested_(false), metrics_()
377 {
378  initializeProblem();
379 }
380 
381 template <typename Adapter>
383 {
384  HELLO;
385 
386  this->env_->debug(DETAILED_STATUS, "PartitioningProblem::initializeProblem");
387 
388  if (getenv("DEBUGME")){
389  std::cout << getpid() << std::endl;
390  sleep(15);
391  }
392 
393 #ifdef HAVE_ZOLTAN2_OVIS
394  ovis_enabled(this->comm_->getRank());
395 #endif
396 
397  // Create a copy of the user's communicator.
398 
399  problemComm_ = this->comm_->duplicate();
400  problemCommConst_ = rcp_const_cast<const Comm<int> > (problemComm_);
401 
402  machine_ = RCP <Zoltan2::MachineRepresentation<typename Adapter::scalar_t> >(new Zoltan2::MachineRepresentation<typename Adapter::scalar_t>(problemComm_));
403 #ifdef HAVE_ZOLTAN2_MPI
404 
405  // TPLs may want an MPI communicator
406 
407  mpiComm_ = Teuchos2MPI(problemComm_);
408 
409 #endif
410 
411  // Number of criteria is number of user supplied weights if non-zero.
412  // Otherwise it is 1 and uniform weight is implied.
413 
414  numberOfWeights_ = this->inputAdapter_->getNumberOfWeightsPerObject();
415 
416  numberOfCriteria_ = (numberOfWeights_ > 1) ? numberOfWeights_ : 1;
417 
418  inputType_ = this->inputAdapter_->inputAdapterType();
419 
420  // The Caller can specify part sizes in setPartSizes(). If he/she
421  // does not, the part size arrays are empty.
422 
423  ArrayRCP<partId_t> *noIds = new ArrayRCP<partId_t> [numberOfCriteria_];
424  ArrayRCP<scalar_t> *noSizes = new ArrayRCP<scalar_t> [numberOfCriteria_];
425 
426  partIds_ = arcp(noIds, 0, numberOfCriteria_, true);
427  partSizes_ = arcp(noSizes, 0, numberOfCriteria_, true);
428 
429  if (this->env_->getDebugLevel() >= DETAILED_STATUS){
430  ostringstream msg;
431  msg << problemComm_->getSize() << " procs,"
432  << numberOfWeights_ << " user-defined weights, "
433  << this->inputAdapter_->inputAdapterName()
434  << " input adapter type.\n";
435  this->env_->debug(DETAILED_STATUS, msg.str());
436  }
437 
438  this->env_->memory("After initializeProblem");
439 }
440 
441 template <typename Adapter>
443  int criteria, int len, partId_t *partIds, scalar_t *partSizes, bool makeCopy)
444 {
445  this->env_->localInputAssertion(__FILE__, __LINE__, "invalid length",
446  len>= 0, BASIC_ASSERTION);
447 
448  this->env_->localInputAssertion(__FILE__, __LINE__, "invalid criteria",
449  criteria >= 0 && criteria < numberOfCriteria_, BASIC_ASSERTION);
450 
451  if (len == 0){
452  partIds_[criteria] = ArrayRCP<partId_t>();
453  partSizes_[criteria] = ArrayRCP<scalar_t>();
454  return;
455  }
456 
457  this->env_->localInputAssertion(__FILE__, __LINE__, "invalid arrays",
458  partIds && partSizes, BASIC_ASSERTION);
459 
460  // The global validity of the partIds and partSizes arrays is performed
461  // by the PartitioningSolution, which computes global part distribution and
462  // part sizes.
463 
464  partId_t *z2_partIds = NULL;
465  scalar_t *z2_partSizes = NULL;
466  bool own_memory = false;
467 
468  if (makeCopy){
469  z2_partIds = new partId_t [len];
470  z2_partSizes = new scalar_t [len];
471  this->env_->localMemoryAssertion(__FILE__, __LINE__, len, z2_partSizes);
472  memcpy(z2_partIds, partIds, len * sizeof(partId_t));
473  memcpy(z2_partSizes, partSizes, len * sizeof(scalar_t));
474  own_memory=true;
475  }
476  else{
477  z2_partIds = partIds;
478  z2_partSizes = partSizes;
479  }
480 
481  partIds_[criteria] = arcp(z2_partIds, 0, len, own_memory);
482  partSizes_[criteria] = arcp(z2_partSizes, 0, len, own_memory);
483 }
484 
485 template <typename Adapter>
486 void PartitioningProblem<Adapter>::solve(bool updateInputData)
487 {
488  HELLO;
489  this->env_->debug(DETAILED_STATUS, "Entering solve");
490 
491  // Create the computational model.
492 
493  this->env_->timerStart(MACRO_TIMERS, "create problem");
494 
495  createPartitioningProblem(updateInputData);
496 
497  this->env_->timerStop(MACRO_TIMERS, "create problem");
498 
499  // TODO: If hierarchical_
500 
501  // Create the solution. The algorithm will query the Solution
502  // for part and weight information. The algorithm will
503  // update the solution with part assignments and quality
504  // metrics. The Solution object itself will convert our internal
505  // global numbers back to application global Ids if needed.
506 
507  RCP<const IdentifierMap<user_t> > idMap =
508  this->baseModel_->getIdentifierMap();
509 
510  PartitioningSolution<Adapter> *soln = NULL;
511 
512  this->env_->timerStart(MACRO_TIMERS, "create solution");
513 
514  try{
515  soln = new PartitioningSolution<Adapter>(
516  this->envConst_, problemCommConst_, idMap, numberOfWeights_,
517  partIds_.view(0, numberOfCriteria_),
518  partSizes_.view(0, numberOfCriteria_));
519  }
521 
522  solution_ = rcp(soln);
523 
524  this->env_->timerStop(MACRO_TIMERS, "create solution");
525 
526  this->env_->memory("After creating Solution");
527 
528  // Call the algorithm
529 
530  try {
531  if (algorithm_ == string("scotch")){
532  AlgPTScotch<Adapter>(this->envConst_, problemComm_,
533 #ifdef HAVE_ZOLTAN2_MPI
534  mpiComm_,
535 #endif
536  this->graphModel_, solution_);
537  }
538  else if (algorithm_ == string("block")){
539  AlgBlock<Adapter>(this->envConst_, problemComm_,
540  this->identifierModel_, solution_);
541  }
542  else if (algorithm_ == string("rcb")){
543  AlgRCB<Adapter>(this->envConst_, problemComm_,
544  this->coordinateModel_, solution_);
545  }
546  else if (algorithm_ == string("multijagged")){
547  AlgPQJagged<Adapter>(this->envConst_, problemComm_,
548  this->coordinateModel_, solution_);
549  }
550  else{
551  throw std::logic_error("partitioning algorithm not supported yet");
552  }
553  }
555 
556  //if mapping is requested
557  {
558 
559  const Teuchos::ParameterEntry *pe = this->envConst_->getParameters().getEntryPtr("mapping_type");
560  int mapping_type = -1;
561  if (pe){
562  mapping_type = pe->getValue(&mapping_type);
563  }
564  //if mapping is 0 -- coordinate mapping
565 
566  if (mapping_type == 0){
567 
568  //partId_t *task_communication_xadj = NULL, *task_communication_adj = NULL;
571  problemComm_.getRawPtr(),
572  machine_.getRawPtr(),
573  this->coordinateModel_.getRawPtr(),
574  solution_.getRawPtr(),
575  this->envConst_.getRawPtr()
576  //,task_communication_xadj,
577  //task_communication_adj
578  );
579  //for now just delete the object.
580  delete ctm;
581  }
582  else if (mapping_type == 1){
583  //if mapping is 1 -- graph mapping
584  }
585  }
586 
587 #ifdef KDDKDD_SHOULD_NEVER_CHANGE_PROBLEMCOMM
588 #ifdef HAVE_ZOLTAN2_MPI
589 
590  // The algorithm may have changed the communicator. Change it back.
591  // KDD: Why would the algorithm change the communicator? TODO
592  // KDD: Should we allow such a side effect? TODO
593 
594  RCP<const mpiWrapper_t > wrappedComm = rcp(new mpiWrapper_t(mpiComm_));
595  problemComm_ = rcp(new Teuchos::MpiComm<int>(wrappedComm));
596  problemCommConst_ = rcp_const_cast<const Comm<int> > (problemComm_);
597 
598 #endif
599 #endif
600 
601  if (metricsRequested_){
602  typedef PartitioningSolution<Adapter> ps_t;
604 
605  psq_t *quality = NULL;
606  RCP<const ps_t> solutionConst = rcp_const_cast<const ps_t>(solution_);
607  RCP<const Adapter> adapter = rcp(this->inputAdapter_, false);
608 
609  try{
610  quality = new psq_t(this->envConst_, problemCommConst_, adapter,
611  solutionConst);
612  }
613  Z2_FORWARD_EXCEPTIONS
614 
615  metrics_ = rcp(quality);
616  }
617 
618  this->env_->debug(DETAILED_STATUS, "Exiting solve");
619 }
620 
621 template <typename Adapter>
623 {
624  HELLO;
625  this->env_->debug(DETAILED_STATUS,
626  "PartitioningProblem::createPartitioningProblem");
627 
628  using std::string;
629  using Teuchos::ParameterList;
630 
631  // A Problem object may be reused. The input data may have changed and
632  // new parameters or part sizes may have been set.
633  //
634  // Save these values in order to determine if we need to create a new model.
635 
636  ModelType previousModel = modelType_;
637  modelFlag_t previousGraphModelFlags = graphFlags_;
638  modelFlag_t previousIdentifierModelFlags = idFlags_;
639  modelFlag_t previousCoordinateModelFlags = coordFlags_;
640 
641  modelType_ = InvalidModel;
642  graphFlags_.reset();
643  idFlags_.reset();
644  coordFlags_.reset();
645 
647  // It's possible at this point that the Problem may want to
648  // add problem parameters to the parameter list in the Environment.
649  //
650  // Since the parameters in the Environment have already been
651  // validated in its constructor, a new Environment must be created:
653  // Teuchos::RCP<const Teuchos::Comm<int> > oldComm = this->env_->comm_;
654  // const ParameterList &oldParams = this->env_->getUnvalidatedParameters();
655  //
656  // ParameterList newParams = oldParams;
657  // newParams.set("new_parameter", "new_value");
658  //
659  // ParameterList &newPartParams = newParams.sublist("partitioning");
660  // newPartParams.set("new_partitioning_parameter", "its_value");
661  //
662  // this->env_ = rcp(new Environment(newParams, oldComm));
664 
665  Environment &env = *(this->env_);
666  ParameterList &pl = env.getParametersNonConst();
667 
668  string defString("default");
669 
670  // Did the user ask for computation of quality metrics?
671 
672  int yesNo=0;
673  const Teuchos::ParameterEntry *pe = pl.getEntryPtr("compute_metrics");
674  if (pe){
675  yesNo = pe->getValue<int>(&yesNo);
676  metricsRequested_ = true;
677  }
678 
679  // Did the user specify a computational model?
680 
681  string model(defString);
682  pe = pl.getEntryPtr("model");
683  if (pe)
684  model = pe->getValue<string>(&model);
685 
686  // Did the user specify an algorithm?
687 
688  string algorithm(defString);
689  pe = pl.getEntryPtr("algorithm");
690  if (pe)
691  algorithm = pe->getValue<string>(&algorithm);
692 
693  // Possible algorithm requirements that must be conveyed to the model:
694 
695  bool needConsecutiveGlobalIds = false;
696  bool removeSelfEdges= false;
697 
699  // Determine algorithm, model, and algorithm requirements. This
700  // is a first pass. Feel free to change this and add to it.
701 
702  if (algorithm != defString){
703  // Figure out the model required by the algorithm
704  if (algorithm == string("block") ||
705  algorithm == string("random") ||
706  algorithm == string("cyclic") ){
707 
708  modelType_ = IdentifierModelType;
709  algorithm_ = algorithm;
710  needConsecutiveGlobalIds = true;
711  }
712  else if (algorithm == string("rcb") ||
713  algorithm == string("rib") ||
714  algorithm == string("multijagged") ||
715  algorithm == string("hsfc")){
716 
717  modelType_ = CoordinateModelType;
718  algorithm_ = algorithm;
719  }
720  else if (algorithm == string("metis") ||
721  algorithm == string("parmetis") ||
722  algorithm == string("scotch") ||
723  algorithm == string("ptscotch")){
724 
725  modelType_ = GraphModelType;
726  algorithm_ = algorithm;
727  removeSelfEdges = true;
728  needConsecutiveGlobalIds = true;
729  }
730  else if (algorithm == string("patoh") ||
731  algorithm == string("phg")){
732 
733  if ((modelType_ != GraphModelType) &&
734  (modelType_ != HypergraphModelType) ){
735  modelType_ = HypergraphModelType;
736  }
737  algorithm_ = algorithm;
738  needConsecutiveGlobalIds = true;
739  }
740  else{
741  // Parameter list should ensure this does not happen.
742  throw std::logic_error("parameter list algorithm is invalid");
743  }
744  }
745  else if (model != defString){
746  // Figure out the algorithm suggested by the model.
747  if (model == string("hypergraph")){
748  modelType_ = HypergraphModelType;
749  if (problemComm_->getSize() > 1)
750  algorithm_ = string("phg");
751  else
752  algorithm_ = string("patoh");
753  needConsecutiveGlobalIds = true;
754  }
755  else if (model == string("graph")){
756  modelType_ = GraphModelType;
757 #ifdef HAVE_ZOLTAN2_SCOTCH
758  if (problemComm_->getSize() > 1)
759  algorithm_ = string("ptscotch");
760  else
761  algorithm_ = string("scotch");
762  removeSelfEdges = true;
763  needConsecutiveGlobalIds = true;
764 #else
765 #ifdef HAVE_ZOLTAN2_PARMETIS
766  if (problemComm_->getSize() > 1)
767  algorithm_ = string("parmetis");
768  else
769  algorithm_ = string("metis");
770  removeSelfEdges = true;
771  needConsecutiveGlobalIds = true;
772 #else
773  if (problemComm_->getSize() > 1)
774  algorithm_ = string("phg");
775  else
776  algorithm_ = string("patoh");
777  removeSelfEdges = true;
778  needConsecutiveGlobalIds = true;
779 #endif
780 #endif
781  }
782  else if (model == string("geometry")){
783  modelType_ = CoordinateModelType;
784  algorithm_ = string("rcb");
785  }
786  else if (model == string("ids")){
787  modelType_ = IdentifierModelType;
788  algorithm_ = string("block");
789  needConsecutiveGlobalIds = true;
790  }
791  else{
792  // Parameter list should ensure this does not happen.
793  env.localBugAssertion(__FILE__, __LINE__,
794  "parameter list model type is invalid", 1, BASIC_ASSERTION);
795  }
796  }
797  else{
798  // Determine an algorithm and model suggested by the input type.
799  // TODO: this is a good time to use the time vs. quality parameter
800  // in choosing an algorithm, and setting some parameters
801 
802  if (inputType_ == MatrixAdapterType){
803  modelType_ = HypergraphModelType;
804  if (problemComm_->getSize() > 1)
805  algorithm_ = string("phg");
806  else
807  algorithm_ = string("patoh");
808  }
809  else if (inputType_ == GraphAdapterType ||
810  inputType_ == MeshAdapterType){
811  modelType_ = GraphModelType;
812  if (problemComm_->getSize() > 1)
813  algorithm_ = string("phg");
814  else
815  algorithm_ = string("patoh");
816  }
817  else if (inputType_ == CoordinateAdapterType){
818  modelType_ = CoordinateModelType;
819  if(algorithm_ != string("multijagged"))
820  algorithm_ = string("rcb");
821  }
822  else if (inputType_ == VectorAdapterType ||
823  inputType_ == IdentifierAdapterType){
824  modelType_ = IdentifierModelType;
825  algorithm_ = string("block");
826  }
827  else{
828  // This should never happen
829  throw std::logic_error("input type is invalid");
830  }
831  }
832 
833  // Hierarchical partitioning?
834 
835  Array<int> valueList;
836  pe = pl.getEntryPtr("topology");
837 
838  if (pe){
839  valueList = pe->getValue<Array<int> >(&valueList);
840 
841  if (!Zoltan2::noValuesAreInRangeList<int>(valueList)){
842  int *n = new int [valueList.size() + 1];
843  levelNumberParts_ = arcp(n, 0, valueList.size() + 1, true);
844  int procsPerNode = 1;
845  for (int i=0; i < valueList.size(); i++){
846  levelNumberParts_[i+1] = valueList[i];
847  procsPerNode *= valueList[i];
848  }
849  // Number of parts in the first level
850  levelNumberParts_[0] = env.numProcs_ / procsPerNode;
851 
852  if (env.numProcs_ % procsPerNode > 0)
853  levelNumberParts_[0]++;
854  }
855  }
856  else{
857  levelNumberParts_.clear();
858  }
859 
860  hierarchical_ = levelNumberParts_.size() > 0;
861 
862  // Object to be partitioned? (rows, columns, etc)
863 
864  string objectOfInterest(defString);
865  pe = pl.getEntryPtr("objects_to_partition");
866  if (pe)
867  objectOfInterest = pe->getValue<string>(&objectOfInterest);
868 
870  // Set model creation flags, if any.
871 
872  if (modelType_ == GraphModelType){
873 
874  // Any parameters in the graph sublist?
875 
876  string symParameter(defString);
877  pe = pl.getEntryPtr("symmetrize_graph");
878  if (pe){
879  symParameter = pe->getValue<string>(&symParameter);
880  if (symParameter == string("transpose"))
881  graphFlags_.set(SYMMETRIZE_INPUT_TRANSPOSE);
882  else if (symParameter == string("bipartite"))
883  graphFlags_.set(SYMMETRIZE_INPUT_BIPARTITE);
884  }
885 
886  int sgParameter = 0;
887  pe = pl.getEntryPtr("subset_graph");
888  if (pe)
889  sgParameter = pe->getValue<int>(&sgParameter);
890 
891  if (sgParameter == 1)
892  graphFlags_.set(GRAPH_IS_A_SUBSET_GRAPH);
893 
894  // Any special behaviors required by the algorithm?
895 
896  if (removeSelfEdges)
897  graphFlags_.set(SELF_EDGES_MUST_BE_REMOVED);
898 
899  if (needConsecutiveGlobalIds)
900  graphFlags_.set(IDS_MUST_BE_GLOBALLY_CONSECUTIVE);
901 
902  // How does user input map to vertices and edges?
903 
904  if (inputType_ == MatrixAdapterType){
905  if (objectOfInterest == defString ||
906  objectOfInterest == string("matrix_rows") )
907  graphFlags_.set(VERTICES_ARE_MATRIX_ROWS);
908  else if (objectOfInterest == string("matrix_columns"))
909  graphFlags_.set(VERTICES_ARE_MATRIX_COLUMNS);
910  else if (objectOfInterest == string("matrix_nonzeros"))
911  graphFlags_.set(VERTICES_ARE_MATRIX_NONZEROS);
912  }
913 
914  else if (inputType_ == MeshAdapterType){
915  if (objectOfInterest == defString ||
916  objectOfInterest == string("mesh_nodes") )
917  graphFlags_.set(VERTICES_ARE_MESH_NODES);
918  else if (objectOfInterest == string("mesh_elements"))
919  graphFlags_.set(VERTICES_ARE_MESH_ELEMENTS);
920  }
921  }
922  else if (modelType_ == IdentifierModelType){
923 
924  // Any special behaviors required by the algorithm?
925 
926  if (needConsecutiveGlobalIds)
927  idFlags_.set(IDS_MUST_BE_GLOBALLY_CONSECUTIVE);
928  }
929  else if (modelType_ == CoordinateModelType){
930 
931  // Any special behaviors required by the algorithm?
932 
933  if (needConsecutiveGlobalIds)
934  coordFlags_.set(IDS_MUST_BE_GLOBALLY_CONSECUTIVE);
935  }
936 
937 
938  if ( newData ||
939  (modelType_ != previousModel) ||
940  (graphFlags_ != previousGraphModelFlags) ||
941  (coordFlags_ != previousCoordinateModelFlags) ||
942  (idFlags_ != previousIdentifierModelFlags) ) {
943 
944  // Create the computational model.
945  // Models are instantiated for base input adapter types (mesh,
946  // matrix, graph, and so on). We pass a pointer to the input
947  // adapter, cast as the base input type.
948 
949  //KDD Not sure why this shadow declaration is needed
950  //KDD Comment out for now; revisit later if problems.
951  //KDD const Teuchos::ParameterList pl = this->envConst_->getParameters();
952  //bool exceptionThrow = true;
953 
954  switch (modelType_) {
955 
956  case GraphModelType:
957  this->graphModel_ = rcp(new GraphModel<base_adapter_t>(
958  this->baseInputAdapter_, this->envConst_, problemComm_, graphFlags_));
959 
960  this->baseModel_ = rcp_implicit_cast<const Model<base_adapter_t> >(
961  this->graphModel_);
962 
963  break;
964 
965  case HypergraphModelType:
966  break;
967 
968  case CoordinateModelType:
970  this->baseInputAdapter_, this->envConst_, problemComm_, coordFlags_));
971 
973  // It's possible at this point that the Problem may want to
974  // add problem parameters to the parameter list in the Environment.
975  //
976  // Since the parameters in the Environment have already been
977  // validated in its constructor, a new Environment must be created:
979  // Teuchos::RCP<const Teuchos::Comm<int> > oldComm = this->env_->comm_;
980  // const ParameterList &oldParams = this->env_->getUnvalidatedParameters();
981  //
982  // ParameterList newParams = oldParams;
983  // newParams.set("new_parameter", "new_value");
984  //
985  // ParameterList &newPartParams = newParams.sublist("partitioning");
986  // newPartParams.set("new_partitioning_parameter", "its_value");
987  //
988  // this->env_ = rcp(new Environment(newParams, oldComm));
990 /*
991  if(algorithm == string("multijagged")){
992 
993  //int coordinateCnt = this->coordinateModel_->getCoordinateDim();
994  //cout << coordinateCnt << " " << pl.getPtr<Array <int> >("pqParts")->size() << endl;
995  //exceptionThrow = coordinateCnt == pl.getPtr<Array <int> >("pqParts")->size();
996  int arraySize = pl.getPtr<Array <int> >("pqParts")->size() - 1;
997  exceptionThrow = arraySize > 0;
998  this->envConst_->localInputAssertion(__FILE__, __LINE__, "invalid length of cut lines. Size of cut lines should be at least 1.",
999  exceptionThrow, BASIC_ASSERTION);
1000 
1001 
1002  int totalPartCount = 1;
1003  for(int i = 0; i < arraySize; ++i){
1004  //cout << pl.getPtr<Array <int> >("pqParts")->getRawPtr()[i] << " ";
1005  totalPartCount *= pl.getPtr<Array <int> >("pqParts")->getRawPtr()[i];
1006 // TODO: Using pointer in parameter list. Ross says, "Bad." Can't print it.
1007  }
1008  Teuchos::ParameterList newParams = pl;
1009 // TODO: KDD I thought we got rid of sublists in the parameter list??
1010  Teuchos::ParameterList &parParams = newParams.sublist("partitioning");
1011 
1012 // TODO: KDD Is there a more elegant solution here than changing the paramlist?
1013 // TODO: How does this even work? Where is newParams used?
1014 
1015  parParams.set("num_global_parts", totalPartCount);
1016 
1017 
1018  //cout << endl;
1019  Teuchos::RCP<const Teuchos::Comm<int> > oldComm = this->envConst_->comm_;
1020 
1021  //this->envConst_ = rcp(new Environment(newParams, oldComm));
1022 
1023 
1024  }
1025 */
1026 
1027  this->baseModel_ = rcp_implicit_cast<const Model<base_adapter_t> >(
1028  this->coordinateModel_);
1029  break;
1030 
1031  case IdentifierModelType:
1033  this->baseInputAdapter_, this->envConst_, problemComm_, idFlags_));
1034 
1035  this->baseModel_ = rcp_implicit_cast<const Model<base_adapter_t> >(
1036  this->identifierModel_);
1037  break;
1038 
1039  default:
1040  cout << __func__ << " Invalid model" << modelType_ << endl;
1041  break;
1042  }
1043 
1044  this->env_->memory("After creating Model");
1045  }
1046 
1047  /*
1048  Teuchos::RCP<const Teuchos::Comm<int> > oldComm = this->env_->comm_;
1049  const ParameterList &oldParams = this->env_->getUnvalidatedParameters();
1050 
1051  ParameterList newParams = oldParams;
1052  int totalPartCount = 1;
1053  const int *partNo = pl.getPtr<Array <int> >("pqParts")->getRawPtr();
1054 
1055  for (int i = 0; i < coordDim; ++i){
1056  totalPartCount *= partNo[i];
1057  }
1058  newParams.set("num_global_parts", totalPartCount);
1059 
1060 
1061  this->env_ = rcp(new Environment(newParams, oldComm));
1062 */
1063 }
1064 
1065 } // namespace Zoltan2
1066 #endif
use columns as graph vertices
RCP< GraphModel< base_adapter_t > > graphModel_
#define HELLO
ArrayRCP< const MetricValues< scalar_t > > getMetrics() const
Get the array of metrics Metrics were only computed if user requested metrics with a parameter...
Time an algorithm (or other entity) as a whole.
use mesh nodes as vertices
ModelType
An identifier for the general type of model.
fast typical checks for valid arguments
#define Z2_FORWARD_EXCEPTIONS
Forward an exception back through call stack.
base_adapter_t * baseInputAdapter_
std::bitset< NUM_MODEL_FLAGS > modelFlag_t
algorithm requires consecutive ids
model must symmetrize input
model must symmetrize input
zoltan2_partId_t partId_t
RCP< const Comm< int > > comm_
void resetParameters(ParameterList *params)
Reset the list of parameters.
Defines the PartitioningSolution class.
Zoltan2::BasicUserTypes< scalar_t, gno_t, lno_t, gno_t > user_t
sub-steps, each method&#39;s entry and exit
const RCP< const Environment > & getEnvironment() const
Get the current Environment. Useful for testing.
void resetParameters(ParameterList *params)
Reset the list of parameters.
RCP< IdentifierModel< base_adapter_t > > identifierModel_
int numProcs_
number of processes (relative to comm_)
InputAdapterType
An enum to identify general types of input adapters.
use matrix rows as graph vertices
This class provides geometric coordinates with optional weights to the Zoltan2 algorithm.
Teuchos::ParameterList & getParametersNonConst()
Returns a reference to a non-const copy of the parameters.
A class that computes and returns quality metrics.
Defines the IdentifierModel interface.
A PartitioningSolution is a solution to a partitioning problem.
use nonzeros as graph vertices
Defines the PartitioningSolutionQuality class.
void localBugAssertion(const char *file, int lineNum, const char *msg, bool ok, AssertionLevel level) const
Test for valid library behavior on local process only.
Problem base class from which other classes (PartitioningProblem, ColoringProblem, OrderingProblem, MatchingProblem, etc.) derive.
Defines the Problem base class.
RCP< CoordinateModel< base_adapter_t > > coordinateModel_
The user parameters, debug, timing and memory profiling output objects, and error checking methods...
MachineRepresentation Class Finds the coordinate of the processor. Used to find the processor coordin...
void printMetrics(ostream &os) const
Print the array of metrics.
double scalar_t
Define IntegerRangeList validator.
const PartitioningSolution< Adapter > & getSolution()
Get the solution to the problem.
PartitioningProblem sets up partitioning problems for the user.
use mesh elements as vertices
GraphModel defines the interface required for graph models.
RCP< Environment > env_
PartitioningProblem(Adapter *A, Teuchos::ParameterList *p)
Constructor where communicator is the Teuchos default.
The base class for all model classes.
algorithm requires no self edges
IdentifierModel defines the interface for all identifier models.
void setPartSizes(int len, partId_t *partIds, scalar_t *partSizes, bool makeCopy=true)
Set or reset relative sizes for the partitions that Zoltan2 will create.
Defines the GraphModel interface.
RCP< const Model< base_adapter_t > > baseModel_
void setPartSizesForCritiera(int criteria, int len, partId_t *partIds, scalar_t *partSizes, bool makeCopy=true)
Set or reset the relative sizes (per weight) for the partitions that Zoltan2 will create...
plain identifier input, just a list of Ids
void solve(bool updateInputData=true)
Direct the problem to create a solution.
RCP< const Environment > envConst_
ignore invalid neighbors
const scalar_t getImbalance(int dim=0) const
Returns the imbalance of the solution.