Zoltan2  Version of the Day
Zoltan2_TaskMapping.hpp
Go to the documentation of this file.
1 #ifndef _ZOLTAN2_COORD_PARTITIONMAPPING_HPP_
2 #define _ZOLTAN2_COORD_PARTITIONMAPPING_HPP_
3 
4 #include <fstream>
5 #include <ctime>
6 #include <vector>
8 #include "Teuchos_ArrayViewDecl.hpp"
11 #include "Teuchos_ReductionOp.hpp"
12 
13 #define gnuPlot
14 
15 namespace Teuchos{
16 
19 template <typename Ordinal, typename T>
20 class Zoltan2_ReduceBestMapping : public ValueTypeReductionOp<Ordinal,T>
21 {
22 private:
23  T _EPSILON;
24 
25 public:
28  Zoltan2_ReduceBestMapping ():_EPSILON (std::numeric_limits<T>::epsilon()){}
29 
32  void reduce( const Ordinal count, const T inBuffer[], T inoutBuffer[]) const
33  {
34 
35  for (Ordinal i=0; i < count; i++){
36  if (inBuffer[0] - inoutBuffer[0] < -_EPSILON){
37  inoutBuffer[0] = inBuffer[0];
38  inoutBuffer[1] = inBuffer[1];
39  } else if(
40  inBuffer[0] - inoutBuffer[0] < _EPSILON &&
41  inBuffer[1] - inoutBuffer[1] < _EPSILON){
42  inoutBuffer[0] = inBuffer[0];
43  inoutBuffer[1] = inBuffer[1];
44  }
45  }
46  }
47 };
48 } // namespace Teuchos
49 
50 
51 namespace Zoltan2{
52 
53 
54 
55 template <typename it>
56 inline it z2Fact(it x) {
57  return (x == 1 ? x : x * z2Fact<it>(x - 1));
58 }
59 
60 template <typename gno_t, typename partId_t>
62 public:
65 };
66 
67 //returns the ith permutation indices.
68 template <typename IT>
69 void ithPermutation(const IT n, IT i, IT *perm)
70 {
71  IT j, k = 0;
72  IT *fact = new IT[n];
73 
74 
75  // compute factorial numbers
76  fact[k] = 1;
77  while (++k < n)
78  fact[k] = fact[k - 1] * k;
79 
80  // compute factorial code
81  for (k = 0; k < n; ++k)
82  {
83  perm[k] = i / fact[n - 1 - k];
84  i = i % fact[n - 1 - k];
85  }
86 
87  // readjust values to obtain the permutation
88  // start from the end and check if preceding values are lower
89  for (k = n - 1; k > 0; --k)
90  for (j = k - 1; j >= 0; --j)
91  if (perm[j] <= perm[k])
92  perm[k]++;
93 
94  delete [] fact;
95 }
96 
97 template <typename partId_t>
98 void getGridCommunicationGraph(partId_t taskCount, partId_t *&task_comm_xadj, partId_t *&task_comm_adj, vector <int> grid_dims){
99  int dim = grid_dims.size();
100  int neighborCount = 2 * dim;
101  task_comm_xadj = allocMemory< partId_t>(taskCount);
102  task_comm_adj = allocMemory <partId_t>(taskCount * neighborCount);
103 
104  partId_t neighBorIndex = 0;
105  for (partId_t i = 0; i < taskCount; ++i){
106  partId_t prevDimMul = 1;
107  for (int j = 0; j < dim; ++j){
108  partId_t lNeighbor = i - prevDimMul;
109  partId_t rNeighbor = i + prevDimMul;
110  prevDimMul *= grid_dims[j];
111  if (lNeighbor >= 0 && lNeighbor/ prevDimMul == i / prevDimMul && lNeighbor < taskCount){
112  task_comm_adj[neighBorIndex++] = lNeighbor;
113  }
114  if (rNeighbor >= 0 && rNeighbor/ prevDimMul == i / prevDimMul && rNeighbor < taskCount){
115  task_comm_adj[neighBorIndex++] = rNeighbor;
116  }
117  }
118  task_comm_xadj[i] = neighBorIndex;
119  }
120 
121 }
122 //returns the center of the parts.
123 template <typename Adapter, typename scalar_t, typename partId_t>
125  const Environment *envConst,
126  const Teuchos::Comm<int> *comm,
129  int coordDim,
130  partId_t ntasks,
131  scalar_t **partCenters){
132 
133  typedef typename Adapter::lno_t lno_t;
134  typedef typename Adapter::gno_t gno_t;
135 
137  ArrayView<const gno_t> gnos;
138  ArrayView<input_t> xyz;
139  ArrayView<input_t> wgts;
140  coords->getCoordinates(gnos, xyz, wgts);
141 
142  //local and global num coordinates.
143  lno_t numLocalCoords = coords->getLocalNumCoordinates();
144  //gno_t numGlobalCoords = coords->getGlobalNumCoordinates();
145 
146 
147 
148  //local number of points in each part.
149  gno_t *point_counts = allocMemory<gno_t>(ntasks);
150  memset(point_counts, 0, sizeof(gno_t) * ntasks);
151 
152  //global number of points in each part.
153  gno_t *global_point_counts = allocMemory<gno_t>(ntasks);
154 
155 
156  scalar_t **pqJagged_coordinates = allocMemory<scalar_t *>(coordDim);
157 
158  for (int dim=0; dim < coordDim; dim++){
159  ArrayRCP<const scalar_t> ar;
160  xyz[dim].getInputArray(ar);
161  //pqJagged coordinate values assignment
162  pqJagged_coordinates[dim] = (scalar_t *)ar.getRawPtr();
163  memset(partCenters[dim], 0, sizeof(scalar_t) * ntasks);
164  }
165 
166  //get parts with parallel gnos.
167  const partId_t *parts = soln_->getPartList();
168  const gno_t *soln_gnos = soln_->getIdList();
169 /*
170  for (lno_t i=0; i < numLocalCoords; i++){
171  cout << "me:" << comm->getRank() << " gno:" << soln_gnos[i] << " tmp.part :" << parts[i]<< endl;
172  }
173  */
174 
175 
176  envConst->timerStart(MACRO_TIMERS, "Mapping - Hashing Creation");
177  //hash vector
178  vector< vector <GNO_LNO_PAIR<gno_t, partId_t> > > hash(numLocalCoords);
179 
180  //insert each point in solution to hash.
181  for (lno_t i=0; i < numLocalCoords; i++){
183  tmp.gno = soln_gnos[i];
184  tmp.part = parts[i];
185  //cout << "gno:" << tmp.gno << " tmp.part :" << tmp.part << endl;
186  //count the local number of points in each part.
187  ++point_counts[tmp.part];
188  lno_t hash_index = tmp.gno % numLocalCoords;
189  hash[hash_index].push_back(tmp);
190  }
191 
192  envConst->timerStop(MACRO_TIMERS, "Mapping - Hashing Creation");
193  //get global number of points in each part.
194  reduceAll<int, gno_t>(*comm, Teuchos::REDUCE_SUM,
195  ntasks, point_counts, global_point_counts
196  );
197 
198 
199 
200  envConst->timerStart(MACRO_TIMERS, "Mapping - Hashing Search");
201  //add up all coordinates in each part.
202  for (lno_t i=0; i < numLocalCoords; i++){
203  gno_t g = gnos[i];
204  lno_t hash_index = g % numLocalCoords;
205  lno_t hash_size = hash[hash_index].size();
206  partId_t p = -1;
207  for (int j =0; j < hash_size; ++j){
208  if (hash[hash_index][j].gno == g){
209  p = hash[hash_index][j].part;
210  break;
211  }
212  }
213  if(p == -1) {
214  cerr << "ERROR AT HASHING FOR GNO:"<< g << " LNO:" << i << endl;
215  }
216  //add uo all coordinates in each part.
217  for(int j = 0; j < coordDim; ++j){
218  scalar_t c = pqJagged_coordinates[j][i];
219  partCenters[j][p] += c;
220  }
221  }
222  envConst->timerStop(MACRO_TIMERS, "Mapping - Hashing Search");
223 
224  for(int j = 0; j < coordDim; ++j){
225  for (partId_t i=0; i < ntasks; ++i){
226  partCenters[j][i] /= global_point_counts[i];
227  }
228  }
229 
230  scalar_t *tmpCoords = allocMemory<scalar_t>(ntasks);
231  for(int j = 0; j < coordDim; ++j){
232  reduceAll<int, scalar_t>(*comm, Teuchos::REDUCE_SUM,
233  ntasks, partCenters[j], tmpCoords
234  );
235 
236  scalar_t *tmp = partCenters[j];
237  partCenters[j] = tmpCoords;
238  tmpCoords = tmp;
239  }
240 
241  freeArray<gno_t> (point_counts);
242  freeArray<gno_t> (global_point_counts);
243 
244  freeArray<scalar_t> (tmpCoords);
245  freeArray<scalar_t *>(pqJagged_coordinates);
246 }
247 
248 
251 template <class IT, class WT>
253  IT heapSize;
254  IT *indices;
255  WT *values;
256  WT _EPSILON;
257 
258 
259 public:
260  void setHeapsize(IT heapsize_){
261  this->heapSize = heapsize_;
262  this->indices = allocMemory<IT>(heapsize_ );
263  this->values = allocMemory<WT>(heapsize_ );
264  this->_EPSILON = numeric_limits<WT>::epsilon();
265  }
266 
268  freeArray<IT>(this->indices);
269  freeArray<WT>(this->values);
270  }
271 
272 
273  void addPoint(IT index, WT distance){
274  WT maxVal = this->values[0];
275  //add only the distance is smaller than the maximum distance.
276  //cout << "indeX:" << index << "distance:" <<distance << " maxVal:" << maxVal << endl;
277  if (distance >= maxVal) return;
278  else {
279  this->values[0] = distance;
280  this->indices[0] = index;
281  this->push_down(0);
282  }
283  }
284 
285  //heap push down operation
286  void push_down(IT index_on_heap){
287  IT child_index1 = 2 * index_on_heap + 1;
288  IT child_index2 = 2 * index_on_heap + 2;
289 
290  IT biggerIndex = -1;
291  if(child_index1 < this->heapSize && child_index2 < this->heapSize){
292 
293  if (this->values[child_index1] < this->values[child_index2]){
294  biggerIndex = child_index2;
295  }
296  else {
297  biggerIndex = child_index1;
298  }
299  }
300  else if(child_index1 < this->heapSize){
301  biggerIndex = child_index1;
302 
303  }
304  else if(child_index2 < this->heapSize){
305  biggerIndex = child_index2;
306  }
307  if (biggerIndex >= 0 && this->values[biggerIndex] > this->values[index_on_heap]){
308  WT tmpVal = this->values[biggerIndex];
309  this->values[biggerIndex] = this->values[index_on_heap];
310  this->values[index_on_heap] = tmpVal;
311 
312  IT tmpIndex = this->indices[biggerIndex];
313  this->indices[biggerIndex] = this->indices[index_on_heap];
314  this->indices[index_on_heap] = tmpIndex;
315  this->push_down(biggerIndex);
316  }
317  }
318 
319  void initValues(){
320  WT MAXVAL = numeric_limits<WT>::max();
321  for(IT i = 0; i < this->heapSize; ++i){
322  this->values[i] = MAXVAL;
323  this->indices[i] = -1;
324  }
325  }
326 
327  //returns the total distance to center in the cluster.
329 
330  WT nc = 0;
331  for(IT j = 0; j < this->heapSize; ++j){
332  nc += this->values[j];
333 
334  //cout << "index:" << this->indices[j] << " distance:" << this->values[j] << endl;
335  }
336  return nc;
337  }
338 
339  //returns the new center of the cluster.
340  bool getNewCenters(WT *center, WT **coords, int dimension){
341  bool moved = false;
342  for(int i = 0; i < dimension; ++i){
343  WT nc = 0;
344  for(IT j = 0; j < this->heapSize; ++j){
345  IT k = this->indices[j];
346  //cout << "i:" << i << " dim:" << dimension << " k:" << k << " heapSize:" << heapSize << endl;
347  nc += coords[i][k];
348  }
349  nc /= this->heapSize;
350  moved = (ABS(center[i] - nc) > this->_EPSILON || moved );
351  center[i] = nc;
352 
353  }
354  return moved;
355  }
356 
357  void copyCoordinates(IT *permutation){
358  for(IT i = 0; i < this->heapSize; ++i){
359  permutation[i] = this->indices[i];
360  }
361  }
362 };
363 
366 template <class IT, class WT>
368 
369  int dimension;
370  KmeansHeap<IT,WT> closestPoints;
371 
372 public:
373  WT *center;
375  freeArray<WT>(center);
376  }
377 
378  void setParams(int dimension_, int heapsize){
379  this->dimension = dimension_;
380  this->center = allocMemory<WT>(dimension_);
381  this->closestPoints.setHeapsize(heapsize);
382  }
383 
384  void clearHeap(){
385  this->closestPoints.initValues();
386  }
387 
388  bool getNewCenters( WT **coords){
389  return this->closestPoints.getNewCenters(center, coords, dimension);
390  }
391 
392  //returns the distance of the coordinate to the center.
393  //also adds it to the heap.
394  WT getDistance(IT index, WT **elementCoords){
395  WT distance = 0;
396  for (int i = 0; i < this->dimension; ++i){
397  WT d = (center[i] - elementCoords[i][index]);
398  distance += d * d;
399  }
400  distance = pow(distance, WT(1.0 / this->dimension));
401  closestPoints.addPoint(index, distance);
402  return distance;
403  }
404 
406  return closestPoints.getTotalDistance();
407  }
408 
409  void copyCoordinates(IT *permutation){
410  closestPoints.copyCoordinates(permutation);
411  }
412 };
413 
417 template <class IT, class WT>
419 
420  int dim;
421  IT numElements;
422  WT **elementCoords;
423  IT numClusters;
424  IT required_elements;
425  KMeansCluster <IT,WT> *clusters;
426  WT *maxCoordinates;
427  WT *minCoordinates;
428 public:
430  freeArray<KMeansCluster <IT,WT> >(clusters);
431  freeArray<WT>(maxCoordinates);
432  freeArray<WT>(minCoordinates);
433  }
434 
438  int dim_ ,
439  IT numElements_,
440  WT **elementCoords_,
441  IT required_elements_):
442  dim(dim_),
443  numElements(numElements_),
444  elementCoords(elementCoords_),
445  numClusters ((1 << dim_) + 1),
446  required_elements(required_elements_)
447  {
448  this->clusters = allocMemory<KMeansCluster <IT,WT> >(this->numClusters);
449  //set dimension and the number of required elements for all clusters.
450  for (int i = 0; i < numClusters; ++i){
451  this->clusters[i].setParams(this->dim, this->required_elements);
452  }
453 
454  this->maxCoordinates = allocMemory <WT> (this->dim);
455  this->minCoordinates = allocMemory <WT> (this->dim);
456 
457  //obtain the min and max coordiantes for each dimension.
458  for (int j = 0; j < dim; ++j){
459  this->minCoordinates[j] = this->maxCoordinates[j] = this->elementCoords[j][0];
460  for(IT i = 1; i < numElements; ++i){
461  WT t = this->elementCoords[j][i];
462  if(t > this->maxCoordinates[j]){
463  this->maxCoordinates[j] = t;
464  }
465  if (t < minCoordinates[j]){
466  this->minCoordinates[j] = t;
467  }
468  }
469  }
470 
471 
472  //assign initial cluster centers.
473  for (int j = 0; j < dim; ++j){
474  int mod = (1 << (j+1));
475  for (int i = 0; i < numClusters - 1; ++i){
476  WT c = 0;
477  if ( (i % mod) < mod / 2){
478  c = this->maxCoordinates[j];
479  //cout << "i:" << i << " j:" << j << " setting max:" << c << endl;
480  }
481  else {
482  c = this->minCoordinates[j];
483  }
484  this->clusters[i].center[j] = c;
485  }
486  }
487 
488  //last cluster center is placed to middle.
489  for (int j = 0; j < dim; ++j){
490  this->clusters[numClusters - 1].center[j] = (this->maxCoordinates[j] + this->minCoordinates[j]) / 2;
491  }
492 
493 
494  /*
495  for (int i = 0; i < numClusters; ++i){
496  //cout << endl << "cluster:" << i << endl << "\t";
497  for (int j = 0; j < dim; ++j){
498  cout << this->clusters[i].center[j] << " ";
499  }
500  }
501  */
502  }
503 
504  //performs kmeans clustering of coordinates.
505  void kmeans(){
506  for(int it = 0; it < 10; ++it){
507  //cout << "it:" << it << endl;
508  for (IT j = 0; j < this->numClusters; ++j){
509  this->clusters[j].clearHeap();
510  }
511  for (IT i = 0; i < this->numElements; ++i){
512  //cout << "i:" << i << " numEl:" << this->numElements << endl;
513  for (IT j = 0; j < this->numClusters; ++j){
514  //cout << "j:" << j << " numClusters:" << this->numClusters << endl;
515  this->clusters[j].getDistance(i,this->elementCoords);
516  }
517  }
518  bool moved = false;
519  for (IT j = 0; j < this->numClusters; ++j){
520  moved =(this->clusters[j].getNewCenters(this->elementCoords) || moved );
521  }
522  if (!moved){
523  break;
524  }
525  }
526 
527 
528  }
529 
530  //finds the cluster in which the coordinates are the closest to each other.
531  void getMinDistanceCluster(IT *procPermutation){
532 
533  WT minDistance = this->clusters[0].getDistanceToCenter();
534  IT minCluster = 0;
535  //cout << "j:" << 0 << " minDistance:" << minDistance << " minTmpDistance:" << minDistance<< " minCluster:" << minCluster << endl;
536  for (IT j = 1; j < this->numClusters; ++j){
537  WT minTmpDistance = this->clusters[j].getDistanceToCenter();
538  //cout << "j:" << j << " minDistance:" << minDistance << " minTmpDistance:" << minTmpDistance<< " minCluster:" << minCluster << endl;
539  if(minTmpDistance < minDistance){
540  minDistance = minTmpDistance;
541  minCluster = j;
542  }
543  }
544 
545  //cout << "minCluster:" << minCluster << endl;
546  this->clusters[minCluster].copyCoordinates(procPermutation);
547  }
548 };
549 
550 
551 
552 #define MINOF(a,b) (((a)<(b))?(a):(b))
553 
560 template <typename T>
561 void fillContinousArray(T *arr, size_t arrSize, T *val){
562  if(val == NULL){
563 
564 #ifdef HAVE_ZOLTAN2_OMP
565 #pragma omp parallel for
566 #endif
567  for(size_t i = 0; i < arrSize; ++i){
568  arr[i] = i;
569  }
570 
571  }
572  else {
573  T v = *val;
574 #ifdef HAVE_ZOLTAN2_OMP
575 #pragma omp parallel for
576 #endif
577  for(size_t i = 0; i < arrSize; ++i){
578  //cout << "writing to i:" << i << " arr:" << arrSize << endl;
579  arr[i] = v;
580  }
581  }
582 }
583 
586 template <typename procId_t>
588 protected:
589  double commCost;
590 public:
591 
592  procId_t no_procs; //the number of processors
593  procId_t no_tasks; //the number of taks.
595  CommunicationModel(procId_t no_procs_, procId_t no_tasks_):
596  commCost(),
597  no_procs(no_procs_),
598  no_tasks(no_tasks_){}
600  procId_t getNProcs() const{
601  return this->no_procs;
602  }
603  procId_t getNTasks()const{
604  return this->no_tasks;
605  }
606 
608  procId_t *task_to_proc,
609  procId_t *task_communication_xadj,
610  procId_t *task_communication_adj){
611 
612  double totalCost = 0;
613 
614  procId_t commCount = 0;
615  for (procId_t task = 0; task < this->no_tasks; ++task){
616  int assigned_proc = task_to_proc[task];
617  procId_t task_adj_begin = 0;
618  procId_t task_adj_end = task_communication_xadj[task];
619  if (task > 0) task_adj_begin = task_communication_xadj[task - 1];
620 
621  commCount += task_adj_end - task_adj_begin;
622  //cout << "task:" << task << " proc:" << assigned_proc << endl;
623  for (procId_t task2 = task_adj_begin; task2 < task_adj_end; ++task2){
624  procId_t neighborTask = task_communication_adj[task2];
625  //cout << "neighborTask :" << neighborTask << endl;
626  int neighborProc = task_to_proc[neighborTask];
627  double distance = getProcDistance(assigned_proc, neighborProc);
628  //cout << "assigned_proc:" << assigned_proc << " neighborProc:" << neighborProc << " d:" << distance << endl;
629 
630  totalCost += distance ;
631  }
632  }
633 
634  this->commCost = totalCost/ commCount;
635  }
636 
638  return this->commCost;
639  }
640 
641  virtual double getProcDistance(int procId1, int procId2) const = 0;
642 
649  virtual void getMapping(
650  int myRank,
651  RCP<const Environment> env,
652  ArrayRCP <procId_t> &proc_to_task_xadj, // = allocMemory<procId_t> (this->no_procs); //holds the pointer to the task array
653  ArrayRCP <procId_t> &proc_to_task_adj, // = allocMemory<procId_t>(this->no_tasks); //holds the indices of tasks wrt to proc_to_task_xadj array.
654  ArrayRCP <procId_t> &task_to_proc //allocMemory<procId_t>(this->no_tasks); //holds the processors mapped to tasks.
655  ) const = 0;
656 };
660 template <typename pcoord_t, typename tcoord_t, typename procId_t>
662 public:
663  //private:
664  int proc_coord_dim; //dimension of the processors
665  pcoord_t **proc_coords; //the processor coordinates. allocated outside of the class.
666  int task_coord_dim; //dimension of the tasks coordinates.
667  tcoord_t **task_coords; //the task coordinates allocated outside of the class.
668 
669 
670  //public:
672  CommunicationModel<procId_t>(),
673  proc_coord_dim(0),
674  proc_coords(0),
675  task_coord_dim(0),
676  task_coords(0){}
677 
679 
689  int pcoord_dim_,
690  pcoord_t **pcoords_,
691  int tcoord_dim_,
692  tcoord_t **tcoords_,
693  procId_t no_procs_,
694  procId_t no_tasks_
695  ):
696  CommunicationModel<procId_t>(no_procs_, no_tasks_),
697  proc_coord_dim(pcoord_dim_), proc_coords(pcoords_),
698  task_coord_dim(tcoord_dim_), task_coords(tcoords_){
699  }
700 
701 
702 
709  void getClosestSubset(procId_t *proc_permutation, procId_t nprocs, procId_t ntasks) const{
710  //currently returns a random subset.
711 
712  procId_t minCoordDim = MINOF(this->task_coord_dim, this->proc_coord_dim);
714  minCoordDim, nprocs,
715  this->proc_coords, ntasks);
716 
717  kma.kmeans();
718  kma.getMinDistanceCluster(proc_permutation);
719 
720  for(int i = ntasks; i < nprocs; ++i){
721  proc_permutation[i] = -1;
722  }
723  /*
724  //fill array.
725  fillContinousArray<procId_t>(proc_permutation, nprocs, NULL);
726  int _u_umpa_seed = 847449649;
727  srand (time(NULL));
728  int a = rand() % 1000 + 1;
729  _u_umpa_seed -= a;
730  //permute array randomly.
731  update_visit_order(proc_permutation, nprocs,_u_umpa_seed, 1);
732  */
733  }
734 
735  //temporary, necessary for random permutation.
736  static procId_t umpa_uRandom(procId_t l, int &_u_umpa_seed)
737  {
738  int a = 16807;
739  int m = 2147483647;
740  int q = 127773;
741  int r = 2836;
742  int lo, hi, test;
743  double d;
744 
745  lo = _u_umpa_seed % q;
746  hi = _u_umpa_seed / q;
747  test = (a*lo)-(r*hi);
748  if (test>0)
749  _u_umpa_seed = test;
750  else
751  _u_umpa_seed = test + m;
752  d = (double) ((double) _u_umpa_seed / (double) m);
753  return (procId_t) (d*(double)l);
754  }
755 
756  virtual double getProcDistance(int procId1, int procId2) const{
757  double distance = 0;
758  for (int i = 0 ; i < this->proc_coord_dim; ++i){
759  distance += ABS(proc_coords[i][procId1] - proc_coords[i][procId2]);
760  }
761  return distance;
762  }
763 
764 
765  //temporary, does random permutation.
766  void update_visit_order(procId_t* visitOrder, procId_t n, int &_u_umpa_seed, procId_t rndm) {
767  procId_t *a = visitOrder;
768 
769 
770  if (rndm){
771  procId_t i, u, v, tmp;
772 
773  if (n <= 4)
774  return;
775 
776  //srand ( time(NULL) );
777 
778  //_u_umpa_seed = _u_umpa_seed1 - (rand()%100);
779  for (i=0; i<n; i+=16)
780  {
781  u = umpa_uRandom(n-4, _u_umpa_seed);
782  v = umpa_uRandom(n-4, _u_umpa_seed);
783  SWAP(a[v], a[u], tmp);
784  SWAP(a[v+1], a[u+1], tmp);
785  SWAP(a[v+2], a[u+2], tmp);
786  SWAP(a[v+3], a[u+3], tmp);
787  }
788  }
789  else {
790  procId_t i, end = n / 4;
791 
792  for (i=1; i<end; i++)
793  {
794  procId_t j=umpa_uRandom(n-i, _u_umpa_seed);
795  procId_t t=a[j];
796  a[j] = a[n-i];
797  a[n-i] = t;
798  }
799  }
800  //PermuteInPlace(visitOrder, n);
801  }
802 
803 
810  virtual void getMapping(
811  int myRank,
812  RCP<const Environment> env,
813  ArrayRCP <procId_t> &rcp_proc_to_task_xadj, // = allocMemory<procId_t> (this->no_procs); //holds the pointer to the task array
814  ArrayRCP <procId_t> &rcp_proc_to_task_adj, // = allocMemory<procId_t>(this->no_tasks); //holds the indices of tasks wrt to proc_to_task_xadj array.
815  ArrayRCP <procId_t> &rcp_task_to_proc //allocMemory<procId_t>(this->no_tasks); //holds the processors mapped to tasks.
816  ) const{
817 
818  rcp_proc_to_task_xadj = ArrayRCP <procId_t> (this->no_procs);
819  rcp_proc_to_task_adj = ArrayRCP <procId_t> (this->no_tasks);
820  rcp_task_to_proc = ArrayRCP <procId_t> (this->no_tasks);
821 
822  procId_t *proc_to_task_xadj = rcp_proc_to_task_xadj.getRawPtr(); //holds the pointer to the task array
823  procId_t *proc_to_task_adj = rcp_proc_to_task_adj.getRawPtr(); //holds the indices of tasks wrt to proc_to_task_xadj array.
824  procId_t *task_to_proc = rcp_task_to_proc.getRawPtr(); //holds the processors mapped to tasks.);
825 
826 
827  procId_t invalid = 0;
828  fillContinousArray<procId_t> (proc_to_task_xadj, this->no_procs, &invalid);
829 
830  //obtain the number of parts that should be divided.
831  procId_t num_parts = MINOF(this->no_procs, this->no_tasks);
832  //obtain the min coordinate dim.
833  procId_t minCoordDim = MINOF(this->task_coord_dim, this->proc_coord_dim);
834 
835  int taskPerm = z2Fact<int>(this->task_coord_dim); //get the number of different permutations for task dimension ordering
836  int procPerm = z2Fact<int>(this->proc_coord_dim); //get the number of different permutations for proc dimension ordering
837  int permutations = taskPerm * procPerm; //total number of permutations
838 
839  //holds the pointers to proc_adjList
840  procId_t *proc_xadj = allocMemory<procId_t> (num_parts);
841  //holds the processors in parts according to the result of partitioning algorithm.
842  //the processors assigned to part x is at proc_adjList[ proc_xadj[x - 1] : proc_xadj[x] ]
843  procId_t *proc_adjList = allocMemory<procId_t>(this->no_procs);
844 
845 
846  procId_t used_num_procs = this->no_procs;
847  if(this->no_procs > this->no_tasks){
848  //obtain the subset of the processors that are closest to each other.
849  this->getClosestSubset(proc_adjList, this->no_procs, this->no_tasks);
850  used_num_procs = this->no_tasks;
851  }
852  else {
853  fillContinousArray<procId_t>(proc_adjList,this->no_procs, NULL);
854  }
855 
856  int myPermutation = myRank % permutations; //the index of the permutation
857 
858  int myProcPerm= myPermutation % procPerm; // the index of the proc permutation
859  int myTaskPerm = myPermutation / procPerm; // the index of the task permutation
860 
861  int *permutation = allocMemory<int> (taskPerm);
862 
863  //get the permutation order from the proc permutation index.
864  ithPermutation<int>(this->proc_coord_dim, myProcPerm, permutation);
865  //reorder the coordinate dimensions.
866  pcoord_t **pcoords = allocMemory<pcoord_t *> (this->proc_coord_dim);
867  for(int i = 0; i < this->proc_coord_dim; ++i){
868  pcoords[i] = this->proc_coords[permutation[i]];
869  //cout << permutation[i] << " ";
870  }
871 
872  //do the partitioning and renumber the parts.
873  env->timerStart(MACRO_TIMERS, "Mapping - Proc Partitioning");
874  sequentialTaskPartitioning<pcoord_t, procId_t, procId_t>(
875  env,
876  this->no_procs,
877  used_num_procs,
878  num_parts,
879  minCoordDim,
880  pcoords,//this->proc_coords,
881  proc_adjList,
882  proc_xadj
883  //,"proc_partitioning"
884  );
885  env->timerStop(MACRO_TIMERS, "Mapping - Proc Partitioning");
886  freeArray<pcoord_t *> (pcoords);
887 
888 
889  procId_t *task_xadj = allocMemory<procId_t> (num_parts);
890  procId_t *task_adjList = allocMemory<procId_t>(this->no_tasks);
891  //fill task_adjList st: task_adjList[i] <- i.
892  fillContinousArray<procId_t>(task_adjList,this->no_tasks, NULL);
893 
894  //get the permutation order from the task permutation index.
895  ithPermutation<int>(this->task_coord_dim, myTaskPerm, permutation);
896 
897  //reorder task coordinate dimensions.
898  tcoord_t **tcoords = allocMemory<tcoord_t *> (this->task_coord_dim);
899  for(int i = 0; i < this->task_coord_dim; ++i){
900  tcoords[i] = this->task_coords[permutation[i]];
901  }
902 
903  env->timerStart(MACRO_TIMERS, "Mapping - Task Partitioning");
904  //partitioning of tasks
905  sequentialTaskPartitioning<tcoord_t, procId_t, procId_t>(
906  env,
907  this->no_tasks,
908  this->no_tasks,
909  num_parts,
910  minCoordDim,
911  tcoords, //this->task_coords,
912  task_adjList,
913  task_xadj
914  //,"task_partitioning"
915  );
916  env->timerStop(MACRO_TIMERS, "Mapping - Task Partitioning");
917  freeArray<pcoord_t *> (tcoords);
918  freeArray<int> (permutation);
919 
920 
921  //filling proc_to_task_xadj, proc_to_task_adj, task_to_proc arrays.
922  for(procId_t i = 0; i < num_parts; ++i){
923 
924  procId_t proc_index_begin = 0;
925  procId_t task_begin_index = 0;
926 
927  if (i > 0) {
928  proc_index_begin = proc_xadj[i - 1];
929  task_begin_index = task_xadj[i - 1];
930  }
931  procId_t proc_index_end = proc_xadj[i];
932  procId_t task_end_index = task_xadj[i];
933 
934 
935  if(proc_index_end - proc_index_begin != 1){
936  cerr << "Error at partitioning of processors" << endl;
937  cerr << "PART:" << i << " is assigned to " << proc_index_end - proc_index_begin << " processors." << std::endl;
938  exit(1);
939  }
940  procId_t assigned_proc = proc_adjList[proc_index_begin];
941  proc_to_task_xadj[assigned_proc] = task_end_index - task_begin_index;
942  }
943 
944 
945  //holds the pointer to the task array
946  procId_t *proc_to_task_xadj_work = allocMemory<procId_t> (this->no_procs);
947  proc_to_task_xadj_work[0] = proc_to_task_xadj[0];
948  for(procId_t i = 1; i < this->no_procs; ++i){
949  proc_to_task_xadj[i] += proc_to_task_xadj[i - 1];
950  proc_to_task_xadj_work[i] = proc_to_task_xadj[i];
951  }
952 
953  for(procId_t i = 0; i < num_parts; ++i){
954 
955  procId_t proc_index_begin = 0;
956  procId_t task_begin_index = 0;
957 
958  if (i > 0) {
959  proc_index_begin = proc_xadj[i - 1];
960  task_begin_index = task_xadj[i - 1];
961  }
962  procId_t task_end_index = task_xadj[i];
963 
964  procId_t assigned_proc = proc_adjList[proc_index_begin];
965 
966  for (procId_t j = task_begin_index; j < task_end_index; ++j){
967  procId_t taskId = task_adjList[j];
968 
969  task_to_proc[taskId] = assigned_proc;
970 
971  proc_to_task_adj [ --proc_to_task_xadj_work[assigned_proc] ] = taskId;
972  }
973  }
974 
975  freeArray<procId_t>(proc_to_task_xadj_work);
976  freeArray<procId_t>(task_xadj);
977  freeArray<procId_t>(task_adjList);
978  freeArray<procId_t>(proc_xadj);
979  freeArray<procId_t>(proc_adjList);
980  }
981 
982 };
983 
984 template <typename Adapter, typename procId_t>
986 protected:
987 
988 #ifndef DOXYGEN_SHOULD_SKIP_THIS
989 
990  typedef typename Adapter::scalar_t pcoord_t;
991  typedef typename Adapter::scalar_t tcoord_t;
992 
993 #endif
994 
995  //RCP<const Environment> env;
996  ArrayRCP<procId_t> proc_to_task_xadj; // = allocMemory<procId_t> (this->no_procs); //holds the pointer to the task array
997  ArrayRCP<procId_t> proc_to_task_adj; // = allocMemory<procId_t>(this->no_tasks); //holds the indices of tasks wrt to proc_to_task_xadj array.
998  ArrayRCP<procId_t> task_to_proc; //allocMemory<procId_t>(this->no_procs); //holds the processors mapped to tasks.
1001  procId_t nprocs;
1002  procId_t ntasks;
1003  ArrayRCP<procId_t>task_communication_xadj;
1004  ArrayRCP<procId_t>task_communication_adj;
1005 
1006 
1007 public:
1008 
1010  //freeArray<procId_t> (proc_to_task_xadj);
1011  //freeArray<procId_t> (proc_to_task_adj);
1012  //freeArray<procId_t> (task_to_proc);
1013  if(this->isOwnerofModel){
1014  delete this->proc_task_comm;
1015  }
1016  }
1028  const Teuchos::Comm<int> *comm_,
1029  const MachineRepresentation<pcoord_t> *machine_,
1032  const Environment *envConst
1033  ): PartitionMapping<Adapter> (comm_, machine_, model_, soln_, envConst),
1034  proc_to_task_xadj(0),
1035  proc_to_task_adj(0),
1036  task_to_proc(0),
1037  isOwnerofModel(true),
1038  proc_task_comm(0),
1041 
1042 
1043  //if mapping type is 0 then it is coordinate mapping
1044  int procDim = machine_->getProcDim();
1045  this->nprocs = machine_->getNumProcs();
1046  //get processor coordinates.
1047  pcoord_t **procCoordinates = machine_->getProcCoords();
1048 
1049  int coordDim = ((Zoltan2::CoordinateModel<typename Adapter::base_adapter_t> *)model_)->getCoordinateDim();
1050  this->ntasks = soln_->getActualGlobalNumberOfParts();
1051  if (procId_t (soln_->getTargetGlobalNumberOfParts()) > this->ntasks){
1052  this->ntasks = soln_->getTargetGlobalNumberOfParts();
1053  }
1054  //cout << "actual: " << this->ntasks << endl;
1055 
1056  //alloc memory for part centers.
1057  tcoord_t **partCenters = NULL;
1058  partCenters = allocMemory<tcoord_t *>(coordDim);
1059  for (int i = 0; i < coordDim; ++i){
1060  partCenters[i] = allocMemory<tcoord_t>(this->ntasks);
1061  }
1062 
1063 
1064  envConst->timerStart(MACRO_TIMERS, "Mapping - Solution Center");
1065  //get centers for the parts.
1066  getSolutionCenterCoordinates<Adapter, typename Adapter::scalar_t,procId_t>(
1067  envConst,
1068  comm_,
1070  this->soln,
1071  coordDim,
1072  ntasks,
1073  partCenters);
1074 
1075  envConst->timerStop(MACRO_TIMERS, "Mapping - Solution Center");
1076 
1077 
1078  //create coordinate communication model.
1079  this->proc_task_comm =
1081  procDim,
1082  procCoordinates,
1083  coordDim,
1084  partCenters,
1085  this->nprocs,
1086  this->ntasks
1087  );
1088 
1089  int myRank = comm_->getRank();
1090 
1091 
1092  envConst->timerStart(MACRO_TIMERS, "Mapping - Processor Task map");
1093  this->doMapping(myRank);
1094  envConst->timerStop(MACRO_TIMERS, "Mapping - Processor Task map");
1095 
1096 
1097  envConst->timerStart(MACRO_TIMERS, "Mapping - Communication Graph");
1098  ((Zoltan2::PartitioningSolution<Adapter> *)soln_)->getCommunicationGraph(
1099  comm_,
1102  );
1103 
1104 
1105 
1106  envConst->timerStop(MACRO_TIMERS, "Mapping - Communication Graph");
1107 #ifdef gnuPlot
1108  if (comm_->getRank() == 0){
1109 
1110  procId_t taskCommCount = task_communication_xadj.size();
1111  std::cout << " TotalComm:" << task_communication_xadj[taskCommCount - 1] << std::endl;
1112  procId_t maxN = task_communication_xadj[0];
1113  for (procId_t i = 1; i < taskCommCount; ++i){
1114  procId_t nc = task_communication_xadj[i] - task_communication_xadj[i - 1];
1115  if (maxN < nc) maxN = nc;
1116  }
1117  std::cout << " maxNeighbor:" << maxN << std::endl;
1118  }
1119 
1120  this->writeGnuPlot(comm_, soln_, coordDim, partCenters);
1121  /*
1122  std::string file = "gggnuPlot";
1123  std::string exten = ".plot";
1124  ofstream mm("2d.txt");
1125  file += toString<int>(comm_->getRank()) + exten;
1126  std::ofstream ff(file.c_str());
1127  //ff.seekg (0, ff.end);
1128  RCP < vector <Zoltan2::coordinateModelPartBox <scalar_t, partId_t> > > outPartBoxes = ((Zoltan2::PartitioningSolution<Adapter> *)soln_)->getPartBoxes();
1129 
1130  for (partId_t i = 0; i < this->ntasks;++i){
1131  (*outPartBoxes)[i].writeGnuPlot(ff, mm);
1132  }
1133  if (coordDim == 2){
1134  ff << "plot \"2d.txt\"" << endl;
1135  //ff << "\n pause -1" << endl;
1136  }
1137  else {
1138  ff << "splot \"2d.txt\"" << endl;
1139  //ff << "\n pause -1" << endl;
1140  }
1141  mm.close();
1142 
1143  ff << "set style arrow 5 nohead size screen 0.03,15,135 ls 1" << endl;
1144  for (partId_t i = 0; i < this->ntasks;++i){
1145  procId_t pb = 0;
1146  if (i > 0) pb = task_communication_xadj[i -1];
1147  procId_t pe = task_communication_xadj[i];
1148  for (procId_t p = pb; p < pe; ++p){
1149  procId_t n = task_communication_adj[p];
1150 
1151  //cout << "i:" << i << " n:" << n << endl;
1152  std::string arrowline = "set arrow from ";
1153  for (int j = 0; j < coordDim - 1; ++j){
1154  arrowline += toString<scalar_t>(partCenters[j][n]) + ",";
1155  }
1156  arrowline += toString<scalar_t>(partCenters[coordDim -1][n]) + " to ";
1157 
1158 
1159  for (int j = 0; j < coordDim - 1; ++j){
1160  arrowline += toString<scalar_t>(partCenters[j][i]) + ",";
1161  }
1162  arrowline += toString<scalar_t>(partCenters[coordDim -1][i]) + " as 5\n";
1163 
1164  //cout << "arrow:" << arrowline << endl;
1165  ff << arrowline;
1166  }
1167  }
1168 
1169  ff << "replot\n pause -1" << endl;
1170  ff.close();
1171  */
1172 #endif
1173 
1174  envConst->timerStart(MACRO_TIMERS, "Mapping - Communication Cost");
1175  this->proc_task_comm->calculateCommunicationCost(
1176  task_to_proc.getRawPtr(),
1177  task_communication_xadj.getRawPtr(),
1178  task_communication_adj.getRawPtr()
1179  );
1180 
1181  envConst->timerStop(MACRO_TIMERS, "Mapping - Communication Cost");
1182 
1183  //cout << "me: " << comm_->getRank() << " cost:" << this->proc_task_comm->getCommunicationCostMetric() << endl;
1184  //processors are divided into groups of size numProc! * numTasks!
1185  //each processor in the group obtains a mapping with a different rotation
1186  //and best one is broadcasted all processors.
1187  this->getBestMapping();
1188 #ifdef gnuPlot
1189  this->writeMapping2(comm_->getRank());
1190 #endif
1191 
1192  for (int i = 0; i < coordDim; ++i){
1193  freeArray<tcoord_t>(partCenters[i]);
1194  }
1195  freeArray<tcoord_t *>(partCenters);
1196 
1197  }
1198 
1210  const Teuchos::Comm<int> *comm_,
1211  const MachineRepresentation<pcoord_t> *machine_,
1214  const Environment *envConst_,
1215  ArrayRCP<procId_t>task_communication_xadj_,
1216  ArrayRCP<procId_t>task_communication_adj_
1217  ): PartitionMapping<Adapter> (comm_, machine_, model_, soln_, envConst_),
1218  proc_to_task_xadj(0),
1219  proc_to_task_adj(0),
1220  task_to_proc(0),
1221  isOwnerofModel(true),
1222  proc_task_comm(0),
1223  task_communication_xadj(task_communication_xadj_),
1224  task_communication_adj(task_communication_adj_){
1225 
1226  //if mapping type is 0 then it is coordinate mapping
1227  int procDim = machine_->getProcDim();
1228  this->nprocs = machine_->getNumProcs();
1229  //get processor coordinates.
1230  pcoord_t **procCoordinates = machine_->getProcCoords();
1231 
1232  int coordDim = ((Zoltan2::CoordinateModel<typename Adapter::base_adapter_t> *)model_)->getCoordinateDim();
1233  this->ntasks = soln_->getActualGlobalNumberOfParts();
1234  //cout << "actual: " << this->ntasks << endl;
1235 
1236  //alloc memory for part centers.
1237  tcoord_t **partCenters = NULL;
1238  partCenters = allocMemory<tcoord_t *>(coordDim);
1239  for (int i = 0; i < coordDim; ++i){
1240  partCenters[i] = allocMemory<tcoord_t>(this->ntasks);
1241  }
1242  //get centers for the parts.
1243  getSolutionCenterCoordinates<Adapter, typename Adapter::scalar_t,procId_t>(
1244  envConst_,
1245  comm_,
1247  this->soln,
1248  coordDim,
1249  ntasks,
1250  partCenters);
1251 
1252  //create coordinate communication model.
1253  this->proc_task_comm =
1255  procDim,
1256  procCoordinates,
1257  coordDim,
1258  partCenters,
1259  this->nprocs,
1260  this->ntasks
1261  );
1262 
1263  int myRank = comm_->getRank();
1264  this->doMapping(myRank);
1265  this->proc_task_comm->calculateCommunicationCost(
1266  task_to_proc.getRawPtr(),
1267  task_communication_xadj.getRawPtr(),
1268  task_communication_adj.getRawPtr()
1269  );
1270 
1271  //cout << "me: " << comm_->getRank() << " cost:" << this->proc_task_comm->getCommunicationCostMetric() << endl;
1272 
1273  //processors are divided into groups of size numProc! * numTasks!
1274  //each processor in the group obtains a mapping with a different rotation
1275  //and best one is broadcasted all processors.
1276  this->getBestMapping();
1277 #ifdef gnuPlot
1278  this->writeMapping2(comm_->getRank());
1279 #endif
1280 
1281  for (int i = 0; i < coordDim; ++i){
1282  freeArray<tcoord_t>(partCenters[i]);
1283  }
1284  freeArray<tcoord_t *>(partCenters);
1285  }
1286 
1292  const Environment *env_,
1294  ):PartitionMapping<Adapter>(env_),
1295  proc_to_task_xadj(0),
1296  proc_to_task_adj(0),
1297  task_to_proc(0),
1298  isOwnerofModel(false),
1299  proc_task_comm(proc_task_comm_),
1300  nprocs(proc_task_comm_->getNProcs()),
1301  ntasks(proc_task_comm_->getNTasks()),
1304  this->doMapping(0);
1305  }
1306 
1312  const Environment *env_,
1313  const Teuchos::Comm<int> *comm_,
1314  const MachineRepresentation<pcoord_t> *machine_,
1315  int taskDim,
1316  procId_t taskCount,
1317  tcoord_t **taskCoords
1318  ):PartitionMapping<Adapter>(env_, comm_, machine_),
1319  proc_to_task_xadj(0),
1320  proc_to_task_adj(0),
1321  task_to_proc(0),
1322  isOwnerofModel(true),
1323  proc_task_comm(0),
1324  nprocs(comm_->getSize()),
1325  ntasks(taskCount),
1328 
1330  machine_->getProcDim(),
1331  machine_->getProcCoords(),
1332  taskDim, taskCoords,
1333  this->nprocs, taskCount
1334  );
1335  this->doMapping(comm_->getRank());
1336  }
1337 
1338 
1341  void doMapping(int myRank){
1342 
1343  if(this->proc_task_comm){
1344  this->proc_task_comm->getMapping(
1345  myRank,
1346  Teuchos::RCP<const Environment>(this->env, false),
1347  this->proc_to_task_xadj, // = allocMemory<procId_t> (this->no_procs); //holds the pointer to the task array
1348  this->proc_to_task_adj, // = allocMemory<procId_t>(this->no_tasks); //holds the indices of tasks wrt to proc_to_task_xadj array.
1349  this->task_to_proc //allocMemory<procId_t>(this->no_procs); //holds the processors mapped to tasks.);
1350  );
1351  }
1352  else {
1353  std::cerr << "communicationModel is not specified in the Mapper" << endl;
1354  exit(1);
1355  }
1356  }
1357 
1359  return this->proc_task_comm->getCommCost();
1360  }
1361 
1364  virtual size_t getLocalNumberOfParts() const{
1365  return 0;
1366  }
1367 
1368 
1371  RCP<Comm<int> > create_subCommunicatior(){
1372  int procDim = this->proc_task_comm->proc_coord_dim;
1373  int taskDim = this->proc_task_comm->task_coord_dim;
1374 
1375  int taskPerm = z2Fact<int>(procDim); //get the number of different permutations for task dimension ordering
1376  int procPerm = z2Fact<int>(taskDim); //get the number of different permutations for proc dimension ordering
1377  int idealGroupSize = taskPerm * procPerm; //total number of permutations
1378 
1379  int myRank = this->comm->getRank();
1380  int commSize = this->comm->getSize();
1381 
1382  int myGroupIndex = myRank / idealGroupSize;
1383 
1384  int prevGroupBegin = (myGroupIndex - 1)* idealGroupSize;
1385  if (prevGroupBegin < 0) prevGroupBegin = 0;
1386  int myGroupBegin = myGroupIndex * idealGroupSize;
1387  int myGroupEnd = (myGroupIndex + 1) * idealGroupSize;
1388  int nextGroupEnd = (myGroupIndex + 2)* idealGroupSize;
1389 
1390  if (myGroupEnd > commSize){
1391  myGroupBegin = prevGroupBegin;
1392  myGroupEnd = commSize;
1393  }
1394  if (nextGroupEnd > commSize){
1395  myGroupEnd = commSize;
1396  }
1397  int myGroupSize = myGroupEnd - myGroupBegin;
1398 
1399  int *myGroup = allocMemory<int>(myGroupSize);
1400  for (int i = 0; i < myGroupSize; ++i){
1401  myGroup[i] = myGroupBegin + i;
1402  }
1403  //cout << "me:" << myRank << " myGroupBegin:" << myGroupBegin << " myGroupEnd:" << myGroupEnd << endl;
1404 
1405  ArrayView<const partId_t> myGroupView(myGroup, myGroupSize);
1406 
1407  RCP<Comm<int> > subComm = this->comm->createSubcommunicator(myGroupView);
1408  freeArray<int>(myGroup);
1409  return subComm;
1410  }
1411 
1412 
1416  //create the sub group.
1417  RCP<Comm<int> > subComm = this->create_subCommunicatior();
1418  //calculate cost.
1419  double myCost = this->proc_task_comm->getCommunicationCostMetric();
1420  double localCost[2], globalCost[2];
1421 
1422  localCost[0] = myCost;
1423  localCost[1] = double(subComm->getRank());
1424 
1425  globalCost[1] = globalCost[0] = std::numeric_limits<double>::max();
1427  reduceAll<int, double>(*subComm, reduceBest,
1428  2, localCost, globalCost
1429  );
1430 
1431  int sender = int(globalCost[1]);
1432 
1433  //cout << "me:" << localCost[1] << " localcost:" << localCost[0]<< " bestcost:" << globalCost[0] << endl;
1434  //cout << "me:" << localCost[1] << " proc:" << globalCost[1] << endl;
1435  broadcast (*subComm, sender, this->ntasks, this->task_to_proc.getRawPtr());
1436  broadcast (*subComm, sender, this->nprocs, this->proc_to_task_xadj.getRawPtr());
1437  broadcast (*subComm, sender, this->ntasks, this->proc_to_task_adj.getRawPtr());
1438  }
1439 
1446  virtual void getProcsForPart(partId_t taskId, int &numProcs, int *procs) const{
1447  numProcs = 1;
1448  procs = this->task_to_proc.getRawPtr() + taskId;
1449  }
1453  inline procId_t getAssignedProcForTask(procId_t taskId){
1454  return this->task_to_proc[taskId];
1455  }
1462  virtual void getPartsForProc(int procId, partId_t &numParts, partId_t *parts) const{
1463 
1464  procId_t task_begin = 0;
1465  if (procId > 0) task_begin = this->proc_to_task_xadj[procId - 1];
1466  procId_t taskend = this->proc_to_task_xadj[procId];
1467  parts = this->proc_to_task_adj.getRawPtr() + task_begin;
1468  numParts = taskend - task_begin;
1469  }
1470 
1471  ArrayView<procId_t> getAssignedTaksForProc(procId_t procId){
1472  procId_t task_begin = 0;
1473  if (procId > 0) task_begin = this->proc_to_task_xadj[procId - 1];
1474  procId_t taskend = this->proc_to_task_xadj[procId];
1475 
1476  /*
1477  cout << "procId_t:" << procId << " taskCount:" << taskend - task_begin << endl;
1478  for(procId_t i = task_begin; i < taskend; ++i){
1479  cout << "procId_t:" << procId << " task:" << proc_to_task_adj[i] << endl;
1480  }
1481  */
1482  if (taskend - task_begin > 0){
1483  ArrayView <procId_t> assignedParts(this->proc_to_task_adj.getRawPtr() + task_begin, taskend - task_begin);
1484  return assignedParts;
1485  }
1486  else {
1487  ArrayView <procId_t> assignedParts;
1488  return assignedParts;
1489  }
1490  }
1491 
1492  //write mapping to gnuPlot code to visualize.
1494  std::ofstream gnuPlotCode ("gnuPlot.plot", std::ofstream::out);
1495 
1496  int mindim = MINOF(proc_task_comm->proc_coord_dim, proc_task_comm->task_coord_dim);
1497  string ss = "";
1498  for(procId_t i = 0; i < this->nprocs; ++i){
1499 
1500  std::string procFile = toString<int>(i) + "_mapping.txt";
1501  if (i == 0){
1502  gnuPlotCode << "plot \"" << procFile << "\"\n";
1503  }
1504  else {
1505  gnuPlotCode << "replot \"" << procFile << "\"\n";
1506  }
1507 
1508  std::ofstream inpFile (procFile.c_str(), std::ofstream::out);
1509 
1510  string gnuPlotArrow = "set arrow from ";
1511  for(int j = 0; j < mindim; ++j){
1512  if (j == mindim - 1){
1513  inpFile << proc_task_comm->proc_coords[j][i];
1514  gnuPlotArrow += toString<float>(proc_task_comm->proc_coords[j][i]);
1515 
1516  }
1517  else {
1518  inpFile << proc_task_comm->proc_coords[j][i] << " ";
1519  gnuPlotArrow += toString<float>(proc_task_comm->proc_coords[j][i]) +",";
1520  }
1521  }
1522  gnuPlotArrow += " to ";
1523 
1524 
1525  inpFile << std::endl;
1526  ArrayView<procId_t> a = this->getAssignedTaksForProc(i);
1527  for(int k = 0; k < a.size(); ++k){
1528  int j = a[k];
1529  //cout << "i:" << i << " j:"
1530  string gnuPlotArrow2 = gnuPlotArrow;
1531  for(int z = 0; z < mindim; ++z){
1532  if(z == mindim - 1){
1533 
1534  //cout << "z:" << z << " j:" << j << " " << proc_task_comm->task_coords[z][j] << endl;
1535  inpFile << proc_task_comm->task_coords[z][j];
1536  gnuPlotArrow2 += toString<float>(proc_task_comm->task_coords[z][j]);
1537  }
1538  else{
1539  inpFile << proc_task_comm->task_coords[z][j] << " ";
1540  gnuPlotArrow2 += toString<float>(proc_task_comm->task_coords[z][j]) +",";
1541  }
1542  }
1543  ss += gnuPlotArrow2 + "\n";
1544  inpFile << std::endl;
1545  }
1546  inpFile.close();
1547 
1548  }
1549  gnuPlotCode << ss;
1550  gnuPlotCode << "\nreplot\n pause -1 \n";
1551  gnuPlotCode.close();
1552 
1553  }
1554 
1555 
1556  //write mapping to gnuPlot code to visualize.
1557  void writeMapping2(int myRank){
1558 
1559  std::string rankStr = toString<int>(myRank);
1560  std::string gnuPlots = "gnuPlot", extentionS = ".plot";
1561  std::string outF = gnuPlots + rankStr+ extentionS;
1562  std::ofstream gnuPlotCode ( outF.c_str(), std::ofstream::out);
1563 
1566  int mindim = MINOF(tmpproc_task_comm->proc_coord_dim, tmpproc_task_comm->task_coord_dim);
1567  string ss = "";
1568  string procs = "", parts = "";
1569  for(procId_t i = 0; i < this->nprocs; ++i){
1570 
1571  //inpFile << std::endl;
1572  ArrayView<procId_t> a = this->getAssignedTaksForProc(i);
1573  if (a.size() == 0){
1574  continue;
1575  }
1576 
1577  //std::ofstream inpFile (procFile.c_str(), std::ofstream::out);
1578 
1579  string gnuPlotArrow = "set arrow from ";
1580  for(int j = 0; j < mindim; ++j){
1581  if (j == mindim - 1){
1582  //inpFile << proc_task_comm->proc_coords[j][i];
1583  gnuPlotArrow += toString<float>(tmpproc_task_comm->proc_coords[j][i]);
1584  procs += toString<float>(tmpproc_task_comm->proc_coords[j][i]);
1585 
1586  }
1587  else {
1588  //inpFile << proc_task_comm->proc_coords[j][i] << " ";
1589  gnuPlotArrow += toString<float>(tmpproc_task_comm->proc_coords[j][i]) +",";
1590  procs += toString<float>(tmpproc_task_comm->proc_coords[j][i])+ " ";
1591  }
1592  }
1593  procs += "\n";
1594 
1595  gnuPlotArrow += " to ";
1596 
1597 
1598  for(int k = 0; k < a.size(); ++k){
1599  int j = a[k];
1600  //cout << "i:" << i << " j:"
1601  string gnuPlotArrow2 = gnuPlotArrow;
1602  for(int z = 0; z < mindim; ++z){
1603  if(z == mindim - 1){
1604 
1605  //cout << "z:" << z << " j:" << j << " " << proc_task_comm->task_coords[z][j] << endl;
1606  //inpFile << proc_task_comm->task_coords[z][j];
1607  gnuPlotArrow2 += toString<float>(tmpproc_task_comm->task_coords[z][j]);
1608  parts += toString<float>(tmpproc_task_comm->task_coords[z][j]);
1609  }
1610  else{
1611  //inpFile << proc_task_comm->task_coords[z][j] << " ";
1612  gnuPlotArrow2 += toString<float>(tmpproc_task_comm->task_coords[z][j]) +",";
1613  parts += toString<float>(tmpproc_task_comm->task_coords[z][j]) + " ";
1614  }
1615  }
1616  parts += "\n";
1617  ss += gnuPlotArrow2 + " nohead\n";
1618  //inpFile << std::endl;
1619  }
1620  //inpFile.close();
1621 
1622  }
1623 
1624 
1625  std::ofstream procFile ("procPlot.plot", std::ofstream::out);
1626  procFile << procs << "\n";
1627  procFile.close();
1628 
1629  std::ofstream partFile ("partPlot.plot", std::ofstream::out);
1630  partFile << parts<< "\n";
1631  partFile.close();
1632 
1633  std::ofstream extraProcFile ("allProc.plot", std::ofstream::out);
1634 
1635  for(procId_t j = 0; j < this->nprocs; ++j){
1636  for(int i = 0; i < mindim; ++i){
1637  extraProcFile << tmpproc_task_comm->proc_coords[i][j] << " ";
1638  }
1639  extraProcFile << endl;
1640  }
1641 
1642  extraProcFile.close();
1643 
1644  gnuPlotCode << ss;
1645  if(mindim == 2){
1646  gnuPlotCode << "plot \"procPlot.plot\" with points pointsize 3\n";
1647  } else {
1648  gnuPlotCode << "splot \"procPlot.plot\" with points pointsize 3\n";
1649  }
1650  gnuPlotCode << "replot \"partPlot.plot\" with points pointsize 3\n";
1651  gnuPlotCode << "replot \"allProc.plot\" with points pointsize 0.65\n";
1652  gnuPlotCode << "\nreplot\n pause -1 \n";
1653  gnuPlotCode.close();
1654 
1655  }
1656 
1657 
1659  const Teuchos::Comm<int> *comm_,
1661  int coordDim,
1662  tcoord_t **partCenters
1663  ){
1664  std::string file = "gggnuPlot";
1665  std::string exten = ".plot";
1666  ofstream mm("2d.txt");
1667  file += toString<int>(comm_->getRank()) + exten;
1668  std::ofstream ff(file.c_str());
1669  //ff.seekg (0, ff.end);
1670  RCP < vector <Zoltan2::coordinateModelPartBox <tcoord_t, partId_t> > > outPartBoxes = ((Zoltan2::PartitioningSolution<Adapter> *)soln_)->getPartBoxes();
1671 
1672  for (partId_t i = 0; i < this->ntasks;++i){
1673  (*outPartBoxes)[i].writeGnuPlot(ff, mm);
1674  }
1675  if (coordDim == 2){
1676  ff << "plot \"2d.txt\"" << endl;
1677  //ff << "\n pause -1" << endl;
1678  }
1679  else {
1680  ff << "splot \"2d.txt\"" << endl;
1681  //ff << "\n pause -1" << endl;
1682  }
1683  mm.close();
1684 
1685  ff << "set style arrow 5 nohead size screen 0.03,15,135 ls 1" << endl;
1686  for (partId_t i = 0; i < this->ntasks;++i){
1687  procId_t pb = 0;
1688  if (i > 0) pb = task_communication_xadj[i -1];
1689  procId_t pe = task_communication_xadj[i];
1690  for (procId_t p = pb; p < pe; ++p){
1691  procId_t n = task_communication_adj[p];
1692 
1693  //cout << "i:" << i << " n:" << n << endl;
1694  std::string arrowline = "set arrow from ";
1695  for (int j = 0; j < coordDim - 1; ++j){
1696  arrowline += toString<tcoord_t>(partCenters[j][n]) + ",";
1697  }
1698  arrowline += toString<tcoord_t>(partCenters[coordDim -1][n]) + " to ";
1699 
1700 
1701  for (int j = 0; j < coordDim - 1; ++j){
1702  arrowline += toString<tcoord_t>(partCenters[j][i]) + ",";
1703  }
1704  arrowline += toString<tcoord_t>(partCenters[coordDim -1][i]) + " as 5\n";
1705 
1706  //cout << "arrow:" << arrowline << endl;
1707  ff << arrowline;
1708  }
1709  }
1710 
1711  ff << "replot\n pause -1" << endl;
1712  ff.close();
1713  }
1714 };
1715 }// namespace Zoltan2
1716 
1717 #endif
void setParams(int dimension_, int heapsize)
CommunicationModel Base Class that performs mapping between the coordinate partitioning result...
void ithPermutation(const IT n, IT i, IT *perm)
static procId_t umpa_uRandom(procId_t l, int &_u_umpa_seed)
void doMapping(int myRank)
doMapping function, calls getMapping function of communicationModel object.
CoordinateCommunicationModel< pcoord_t, tcoord_t, procId_t > * proc_task_comm
#define SWAP(a, b, temp)
Time an algorithm (or other entity) as a whole.
RCP< Comm< int > > create_subCommunicatior()
creates and returns the subcommunicator for the processor group.
void update_visit_order(procId_t *visitOrder, procId_t n, int &_u_umpa_seed, procId_t rndm)
pcoord_t ** getProcCoords() const
getProcDim function returns the coordinates of processors in two dimensional array.
WT getDistance(IT index, WT **elementCoords)
const Teuchos::Comm< int > * comm
virtual size_t getLocalNumberOfParts() const
Returns the number of parts to be assigned to this process.
virtual void getMapping(int myRank, RCP< const Environment > env, ArrayRCP< procId_t > &proc_to_task_xadj, ArrayRCP< procId_t > &proc_to_task_adj, ArrayRCP< procId_t > &task_to_proc) const =0
Function is called whenever nprocs &gt; no_task. Function returns only the subset of processors that are...
Zoltan2::StridedData< lno_t, scalar_t > input_t
Definition: GraphModel.cpp:80
const Zoltan2::PartitioningSolution< Adapter > * soln
ArrayRCP< procId_t > task_communication_xadj
bool getNewCenters(WT **coords)
ArrayView< procId_t > getAssignedTaksForProc(procId_t procId)
CoordinateCommunicationModel(int pcoord_dim_, pcoord_t **pcoords_, int tcoord_dim_, tcoord_t **tcoords_, procId_t no_procs_, procId_t no_tasks_)
Class Constructor:
zoltan2_partId_t partId_t
ArrayRCP< procId_t > proc_to_task_xadj
void getSolutionCenterCoordinates(const Environment *envConst, const Teuchos::Comm< int > *comm, const Zoltan2::CoordinateModel< typename Adapter::base_adapter_t > *coords, const Zoltan2::PartitioningSolution< Adapter > *soln_, int coordDim, partId_t ntasks, scalar_t **partCenters)
void getMinDistanceCluster(IT *procPermutation)
CoordinateTaskMapper(const Environment *env_, const Teuchos::Comm< int > *comm_, const MachineRepresentation< pcoord_t > *machine_, int taskDim, procId_t taskCount, tcoord_t **taskCoords)
Constructor. Given the machine object and task centers, performs mapping.
virtual double getProcDistance(int procId1, int procId2) const =0
void timerStop(TimerType tt, const char *timerName) const
Stop a named timer.
This class provides geometric coordinates with optional weights to the Zoltan2 algorithm.
CoordinateTaskMapper(const Environment *env_, CoordinateCommunicationModel< pcoord_t, tcoord_t, procId_t > *proc_task_comm_)
Constructor. Sequential Constructor for test.
size_t getCoordinates(ArrayView< const gno_t > &Ids, ArrayView< input_t > &xyz, ArrayView< input_t > &wgts) const
Returns the coordinate ids, values and optional weights.
PartitionMapping maps a solution or an input distribution to ranks.
const zoltan2_partId_t * getPartList() const
Returns the part list corresponding to the global ID list.
A PartitioningSolution is a solution to a partitioning problem.
void copyCoordinates(IT *permutation)
void getClosestSubset(procId_t *proc_permutation, procId_t nprocs, procId_t ntasks) const
Function is called whenever nprocs &gt; no_task. Function returns only the subset of processors that are...
Zoltan2_ReduceBestMapping Class, reduces the minimum cost mapping, ties breaks with minimum proc id...
procId_t getAssignedProcForTask(procId_t taskId)
getAssignedProcForTask function, returns the assigned processor id for the given task ...
KMeansCluster Class.
void reduce(const Ordinal count, const T inBuffer[], T inoutBuffer[]) const
Implement Teuchos::ValueTypeReductionOp interface.
The StridedData class manages lists of weights or coordinates.
ArrayRCP< procId_t > task_communication_adj
virtual double getProcDistance(int procId1, int procId2) const
CommunicationModel(procId_t no_procs_, procId_t no_tasks_)
The user parameters, debug, timing and memory profiling output objects, and error checking methods...
void addPoint(IT index, WT distance)
bool getNewCenters(WT *center, WT **coords, int dimension)
MachineRepresentation Class Finds the coordinate of the processor. Used to find the processor coordin...
virtual void getMapping(int myRank, RCP< const Environment > env, ArrayRCP< procId_t > &rcp_proc_to_task_xadj, ArrayRCP< procId_t > &rcp_proc_to_task_adj, ArrayRCP< procId_t > &rcp_task_to_proc) const
Function is called whenever nprocs &gt; no_task. Function returns only the subset of processors that are...
double scalar_t
size_t getLocalNumCoordinates() const
Returns the number of coordinates on this process.
virtual void getProcsForPart(partId_t taskId, int &numProcs, int *procs) const
getAssignedProcForTask function, returns the assigned tasks with the number of tasks.
CoordinateModelInput Class that performs mapping between the coordinate partitioning result and mpi r...
const gid_t * getIdList() const
Returns the user&#39;s global ID list.
CoordinateTaskMapper(const Teuchos::Comm< int > *comm_, const MachineRepresentation< pcoord_t > *machine_, const Zoltan2::Model< typename Adapter::base_adapter_t > *model_, const Zoltan2::PartitioningSolution< Adapter > *soln_, const Environment *envConst)
Constructor. When this constructor is called, in order to calculate the communication metric...
#define ABS(x)
void getBestMapping()
finds the lowest cost mapping and broadcasts solution to everyone.
Zoltan2_ReduceBestMapping()
Default Constructor.
CoordinateTaskMapper(const Teuchos::Comm< int > *comm_, const MachineRepresentation< pcoord_t > *machine_, const Zoltan2::Model< typename Adapter::base_adapter_t > *model_, const Zoltan2::PartitioningSolution< Adapter > *soln_, const Environment *envConst_, ArrayRCP< procId_t >task_communication_xadj_, ArrayRCP< procId_t >task_communication_adj_)
Constructor When this constructor is called, it is assumed that the communication graph is already co...
void writeGnuPlot(const Teuchos::Comm< int > *comm_, const Zoltan2::PartitioningSolution< Adapter > *soln_, int coordDim, tcoord_t **partCenters)
int getProcDim() const
getProcDim function returns the dimension of the physical processor layout.
KmeansHeap Class, max heap, but holds the minimum values.
void fillContinousArray(T *arr, size_t arrSize, T *val)
fillContinousArray function
void push_down(IT index_on_heap)
void calculateCommunicationCost(procId_t *task_to_proc, procId_t *task_communication_xadj, procId_t *task_communication_adj)
size_t getActualGlobalNumberOfParts() const
Returns the actual global number of parts provided in setParts().
KMeansAlgorithm Class that performs clustering of the coordinates, and returns the closest set of coo...
void timerStart(TimerType tt, const char *timerName) const
Start a named timer.
KMeansAlgorithm(int dim_, IT numElements_, WT **elementCoords_, IT required_elements_)
KMeansAlgorithm Constructor.
int getNumProcs() const
getNumProcs function returns the number of processors.
void copyCoordinates(IT *permutation)
Contains the PQ-jagged algorthm.
size_t getTargetGlobalNumberOfParts() const
Returns the global number of parts desired in the solution.
virtual void getPartsForProc(int procId, partId_t &numParts, partId_t *parts) const
getAssignedProcForTask function, returns the assigned tasks with the number of tasks.
#define MINOF(a, b)
void getGridCommunicationGraph(partId_t taskCount, partId_t *&task_comm_xadj, partId_t *&task_comm_adj, vector< int > grid_dims)
void setHeapsize(IT heapsize_)