Zoltan2  Version of the Day
Zoltan2_AlgPQJagged.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_ALGPQJagged_HPP_
51 #define _ZOLTAN2_ALGPQJagged_HPP_
52 
55 #include <Zoltan2_Metric.hpp> // won't need thiss
56 #include <Tpetra_Distributor.hpp>
57 #include <Teuchos_ParameterList.hpp>
59 #include <new> // ::operator new[]
60 #include <algorithm> // std::sort
61 
62 
63 
64 //#define enable_migration2
65 
66 #ifdef enable_migration2
67 #include "zoltan_comm_cpp.h"
68 #endif
69 //#define FIRST_TOUCH
70 //#define BINARYCUTSEARCH
71 //#define Zoltan_Comm
72 
73 #include <bitset>
74 
75 #define EPS_SCALE 1
76 #define LEAST_SIGNIFICANCE 0.0001
77 #define SIGNIFICANCE_MUL 1000
78 #define FUTURE_REDUCEALL_CUTOFF 1500000
79 #define MIN_WORK_LAST_DIM 4000
80 //#define INCLUDE_ZOLTAN2_EXPERIMENTAL
81 #ifdef HAVE_ZOLTAN2_OMP
82 #include <omp.h>
83 #endif
84 #define ABS(x) ((x) >= 0 ? (x) : -(x))
85 
86 #define LEAF_IMBALANCE_FACTOR 0.1
87 #define BINARYCUTOFF 32
88 
89 //imbalance calculation. Wreal / Wexpected - 1
90 #define imbalanceOf(Wachieved, totalW, expectedRatio) \
91  (Wachieved) / ((totalW) * (expectedRatio)) - 1
92 #define imbalanceOf2(Wachieved, wExpected) \
93  (Wachieved) / (wExpected) - 1
94 #define MAXOF (a,b) (((a)>(b))?(a):(b))
95 
96 #define KCUTOFF 0.80
97 #define forceMigration 1500000
98 #define Z2_DEFAULT_CON_PART_COUNT 16
99 
100 using std::vector;
101 
102 namespace Teuchos{
103 template <typename Ordinal, typename T>
104 class PQJaggedCombinedReductionOp : public ValueTypeReductionOp<Ordinal,T>
105 {
106 private:
107  Ordinal numSum_0, numMin_1, numMin_2;
108  std::vector <Ordinal> *partVector;
109  Ordinal vectorBegin;
110  Ordinal k;
111  int reductionType;
112 
113 public:
116  PQJaggedCombinedReductionOp ():numSum_0(0), numMin_1(0),
117  numMin_2(0), k(0), partVector(NULL), vectorBegin(0), reductionType(0){}
118 
125  PQJaggedCombinedReductionOp (Ordinal nsum, Ordinal nmin1, Ordinal nmin2, Ordinal k_):
126  numSum_0(nsum), numMin_1(nmin1), numMin_2(nmin2),
127  partVector(NULL),vectorBegin(0),
128  k(k_),
129  reductionType(0){}
130 
131 
132  PQJaggedCombinedReductionOp (std::vector <Ordinal> *pVector, Ordinal vBegin, Ordinal k_):
133 // PQJaggedCombinedReductionOp (vector <Ordinal> *pVector, Ordinal vBegin, Ordinal k_):
134  numSum_0(0), numMin_1(0), numMin_2(0),
135  partVector(pVector), vectorBegin(vBegin),
136  k(k_),
137  reductionType(1){}
138 
139 
142  void reduce( const Ordinal count, const T inBuffer[], T inoutBuffer[]) const
143  {
144  if (reductionType == 0){
145  Ordinal next=0;
146  for(Ordinal ii = 0; ii < k ; ++ii){
147  for (Ordinal i=0; i < numSum_0; i++, next++)
148  inoutBuffer[next] += inBuffer[next];
149 
150  for (Ordinal i=0; i < numMin_1; i++, next++)
151  if (inoutBuffer[next] < inBuffer[next])
152  inoutBuffer[next] = inBuffer[next];
153 
154  for (Ordinal i=0; i < numMin_2; i++, next++)
155  if (inoutBuffer[next] > inBuffer[next])
156  inoutBuffer[next] = inBuffer[next];
157  }
158  }
159  else {
160  Ordinal next=0;
161  for(Ordinal ii = 0; ii < k ; ++ii){
162  Ordinal partPartition = (*partVector)[ii + vectorBegin];
163  Ordinal tnumSum_ = 2 * partPartition - 1;
164  Ordinal tnumMin_1 = partPartition - 1;
165  Ordinal tnumMin_2 = tnumMin_1 ;
166  for (Ordinal i=0; i < tnumSum_; i++, next++)
167  inoutBuffer[next] += inBuffer[next];
168 
169  for (Ordinal i=0; i < tnumMin_1; i++, next++)
170  if (inoutBuffer[next] < inBuffer[next])
171  inoutBuffer[next] = inBuffer[next];
172 
173  for (Ordinal i=0; i < tnumMin_2; i++, next++)
174  if (inoutBuffer[next] > inBuffer[next])
175  inoutBuffer[next] = inBuffer[next];
176  }
177  }
178  }
179 };
180 
181 
182 template <typename Ordinal, typename T>
183 class PQJaggedCombinedMinMaxTotalReductionOp : public ValueTypeReductionOp<Ordinal,T>
184 {
185 private:
186  Ordinal numMin, numMax, numTotal;
187 
188 public:
191  PQJaggedCombinedMinMaxTotalReductionOp ():numMin(0), numMax(0), numTotal(0){}
192 
199  PQJaggedCombinedMinMaxTotalReductionOp (Ordinal nmin, Ordinal nmax, Ordinal nTotal):
200  numMin(nmin), numMax(nmax), numTotal(nTotal){}
201 
204  void reduce( const Ordinal count, const T inBuffer[], T inoutBuffer[]) const
205  {
206  Ordinal next=0;
207 
208  for (Ordinal i=0; i < numMin; i++, next++)
209  if (inoutBuffer[next] > inBuffer[next])
210  inoutBuffer[next] = inBuffer[next];
211 
212  for (Ordinal i=0; i < numMax; i++, next++)
213  if (inoutBuffer[next] < inBuffer[next])
214  inoutBuffer[next] = inBuffer[next];
215 
216 
217  for (Ordinal i=0; i < numTotal; i++, next++)
218  inoutBuffer[next] += inBuffer[next];
219  }
220 };
221 } // namespace Teuchos
222 
223 namespace Zoltan2{
224 
225 //diffclock for temporary timing experiments.
226 
227 #ifdef mpi_communication
228 partId_t concurrent = 0;
229 void sumMinMin(void *in, void *inout, int *count, MPI_Datatype *type) {
230 
231  int k = *count;
232  int numCut = (k - 1) / 4;
233  int total_part_count = numCut * 2 + 1;
234  int next = 0;
235 
236  float *inoutBuffer = (float *) inout;
237  float *inBuffer = (float *) in;
238 
239 
240  for(partId_t ii = 0; ii < concurrent ; ++ii){
241  for (long i=0; i < total_part_count; i++, next++)
242  inoutBuffer[next] += inBuffer[next];
243 
244  for (long i=0; i < numCut; i++, next++)
245  if (inoutBuffer[next] > inBuffer[next])
246  inoutBuffer[next] = inBuffer[next];
247 
248  for (long i=0; i < numCut; i++, next++)
249  if (inoutBuffer[next] > inBuffer[next])
250  inoutBuffer[next] = inBuffer[next];
251  }
252 }
253 
254 
255 void minMaxSum(void *in, void *inout, int *count, MPI_Datatype *type) {
256  // long k = (*((int *) count));
257  int k = *count;
258  int num = k / 3;
259  int next = 0;
260  float *inoutBuffer = (float *) inout;
261  float *inBuffer = (float *) in;
262 
263 
264  for (long i=0; i < num; i++, next++)
265  if (inoutBuffer[next] > inBuffer[next])
266  inoutBuffer[next] = inBuffer[next];
267  for (long i=0; i < num; i++, next++)
268  if (inoutBuffer[next] < inBuffer[next])
269  inoutBuffer[next] = inBuffer[next];
270  for (long i=0; i < num; i++, next++)
271  inoutBuffer[next] += inBuffer[next];
272 
273 }
274 #endif
275 
280 template <typename lno_t, typename partId_t>
282 private:
283  lno_t *linkedList; //initially filled with -1's.
284  lno_t *partBegins; //initially filled with -1's.
285  lno_t *partEnds; //initially filled with -1's.
286 public:
287 
288  //default constructor
290 
300  void set(lno_t *linkedList_, lno_t *partBegins_, lno_t *partEnds_){
301  linkedList = linkedList_;
302  partBegins = partBegins_;
303  partEnds = partEnds_;
304  }
305 
306  //user is responsible from providing the correct number of part counts
313  void inserToPart (partId_t partNo, lno_t coordinateIndex){
314 
315  switch (partEnds[partNo]){
316  case -1: // this means partBegins[partNo] is also -1.
317  partBegins[partNo] = coordinateIndex;
318  partEnds[partNo] = coordinateIndex;
319  break;
320  default:
321  linkedList[coordinateIndex] = partBegins[partNo];
322  partBegins[partNo] = coordinateIndex;
323  break;
324  }
325 
326 
327  }
328 
332  lno_t *getLinkedList(){ return linkedList;}
333 
337  lno_t *getPartBegins(){ return partBegins;}
341  lno_t *getPartEnds(){ return partEnds;}
342 
343 };
344 
345 template<typename T>
346 inline void firstTouch(T *arrayName, size_t arraySize){
347 #ifdef HAVE_ZOLTAN2_OMP
348 #pragma omp parallel for
349 #endif
350  for(size_t jj = 0; jj < arraySize; ++jj){
351  arrayName[jj] = 0;
352  }
353 }
354 
365 template <typename scalar_t>
366 inline scalar_t pivotPos (scalar_t * cutUpperBounds, scalar_t *cutLowerBounds,size_t currentCutIndex, scalar_t *cutUpperWeight, scalar_t *cutLowerWeight, scalar_t ew, scalar_t _EPSILON){
367 
368  if(ABS(cutUpperWeight[currentCutIndex] - cutLowerWeight[currentCutIndex]) < _EPSILON){
369  return cutLowerBounds[currentCutIndex];
370  }
371 
372  scalar_t newCut =((cutUpperBounds[currentCutIndex] - cutLowerBounds[currentCutIndex]) /
373  (cutUpperWeight[currentCutIndex] - cutLowerWeight[currentCutIndex])) * (ew - cutLowerWeight[currentCutIndex]) + cutLowerBounds[currentCutIndex];
374  /*
375  cout << "cutIndex:" << currentCutIndex <<
376  " upper:" << cutUpperBounds[currentCutIndex] << " uw:" << cutUpperWeight[currentCutIndex] <<
377  " lower:" << cutLowerBounds[currentCutIndex] << " lw:" << cutLowerWeight[currentCutIndex] <<
378  " found:" << newCut << endl;
379  */
380  return newCut;
381 }
382 
383 template <typename T>
385  const Teuchos::ParameterList &pl,
386  T &imbalanceTolerance,
387  multiCriteriaNorm &mcnorm,
388  std::bitset<NUM_RCB_PARAMS> &params,
389  int &numTestCuts,
390  bool &ignoreWeights){
391 
392  string obj;
393 
394  const Teuchos::ParameterEntry *pe = pl.getEntryPtr("partitioning_objective");
395  if (pe)
396  obj = pe->getValue(&obj);
397 
398  if (!pe){
399  params.set(rcb_balanceWeight);
400  mcnorm = normBalanceTotalMaximum;
401  }
402  else if (obj == string("balance_object_count")){
403  params.set(rcb_balanceCount);
404  }
405  else if (obj == string("multicriteria_minimize_total_weight")){
406  params.set(rcb_minTotalWeight);
407  mcnorm = normMinimizeTotalWeight;
408  }
409  else if (obj == string("multicriteria_minimize_maximum_weight")){
410  params.set(rcb_minMaximumWeight);
411  mcnorm = normMinimizeMaximumWeight;
412  }
413  else if (obj == string("multicriteria_balance_total_maximum")){
414  params.set(rcb_balanceTotalMaximum);
415  mcnorm = normBalanceTotalMaximum;
416  }
417  else{
418  params.set(rcb_balanceWeight);
419  mcnorm = normBalanceTotalMaximum;
420  }
421 
422  int val = 0;
423  pe = pl.getEntryPtr("average_cuts");
424  if (pe)
425  val = pe->getValue(&val);
426 
427  if (val == 1)
428  params.set(rcb_averageCuts);
429 
430  imbalanceTolerance = .1;
431  pe = pl.getEntryPtr("imbalance_tolerance");
432  if (pe){
433  double tol;
434  tol = pe->getValue(&tol);
435  imbalanceTolerance = tol - 1.0;
436  }
437 
438  if (imbalanceTolerance <= 0)
439  imbalanceTolerance = 10e-4;
440 
441  numTestCuts = 1;
442  pe = pl.getEntryPtr("bisection_num_test_cuts");
443  if (pe)
444  numTestCuts = pe->getValue(&numTestCuts);
445 
446 
447  ignoreWeights = params.test(rcb_balanceCount);
448 }
449 
450 
469 template <typename T>
471  const Teuchos::ParameterList &pl,
472  bool &allowNonrectilinear,
473  partId_t &concurrentPartCount,
474  int &migration_actualMigration_option,
475  int &migration_check_option,
476  int &migration_all2all_option,
477  T &migration_imbalance_cut_off,
478  int &migration_assignment_type,
479  int &keep_part_boxes,
480  int &enable_rcb,
481  int &recursion_depth){
482 
483 
484  const Teuchos::ParameterEntry *pe = pl.getEntryPtr("partitioning_objective");
485  migration_imbalance_cut_off = .1;
486  pe = pl.getEntryPtr("migration_imbalance_cut_off");
487  if (pe){
488  double tol;
489  tol = pe->getValue(&tol);
490  migration_imbalance_cut_off = tol - 1.0;
491  }
492 
493  pe = pl.getEntryPtr("migration_all_to_all_type");
494  if (pe){
495  migration_all2all_option = pe->getValue(&concurrentPartCount);
496  }else {
497  migration_all2all_option = 1;
498  }
499 
500  pe = pl.getEntryPtr("migration_check_option");
501  if (pe){
502  migration_check_option = pe->getValue(&concurrentPartCount);
503  }else {
504  migration_check_option = 0;
505  }
506  if (migration_check_option > 1) migration_check_option = -1;
507 
508  pe = pl.getEntryPtr("migration_processor_assignment_type");
509  if (pe){
510  migration_assignment_type = pe->getValue(&concurrentPartCount);
511  }else {
512  migration_assignment_type = 1;
513  }
514  pe = pl.getEntryPtr("migration_doMigration_type");
515  if (pe){
516  migration_actualMigration_option = pe->getValue(&migration_actualMigration_option);
517  }else {
518  migration_actualMigration_option = 1;
519  }
520 
521  pe = pl.getEntryPtr("parallel_part_calculation_count");
522  if (pe){
523  concurrentPartCount = pe->getValue(&concurrentPartCount);
524  }else {
525  concurrentPartCount = 0; // Set to invalid value
526  }
527 
528  pe = pl.getEntryPtr("keep_part_boxes");
529  if (pe){
530  keep_part_boxes = pe->getValue(&keep_part_boxes);
531  }else {
532  keep_part_boxes = 0; // Set to invalid value
533  }
534 
535  if (keep_part_boxes == 0){
536  pe = pl.getEntryPtr("mapping_type");
537  if (pe){
538  int mapping_type = -1;
539  mapping_type = pe->getValue(&mapping_type);
540  if (mapping_type == 0){
541  keep_part_boxes = 1;
542  }
543  }
544  }
545 
546  pe = pl.getEntryPtr("mj_enable_rcb");
547  if (pe){
548  enable_rcb = pe->getValue(&enable_rcb);
549  }else {
550  enable_rcb = 0; // Set to invalid value
551  }
552 
553  pe = pl.getEntryPtr("recursion_depth");
554  if (pe){
555  recursion_depth = pe->getValue(&recursion_depth);
556  }else {
557  recursion_depth = -1; // Set to invalid value
558  }
559 
560  int val = 0;
561  pe = pl.getEntryPtr("rectilinear_blocks");
562  if (pe)
563  val = pe->getValue(&val);
564 
565  if (val == 1){
566  allowNonrectilinear = false;
567  } else {
568  allowNonrectilinear = true;
569  }
570 
571 
572 }
573 
574 
586 template <typename Adapter>
588  typename Adapter::base_adapter_t> > &coords, int &coordDim,
589  int &weightDim, size_t &numLocalCoords, global_size_t &numGlobalCoords, int &criteriaDim, const bool &ignoreWeights){
590 
591  coordDim = coords->getCoordinateDim();
592  weightDim = coords->getCoordinateWeightDim();
593  numLocalCoords = coords->getLocalNumCoordinates();
594  numGlobalCoords = coords->getGlobalNumCoordinates();
595  criteriaDim = (weightDim ? weightDim : 1);
596  if (criteriaDim > 1 && ignoreWeights)
597  criteriaDim = 1;
598 
599 }
600 
601 
627 template <typename Adapter, typename scalar_t, typename gno_t>
629  const RCP<const Environment> &env, const RCP<const CoordinateModel<
630  typename Adapter::base_adapter_t> > &coords,
631  RCP<PartitioningSolution<Adapter> > &solution,
632  std::bitset<NUM_RCB_PARAMS> &params,
633  const int &coordDim,
634  const int &weightDim,
635  const size_t &numLocalCoords,
636  size_t &numGlobalParts,
637  int &pqJagged_multiVectorDim,
638  scalar_t **pqJagged_values,
639  const int &criteriaDim,
640  scalar_t **pqJagged_weights,
641  ArrayView<const gno_t> &pqJagged_gnos,
642  bool &ignoreWeights,
643  bool *pqJagged_uniformWeights,
644  bool *pqJagged_uniformParts,
645  scalar_t **pqJagged_partSizes
646 ){
647  //typedef typename Adapter::node_t node_t;
648  typedef typename Adapter::lno_t lno_t;
650 
651  ArrayView<const gno_t> gnos;
652  ArrayView<input_t> xyz;
653  ArrayView<input_t> wgts;
654 
655  coords->getCoordinates(gnos, xyz, wgts);
656  pqJagged_gnos = gnos;
657 
658 
659  //std::cout << std::endl;
660 
661  for (int dim=0; dim < coordDim; dim++){
662  ArrayRCP<const scalar_t> ar;
663  xyz[dim].getInputArray(ar);
664  //pqJagged coordinate values assignment
665  pqJagged_values[dim] = (scalar_t *)ar.getRawPtr();
666  }
667 
668  if (weightDim == 0 || ignoreWeights){
669 
670  pqJagged_uniformWeights[0] = true;
671  pqJagged_weights[0] = NULL;
672  }
673  else{
674  for (int wdim = 0; wdim < weightDim; wdim++){
675  if (wgts[wdim].size() == 0){
676  pqJagged_uniformWeights[wdim] = true;
677  pqJagged_weights[wdim] = NULL;
678  }
679  else{
680  ArrayRCP<const scalar_t> ar;
681  wgts[wdim].getInputArray(ar);
682  pqJagged_uniformWeights[wdim] = false;
683  pqJagged_weights[wdim] = (scalar_t *) ar.getRawPtr();
684  }
685  }
686  }
687 
689  // From the Solution we get part information.
690  // If the part sizes for a given criteria are not uniform,
691  // then they are values that sum to 1.0.
692 
693  numGlobalParts = solution->getTargetGlobalNumberOfParts();
694 
695  for (int wdim = 0; wdim < criteriaDim; wdim++){
696  if (solution->criteriaHasUniformPartSizes(wdim)){
697  pqJagged_uniformParts[wdim] = true;
698  pqJagged_partSizes[wdim] = NULL;
699  }
700  else{
701  //TODO
702  scalar_t *tmp = new scalar_t [numGlobalParts];
703  env->localMemoryAssertion(__FILE__, __LINE__, numGlobalParts, tmp) ;
704  for (size_t i=0; i < numGlobalParts; i++){
705  tmp[i] = solution->getCriteriaPartSize(wdim, i);
706  }
707  pqJagged_partSizes[wdim] = tmp;
708  }
709  }
710 
711  // It may not be possible to solve the partitioning problem
712  // if we have multiple weight dimensions with part size
713  // arrays that differ. So let's be aware of this possibility.
714 
715  bool multiplePartSizeSpecs = false;
716 
717  if (criteriaDim > 1){
718  for (int wdim1 = 0; wdim1 < criteriaDim; wdim1++)
719  for (int wdim2 = wdim1+1; wdim2 < criteriaDim; wdim2++)
720  if (!solution->criteriaHaveSamePartSizes(wdim1, wdim2)){
721  multiplePartSizeSpecs = true;
722  break;
723  }
724  }
725 
726  if (multiplePartSizeSpecs)
727  params.set(rcb_multiplePartSizeSpecs);
728 
730  // Create the distributed data for the algorithm.
731  //
732  // It is a multivector containing one vector for each coordinate
733  // dimension, plus a vector for each weight dimension that is not
734  // uniform.
735 
736  pqJagged_multiVectorDim = coordDim;
737  for (int wdim = 0; wdim < criteriaDim; wdim++){
738  if (!pqJagged_uniformWeights[wdim]) pqJagged_multiVectorDim++;
739  }
740 
741 }
742 
743 
747 template <typename scalar_t, typename gno_t>
748 void pqJagged_printInput(int coordDim, int weightDim, size_t numLocalCoords, global_size_t numGlobalCoords,
749  int criteriaDim, scalar_t **pqJagged_values, scalar_t **pqJagged_weights,
750  bool *pqJagged_uniformParts, bool *pqJagged_uniformWeights, gno_t *pqJagged_gnos,
751  bool ignoreWeights,size_t numGlobalParts, scalar_t **pqJagged_partSizes){
752 
753  std::cout << "numLocalCoords:" << numLocalCoords << std::endl;
754  std::cout << "coordDim:" << coordDim << std::endl;
755  for(size_t i = 0; i < numLocalCoords; ++i){
756  for (int ii = 0; ii < coordDim; ++ii){
757  std::cout << pqJagged_values[ii][i] << " ";
758  }
759  std::cout << std::endl;
760  }
761 
762 
763  std::cout << "criteriaDim:" << criteriaDim << std::endl;
764  std::cout << "weightDim:" << weightDim << std::endl;
765  if(weightDim){
766  for(size_t i = 0; i < numLocalCoords; ++i){
767  for (int ii = 0; ii < weightDim; ++ii){
768  std::cout << pqJagged_weights[ii][i] << " ";
769  }
770  std::cout << std::endl;
771  }
772  }
773 
774  std::cout << "pqJagged_uniformWeights:" << pqJagged_uniformWeights[0] << std::endl;
775  for(int i = 0; i < criteriaDim; ++i){
776  std::cout << pqJagged_uniformWeights[i] << " ";
777  }
778  std::cout << std::endl;
779 
780 
781  std::cout << "gnos" << std::endl;
782  for(size_t i = 0; i < numLocalCoords; ++i){
783  std::cout << pqJagged_gnos[i] << " ";
784  }
785  std::cout << std::endl;
786 
787  std::cout << "ignoreWeights:" << ignoreWeights << std::endl;
788 
789  std::cout << "pqJagged_uniformParts:" << pqJagged_uniformParts[0] << std::endl;
790  for(int i = 0; i < criteriaDim; ++i){
791  std::cout << pqJagged_uniformParts[i] << " ";
792  }
793  std::cout << std::endl;
794 
795  std::cout << "pqJagged_partSizes:" << std::endl;
796  std::cout << "numGlobalParts:" << numGlobalParts << std::endl;
797  for(int i = 0; i < criteriaDim; ++i){
798  if(!pqJagged_uniformParts[i])
799  for(size_t ii = 0; ii < numGlobalParts; ++ii){
800  std::cout << pqJagged_partSizes[i][ii] << " ";
801  }
802  std::cout << std::endl;
803  }
804 }
805 
806 
827 template <typename scalar_t, typename lno_t>
829  lno_t *partitionedPointPermutations,
830  scalar_t *pqJagged_coordinates,
831  bool pqJagged_uniformWeights,
832  scalar_t *pqJagged_weights,
833 
834 
835  int numThreads,
836  lno_t coordinateBegin,
837  lno_t coordinateEnd,
838 
839  scalar_t *max_min_array /*sized nothreads * 2*/,
840  scalar_t maxScalar,
841  scalar_t minScalar,
842 
843  scalar_t &minCoordinate,
844  scalar_t &maxCoordinate,
845  scalar_t &totalWeight
846 ){
847 
848  //if the part is empty.
849  //set the min and max coordinates as reverse.
850  if(coordinateBegin >= coordinateEnd)
851  {
852  minCoordinate = maxScalar;
853  maxCoordinate = minScalar;
854  totalWeight = 0;
855  }
856  else {
857  scalar_t mytotalWeight = 0;
858 #ifdef HAVE_ZOLTAN2_OMP
859 #pragma omp parallel
860 #endif
861  {
862  //if uniform weights are used, then weight is equal to count.
863  if (pqJagged_uniformWeights) {
864 #ifdef HAVE_ZOLTAN2_OMP
865 #pragma omp single
866 #endif
867  {
868  mytotalWeight = coordinateEnd - coordinateBegin;
869  }
870 
871  }
872  else {
873  //if not uniform, then weights are reducted from threads.
874 #ifdef HAVE_ZOLTAN2_OMP
875 #pragma omp for reduction(+:mytotalWeight)
876 #endif
877  for (lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
878  int i = partitionedPointPermutations[ii];
879  mytotalWeight += pqJagged_weights[i];
880  }
881  }
882 
883  int myId = 0;
884 #ifdef HAVE_ZOLTAN2_OMP
885  myId = omp_get_thread_num();
886 #endif
887  scalar_t myMin, myMax;
888 /*
889  problemComm->barrier();
890  cout << "initial me:" << problemComm->getRank()
891  << " coordinateBegin:" << coordinateBegin
892  << " ind:" << partitionedPointPermutations[coordinateBegin] << endl;
893 */
894  myMin=myMax
895  =pqJagged_coordinates[partitionedPointPermutations[coordinateBegin]];
896 // problemComm->barrier();
897  // cout << "initial me:" << problemComm->getRank() << " myMin:" << myMin << " myMax:" << myMax << endl;
898 
899 
900 #ifdef HAVE_ZOLTAN2_OMP
901 #pragma omp for
902 #endif
903  for(lno_t j = coordinateBegin + 1; j < coordinateEnd; ++j){
904  int i = partitionedPointPermutations[j];
905  if(pqJagged_coordinates[i] > myMax) myMax = pqJagged_coordinates[i];
906  if(pqJagged_coordinates[i] < myMin) myMin = pqJagged_coordinates[i];
907  }
908  max_min_array[myId] = myMin;
909  max_min_array[myId + numThreads] = myMax;
910 /*
911  problemComm->barrier();
912  cout << "after me:" << problemComm->getRank() << " myMin:" << myMin << " myMax:" << myMax << endl;
913 */
914 
915 
916 #ifdef HAVE_ZOLTAN2_OMP
917 //we need a barrier here, because max_min_array might not be filled by some of the threads.
918 #pragma omp barrier
919 #pragma omp single nowait
920 #endif
921  {
922  minCoordinate = max_min_array[0];
923  for(int i = 1; i < numThreads; ++i){
924  if(max_min_array[i] < minCoordinate) minCoordinate = max_min_array[i];
925  }
926  }
927 
928 
929 
930 #ifdef HAVE_ZOLTAN2_OMP
931 #pragma omp single nowait
932 #endif
933  {
934  maxCoordinate = max_min_array[numThreads];
935  for(int i = numThreads + 1; i < numThreads * 2; ++i){
936  if(max_min_array[i] > maxCoordinate) maxCoordinate = max_min_array[i];
937  }
938  }
939  }
940  totalWeight = mytotalWeight;
941  }
942 
943 }
944 
945 template <typename partId_t>
946 inline partId_t getPartCount(partId_t numFuture, float root, float fEpsilon){
947  float fp = pow(numFuture, root);
948  partId_t ip = partId_t (fp);
949  if (fp - ip < fEpsilon){
950  return ip;
951  }
952  else {
953  return ip + 1;
954  }
955 }
956 
957 
967 template <typename scalar_t>
969  RCP<Comm<int> > &comm,
970  const RCP<const Environment> &env,
971  partId_t concurrentPartCount,
972  scalar_t *localMinMaxTotal,
973  scalar_t *globalMinMaxTotal){
974 
975 
976  //reduce min for first concurrentPartCount elements, reduce max for next concurrentPartCount elements,
977  //reduce sum for the last concurrentPartCount elements.
978  if(comm->getSize() > 1){
979 
980 #ifndef mpi_communication
982  concurrentPartCount,
983  concurrentPartCount,
984  concurrentPartCount);
985 #endif
986 
987 #ifdef mpi_communication
988  MPI_Op myop;
989  MPI_Op_create(minMaxSum, 0, &myop); /* step 3 */
990 #endif
991 
992  try{
993 
994 
995 #ifdef mpi_communication
996 
997  MPI_Allreduce(localMinMaxTotal, globalMinMaxTotal, 3 * concurrentPartCount, MPI_FLOAT, myop,MPI_COMM_WORLD);
998 #endif
999 #ifndef mpi_communication
1000  reduceAll<int, scalar_t>(*comm, reductionOp,
1001  3 * concurrentPartCount, localMinMaxTotal, globalMinMaxTotal
1002  );
1003 #endif
1004 
1005  }
1007  }
1008  else {
1009  partId_t s = 3 * concurrentPartCount;
1010  for (partId_t i = 0; i < s; ++i){
1011  globalMinMaxTotal[i] = localMinMaxTotal[i];
1012  }
1013  }
1014 }
1015 
1016 
1040 template <typename scalar_t>
1042  scalar_t minCoordinate,
1043  scalar_t maxCoordinate,
1044 
1045  bool pqJagged_uniformParts,
1046  bool pqJagged_uniformWeights,
1047 
1048  scalar_t *pqJagged_partSizes /*p sized, weight ratios of each part*/,
1049  partId_t noCuts/*p-1*/ ,
1050  scalar_t globalTotalWeight,
1051 
1052  scalar_t *cutCoordinates /*p - 1 sized, coordinate of each cut line*/,
1053  scalar_t *cutPartRatios /*cumulative weight ratios, at left side of each cut line. p-1 sized*/,
1054  int numThreads,
1055 
1056  vector <partId_t> *currentPartitions, //the vecto
1057  vector <partId_t> *futurePartitions,
1058  partId_t partIndex,
1059  partId_t futureArrayIndex
1060 ){
1061 
1062  scalar_t coordinateRange = maxCoordinate - minCoordinate;
1063  if(pqJagged_uniformParts){
1064  {
1065  partId_t cumulative = 0;
1066  scalar_t totalInnerPartCount = scalar_t((*currentPartitions)[partIndex]);
1067  scalar_t unitWeight = globalTotalWeight / totalInnerPartCount;
1068  for(partId_t i = 0; i < noCuts; ++i){
1069  cumulative += (*futurePartitions)[i + futureArrayIndex];
1070  //cutPartRatios[i] = (cumulative /*+ (*futurePartitions)[i + futureArrayIndex]*/) / (totalInnerPartCount);
1071  cutPartRatios[i] = cumulative * unitWeight;
1072  cutCoordinates[i] = minCoordinate + (coordinateRange * cumulative) / totalInnerPartCount;
1073  }
1074  cutPartRatios[noCuts] = 1;
1075  }
1076  if (pqJagged_uniformWeights){
1077  for(partId_t i = 0; i < noCuts + 1; ++i){
1078  cutPartRatios[i] = long(cutPartRatios[i] + 0.5);
1079  }
1080  }
1081 
1082 
1083 
1084  }
1085  else {
1086  /*
1087  //TODO fix here!!
1088  cutPartRatios[0] = pqJagged_partSizes[0];
1089  cutCoordinates[0] = coordinateRange * cutPartRatios[0];
1090  for(partId_t i = 1; i < noCuts; ++i){
1091  cutPartRatios[i] = pqJagged_partSizes[i] + cutPartRatios[i - 1];
1092  cutCoordinates[i] = coordinateRange * cutPartRatios[i];
1093  }
1094  */
1095  }
1096 }
1097 
1098 
1135 template <typename scalar_t>
1137  const RCP<const Environment> &env,
1138  RCP<Comm<int> > &comm,
1139  const size_t &total_part_count,
1140  const partId_t &noCuts,
1141  const scalar_t &maxCoordinate,
1142  const scalar_t &minCoordinate,
1143  const scalar_t &globalTotalWeight,
1144  const scalar_t &imbalanceTolerance,
1145  //scalar_t maxCoordinate,
1146  //scalar_t minCoordinate,
1147 
1148  scalar_t * globalPartWeights,
1149  const scalar_t * localPartWeights,
1150  const scalar_t *targetPartWeightRatios,
1151  bool *isDone,
1152 
1153  scalar_t *cutCoordinates,
1154  scalar_t *cutUpperBounds,
1155  scalar_t *cutLowerBounds,
1156  scalar_t *leftClosestDistance,
1157  scalar_t *rightClosestDistance,
1158  scalar_t * cutLowerWeight,
1159  scalar_t * cutUpperWeight,
1160  scalar_t *newCutCoordinates,
1161 
1162  bool allowNonRectelinearPart,
1163  float *nonRectelinearPartRatios,
1164  partId_t *rectilinearCutCount,
1165  scalar_t *localCutWeights,
1166  scalar_t *globalCutWeights,
1167 
1168  partId_t &myNoneDoneCount
1169 )
1170 {
1171 
1172 
1173  scalar_t seenW = 0;
1174  float expected = 0;
1175  scalar_t leftImbalance = 0, rightImbalance = 0;
1176  scalar_t _EPSILON = numeric_limits<scalar_t>::epsilon();
1177  //scalar_t _EPSILON = numeric_limits<float>::epsilon();
1178 
1179 #ifdef HAVE_ZOLTAN2_OMP
1180 #pragma omp for
1181 #endif
1182  for (partId_t i = 0; i < noCuts; i++){
1183 
1184  //if a left and right closes point is not found, set the distance to 0.
1185  if(minCoordinate - leftClosestDistance[i] > _EPSILON)
1186  leftClosestDistance[i] = cutCoordinates[i];
1187  if(rightClosestDistance[i] - maxCoordinate > _EPSILON)
1188  rightClosestDistance[i] = cutCoordinates[i];
1189 
1190  }
1191 
1192 #ifdef HAVE_ZOLTAN2_OMP
1193 #pragma omp for
1194 #endif
1195  for (partId_t i = 0; i < noCuts; i++){
1196  globalCutWeights[i] = 0;
1197  localCutWeights[i] = 0;
1198  //if already determined at previous iterations, do nothing.
1199  if(isDone[i]) {
1200  newCutCoordinates[i] = cutCoordinates[i];
1201  continue;
1202  }
1203  //current weight of the part at the left of the cut line.
1204  seenW = globalPartWeights[i * 2];
1205 
1206 
1207  //expected ratio
1208  expected = targetPartWeightRatios[i];
1209  //leftImbalance = imbalanceOf(seenW, globalTotalWeight, expected);
1210  leftImbalance = imbalanceOf2(seenW, expected);
1211  //rightImbalance = imbalanceOf(globalTotalWeight - seenW, globalTotalWeight, 1 - expected);
1212  rightImbalance = imbalanceOf2(globalTotalWeight - seenW, globalTotalWeight - expected);
1213 
1214  bool isLeftValid = ABS(leftImbalance) - imbalanceTolerance < _EPSILON ;
1215  bool isRightValid = ABS(rightImbalance) - imbalanceTolerance < _EPSILON;
1216 
1217 /*
1218  cout << "\t\tc:" << i << "leftImbalance:" << leftImbalance <<
1219  " seenW:" << seenW <<
1220  " lineW:" << globalPartWeights[i * 2 + 1] <<
1221  " globalTotalWeight:" << globalTotalWeight <<
1222  " expected:" << expected <<
1223  " r:" << rightImbalance <<
1224  " upper:" <<cutUpperBounds[i] <<
1225  " lower:" << cutLowerBounds[i] <<
1226  " leftValid:" << isLeftValid <<
1227  " rightValid:" << isRightValid <<
1228  " imbalanceTolerance:" << imbalanceTolerance <<
1229  endl;
1230 */
1231  //if the cut line reaches to desired imbalance.
1232  if(isLeftValid && isRightValid){
1233 
1234  isDone[i] = true;
1235 #ifdef HAVE_ZOLTAN2_OMP
1236 #pragma omp atomic
1237 #endif
1238  myNoneDoneCount -= 1;
1239  newCutCoordinates [i] = cutCoordinates[i];
1240  continue;
1241  }
1242  else if(leftImbalance < 0){
1243 
1244  scalar_t ew = expected; //globalTotalWeight * expected;
1245  if(allowNonRectelinearPart){
1246 
1247  if (globalPartWeights[i * 2 + 1] == ew){
1248 
1249  isDone[i] = true;
1250 #ifdef HAVE_ZOLTAN2_OMP
1251 #pragma omp atomic
1252 #endif
1253  myNoneDoneCount -= 1;
1254  newCutCoordinates [i] = cutCoordinates[i];
1255 
1256  //nonRectelinearPartRatios[i] = 1;
1257  nonRectelinearPartRatios[i] = localPartWeights[i * 2 + 1] - localPartWeights[i * 2];
1258  /*
1259  cout << "setting i" << i <<
1260  " to:" << localPartWeights[i * 2 + 1] <<
1261  " - " << localPartWeights[i * 2] <<
1262  " = " << nonRectelinearPartRatios[i] <<
1263  endl;
1264  */
1265  continue;
1266  }
1267  else if (globalPartWeights[i * 2 + 1] > ew){
1268  isDone[i] = true;
1269 #ifdef HAVE_ZOLTAN2_OMP
1270 #pragma omp atomic
1271 #endif
1272  *rectilinearCutCount += 1;
1273 
1274 #ifdef HAVE_ZOLTAN2_OMP
1275 #pragma omp atomic
1276 #endif
1277  myNoneDoneCount -= 1;
1278  newCutCoordinates [i] = cutCoordinates[i];
1279  scalar_t myWeightOnLine = localPartWeights[i * 2 + 1] - localPartWeights[i * 2];
1280  localCutWeights[i] = myWeightOnLine;
1281  continue;
1282  }
1283  }
1284  //when moving right, set lower bound to current line.
1285  cutLowerBounds[i] = /*cutCoordinates[i] + */rightClosestDistance[i];
1286  cutLowerWeight[i] = seenW;
1287 
1288  //compare the upper bound with the current lines.
1289  for (partId_t ii = i + 1; ii < noCuts ; ++ii){
1290  scalar_t pw = globalPartWeights[ii * 2];
1291  scalar_t lw = globalPartWeights[ii * 2 + 1];
1292  if(pw >= ew){
1293  if(pw == ew){
1294 
1295  cutUpperBounds[i] = cutCoordinates[ii];
1296  cutUpperWeight[i] = pw;
1297  cutLowerBounds[i] = cutCoordinates[ii];
1298  cutLowerWeight[i] = pw;
1299  } else if (pw < cutUpperWeight[i]){
1300  //if a cut line is more strict than the current upper bound,
1301  //update the upper bound.
1302  cutUpperBounds[i] = /*cutCoordinates[ii] - */leftClosestDistance[ii];
1303  cutUpperWeight[i] = pw;
1304  }
1305  break;
1306  }
1307  //if comes here then pw < ew
1308  if(lw >= ew){
1309  cutUpperBounds[i] = cutCoordinates[ii];
1310  cutUpperWeight[i] = lw;
1311  cutLowerBounds[i] = cutCoordinates[ii];
1312  cutLowerWeight[i] = pw;
1313  break;
1314  }
1315  //if a stricter lower bound is found,
1316  //update the lower bound.
1317  if (pw <= ew && pw >= cutLowerWeight[i]){
1318  cutLowerBounds[i] = /*cutCoordinates[ii] +*/ rightClosestDistance[ii] ;
1319  cutLowerWeight[i] = pw;
1320  }
1321  }
1322 
1323 
1324  scalar_t newPivot = pivotPos<scalar_t> (cutUpperBounds, cutLowerBounds,i, cutUpperWeight, cutLowerWeight, ew, _EPSILON);
1325 
1326  //if cut line does not move significantly.
1327  if (ABS(cutCoordinates[i] - newPivot) < _EPSILON * EPS_SCALE || cutLowerBounds[i] - cutUpperBounds[i] > _EPSILON/*cutUpperBounds[i] < cutLowerBounds[i]*/){
1328  isDone[i] = true;
1329 #ifdef HAVE_ZOLTAN2_OMP
1330 #pragma omp atomic
1331 #endif
1332  myNoneDoneCount -= 1;
1333  newCutCoordinates [i] = cutCoordinates[i];
1334  } else {
1335  newCutCoordinates [i] = newPivot;
1336  }
1337  } else {
1338 
1339  //moving to left.
1340  scalar_t ew = expected; //globalTotalWeight * expected;
1341  //moving left, set upper to current line.
1342  //cout << "setting upper bound to:" << leftClosestDistance[i] << endl;
1343  cutUpperBounds[i] = /*cutCoordinates[i] -*/ leftClosestDistance[i];
1344  cutUpperWeight[i] = seenW;
1345 
1346  // compare the current cut line weights with previous upper and lower bounds.
1347  for (int ii = i - 1; ii >= 0; --ii){
1348  scalar_t pw = globalPartWeights[ii * 2];
1349  scalar_t lw = globalPartWeights[ii * 2 + 1];
1350  if(pw <= ew){
1351  if(pw == ew){
1352  cutUpperBounds[i] = cutCoordinates[ii];
1353  cutUpperWeight[i] = pw;
1354  cutLowerBounds[i] = cutCoordinates[ii];
1355  cutLowerWeight[i] = pw;
1356  }
1357  else if (pw > cutLowerWeight[i]){
1358  cutLowerBounds[i] = /*cutCoordinates[ii] +*/ rightClosestDistance[ii];
1359  cutLowerWeight[i] = pw;
1360  if(lw > ew){
1361  cutUpperBounds[i] = /*cutCoordinates[ii] +*/ rightClosestDistance[ii];
1362 
1363  cutUpperWeight[i] = lw;
1364  }
1365  }
1366  break;
1367  }
1368  if (pw >= ew && (pw < cutUpperWeight[i] || (pw == cutUpperWeight[i] && cutUpperBounds[i] > /*cutCoordinates[ii] - */leftClosestDistance[ii]))){
1369  cutUpperBounds[i] = /*cutCoordinates[ii] - */leftClosestDistance[ii] ;
1370 
1371  cutUpperWeight[i] = pw;
1372  }
1373  }
1374 
1375  scalar_t newPivot = pivotPos<scalar_t> (cutUpperBounds, cutLowerBounds,i, cutUpperWeight, cutLowerWeight, ew, _EPSILON);
1376  //if cut line does not move significantly.
1377  if (ABS(cutCoordinates[i] - newPivot) < _EPSILON * EPS_SCALE || cutLowerBounds[i] - cutUpperBounds[i] > _EPSILON ){
1378  isDone[i] = true;
1379 
1380 #ifdef HAVE_ZOLTAN2_OMP
1381 #pragma omp atomic
1382 #endif
1383  myNoneDoneCount -= 1;
1384  newCutCoordinates [ i] = cutCoordinates[i];
1385  } else {
1386  newCutCoordinates [ i] = newPivot;
1387  }
1388  }
1389  }
1390 
1391 
1392 
1393  //communication to determine the ratios of processors for the distribution of coordinates on the cut lines.
1394 #ifdef HAVE_ZOLTAN2_OMP
1395  //#pragma omp barrier
1396 #pragma omp single
1397 #endif
1398  {
1399  if(*rectilinearCutCount > 0){
1400  try{
1401  Teuchos::scan<int,scalar_t>(
1402  *comm, Teuchos::REDUCE_SUM,
1403  noCuts,localCutWeights, globalCutWeights
1404  );
1405  }
1407 
1408 
1409  for (partId_t i = 0; i < noCuts; ++i){
1410  //cout << "gw:" << globalCutWeights[i] << endl;
1411  if(globalCutWeights[i] > 0) {
1412  //scalar_t ew = globalTotalWeight * targetPartWeightRatios[i];
1413  scalar_t ew = targetPartWeightRatios[i];
1414  //ew = long (ew * long(1000)) / scalar_t(1000.0);
1415  //globalPartWeights[i * 2] = long(globalPartWeights[i * 2] * long(1000)) / scalar_t (1000);
1416  scalar_t expectedWeightOnLine = ew - globalPartWeights[i * 2];
1417  scalar_t myWeightOnLine = localCutWeights[i];
1418  scalar_t weightOnLineBefore = globalCutWeights[i];
1419  scalar_t incMe = expectedWeightOnLine - weightOnLineBefore;
1420  scalar_t mine = incMe + myWeightOnLine;
1421  if(mine < 0){
1422  nonRectelinearPartRatios[i] = 0;
1423 /*
1424  cout << "setting i" << i <<
1425  " to:" << nonRectelinearPartRatios[i] <<
1426  endl;
1427 */
1428  }
1429  else if(mine >= myWeightOnLine){
1430  //nonRectelinearPartRatios[i] = 1;
1431  nonRectelinearPartRatios[i] = myWeightOnLine;
1432 /*
1433  cout << "setting i" << i <<
1434  " to:" << myWeightOnLine <<
1435  " myWeight= " << nonRectelinearPartRatios[i] <<
1436  endl;
1437 */
1438  }
1439  else {
1440  //nonRectelinearPartRatios[i] = mine / myWeightOnLine;
1441  nonRectelinearPartRatios[i] = mine ;
1442 /*
1443  cout << "setting i" << i <<
1444  " to:" << mine <<
1445  " mine= " << nonRectelinearPartRatios[i] <<
1446  " expectedWeightOnLine:" << expectedWeightOnLine <<
1447  " ratio:" << targetPartWeightRatios[i] <<
1448  " ew:" << ew << " globalPartWeights[i * 2]:" << globalPartWeights[i * 2] <<
1449  " weightOnLineBefore:" << weightOnLineBefore <<
1450  " incMe:" << incMe <<
1451  " mine:" << mine <<
1452  endl;
1453 */
1454  }
1455 
1456  }
1457  }
1458  *rectilinearCutCount = 0;
1459  }
1460  }
1461 }
1462 
1463 
1492 template <typename scalar_t, typename lno_t>
1494  size_t total_part_count,
1495  partId_t noCuts,
1496  scalar_t maxCoordinate,
1497  scalar_t minCoordinate,
1498  scalar_t _EPSILON,
1499  int numThreads,
1500  lno_t coordinateBegin,
1501  lno_t coordinateEnd,
1502  lno_t *partitionedPointPermutations,
1503  scalar_t *pqJagged_coordinates,
1504  bool pqJagged_uniformWeights,
1505  scalar_t *pqJagged_weights,
1506 
1507  scalar_t *cutCoordinates_tmp, //TODO change name
1508  bool *isDone,
1509  double *myPartWeights,
1510  scalar_t *myLeftClosest,
1511  scalar_t *myRightClosest,
1512  bool useBinarySearch,
1513  partId_t *partIds
1514 ){
1515 
1516  // initializations for part weights, left/right closest
1517  for (size_t i = 0; i < total_part_count; ++i){
1518  myPartWeights[i] = 0;
1519  }
1520 
1521 
1522  for(partId_t i = 0; i < noCuts; ++i){
1523  //if(isDone[i]) continue;
1524  //myLeftClosest[i] = maxScalar;
1525  myLeftClosest[i] = minCoordinate - 1;
1526  myRightClosest[i] = maxCoordinate + 1;
1527  }
1528  if(useBinarySearch){
1529 
1530  //lno_t comparison_count = 0;
1531  scalar_t minus_EPSILON = -_EPSILON;
1532 #ifdef HAVE_ZOLTAN2_OMP
1533 //no need for the barrier as all threads uses their local memories.
1534 #pragma omp for
1535 #endif
1536  for (lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
1537  int i = partitionedPointPermutations[ii];
1538  partId_t j = partIds[i] / 2;
1539 
1540 
1541  if(j >= noCuts){
1542  j = noCuts - 1;
1543  }
1544 
1545  partId_t lc = 0;
1546  partId_t uc = noCuts - 1;
1547 
1548  scalar_t w = pqJagged_uniformWeights? 1:pqJagged_weights[i];
1549  bool isInserted = false;
1550  bool onLeft = false;
1551  bool onRight = false;
1552  partId_t lastPart = -1;
1553 
1554  scalar_t coord = pqJagged_coordinates[i];
1555 
1556  while(uc >= lc)
1557  {
1558  //comparison_count++;
1559  lastPart = -1;
1560  onLeft = false;
1561  onRight = false;
1562  scalar_t cut = cutCoordinates_tmp[j];
1563  scalar_t distance = coord - cut;
1564  scalar_t absdistance = ABS(distance);
1565 
1566  if(absdistance < _EPSILON){
1567 
1568  myPartWeights[j * 2 + 1] += w;
1569  partIds[i] = j * 2 + 1;
1570  //cout << "\ti:" << i << " assigned:" << j * 2 + 1 << endl;
1571 
1572  myLeftClosest[j] = coord;
1573  myRightClosest[j] = coord;
1574  partId_t kk = j + 1;
1575  while(kk < noCuts){
1576  // Needed when cuts shared the same position
1577  // kddnote Can this loop be disabled for RECTILINEAR BLOCKS?
1578  // kddnote Mehmet says it is probably needed anyway.
1579  distance =ABS(cutCoordinates_tmp[kk] - cut);
1580  if(distance < _EPSILON){
1581  myPartWeights[2 * kk + 1] += w;
1582 
1583  myLeftClosest[kk] = coord;
1584  myRightClosest[kk] = coord;
1585  kk++;
1586  }
1587  else{
1588  if(coord - myLeftClosest[kk] > _EPSILON){
1589  myLeftClosest[kk] = coord;
1590  }
1591  break;
1592  }
1593  }
1594 
1595  kk = j - 1;
1596  while(kk >= 0){
1597  distance =ABS(cutCoordinates_tmp[kk] - cut);
1598  if(distance < _EPSILON){
1599  myPartWeights[2 * kk + 1] += w;
1600 
1601  //try to write the partId as the leftmost cut.
1602  partIds[i] = kk * 2 + 1;
1603  myLeftClosest[kk] = coord;
1604  myRightClosest[kk] = coord;
1605  kk--;
1606  }
1607  else{
1608  if(myRightClosest[kk] - coord > _EPSILON){
1609  myRightClosest[kk] = coord;
1610  }
1611  break;
1612  }
1613  }
1614 
1615 
1616 
1617  isInserted = true;
1618  break;
1619  }
1620  else {
1621  if (distance < 0) {
1622  /*
1623  if (myLeftClosest[j] > distance){
1624  myLeftClosest[j] = distance;
1625  }
1626  */
1627  bool _break = false;
1628  if(j > 0){
1629  distance = coord - cutCoordinates_tmp[j - 1];
1630  if(distance > _EPSILON){
1631  /*
1632  if (myRightClosest[j - 1] > distance){
1633  myRightClosest[j - 1] = distance;
1634  }
1635  */
1636  _break = true;
1637  }
1638  /*
1639  else if(distance < minus_EPSILON){
1640  distance = -distance;
1641  if (myLeftClosest[j - 1] > distance){
1642  myLeftClosest[j - 1] = distance;
1643  }
1644  }
1645  else {
1646  myLeftClosest[j - 1] = 0;
1647  myRightClosest[j - 1 ] = 0;
1648  }*/
1649  }
1650  uc = j - 1;
1651  onLeft = true;
1652  lastPart = j;
1653  if(_break) break;
1654  }
1655  else {
1656  /*
1657  if (myRightClosest[j] > distance){
1658  myRightClosest[j] = distance;
1659  }
1660  */
1661  bool _break = false;
1662  if(j < noCuts - 1){
1663  scalar_t distance_ = coord - cutCoordinates_tmp[j + 1];
1664  /*
1665  if(distance > _EPSILON){
1666  if (myRightClosest[j + 1] > distance){
1667  myRightClosest[j + 1] = distance;
1668  }
1669  } else */if(distance_ < minus_EPSILON){
1670  /*
1671  distance = -distance;
1672  if (myLeftClosest[j + 1] > distance){
1673  myLeftClosest[j + 1] = distance;
1674  }*/
1675  _break = true;
1676  }
1677  /*
1678  else {
1679  myLeftClosest[j + 1] = 0;
1680  myRightClosest[j + 1 ] = 0;
1681  }
1682  */
1683  }
1684  lc = j + 1;
1685  onRight = true;
1686  lastPart = j;
1687  if(_break) break;
1688  }
1689  }
1690 
1691  j = (uc + lc) / 2;
1692  }
1693  if(!isInserted){
1694  if(onRight){
1695 
1696 
1697  //cout << "\ti:" << i << " assigned:" << 2 * lastPart + 2 << endl;
1698  myPartWeights[2 * lastPart + 2] += w;
1699  partIds[i] = 2 * lastPart + 2;
1700  //scalar_t distance = coord - cutCoordinates_tmp[lastPart];
1701  if(myRightClosest[lastPart] - coord > _EPSILON){
1702  myRightClosest[lastPart] = coord;
1703  }
1704  if(lastPart+1 < noCuts){
1705  //scalar_t distance_ = cutCoordinates_tmp[lastPart + 1] - coord;
1706  if(coord - myLeftClosest[lastPart + 1] > _EPSILON){
1707  myLeftClosest[lastPart + 1] = coord;
1708  }
1709  }
1710 
1711  }
1712  else if(onLeft){
1713  //cout << "\ti:" << i << " assigned:" << 2 * lastPart << endl;
1714  myPartWeights[2 * lastPart] += w;
1715  partIds[i] = 2 * lastPart;
1716  //scalar_t distance = cutCoordinates_tmp[lastPart ] - coord;
1717  if(coord - myLeftClosest[lastPart] > _EPSILON){
1718  myLeftClosest[lastPart] = coord;
1719  }
1720 
1721  if(lastPart-1 >= 0){
1722  //scalar_t distance_ = coord - cutCoordinates_tmp[lastPart - 1];
1723  if(myRightClosest[lastPart -1] - coord > _EPSILON){
1724  myRightClosest[lastPart -1] = coord;
1725  }
1726  }
1727  }
1728  }
1729  }
1730  }
1731  else {
1732 
1733 #ifdef HAVE_ZOLTAN2_OMP
1734 #pragma omp for
1735 #endif
1736  for (lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
1737  int i = partitionedPointPermutations[ii];
1738 
1739  scalar_t w = pqJagged_uniformWeights ? 1 : pqJagged_weights[i];
1740 
1741  scalar_t coord = pqJagged_coordinates[i];
1742 
1743  partId_t j = partIds[i] / 2;
1744 
1745  if(j >= noCuts){
1746  j = noCuts - 1;
1747  }
1748  scalar_t cut = cutCoordinates_tmp[j];
1749  scalar_t distance = coord - cut;
1750  scalar_t absdistance = ABS(distance);
1751 
1752  //comp++;
1753  if(absdistance < _EPSILON){
1754  myPartWeights[j * 2 + 1] += w;
1755 
1756  myLeftClosest[j] = 0;
1757  myRightClosest[j] = 0;
1758  partIds[i] = j * 2 + 1;
1759 
1760  //bas
1761  partId_t kk = j + 1;
1762  while(kk < noCuts){ // Needed when cuts shared the same position
1763  // kddnote Can this loop be disabled for RECTILINEAR BLOCKS?
1764  // kddnote Mehmet says it is probably needed anyway.
1765  distance =ABS(cutCoordinates_tmp[kk] - cut);
1766  if(distance < _EPSILON){
1767  //cout << "yo" << endl;
1768  myPartWeights[2 * kk + 1] += w;
1769 
1770  //cout << "2to part:" << 2*kk+1 << " coord:" << coord << endl;
1771  myLeftClosest[kk] = 0;
1772  myRightClosest[kk] = 0;
1773  kk++;
1774  }
1775  else{
1776  if(myLeftClosest[kk] > distance){
1777  myLeftClosest[kk] = distance;
1778  }
1779  break;
1780  }
1781  }
1782 
1783  kk = j - 1;
1784  while(kk >= 0){
1785  distance =ABS(cutCoordinates_tmp[kk] - cut);
1786  if(distance < _EPSILON){
1787  myPartWeights[2 * kk + 1] += w;
1788  //cout << "3to part:" << 2*kk+1 << " coord:" << coord << endl;
1789 
1790  myLeftClosest[kk] = 0;
1791  myRightClosest[kk] = 0;
1792  kk--;
1793  }
1794  else{
1795  if(myRightClosest[kk] > distance){
1796  myRightClosest[kk] = distance;
1797  }
1798  break;
1799  }
1800  }
1801  }
1802  else if (distance < 0) {
1803  while((absdistance > _EPSILON) && distance < 0){
1804  //comp++;
1805  if (myLeftClosest[j] > absdistance){
1806  myLeftClosest[j] = absdistance;
1807  }
1808  --j;
1809  if(j < 0) break;
1810  distance = coord - cutCoordinates_tmp[j];
1811 
1812  absdistance = ABS(distance);
1813  }
1814  if(absdistance < _EPSILON)
1815  {
1816  myPartWeights[j * 2 + 1] += w;
1817  myLeftClosest[j] = 0;
1818  myRightClosest[j] = 0;
1819  cut = cutCoordinates_tmp[j];
1820  //cout << "4to part:" << 2*j+1 <<" j:" << j << " coord:" << coord << endl;
1821  //cout << "cut:" << cutCoordinates_tmp[j] << " dis:" << distance << endl;
1822  partIds[i] = j * 2 + 1;
1823 
1824  partId_t kk = j + 1;
1825  while(kk < noCuts){ // Needed when cuts shared the same position
1826  // kddnote Can this loop be disabled for RECTILINEAR BLOCKS?
1827  // kddnote Mehmet says it is probably needed anyway.
1828  distance =ABS(cutCoordinates_tmp[kk] - cut);
1829  //cout << "distance:" << distance << endl;
1830  if(distance < _EPSILON){
1831  myPartWeights[2 * kk + 1] += w;
1832  //cout << "5to part:" << 2*kk+1 << " kk:" << kk << " coord:" << coord << endl;
1833  //cout << "cut:" << cutCoordinates_tmp[kk] << " dis:" << distance << endl;
1834  myLeftClosest[kk] = 0;
1835  myRightClosest[kk] = 0;
1836  kk++;
1837  }
1838  else{
1839  if(myLeftClosest[kk] > distance){
1840  myLeftClosest[kk] = distance;
1841  }
1842  break;
1843  }
1844  }
1845 
1846  kk = j - 1;
1847  while(kk >= 0){
1848  distance =ABS(cutCoordinates_tmp[kk] - cut);
1849  if(distance < _EPSILON){
1850  myPartWeights[2 * kk + 1] += w;
1851  //cout << "6to part:" << 2*kk+1 << " coord:" << coord << endl;
1852  //cout << "cut:" << cutCoordinates_tmp[kk] << " dis:" << distance << endl;
1853 
1854  myLeftClosest[kk] = 0;
1855  myRightClosest[kk] = 0;
1856  kk--;
1857  }
1858  else{
1859  if(myRightClosest[kk] > distance){
1860  myRightClosest[kk] = distance;
1861  }
1862  break;
1863  }
1864  }
1865  }
1866  else {
1867  myPartWeights[j * 2 + 2] += w;
1868  if (j >= 0 && myRightClosest[j] > absdistance){
1869  myRightClosest[j] = absdistance;
1870  }
1871  partIds[i] = j * 2 + 2;
1872  }
1873 
1874  }
1875  //if it is on the left
1876  else {
1877 
1878  while((absdistance > _EPSILON) && distance > 0){
1879  //comp++;
1880  if ( myRightClosest[j] > absdistance){
1881  myRightClosest[j] = absdistance;
1882  }
1883  ++j;
1884  if(j >= noCuts) break;
1885  distance = coord - cutCoordinates_tmp[j];
1886  absdistance = ABS(distance);
1887  }
1888 
1889 
1890 
1891  if(absdistance < _EPSILON)
1892  {
1893  myPartWeights[j * 2 + 1] += w;
1894  myLeftClosest[j] = 0;
1895  myRightClosest[j] = 0;
1896  partIds[i] = j * 2 + 1;
1897  cut = cutCoordinates_tmp[j];
1898  partId_t kk = j + 1;
1899  while(kk < noCuts){ // Needed when cuts shared the same position
1900  // kddnote Can this loop be disabled for RECTILINEAR BLOCKS?
1901  // kddnote Mehmet says it is probably needed anyway.
1902  distance =ABS(cutCoordinates_tmp[kk] - cut);
1903  if(distance < _EPSILON){
1904  myPartWeights[2 * kk + 1] += w;
1905  myLeftClosest[kk] = 0;
1906  myRightClosest[kk] = 0;
1907  kk++;
1908  }
1909  else{
1910  if(myLeftClosest[kk] > distance){
1911  myLeftClosest[kk] = distance;
1912  }
1913  break;
1914  }
1915  }
1916 
1917  kk = j - 1;
1918  while(kk >= 0){
1919  distance =ABS(cutCoordinates_tmp[kk] - cut);
1920  if(distance < _EPSILON){
1921  myPartWeights[2 * kk + 1] += w;
1922 
1923  myLeftClosest[kk] = 0;
1924  myRightClosest[kk] = 0;
1925  kk--;
1926  }
1927  else{
1928  if(myRightClosest[kk] > distance){
1929  myRightClosest[kk] = distance;
1930  }
1931  break;
1932  }
1933  }
1934  }
1935  else {
1936  myPartWeights[j * 2] += w;
1937  if (j < noCuts && myLeftClosest[j] > absdistance){
1938  myLeftClosest[j] = absdistance;
1939  }
1940  partIds[i] = j * 2 ;
1941  }
1942  }
1943  }
1944 
1945  /*
1946 #ifdef HAVE_ZOLTAN2_OMP
1947 #pragma omp for
1948 #endif
1949 for (lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
1950 int i = partitionedPointPermutations[ii];
1951 
1952 scalar_t w = pqJagged_uniformWeights? 1:pqJagged_weights[i];
1953 //get a coordinate and compare it with cut lines from left to right.
1954 for(partId_t j = 0; j < noCuts; ++j){
1955 
1956 if(isDone[j]) continue;
1957 scalar_t distance = pqJagged_coordinates[i] - cutCoordinates_tmp[j];
1958 scalar_t absdistance = ABS(distance);
1959 if(absdistance < _EPSILON){
1960 myPartWeights[j * 2] -= w;
1961 //myPartWeights[j * 2] += w;
1962 myLeftClosest[j] = 0;
1963 myRightClosest[j] = 0;
1964 //break;
1965 }
1966 else
1967 if (distance < 0) {
1968 distance = -distance;
1969 if (myLeftClosest[j] > distance){
1970 myLeftClosest[j] = distance;
1971 }
1972 break;
1973 }
1974 //if it is on the left
1975 else {
1976  //if on the right, continue with the next line.
1977  myPartWeights[j * 2] -= w;
1978  myPartWeights[j * 2 + 1] -= w;
1979  //myPartWeights[j * 2] += w;
1980  //myPartWeights[j * 2 + 1] += w;
1981 
1982  if ( myRightClosest[j] > distance){
1983  myRightClosest[j] = distance;
1984  }
1985  }
1986  }
1987  }
1988  */
1989 
1990  }
1991 
1992  // prefix sum computation.
1993  for (size_t i = 1; i < total_part_count; ++i){
1994  // if check for cuts sharing the same position; all cuts sharing a position
1995  // have the same weight == total weight for all cuts sharing the position.
1996  // don't want to accumulate that total weight more than once.
1997  if(i % 2 == 0 && i > 1 && i < total_part_count - 1 &&
1998  ABS(cutCoordinates_tmp[i / 2] - cutCoordinates_tmp[i /2 - 1]) < _EPSILON){
1999  myPartWeights[i] = myPartWeights[i-2];
2000  continue;
2001  }
2002  myPartWeights[i] += myPartWeights[i-1];
2003  }
2004 }
2005 
2006 
2021 template <typename scalar_t>
2023  const vector <partId_t> &pVector,
2024  partId_t vBegin,
2025 
2026  partId_t concurrentPartCount,
2027  int numThreads,
2028  bool *isDone,
2029  scalar_t **leftClosestPoints,
2030  scalar_t **rightClosestPoints,
2031  double **partWeights,
2032  //scalar_t *localMinMaxTotal,
2033  scalar_t *totalPartWeights_leftClosest_rightCloset
2034 
2035 ){
2036 #ifdef HAVE_ZOLTAN2_OMP
2037 //needs barrier here, as it requires all threads to finish pqJagged_1DPart_getPartWeights
2038 #pragma omp barrier
2039 #pragma omp single
2040 #endif
2041  {
2042  size_t tlr_shift = 0;
2043  partId_t cut_shift = 0;
2044  for(partId_t i = 0; i < concurrentPartCount; ++i){
2045 
2046  partId_t partNo = pVector[vBegin + i];
2047  partId_t noCuts = partNo - 1;
2048  size_t total_part_count = partNo + size_t (noCuts) ;
2049 
2050  for(partId_t ii = 0; ii < noCuts ; ++ii){
2051  partId_t next = tlr_shift + ii;
2052  partId_t nCut = cut_shift + ii;
2053  if(isDone[nCut]) continue;
2054  scalar_t minl = leftClosestPoints[0][nCut], minr = rightClosestPoints[0][nCut];
2055 
2056  for (int j = 1; j < numThreads; ++j){
2057  if (rightClosestPoints[j][nCut] < minr ){
2058  minr = rightClosestPoints[j][nCut];
2059  }
2060  if (leftClosestPoints[j][nCut] > minl ){
2061  minl = leftClosestPoints[j][nCut];
2062  }
2063  }
2064  totalPartWeights_leftClosest_rightCloset[total_part_count + next] = minl;
2065  totalPartWeights_leftClosest_rightCloset[total_part_count + noCuts + next] = minr;
2066  }
2067  tlr_shift += (total_part_count + 2 * noCuts);
2068  cut_shift += noCuts;
2069  }
2070 
2071  tlr_shift = 0;
2072  cut_shift = 0;
2073  size_t totalPartShift = 0;
2074 
2075  for(partId_t i = 0; i < concurrentPartCount; ++i){
2076 
2077  partId_t partNo = pVector[vBegin + i];
2078  partId_t noCuts = partNo - 1;
2079  size_t total_part_count = partNo + size_t (noCuts) ;
2080 
2081  for(size_t j = 0; j < total_part_count; ++j){
2082 
2083  partId_t cutInd = j / 2 + cut_shift;
2084 
2085  if(j != total_part_count - 1 && isDone[cutInd]) continue;
2086  double pwj = 0;
2087  for (int k = 0; k < numThreads; ++k){
2088  pwj += partWeights[k][totalPartShift + j];
2089  }
2090  //size_t jshift = j % total_part_count + i * (total_part_count + 2 * noCuts);
2091  totalPartWeights_leftClosest_rightCloset[tlr_shift + j] = pwj;
2092  }
2093  cut_shift += noCuts;
2094  tlr_shift += total_part_count + 2 * noCuts;
2095  totalPartShift += total_part_count;
2096  }
2097  }
2098 }
2099 
2100 
2101 
2102 
2147 template <typename scalar_t, typename lno_t>
2149  const RCP<const Environment> &env,
2150  RCP<Comm<int> > &comm,
2151 
2152  lno_t *partitionedPointPermutations,
2153  scalar_t *pqJagged_coordinates,
2154  bool pqJagged_uniformWeights,
2155  scalar_t *pqJagged_weights,
2156 
2157  scalar_t *targetPartWeightRatios, // the weight ratios at left side of the cuts. last is 1.
2158  scalar_t *globalMinMaxTotal,
2159  scalar_t *localMinMaxTotal,
2160 
2161  int numThreads,
2162  //scalar_t maxScalar,
2163  //scalar_t minScalar,
2164  scalar_t imbalanceTolerance,
2165  partId_t currentPartBeginIndex,
2166  partId_t concurrentPartCount,
2167  lno_t *inTotalCounts,
2168 
2169  scalar_t *cutCoordinates,
2170  scalar_t *cutCoordinatesWork, // work array to manipulate coordinate of cutlines in different iterations.
2171  scalar_t **leftClosestDistance,
2172  scalar_t **rightClosestDistance,
2173  scalar_t *cutUpperBounds, //to determine the next cut line with binary search
2174  scalar_t *cutLowerBounds, //to determine the next cut line with binary search
2175  scalar_t *cutUpperWeight, //to determine the next cut line with binary search
2176  scalar_t *cutLowerWeight, //to determine the next cut line with binary search
2177  bool *isDone,
2178  double **partWeights,
2179  scalar_t *local_totalPartWeights_leftClosest_rightCloset,
2180  scalar_t *global_totalPartWeights_leftClosest_rightCloset,
2181  bool allowNonRectelinearPart,
2182  float *nonRectelinearPartRatios,
2183  scalar_t *localCutWeights,
2184  scalar_t *globalCutWeights,
2185 
2186  partId_t allDone,
2187  partId_t *myNonDoneCounts,
2188  bool useBinarySearch,
2189 
2190  partId_t * partIds,
2191  vector <partId_t> &pVector
2192 ){
2193 
2194  partId_t recteLinearCutCount = 0;
2195  scalar_t *cutCoordinates_tmp = cutCoordinates;
2196 
2197 
2198 #ifdef mpi_communication
2199  MPI_Op myop;
2200  MPI_Op_create(sumMinMin, 0, &myop); /* step 3 */
2201 #endif
2202 
2203 
2204  scalar_t _EPSILON = numeric_limits<scalar_t>::epsilon();
2205 
2207  reductionOp = new Teuchos::PQJaggedCombinedReductionOp<partId_t, scalar_t>(&pVector , currentPartBeginIndex , concurrentPartCount);
2208 
2209 
2210  size_t totalReductionSize = 0;
2211 #ifdef HAVE_ZOLTAN2_OMP
2212 #pragma omp parallel shared(allDone, recteLinearCutCount)
2213 #endif
2214  {
2215  int me = 0;
2216 #ifdef HAVE_ZOLTAN2_OMP
2217  me = omp_get_thread_num();
2218 #endif
2219  double *myPartWeights = partWeights[me];
2220  scalar_t *myLeftClosest = leftClosestDistance[me];
2221  scalar_t *myRightClosest = rightClosestDistance[me];
2222 
2223 #ifdef HAVE_ZOLTAN2_OMP
2224 #pragma omp single
2225 #endif
2226  {
2227  //initialize the lower and upper bounds of the cuts.
2228  partId_t next = 0;
2229  for(partId_t i = 0; i < concurrentPartCount; ++i){
2230 
2231  partId_t partNo = pVector[currentPartBeginIndex + i];
2232  partId_t noCuts = partNo - 1;
2233  totalReductionSize += (4 * noCuts + 1);
2234 
2235  for(partId_t ii = 0; ii < noCuts; ++ii){
2236  isDone[next] = false;
2237  cutLowerBounds[next] = globalMinMaxTotal[i]; //min coordinate
2238  cutUpperBounds[next] = globalMinMaxTotal[i + concurrentPartCount]; //max coordinate
2239 
2240  cutUpperWeight[next] = globalMinMaxTotal[i + 2 * concurrentPartCount]; //total weight
2241  cutLowerWeight[next] = 0;
2242 
2243  if(allowNonRectelinearPart){
2244  nonRectelinearPartRatios[next] = 0;
2245  }
2246  ++next;
2247  }
2248  }
2249  }
2250 
2251  //no need to have barrier here.
2252  //pragma omp single have implicit barrier.
2253 
2254  int iteration = 0;
2255  while (allDone != 0){
2256  iteration += 1;
2257  partId_t cutShifts = 0;
2258  size_t totalPartShift = 0;
2259 
2260 
2261  for (partId_t kk = 0; kk < concurrentPartCount; ++kk){
2262  partId_t partNo = -1;
2263  partNo = pVector[currentPartBeginIndex + kk];
2264 
2265 
2266 
2267  //cout << "p:" << partNo << endl;
2268  partId_t noCuts = partNo - 1;
2269  size_t total_part_count = partNo + size_t (noCuts) ;
2270  if (myNonDoneCounts[kk] > 0){
2271 
2272  //although isDone shared, currentDone is private and same for all.
2273  bool *currentDone = isDone + cutShifts;
2274  double *myCurrentPartWeights = myPartWeights + totalPartShift;
2275  scalar_t *myCurrentLeftClosest = myLeftClosest + cutShifts;
2276  scalar_t *myCurrentRightClosest = myRightClosest + cutShifts;
2277 
2278  partId_t current = currentPartBeginIndex + kk;
2279  lno_t coordinateBegin = current ==0 ? 0: inTotalCounts[current -1];
2280  lno_t coordinateEnd = inTotalCounts[current];
2281  scalar_t *cutCoordinates_ = cutCoordinates_tmp + cutShifts;
2282 
2283  scalar_t minCoordinate = globalMinMaxTotal[kk];
2284  scalar_t maxCoordinate = globalMinMaxTotal[kk + concurrentPartCount];
2285 
2286  // compute part weights using existing cuts
2287  pqJagged_1DPart_getPartWeights<scalar_t, lno_t>(
2288  total_part_count,
2289  noCuts,
2290  maxCoordinate,//globalMinMaxTotal[kk + concurrentPartCount],//maxScalar,
2291  minCoordinate,//globalMinMaxTotal[kk]//minScalar,
2292  _EPSILON,
2293  numThreads,
2294  coordinateBegin,
2295  coordinateEnd,
2296  partitionedPointPermutations,
2297  pqJagged_coordinates,
2298  pqJagged_uniformWeights,
2299  pqJagged_weights,
2300  cutCoordinates_,
2301  currentDone,
2302  myCurrentPartWeights,
2303  myCurrentLeftClosest,
2304  myCurrentRightClosest,
2305  useBinarySearch,
2306  partIds);
2307 
2308 
2309  }
2310 
2311  cutShifts += noCuts;
2312  totalPartShift += total_part_count;
2313  }
2314 
2315  //sum up the results of threads
2316  accumulateThreadResults<scalar_t>(
2317  pVector,
2318  currentPartBeginIndex,
2319  concurrentPartCount,
2320  numThreads, isDone,
2321  leftClosestDistance, rightClosestDistance, partWeights,
2322  //localMinMaxTotal,
2323  local_totalPartWeights_leftClosest_rightCloset
2324  );
2325  /*
2326 #pragma omp single
2327  {
2328  int cutShifts = 0;
2329  int partNo = pVector[currentPartBeginIndex];
2330  cout << "iteration:" << iteration << endl;
2331 
2332  scalar_t *cutCoordinates_ = cutCoordinates_tmp + cutShifts;
2333  scalar_t *myCurrentLeftClosest = myLeftClosest + cutShifts;
2334  scalar_t *myCurrentRightClosest = myRightClosest + cutShifts;
2335  bool *currentDone = isDone + cutShifts;
2336 
2337  for (int i = 0; i < partNo - 1; ++i){
2338  if (currentDone[i]){
2339  cout << "\tcut:" << i << " c:" << cutCoordinates_[i] <<
2340  " lc:" << local_totalPartWeights_leftClosest_rightCloset[2 * partNo - 1 + i] <<
2341  " rc:" << local_totalPartWeights_leftClosest_rightCloset[partNo - 1 + 2 * partNo - 1 + i]<<
2342  " w:" << local_totalPartWeights_leftClosest_rightCloset[2 * i]<<
2343  " done" <<endl;
2344  }else {
2345 
2346  cout << "\tcut:" << i << " c:" << cutCoordinates_[i] <<
2347  " lc:" << local_totalPartWeights_leftClosest_rightCloset[2 * partNo - 1 + i] <<
2348  " rc:" << local_totalPartWeights_leftClosest_rightCloset[partNo - 1 + 2 * partNo - 1 + i]<<
2349  " w:" << local_totalPartWeights_leftClosest_rightCloset[2 * i]<<
2350  " not done" << endl;
2351  }
2352  }
2353  }
2354  */
2355  //now sum up the results of mpi processors.
2356 #ifdef HAVE_ZOLTAN2_OMP
2357 #pragma omp single
2358 #endif
2359  {
2360  if(comm->getSize() > 1){
2361  try{
2362 #ifdef mpi_communication
2363 
2364  MPI_Allreduce(local_totalPartWeights_leftClosest_rightCloset, global_totalPartWeights_leftClosest_rightCloset,
2365 
2366  (total_part_count + 2 * noCuts) * concurrentPartCount, MPI_FLOAT, myop,MPI_COMM_WORLD);
2367 #endif
2368 #ifndef mpi_communication
2369 
2370  reduceAll<int, scalar_t>(
2371  *comm,
2372  *reductionOp,
2373  totalReductionSize,
2374  local_totalPartWeights_leftClosest_rightCloset,
2375  global_totalPartWeights_leftClosest_rightCloset
2376  );
2377 #endif
2378  }
2380  }
2381  else {
2382  memcpy(global_totalPartWeights_leftClosest_rightCloset,
2383  local_totalPartWeights_leftClosest_rightCloset,
2384  totalReductionSize * sizeof(scalar_t)
2385  );
2386  }
2387  }
2388  partId_t cutShift = 0;
2389  size_t tlrShift = 0;
2390  for (partId_t kk = 0; kk < concurrentPartCount; ++kk){
2391  partId_t partNo = -1;
2392  partNo = pVector[currentPartBeginIndex + kk];
2393 
2394  partId_t noCuts = partNo - 1;
2395  size_t total_part_count = partNo + size_t (noCuts) ;
2396 
2397  if (myNonDoneCounts[kk] == 0) {
2398  cutShift += noCuts;
2399  tlrShift += (total_part_count + 2 * noCuts);
2400  continue;
2401  }
2402 
2403  scalar_t *localPartWeights = local_totalPartWeights_leftClosest_rightCloset + tlrShift ;
2404  scalar_t *gtlr = global_totalPartWeights_leftClosest_rightCloset + tlrShift;
2405  scalar_t *glc = gtlr + total_part_count; //left closest points
2406  scalar_t *grc = gtlr + total_part_count + noCuts; //right closest points
2407  scalar_t *globalPartWeights = gtlr;
2408  bool *currentDone = isDone + cutShift;
2409 
2410  scalar_t *currentTargetPartWeightRatios = targetPartWeightRatios + cutShift + kk;
2411  float *currentnonRectelinearPartRatios = nonRectelinearPartRatios + cutShift;
2412 
2413  scalar_t minCoordinate = globalMinMaxTotal[kk];
2414  scalar_t maxCoordinate = globalMinMaxTotal[kk + concurrentPartCount];
2415  scalar_t globalTotalWeight = globalMinMaxTotal[kk + concurrentPartCount * 2];
2416  scalar_t *currentcutLowerWeight = cutLowerWeight + cutShift;
2417  scalar_t *currentcutUpperWeight = cutUpperWeight + cutShift;
2418  scalar_t *currentcutUpperBounds = cutUpperBounds + cutShift;
2419  scalar_t *currentcutLowerBounds = cutLowerBounds + cutShift;
2420 
2421  partId_t prevDoneCount = myNonDoneCounts[kk];
2422 
2423  // Now compute the new cut coordinates.
2424  getNewCoordinates<scalar_t>(
2425  env,
2426  comm,
2427  total_part_count,
2428  noCuts,
2429  maxCoordinate,
2430  minCoordinate,
2431  globalTotalWeight,
2432  imbalanceTolerance,
2433  //maxCoordinate,//globalMinMaxTotal[kk + concurrentPartCount],//maxScalar,
2434  //minCoordinate,//globalMinMaxTotal[kk],//minScalar,
2435  globalPartWeights,
2436  localPartWeights,
2437  currentTargetPartWeightRatios,
2438  currentDone,
2439 
2440  cutCoordinates_tmp + cutShift,
2441  currentcutUpperBounds,
2442  currentcutLowerBounds,
2443  glc,
2444  grc,
2445  currentcutLowerWeight,
2446  currentcutUpperWeight,
2447  cutCoordinatesWork +cutShift, //new cut coordinates
2448 
2449  allowNonRectelinearPart,
2450  currentnonRectelinearPartRatios,
2451  &recteLinearCutCount,
2452  localCutWeights,
2453  globalCutWeights,
2454  myNonDoneCounts[kk]
2455  );
2456 
2457  cutShift += noCuts;
2458  tlrShift += (total_part_count + 2 * noCuts);
2459  partId_t reduction = prevDoneCount - myNonDoneCounts[kk];
2460 #ifdef HAVE_ZOLTAN2_OMP
2461 //#pragma omp barrier
2462 //ne need for the barrier as getNewCoordinates function have a implicit barrier at the end.
2463 #pragma omp single
2464 #endif
2465  {
2466  allDone -= reduction;
2467  }
2468 
2469  }
2470 #ifdef HAVE_ZOLTAN2_OMP
2471 #pragma omp barrier
2472 #pragma omp single
2473 #endif
2474  {
2475  scalar_t *t = cutCoordinates_tmp;
2476  cutCoordinates_tmp = cutCoordinatesWork;
2477  cutCoordinatesWork = t;
2478  }
2479  }
2480  /*
2481  if(comm->getRank() == 0)
2482  if(me == 0) cout << "it:" << iteration << endl;
2483  */
2484  // Needed only if keep_cuts; otherwise can simply swap array pointers
2485  // cutCoordinates and cutCoordinatesWork.
2486  // (at first iteration, cutCoordinates == cutCoorindates_tmp).
2487  // computed cuts must be in cutCoordinates.
2488  if (cutCoordinates != cutCoordinates_tmp){
2489 #ifdef HAVE_ZOLTAN2_OMP
2490 #pragma omp single
2491 #endif
2492  {
2493  partId_t next = 0;
2494  for(partId_t i = 0; i < concurrentPartCount; ++i){
2495  partId_t partNo = -1;
2496  partNo = pVector[currentPartBeginIndex + i];
2497  //cout << "kk:" << " partition - 5:" << partNo << endl;
2498  partId_t noCuts = partNo - 1;
2499  for(partId_t ii = 0; ii < noCuts; ++ii){
2500  cutCoordinates[next + ii] = cutCoordinates_tmp[next + ii];
2501  }
2502  next += noCuts;
2503  }
2504  }
2505 
2506 #ifdef HAVE_ZOLTAN2_OMP
2507 #pragma omp single
2508 #endif
2509  {
2510  cutCoordinatesWork = cutCoordinates_tmp;
2511  }
2512  }
2513  }
2514  delete reductionOp;
2515 }
2516 
2517 
2518 
2519 template <typename T>
2520 T *allocMemory(size_t size){
2521  if (size > 0){
2522  T * a = new T[size];
2523  if (a == NULL) {
2524  throw "cannot allocate memory";
2525  }
2526  return a;
2527  }
2528  else {
2529  return NULL;
2530  }
2531 }
2532 
2533 template <typename T>
2534 void freeArray(T *&array){
2535  if(array != NULL){
2536  delete [] array;
2537  array = NULL;
2538  }
2539 }
2540 
2541 
2542 
2543 template <typename tt>
2544 std::string toString(tt obj){
2545  std::stringstream ss (std::stringstream::in |std::stringstream::out);
2546  ss << obj;
2547  std::string tmp = "";
2548  ss >> tmp;
2549  return tmp;
2550 }
2551 
2552 
2553 
2554 
2555 
2556 template <typename IT, typename CT, typename WT>
2558 {
2559 public:
2560  IT index;
2561  CT count;
2562  //unsigned int val;
2563  WT *val;
2565 
2567  this->index = 0;
2568  this->count = 0;
2569  this->val = NULL;
2570  this->_EPSILON = numeric_limits<WT>::epsilon();
2571  }
2572 
2573 
2574  uMultiSortItem(IT index_ ,CT count_, WT *vals_){
2575  this->index = index_;
2576  this->count = count_;
2577  this->val = vals_;
2578  this->_EPSILON = numeric_limits<WT>::epsilon();
2579  }
2580 
2582  this->index = other.index;
2583  this->count = other.count;
2584  this->val = other.val;
2585  this->_EPSILON = other._EPSILON;
2586  }
2587 
2589  //freeArray<WT>(this->val);
2590  }
2591 
2592  void set(IT index_ ,CT count_, WT *vals_){
2593  this->index = index_;
2594  this->count = count_;
2595  this->val = vals_;
2596  }
2597 
2598 
2600  this->index = other.index;
2601  this->count = other.count;
2602  this->val = other.val;
2603  return *(this);
2604  }
2605 
2606  bool operator<(const uMultiSortItem<IT,CT,WT>& other) const{
2607  assert (this->count == other.count);
2608  for(CT i = 0; i < this->count; ++i){
2609  //if the values are equal go to next one.
2610  if (ABS(this->val[i] - other.val[i]) < this->_EPSILON){
2611  continue;
2612  }
2613  //if next value is smaller return true;
2614  if(this->val[i] < other.val[i]){
2615  return true;
2616  }
2617  //if next value is bigger return false;
2618  else {
2619  return false;
2620  }
2621  }
2622  //if they are totally equal.
2623  return false;
2624  }
2625  bool operator>(const uMultiSortItem<IT,CT,WT>& other) const{
2626  assert (this->count == other.count);
2627  for(CT i = 0; i < this->count; ++i){
2628  //if the values are equal go to next one.
2629  if (ABS(this->val[i] - other.val[i]) < this->_EPSILON){
2630  continue;
2631  }
2632  //if next value is bigger return true;
2633  if(this->val[i] > other.val[i]){
2634  return true;
2635  }
2636  //if next value is smaller return false;
2637  else //(this->val[i] > other.val[i])
2638  {
2639  return false;
2640  }
2641  }
2642  //if they are totally equal.
2643  return false;
2644  }
2645 };// uSortItem;
2646 
2647 
2648 template <class IT, class WT>
2650 {
2651  IT id;
2652  //unsigned int val;
2653  WT val;
2654 };// uSortItem;
2655 
2656 
2657 
2658 
2659 template <class IT, class WT>
2660 void uqsort(IT n, uSortItem<IT, WT> * arr)
2661 {
2662 #define SWAP(a,b,temp) temp=(a);(a)=(b);(b)=temp;
2663  int NSTACK = 50;
2664  int M = 7;
2665  IT i, ir=n, j, k, l=1;
2666  IT jstack=0, istack[50];
2667  WT aval;
2668  uSortItem<IT,WT> a, temp;
2669 
2670  --arr;
2671  for (;;)
2672  {
2673  if (ir-l < M)
2674  {
2675  for (j=l+1;j<=ir;j++)
2676  {
2677  a=arr[j];
2678  aval = a.val;
2679  for (i=j-1;i>=1;i--)
2680  {
2681  if (arr[i].val <= aval)
2682  break;
2683  arr[i+1] = arr[i];
2684  }
2685  arr[i+1]=a;
2686  }
2687  if (jstack == 0)
2688  break;
2689  ir=istack[jstack--];
2690  l=istack[jstack--];
2691  }
2692  else
2693  {
2694  k=(l+ir) >> 1;
2695  SWAP(arr[k],arr[l+1], temp)
2696  if (arr[l+1].val > arr[ir].val)
2697  {
2698  SWAP(arr[l+1],arr[ir],temp)
2699  }
2700  if (arr[l].val > arr[ir].val)
2701  {
2702  SWAP(arr[l],arr[ir],temp)
2703  }
2704  if (arr[l+1].val > arr[l].val)
2705  {
2706  SWAP(arr[l+1],arr[l],temp)
2707  }
2708  i=l+1;
2709  j=ir;
2710  a=arr[l];
2711  aval = a.val;
2712  for (;;)
2713  {
2714  do i++; while (arr[i].val < aval);
2715  do j--; while (arr[j].val > aval);
2716  if (j < i) break;
2717  SWAP(arr[i],arr[j],temp);
2718  }
2719  arr[l]=arr[j];
2720  arr[j]=a;
2721  jstack += 2;
2722  if (jstack > NSTACK){
2723  cout << "uqsort: NSTACK too small in sort." << endl;
2724  exit(1);
2725  }
2726  if (ir-i+1 >= j-l)
2727  {
2728  istack[jstack]=ir;
2729  istack[jstack-1]=i;
2730  ir=j-1;
2731  }
2732  else
2733  {
2734  istack[jstack]=j-1;
2735  istack[jstack-1]=l;
2736  l=i;
2737  }
2738  }
2739  }
2740 }
2741 
2742 #ifdef enable_migration2
2743 template <typename gno_t, typename lno_t,typename scalar_t, typename node_t>
2744 RCP<const Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> > create_initial_multi_vector(
2745  const RCP<const Environment> &env,
2746  RCP<Comm<int> > &comm,
2747  gno_t numGlobalPoints,
2748  lno_t numLocalPoints,
2749  int coord_dim,
2750  scalar_t **coords,
2751  int weight_dim,
2752  scalar_t **weight,
2753 
2754  int pqJagged_multiVectorDim
2755 ){
2756  typedef Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> tMVector_t;
2757 #ifdef memory_debug
2758  sleep(1); env->memory("initial multivector before map");
2759 #endif
2760  RCP<Tpetra::Map<lno_t, gno_t, node_t> > mp = rcp(
2761  new Tpetra::Map<lno_t, gno_t, node_t> (numGlobalPoints, numLocalPoints, 0, comm));
2762 
2763 
2764 #ifdef memory_debug
2765  if(comm->getRank() == 0) cout << "nn:"<< numLocalPoints<<"created map:" << mp.getRawPtr() << endl;
2766  sleep(1); env->memory("initial multivector after map");
2767 #endif
2768  Teuchos::Array<Teuchos::ArrayView<const scalar_t> > coordView(pqJagged_multiVectorDim);
2769  for (int i=0; i < coord_dim; i++){
2770  //cout << "setting i:" << i << endl;
2771  if(numLocalPoints > 0){
2772  Teuchos::ArrayView<const scalar_t> a(coords[i], numLocalPoints);
2773  coordView[i] = a;
2774  } else{
2775  Teuchos::ArrayView<const scalar_t> a;
2776  coordView[i] = a;
2777  }
2778 #ifdef memory_debug
2779  sleep(1); env->memory("initial multivector after coordinates -" + toString<int>(i));
2780 #endif
2781  }
2782 #ifdef memory_debug
2783  sleep(1); env->memory("initial multivector after coordinates");
2784 #endif
2785  for (int i=0; i < weight_dim; ++i){
2786  int j = i + coord_dim;
2787  //if (j >= pqJagged_multiVectorDim - 1) break;
2788  //cout << "setting j:" << j << endl;
2789  if(numLocalPoints > 0){
2790  Teuchos::ArrayView<const scalar_t> a(weight[i], numLocalPoints);
2791  coordView[j] = a;
2792  } else{
2793  Teuchos::ArrayView<const scalar_t> a;
2794  coordView[j] = a;
2795  }
2796  }
2797 
2798 #ifdef memory_debug
2799  sleep(1); env->memory("initial multivector after weights");
2800 #endif
2801 #ifdef migrate_gid
2802  if(numLocalPoints > 0){
2803  //cout << "writing :" << weight_dim + coord_dim << endl;
2804  Teuchos::ArrayView<const scalar_t> a(mappedGnos, numLocalPoints);
2805  coordView[pqJagged_multiVectorDim - 1] = a;
2806  } else{
2807  Teuchos::ArrayView<const scalar_t> a;
2808  coordView[pqJagged_multiVectorDim - 1] = a;
2809  }
2810 #endif
2811  RCP< Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> >tmVector =
2812  RCP< Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> >(
2813  new Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t>( mp, coordView.view(0, pqJagged_multiVectorDim), pqJagged_multiVectorDim));
2814 
2815 #ifdef memory_debug
2816  sleep(1); env->memory("initial multivector after create");
2817 #endif
2818  RCP<const tMVector_t> coordsConst = Teuchos::rcp_const_cast<const tMVector_t>(tmVector);
2819 
2820 #ifdef memory_debug
2821  sleep(1); env->memory("initial multivector after cast");
2822 #endif
2823  return coordsConst;
2824 }
2825 
2826 
2827 //fills up the p_gno_np_global_num_coord_each_part_actual array and
2828 //returns the allocation size of arrays.
2829 template <typename gno_t,
2830  typename lno_t,
2831  typename partId_t>
2832 void getProcessorCoordinatePartCounts(
2833 
2834  RCP<Comm<int> > &pcomm,
2835  const RCP<const Environment> &env,
2836  RCP<Comm<int> > &comm,
2837 
2838  int migration_proc_assignment_type,
2839  partId_t nprocs,
2840  partId_t myRank,
2841  partId_t num_parts,
2842  lno_t *partBeginArray,
2843  gno_t *&p_gno_np_global_num_coord_each_part_actual
2844  ){
2845 
2846  //if nprocs is less than numparts we still need to allocate more memory.
2847  if (nprocs <= num_parts) migration_proc_assignment_type = 1;
2848 
2849  //initially allocation_size is num_parts
2850  size_t allocation_size = num_parts;
2851  if (migration_proc_assignment_type == 1){
2852  //increase it by nprocs + 1 so that everyone will
2853  //know how many coordinate each processors has in each part.
2854  allocation_size = num_parts * (nprocs + 1);
2855  }
2856 
2857 
2858  //this will be output
2859  p_gno_np_global_num_coord_each_part_actual = allocMemory<gno_t>(allocation_size);
2860 
2861  //allocate memory for the local num coordinates in each part.
2862  gno_t *p_gno_np_local_num_coord_each_part_actual = allocMemory<gno_t>(allocation_size);
2863 
2864 
2865  gno_t *p_gno_np_local_num_coord_each_part = p_gno_np_local_num_coord_each_part_actual;
2866  gno_t *p_gno_np_local_num_coord_each_part_mypart = p_gno_np_local_num_coord_each_part_actual;
2867 
2868 
2869 
2870  //each processor will write a certain index of the local arrays.
2871  //then this arrays will be used in reduceAll function.
2872  if (migration_proc_assignment_type == 1){
2873  partId_t shift_amount = nprocs * num_parts;
2874  partId_t my_part_shift = myRank * num_parts;
2875  p_gno_np_local_num_coord_each_part += shift_amount;
2876  p_gno_np_local_num_coord_each_part_mypart += my_part_shift;
2877  }
2878 
2879  memset(p_gno_np_local_num_coord_each_part_actual, 0, sizeof(gno_t)*allocation_size);
2880 
2881  //write the number of coordinates in each part.
2882  for (partId_t i = 0; i < num_parts; ++i){
2883  lno_t pBegin = 0;
2884  if (i > 0){
2885  pBegin = partBeginArray[i - 1];
2886  }
2887  lno_t pEnd = partBeginArray[i];
2888  p_gno_np_local_num_coord_each_part[i] = pEnd - pBegin;
2889  }
2890 
2891  //copy the local num parts to the last portion of array,
2892  //so that this portion will represent the global num points in each part after the reduction.
2893  if (migration_proc_assignment_type == 1){
2894  memcpy (p_gno_np_local_num_coord_each_part_mypart,
2895  p_gno_np_local_num_coord_each_part,
2896  sizeof(gno_t) * (num_parts) );
2897  }
2898 
2899 
2900  //reduceAll operation.
2901  //when allocation_size = num_parts * (nprocs + 1),
2902  //the portion that belongs to a processor with index p
2903  //will start from myRank * num_parts.
2904  //the global number of points will be held at the index
2905  //nprocs * num_parts size
2906  try{
2907  reduceAll<int, gno_t>(
2908  *comm,
2909  Teuchos::REDUCE_SUM,
2910  allocation_size,
2911  p_gno_np_local_num_coord_each_part_actual,
2912  p_gno_np_global_num_coord_each_part_actual);
2913  }
2915  freeArray<gno_t>(p_gno_np_local_num_coord_each_part_actual);
2916  //free local num coordinates array, as it is no use after this point.
2917 
2918 
2919 }
2920 
2921 
2922 //checks if should do migration or not.
2923 //It returns true to point that migration should be done when
2924 // -futureReduceAlls are higher than a predetermined value
2925 // -numCoordinates that left for the last dimension partitioning is less than a predetermined value
2926 // -the imbalance of the processors on the parts are higher than given threshold.
2927 //returns false otherwise, and migration is not performed.
2928 template <typename gno_t, typename lno_t, typename partId_t>
2929 bool checkMigration(
2930 
2931  RCP<Comm<int> > &pcomm,
2932  const RCP<const Environment> &env,
2933  RCP<Comm<int> > &comm,
2934 
2935  int migration_check_option,
2936  size_t futureReduceAll,
2937  lno_t numCoordinatesForLastDimPartitioning,
2938  float migration_imbalance_cut_off,
2939 
2940  int migration_proc_assignment_type,
2941  partId_t nprocs,
2942  partId_t myRank,
2943  partId_t num_parts,
2944 
2945  gno_t *p_gno_np_global_num_coord_each_part_actual,
2946  lno_t *partBeginArray
2947  ){
2948 
2949  if (futureReduceAll > FUTURE_REDUCEALL_CUTOFF) return true;
2950  if (numCoordinatesForLastDimPartitioning < MIN_WORK_LAST_DIM) return true;
2951 
2952  if (migration_check_option == 0){
2953  double diff = 0, global_diff = 0;
2954  if (migration_proc_assignment_type == 0 )
2955  {
2956 
2957  for (partId_t i = 0; i < num_parts; ++i){
2958  double ideal_num = p_gno_np_global_num_coord_each_part_actual[i] / double(nprocs);
2959 
2960  lno_t pBegin = 0;
2961  if (i > 0){
2962  pBegin = partBeginArray[i - 1];
2963  }
2964  lno_t pEnd = partBeginArray[i];
2965  diff += ABS(ideal_num -
2966  (pEnd - pBegin)) / (ideal_num);
2967  }
2968  diff /= num_parts;
2969  reduceAll<int, double>(
2970  *comm,
2971  Teuchos::REDUCE_SUM,
2972  1,
2973  &diff,
2974  &global_diff);
2975  }
2976  else {
2977  size_t global_shift = nprocs * num_parts;
2978  for (partId_t ii = 0; ii < nprocs; ++ii){
2979  for (partId_t i = 0; i < num_parts; ++i){
2980  double ideal_num = p_gno_np_global_num_coord_each_part_actual[global_shift + i] / double(nprocs);
2981  global_diff += ABS(ideal_num -
2982  p_gno_np_global_num_coord_each_part_actual[ii * num_parts + i]) / (ideal_num);
2983  }
2984  }
2985  global_diff /= num_parts;
2986 
2987  }
2988  global_diff /= nprocs;
2989  if (myRank == 0) {
2990  cout << "imbalance for next iteration:" << global_diff << endl;
2991  }
2992 
2993 
2994 
2995  if(global_diff <= migration_imbalance_cut_off){
2996  return false;
2997  }
2998  else {
2999  return true;
3000  }
3001  }
3002  else {
3003  return true;
3004  }
3005 }
3006 
3007 
3008 //creates the new multivector in which the partId's are also added.
3009 //this function is only called when nprocs < num_parts, in this case
3010 //a processor will have coordinates from multiple parts.
3011 //the partId's are migrated as well to separate the points from different parts.
3012 template <typename gno_t, typename lno_t,typename scalar_t, typename node_t>
3013 RCP< Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> > createNewMultivector(
3014  RCP<Comm<int> > &comm,
3015  gno_t numGlobalPoints,
3016  lno_t numLocalPoints,
3017 
3018  int coord_dim,
3019  scalar_t **coords,
3020 
3021  int weight_dim,
3022  scalar_t **weight,
3023 
3024  partId_t num_parts,
3025  partId_t *partBeginArray,
3026  lno_t *permutationArray,
3027 
3028  int &multiVectorDim,
3029  RCP<const Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> > old_mvector
3030  ){
3031 
3032 
3033  typedef Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> tMVector_t;
3034  RCP<const Tpetra::Map<lno_t, gno_t, node_t> > mp = old_mvector->getMap();
3035 
3036  Teuchos::Array<Teuchos::ArrayView<const scalar_t> > coordView(multiVectorDim + 1);
3037 
3038  for (int i=0; i < coord_dim; i++){
3039  if(numLocalPoints > 0){
3040  Teuchos::ArrayView<const scalar_t> a(coords[i], numLocalPoints);
3041  coordView[i] = a;
3042  } else{
3043  Teuchos::ArrayView<const scalar_t> a;
3044  coordView[i] = a;
3045  }
3046  }
3047 
3048  for (int i=0; i < weight_dim; i++){
3049  int j = i + coord_dim;
3050  if(numLocalPoints > 0){
3051  Teuchos::ArrayView<const scalar_t> a(weight[i], numLocalPoints);
3052  coordView[j] = a;
3053  } else{
3054  Teuchos::ArrayView<const scalar_t> a;
3055  coordView[j] = a;
3056  }
3057  }
3058  scalar_t *assigned_parts = allocMemory<scalar_t>(numLocalPoints);
3059 
3060 
3061  for (partId_t i = 0; i < num_parts; ++i){
3062  lno_t pBegin = 0;
3063  if (i > 0) pBegin = partBeginArray[i - 1];
3064  lno_t pEnd = partBeginArray[i];
3065 
3066  //cout << "when setting me:" << comm->getRank() << " p:" << i << " c:" << pEnd - pBegin << " assigned_parts:" << assigned_parts<< endl;
3067  scalar_t p = scalar_t (i);
3068  for (lno_t j = pBegin; j < pEnd; ++j){
3069  lno_t ind = permutationArray[j];
3070  assigned_parts[ind] = p;
3071  }
3072  }
3073  if(numLocalPoints > 0){
3074  Teuchos::ArrayView<const scalar_t> a(assigned_parts, numLocalPoints);
3075  coordView[multiVectorDim] = a;
3076  } else{
3077  Teuchos::ArrayView<const scalar_t> a;
3078  coordView[multiVectorDim] = a;
3079  }
3080  multiVectorDim += 1;
3081 
3082  RCP< Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> >tmVector = RCP< Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> >(
3083  new Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t>( mp, coordView.view(0, multiVectorDim), multiVectorDim));
3084 
3085  RCP<const tMVector_t> coordsConst = Teuchos::rcp_const_cast<const tMVector_t>(tmVector);
3086 
3087  return tmVector;
3088 }
3089 
3090 
3091 template <typename partId_t, typename lno_t, typename gno_t>
3092 void fillContinousSendBuffer2(partId_t num_parts,
3093  lno_t *partBegins,
3094  lno_t *permutation,
3095  const gno_t *gno_list,
3096  uSortItem<partId_t, partId_t> * part_assignment, //input sorted wrt processors
3097  gno_t *sendBuf,
3098  partId_t &partBeginIndex,
3099  vector<partId_t> *newFuturePartitions,
3100  partId_t myRank
3101  ){
3102 
3103  lno_t nextInd = 0;
3104  partId_t partShift = partBeginIndex;
3105  partId_t previous_processor = -1;
3106  for(partId_t i = 0; i < num_parts; ++i){
3107  partId_t p = part_assignment[i].id;
3108  //assigned processors are sorted.
3109  //partId_t assigned_proc = part_assignment[i].val;
3110 
3111  lno_t pBegin = 0;
3112  if (p > 0) pBegin = partBegins[p - 1];
3113  lno_t pEnd = partBegins[p];
3114 
3115  partId_t assigned_proc = part_assignment[i].val;
3116  if (myRank == assigned_proc && previous_processor != assigned_proc){
3117  partBeginIndex = partShift;
3118  }
3119  previous_processor = assigned_proc;
3120  partShift += (*newFuturePartitions)[p];
3121 
3122  for (lno_t j=pBegin; j < pEnd; j++){
3123  lno_t localInd = permutation[j];
3124  gno_t to_send = gno_list[localInd];
3125  sendBuf[nextInd++] = to_send;
3126  }
3127  //cout << "sent to:" << part_assignment[i].val << " this much:" << pEnd - pBegin << " because of part:" << p << endl;
3128  }
3129 }
3130 
3131 
3132 template <typename partId_t, typename lno_t>
3133 void Z1fillSendBuffer2(partId_t num_parts,
3134  lno_t *partBegins,
3135  lno_t *permutation,
3136  uSortItem<partId_t, partId_t> * part_assignment, //input sorted wrt processors
3137  int *coordinate_destionations,
3138  partId_t &partBeginIndex,
3139  vector<partId_t> *newFuturePartitions,
3140  partId_t myRank
3141  ){
3142 
3143 
3144  partId_t partShift = partBeginIndex;
3145  partId_t previous_processor = -1;
3146  for(partId_t i = 0; i < num_parts; ++i){
3147  partId_t p = part_assignment[i].id;
3148  //assigned processors are sorted.
3149  //partId_t assigned_proc = part_assignment[i].val;
3150 
3151  lno_t pBegin = 0;
3152  if (p > 0) pBegin = partBegins[p - 1];
3153  lno_t pEnd = partBegins[p];
3154 
3155  partId_t assigned_proc = part_assignment[i].val;
3156  if (myRank == assigned_proc && previous_processor != assigned_proc){
3157  partBeginIndex = partShift;
3158  }
3159  previous_processor = assigned_proc;
3160  partShift += (*newFuturePartitions)[p];
3161 
3162  for (lno_t j=pBegin; j < pEnd; j++){
3163  lno_t localInd = permutation[j];
3164  coordinate_destionations[localInd] = assigned_proc;
3165 /*
3166  cout << " i:" << localInd <<
3167  " sending to:" << coordinate_destionations[localInd] <<
3168  endl;
3169  */
3170 
3171  }
3172  }
3173 }
3174 
3175 template <typename partId_t, typename lno_t, typename gno_t>
3176 void fillContinousSendBuffer1(
3177 
3178  RCP<Comm<int> > &pcomm, //original communication.
3179  partId_t numParts,
3180  lno_t *partBegins,
3181  lno_t *permutation,
3182 
3183  const gno_t *gno_list,
3184  partId_t nprocs,
3185 
3186  partId_t *part_assign_begins,
3187  partId_t *proc_chains,
3188 
3189  lno_t *sendCount,
3190  gno_t *sendBuf
3191  ){
3192  //function will fill the sendBuf array in a consecutive way.
3193 
3194  //initially allocate array to store prefixSum of sendCounts,
3195  //so that we know where to write the send gnos for other processors.
3196  lno_t *_sendCount_psum = allocMemory<lno_t>(nprocs);
3197  lno_t prefixsum = 0;
3198  for (int i = 0; i < nprocs; ++i ){
3199  _sendCount_psum[i] = prefixsum;
3200  prefixsum += sendCount[i];
3201  }
3202 
3203  /*
3204  for (int i = 0; i < nprocs; ++i ){
3205  cout << "me:" << pcomm->getRank() << " i:" << i << " _sendCount_psum:" << _sendCount_psum[i] << endl;
3206  }
3207  pcomm->barrier();
3208  cout << "me:" << pcomm->getRank() << " reached -1" << endl;
3209  */
3210  //now distribute all parts.
3211  for (partId_t p = 0; p < numParts; ++p){
3212  lno_t pBegin = 0;
3213  if (p > 0) pBegin = partBegins[p - 1];
3214  lno_t pEnd = partBegins[p];
3215 
3216  //get the first part that current processor will send its part-p.
3217  partId_t proc_to_sent = part_assign_begins[p];
3218  //initialize how many point I sent to this processor.
3219  lno_t totalSend = 0;
3220  for (lno_t j=pBegin; j < pEnd; j++){
3221  lno_t localInd = permutation[j];
3222  gno_t to_send = gno_list[localInd];
3223  //if the sendCount to this processor
3224  //reached its limit then start sending to the next processor.
3225  while (totalSend >= sendCount[proc_to_sent]){
3226  totalSend = 0;
3227  //assign new processor to part_assign_begin[p]
3228  part_assign_begins[p] = proc_chains[proc_to_sent];
3229  //remove the previous processor
3230  proc_chains[proc_to_sent] = -1;
3231  //choose the next processor as the next one to send.
3232  proc_to_sent = part_assign_begins[p];
3233  }
3234  //write the gno index to corresponding position in sendBuf.
3235  sendBuf[_sendCount_psum[proc_to_sent] + totalSend++] = to_send;
3236  }
3237 
3238  }
3239  freeArray<lno_t>(_sendCount_psum);
3240 }
3241 
3242 
3243 
3244 template <typename partId_t, typename lno_t>
3245 void Z1fillSendBuffer1(
3246 
3247  RCP<Comm<int> > &pcomm, //original communication.
3248  partId_t numParts,
3249  lno_t *partBegins,
3250  lno_t *permutation,
3251 
3252 
3253  partId_t nprocs,
3254 
3255  partId_t *part_assign_begins,
3256  partId_t *proc_chains,
3257 
3258  lno_t *sendCount,
3259  int *coordinate_destionations
3260  ){
3261  for (partId_t p = 0; p < numParts; ++p){
3262  lno_t pBegin = 0;
3263  if (p > 0) pBegin = partBegins[p - 1];
3264  lno_t pEnd = partBegins[p];
3265 
3266  //get the first part that current processor will send its part-p.
3267  partId_t proc_to_sent = part_assign_begins[p];
3268  //initialize how many point I sent to this processor.
3269  lno_t totalSend = 0;
3270  for (lno_t j=pBegin; j < pEnd; j++){
3271  lno_t localInd = permutation[j];
3272  while (totalSend >= sendCount[proc_to_sent]){
3273  totalSend = 0;
3274  //assign new processor to part_assign_begin[p]
3275  part_assign_begins[p] = proc_chains[proc_to_sent];
3276  //remove the previous processor
3277  proc_chains[proc_to_sent] = -1;
3278  //choose the next processor as the next one to send.
3279  proc_to_sent = part_assign_begins[p];
3280  }
3281  //write the gno index to corresponding position in sendBuf.
3282  coordinate_destionations[localInd] = proc_to_sent;
3283  ++totalSend;
3284  }
3285 
3286  }
3287 }
3288 
3289 
3290 template <typename partId_t, typename lno_t, typename gno_t>
3291 void procAssignment2(
3292  int assignment_type, //either assign to minimize migration, or assign to increase locality.
3293  gno_t * p_gno_np_global_num_coord_each_part_actual,
3294  gno_t nGlobalObj,
3295  //lno_t nLocal,
3296  partId_t num_parts,
3297  partId_t nprocs,
3298  partId_t myRank,
3299 
3300 
3301  lno_t *partBegins, //holds the beginning of each part.
3302  lno_t *permutation, //the permutation array ordered wrt partBegins array.
3303  const gno_t *gnoList, //gno array
3304 
3305  gno_t *sendBuf, //output: sized nLocal, the buffer is filled by the function with gnos.
3306  lno_t *sendCount, //output: sized nprocs, show the number of send point counts to each proc.
3307 
3308  //TODO futurePartIndex might need to be changed.sendBuf,
3309  vector<partId_t> *newFuturePartitions,//input how many more partitions the part will be partitioned into.
3310  partId_t &out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
3311  vector<partId_t> &out_part_index, //output: the part indices which the processor is assigned to.
3312  partId_t &partIndexBegin, //output: how much the part number should be shifted when setting the solution
3313  int doMigrationType,
3314  int *coordinate_destionations
3315  ){
3316 
3317 
3318  out_num_part = 0;
3319 
3320  gno_t *p_gno_np_global_num_coord_each_part = p_gno_np_global_num_coord_each_part_actual + nprocs * num_parts;
3321  //gno_t *p_gno_np_global_num_coord_each_part_mypart = p_gno_np_global_num_coord_each_part_actual + myRank * num_parts;
3322 
3323  out_part_index.clear();
3324 
3325  //to sort the parts that is assigned to the processors.
3326  //id is the part number, sort value is the assigned processor id.
3327  uSortItem<partId_t, partId_t> * part_assignment = allocMemory <uSortItem<partId_t, partId_t> >(num_parts);
3328  uSortItem<partId_t, gno_t> * proc_load_sort = allocMemory <uSortItem<partId_t, gno_t> >(nprocs);
3329 
3330 
3331  //calculate the optimal number of coordinates
3332  //that should be assigned to each processor.
3333  lno_t work_each = nGlobalObj / (float (nprocs)) + 0.5f;
3334  //to hold the left space as the number of coordinates to the optimal number in each proc.
3335  lno_t *space_in_each_processor = allocMemory <lno_t>(nprocs);
3336  //initialize left space in each.
3337  for (partId_t i = 0; i < nprocs; ++i){
3338  space_in_each_processor[i] = work_each;
3339  }
3340 
3341 
3342  //to sort the parts with decreasing order of their coordiantes.
3343  //id are the part numbers, sort value is the number of points in each.
3344  uSortItem<partId_t, gno_t> * part_loads = allocMemory <uSortItem<partId_t, gno_t> >(num_parts);
3345 
3346  //initially we will sort the parts according to the number of coordinates they have.
3347  //so that we will start assigning with the part that has the most number of coordinates.
3348  for (partId_t i = 0; i < num_parts; ++i){
3349  part_loads[i].id = i;
3350  part_loads[i].val = p_gno_np_global_num_coord_each_part[i];
3351  }
3352  //sort parts with increasing order of loads.
3353  uqsort<partId_t, gno_t>(num_parts, part_loads);
3354 
3355 
3356  //assigning parts to the processors
3357  //traverse the part win decreasing order of load.
3358  //first assign the heaviest part.
3359  for (partId_t j = 0; j < num_parts; ++j){
3360  //sorted with increasing order, traverse inverse.
3361  partId_t i = part_loads[num_parts - 1 - j].id;
3362  //load of the part
3363  gno_t load = p_gno_np_global_num_coord_each_part[i];
3364 
3365  //assigned processors
3366  partId_t assigned_proc = -1;
3367  //if not fit best processor.
3368  partId_t best_proc_to_assign = 0;
3369 
3370 
3371  //sort processors with increasing number of points in this part.
3372  for (partId_t ii = 0; ii < nprocs; ++ii){
3373  proc_load_sort[ii].id = ii;
3374  //how many points processor ii has in part i?
3375  proc_load_sort[ii].val = p_gno_np_global_num_coord_each_part_actual[ii * num_parts + i];
3376  }
3377  uqsort<partId_t, gno_t>(nprocs, proc_load_sort);
3378 
3379  //traverse all processors with increasing load.
3380  //TODO there should be a mistake here. (inefficiency)
3381  //should traverse from end to beginning.
3382  //currently gets the processors with least number of coordinates,
3383  //and assings the part to this part.
3384  for (partId_t iii = nprocs - 1; iii >= 0; --iii){
3385 
3386  partId_t ii = proc_load_sort[iii].id;
3387  lno_t left_space = space_in_each_processor[ii] - load;
3388  //if enought space, assign to this part.
3389  if(left_space >= 0 ){
3390  assigned_proc = ii;
3391  break;
3392  }
3393  //if space is not enough, store the best candidate part.
3394  if (space_in_each_processor[best_proc_to_assign] < space_in_each_processor[ii]){
3395  best_proc_to_assign = ii;
3396  }
3397  }
3398  if (assigned_proc == -1){
3399  assigned_proc = best_proc_to_assign;
3400  }
3401  space_in_each_processor[assigned_proc] -= load;
3402 
3403  //to sort later, part-i is assigned to the proccessor - assignment.
3404  part_assignment[j].id = i; //part i
3405  part_assignment[j].val = assigned_proc; //assigned to processor - assignment.
3406 
3407 
3408  //if assigned processor is me, increase the number.
3409  if (assigned_proc == myRank){
3410  out_num_part++;//assigned_part_count;
3411  out_part_index.push_back(i);
3412  }
3413  //increase the send to that processor by the number of points in that part.
3414  sendCount[assigned_proc] += p_gno_np_global_num_coord_each_part_actual[myRank * num_parts + i];
3415  }
3416  freeArray< uSortItem<partId_t, gno_t> > (proc_load_sort);
3417  freeArray<uSortItem<partId_t, gno_t> >(part_loads);
3418  freeArray<lno_t >(space_in_each_processor);
3419 
3420 
3421  //sort assignments with respect to the assigned processors.
3422  uqsort<partId_t, partId_t>(num_parts, part_assignment);
3423  //fill sendBuf.
3424 
3425  if (doMigrationType == 0){
3426  fillContinousSendBuffer2< partId_t, lno_t, gno_t>(
3427  num_parts,
3428  partBegins,
3429  permutation,
3430  gnoList,
3431  part_assignment, //input sorted wrt processors
3432  sendBuf,
3433  partIndexBegin,
3434  newFuturePartitions,
3435  myRank
3436  );
3437  }
3438  else {
3439  Z1fillSendBuffer2< partId_t, lno_t>(
3440  num_parts,
3441  partBegins,
3442  permutation,
3443  part_assignment, //input sorted wrt processors
3444  coordinate_destionations,
3445  partIndexBegin,
3446  newFuturePartitions,
3447  myRank
3448  );
3449  }
3450 
3451 
3452  freeArray<uSortItem<partId_t, partId_t> >(part_assignment);
3453 }
3454 
3455 template <typename partId_t, typename lno_t, typename gno_t>
3456 void procAssignment1(
3457  RCP<Comm<int> > &pcomm, //original communication.
3458  int assignment_type, //either assign to minimize migration, or assign to increase locality.
3459  gno_t * p_gno_np_global_num_coord_each_part_actual,
3460  gno_t nGlobalObj,
3461  lno_t nLocal,
3462  partId_t num_parts,
3463  partId_t nprocs,
3464  partId_t myRank,
3465 
3466 
3467  lno_t *partBegins, //holds the beginning of each part.
3468  lno_t *permutation, //the permutation array ordered wrt partBegins array.
3469  const gno_t *gnoList, //gno array
3470 
3471  gno_t *sendBuf, //output: sized nLocal, the buffer is filled by the function with gnos.
3472  lno_t *sendCount, //output: sized nprocs, show the number of send point counts to each proc.
3473  vector<partId_t> &ids, //output: this holds the id of the processors for the next subcommunicatior.
3474 
3475 
3476  //TODO futurePartIndex might need to be changed.
3477  vector<partId_t> *newFuturePartitions,//input how many more partitions the part will be partitioned into.
3478  //partId_t &out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
3479  partId_t &out_part_index, //output: the part index which the processor is assigned to.
3480  partId_t &partIndexBegin, //output: how much the part number should be shifted when setting the solution
3481  int doMigrationType,
3482  int *coordinate_destionations
3483  ){
3484 
3485 
3486 
3487 
3488  gno_t *p_gno_np_global_num_coord_each_part = p_gno_np_global_num_coord_each_part_actual + nprocs * num_parts;
3489  //gno_t *p_gno_np_global_num_coord_each_part_mypart = p_gno_np_global_num_coord_each_part_actual + myRank * num_parts;
3490 
3491 
3492  partId_t *p_pid_np_num_procs_each_part = allocMemory<partId_t>(num_parts);
3493 
3494  bool did_i_find_my_group = false;
3495 
3496 
3497 
3498  partId_t left_proc = nprocs;
3499  partId_t min_required_for_rest = num_parts - 1;
3500 
3501  float max_difference = 0;
3502  partId_t max_differ_part = 0;
3503 
3504  //find how many processor each part requires.
3505  for (partId_t i=0; i < num_parts; i++){
3506 
3507  //scalar portion of the required processors
3508  float scalar_required_proc = nprocs *
3509  (float (p_gno_np_global_num_coord_each_part[i])
3510  / float(nGlobalObj)
3511  );
3512 
3513  //round it to the integer.
3514  partId_t required_proc = static_cast<partId_t> (
3515  floor (0.5f + scalar_required_proc));
3516 
3517 
3518 
3519  if (left_proc - required_proc < min_required_for_rest){
3520  required_proc = left_proc - (min_required_for_rest);
3521  }
3522  left_proc -= required_proc;
3523  --min_required_for_rest;
3524  p_pid_np_num_procs_each_part[i] = required_proc;
3525 
3526  //because of the roundings some processors might be left as unassigned.
3527  //we want to assign those processors to the part with most imbalance.
3528  float imbalance_wrt_ideal = (scalar_required_proc - required_proc) / required_proc;
3529  if (imbalance_wrt_ideal > max_difference){
3530  max_difference = imbalance_wrt_ideal;
3531  max_differ_part = i;
3532  }
3533  }
3534 
3535  /*
3536  pcomm->barrier();
3537  cout << "me:" << pcomm->getRank() << " reached 1" << endl;
3538  */
3539  //assign extra processors to those parts.
3540  if (left_proc > 0){
3541  p_pid_np_num_procs_each_part[max_differ_part] += left_proc;
3542  }
3543 
3544  //now find what are the best processors with least migration for each part.
3545  //or assign the parts according to processors locality.
3546 
3547  partId_t *part_assign_begins = allocMemory<partId_t>(num_parts);
3548  partId_t *proc_chains = allocMemory<partId_t>(nprocs);
3549  partId_t *proc_part_assignments = allocMemory<partId_t>(nprocs);
3550 
3551  //initialize the assignment of each processor.
3552  //this has a linked list implementation.
3553  //the beginning of processors assigned
3554  //to each part is hold at part_assign_begins[part].
3555  //then the next processor assigned to that part is located at
3556  //proc_part_assignments[part_assign_begins[part]], this is a chain
3557  //until the value of -1 is reached.
3558  for (int i = 0; i < nprocs; ++i ){
3559  proc_part_assignments[i] = -1;
3560  proc_chains[i] = -1;
3561  }
3562  for (int i = 0; i < num_parts; ++i ){
3563  part_assign_begins[i] = -1;
3564  }
3565 
3566  partId_t next_proc_to_assign = 0;
3567 
3568  /*
3569  pcomm->barrier();
3570  cout << "me:" << pcomm->getRank() << " reached 2" << endl;
3571  */
3572  //Allocate memory for sorting data structure.
3573  uSortItem<partId_t, lno_t> * proc_points_in_part = allocMemory <uSortItem<partId_t, partId_t> > (nprocs);
3574  for(partId_t i = 0; i < num_parts; ++i){
3575 
3576  //if the assignment type is 0, then the algorithm tries to minimize the cost
3577  //of migration, by assigning the processors with highest number of coordinates on that part.
3578  if(assignment_type == 0){
3579  for(partId_t ii = 0; ii < nprocs; ++ii){
3580 
3581  proc_points_in_part[ii].id = ii;
3582 
3583  if (proc_part_assignments[ii] == -1){
3584  proc_points_in_part[ii].val = p_gno_np_global_num_coord_each_part_actual[ii * num_parts + i];
3585  }
3586  else {
3587  //if processor is already assigned, insert -nLocal - 1.
3588  proc_points_in_part[ii].val = -p_gno_np_global_num_coord_each_part_actual[ii * num_parts + i] - 1;
3589  }
3590  }
3591  }
3592  else {
3593 
3594  //in this case we assign only the parts according to their closeness,
3595  //assuming that consecutive ranks are close to each other.
3596  partId_t required_proc = p_pid_np_num_procs_each_part[i];
3597  partId_t last_proc_to_assign = next_proc_to_assign + required_proc;
3598  for(partId_t ii = 0; ii < nprocs; ++ii){
3599  proc_points_in_part[ii].id = ii;
3600  if (ii >= next_proc_to_assign && ii < last_proc_to_assign){
3601  proc_points_in_part[ii].val = p_gno_np_global_num_coord_each_part_actual[ii * num_parts + i];
3602  }
3603  else {
3604  proc_points_in_part[ii].val = -p_gno_np_global_num_coord_each_part_actual[ii * num_parts + i] - 1;
3605  }
3606  }
3607  next_proc_to_assign = last_proc_to_assign;
3608  }
3609 
3610  //sort the processors in the part.
3611  uqsort<partId_t, partId_t>(nprocs, proc_points_in_part);
3612 
3613  partId_t required_proc_count = p_pid_np_num_procs_each_part[i];
3614  gno_t total_num_points_in_part = p_gno_np_global_num_coord_each_part[i];
3615  gno_t ideal_num_points_in_procs =
3616  ceil (total_num_points_in_part / float (required_proc_count));
3617 
3618  //starts sending to heaviest part.
3619  partId_t next_part_to_send = nprocs - required_proc_count;
3620  partId_t next_part_to_send_id = proc_points_in_part[next_part_to_send].id;
3621  lno_t space_left = ideal_num_points_in_procs - proc_points_in_part[next_part_to_send].val;
3622 
3623  //find the assigned processors.
3624  for(partId_t ii = nprocs - 1; ii >= nprocs - required_proc_count; --ii){
3625 
3626  partId_t partid = proc_points_in_part[ii].id;
3627  proc_part_assignments[partid] = i;
3628 
3629  /*
3630  if(myRank == 0){
3631  cout << "proc:" << partid <<
3632  " assigned to part:" << i <<
3633  " as it has:" << proc_points_in_part[ii].val <<
3634  " points in this part." << endl;
3635  }
3636  */
3637  }
3638 
3639 
3640  bool did_change_anything = false;
3641  for(partId_t ii = 0; ii < nprocs; ++ii){
3642  if (proc_points_in_part[ii].val < 0){
3643  did_change_anything = true;
3644  proc_points_in_part[ii].val = -proc_points_in_part[ii].val - 1;
3645  }
3646  else {
3647  break;
3648  }
3649  }
3650 
3651  if(did_change_anything){
3652  //resort the processors in the part.
3653  uqsort<partId_t, partId_t>(nprocs - required_proc_count, proc_points_in_part);
3654  }
3655 
3656  /*
3657  for(partId_t ii = nprocs - required_proc_count - 1; ii >= 0; --ii){
3658 
3659  partId_t partid = proc_points_in_part[ii].id;
3660 
3661  if(myRank == 0){
3662  cout << "proc:" << partid <<
3663  " is not assigned to part:" << i <<
3664  " as it has:" << proc_points_in_part[ii].val <<
3665  " points in this part." << endl;
3666  }
3667  }
3668  */
3669 
3670  //check if this processors is one of the procs assigned to this part.
3671  //if it is, then get the group.
3672  if (!did_i_find_my_group){
3673  for(partId_t ii = nprocs - 1; ii >= nprocs - required_proc_count; --ii){
3674  partId_t partid = proc_points_in_part[ii].id;
3675  //ids[nprocs - 1 - ii] = partid;
3676  ids.push_back(partid);
3677  //proc_part_assignments[partid] = i;
3678 
3679  if(partid == myRank){
3680  did_i_find_my_group = true;
3681  part_assign_begins[i] = myRank;
3682  proc_chains[myRank] = -1;
3683  sendCount[myRank] = proc_points_in_part[ii].val;
3684  //TODO futurePartIndex might need to be changed.
3685  //partIndexBegin += i * futurePartIndex;
3686  for (partId_t in = 0; in < i; ++in){
3687  partIndexBegin += (*newFuturePartitions)[in];
3688  }
3689 
3690  out_part_index = i;
3691  }
3692  }
3693  /*
3694  if (did_i_find_my_group){
3695  groupSize = required_proc_count;
3696  }
3697  */
3698  if (!did_i_find_my_group){
3699  ids.clear();
3700  }
3701  }
3702 
3703  //send points of the nonassigned coordinates to the assigned coordinates.
3704  //TODO play with this part, to get a better communication imbalance.
3705  //starts from the heaviest nonassigned processor.
3706  for(partId_t ii = nprocs - required_proc_count - 1; ii >= 0; --ii){
3707  partId_t partid = proc_points_in_part[ii].id;
3708  lno_t to_sent = proc_points_in_part[ii].val;
3709 
3710  //we set number of points to -to_sent - 1 for the assigned processors.
3711  //we reverse it here.
3712  if (to_sent < 0) to_sent = -to_sent - 1;
3713 
3714  //now sends the
3715  while (to_sent > 0){
3716  //if the processor has enough space.
3717 
3718  if (to_sent <= space_left){
3719  /*
3720  if(myRank == 0){
3721  cout << " proc:" << partid
3722  << " needs to send:"
3723  << to_sent << " and left space:"
3724  << space_left << " on proc:"
3725  << next_part_to_send_id << " because of part:" << i << endl;
3726  }
3727  */
3728 
3729  space_left -= to_sent;
3730 
3731  if (myRank == partid){
3732  //set my sent count to the sent processor.
3733  sendCount[next_part_to_send_id] = to_sent;
3734  //save the processor in the list (proc_chains and part_assign_begins)
3735  //that the processor
3736  //will send its point in part-i.
3737  partId_t prev_begin = part_assign_begins[i];
3738  part_assign_begins[i] = next_part_to_send_id;
3739  proc_chains[next_part_to_send_id] = prev_begin;
3740  }
3741  to_sent = 0;
3742  }
3743  else {
3744  /*
3745  if(myRank == 0){
3746  cout << " proc:" << partid
3747  << " needs to send:"
3748  << to_sent << " but left space:"
3749  << space_left << " on proc:"
3750  << next_part_to_send_id << " because of part:" << i << endl;
3751  }
3752  */
3753  //there might be no space left in the processor.
3754  if(space_left > 0){
3755  to_sent -= space_left;
3756 
3757  //send as the space left in the processor.
3758  if (myRank == partid){
3759  sendCount[next_part_to_send_id] = space_left;
3760  partId_t prev_begin = part_assign_begins[i];
3761  part_assign_begins[i] = next_part_to_send_id;
3762  proc_chains[next_part_to_send_id] = prev_begin;
3763 
3764  }
3765  }
3766  //change the sent part
3767  ++next_part_to_send;
3768 
3769 #ifdef debug_
3770  //TODO remove comment
3771  if(next_part_to_send < nprocs - required_proc_count ){
3772  cout << "this should not happen next part to send:" << next_part_to_send << endl;
3773 
3774  }
3775 #endif
3776  next_part_to_send_id = proc_points_in_part[next_part_to_send].id;
3777  space_left = ideal_num_points_in_procs - proc_points_in_part[next_part_to_send].val;
3778  }
3779  }
3780  }
3781 
3782  }
3783 
3784  /*
3785  pcomm->barrier();
3786  cout << "me:" << pcomm->getRank() << " reached 3:" << nLocal << endl;
3787  */
3788  if (doMigrationType == 0){
3789  fillContinousSendBuffer1 <partId_t, lno_t, gno_t> (
3790  pcomm,
3791  num_parts,
3792  partBegins,
3793  permutation,
3794 
3795  gnoList,
3796  nprocs,
3797 
3798  part_assign_begins,
3799  proc_chains,
3800 
3801  sendCount,
3802  sendBuf
3803  );
3804  } else {
3805  Z1fillSendBuffer1 <partId_t, lno_t> (
3806  pcomm,
3807  num_parts,
3808  partBegins,
3809  permutation,
3810  nprocs,
3811 
3812  part_assign_begins,
3813  proc_chains,
3814 
3815  sendCount,
3816  coordinate_destionations
3817  );
3818 
3819  }
3820  /*
3821  pcomm->barrier();
3822  cout << "me:" << pcomm->getRank() << " reached 4" << endl;
3823  */
3824  freeArray<partId_t>(part_assign_begins);
3825  freeArray<partId_t>(proc_chains);
3826  freeArray<partId_t>(proc_part_assignments);
3827  freeArray<uSortItem<partId_t, partId_t> > (proc_points_in_part);
3828  freeArray<partId_t > (p_pid_np_num_procs_each_part);
3829 
3830 }
3831 
3832 template <typename partId_t, typename lno_t, typename gno_t>
3833 void getProcGroups_SendCounts_SendBuff(
3834 
3835  RCP<Comm<int> > &pcomm, //original communication.
3836  int migration_proc_assignment_type,
3837  int assignment_type, //either assign to minimize migration, or assign to increase locality.
3838 
3839  gno_t * p_gno_np_global_num_coord_each_part_actual,
3840  gno_t nGlobalObj,
3841  lno_t nLocal,
3842  partId_t num_parts,
3843  partId_t nprocs,
3844  partId_t myRank,
3845 
3846 
3847  lno_t *partBegins, //holds the beginning of each part.
3848  lno_t *permutation, //the permutation array ordered wrt partBegins array.
3849  const gno_t *gnoList, //gno array
3850 
3851  gno_t *sendBuf, //output: sized nLocal, the buffer is filled by the function with gnos.
3852  lno_t *sendCount, //output: sized nprocs, show the number of send point counts to each proc.
3853  vector<partId_t> &ids, //output: this holds the id of the processors for the next subcommunicatior.
3854 
3855 
3856  //TODO futurePartIndex might need to be changed.
3857  //partId_t futurePartIndex,//input how many more partitions the part will be partitioned into.
3858  vector<partId_t> *newFuturePartitions,
3859  partId_t &out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
3860  vector<partId_t> &out_part_indices, //output: the part index which the processor is assigned to.
3861  partId_t &partIndexBegin, //output: how much the part number should be shifted when setting the solution
3862  int doMigrationType,
3863  int *coordinate_destionations
3864  ){
3865 
3876  ids.clear();
3877  /*
3878  if (myRank == 0){
3879  cout << endl << endl;
3880  }
3881  */
3882  if (1 || nLocal > 0){
3883  if (nprocs > num_parts){
3884 
3885  partId_t out_part_index = 0;
3886  /*
3887  pcomm->barrier();
3888  cout << "me:" << pcomm->getRank() << endl;
3889  */
3890  procAssignment1<partId_t, lno_t, gno_t>(
3891  pcomm,
3892  assignment_type, //either assign to minimize migration, or assign to increase locality.
3893  p_gno_np_global_num_coord_each_part_actual,
3894  nGlobalObj,
3895  nLocal,
3896  num_parts,
3897  nprocs,
3898  myRank,
3899 
3900 
3901  partBegins, //holds the beginning of each part.
3902  permutation, //the permutation array ordered wrt partBegins array.
3903  gnoList, //gno array
3904 
3905  sendBuf, //output: sized nLocal, the buffer is filled by the function with gnos.
3906  sendCount, //output: sized nprocs, show the number of send point counts to each proc.
3907  ids, //output: this holds the id of the processors for the next subcommunicatior.
3908 
3909 
3910  //TODO futurePartIndex might need to be changed.
3911  newFuturePartitions,//input how many more partitions the part will be partitioned into.
3912  //partId_t &out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
3913  out_part_index, //output: the part index which the processor is assigned to.
3914  partIndexBegin, //output: how much the part number should be shifted when setting the solution
3915  doMigrationType,
3916  coordinate_destionations
3917  );
3918 
3919  /*
3920  pcomm->barrier();
3921  cout << "me:" << pcomm->getRank() << " out"<< endl;
3922  */
3923  out_num_part = 1;
3924  out_part_indices.clear();
3925  out_part_indices.push_back(out_part_index);
3926  /*
3927  pcomm->barrier();
3928  cout << "me:" << pcomm->getRank() << " finish out"<< endl;
3929  */
3930 
3931 
3932  /*
3933  int partsendCount = 0;
3934  lno_t sc = 0;
3935  for(int i = 0; i < nprocs; ++i){
3936 
3937  if(sendCount[i] > 0){
3938  partsendCount++;
3939  sc += sendCount[i];
3940  }
3941  }
3942  cout << "me:" << myRank <<
3943  " sending to:" << partsendCount <<
3944  " many processors with assignment-1:" <<
3945  " I am assigned to:" << out_part_index << endl;
3946 
3947 
3948 
3949  for(int i = 0; i < num_parts; ++i){
3950  cout << "me:" << myRank <<
3951  " have " << p_gno_np_global_num_coord_each_part_actual[myRank * num_parts + i] <<
3952  " in part:" << i << endl;
3953  }
3954  */
3955 
3956  }
3957  else {
3958  ids.push_back(myRank);
3959 
3960  procAssignment2<partId_t, lno_t, gno_t>(
3961  assignment_type, //either assign to minimize migration, or assign to increase locality.
3962  p_gno_np_global_num_coord_each_part_actual,
3963  nGlobalObj,
3964  //lno_t nLocal,
3965  num_parts,
3966  nprocs,
3967  myRank,
3968 
3969 
3970  partBegins, //holds the beginning of each part.
3971  permutation, //the permutation array ordered wrt partBegins array.
3972  gnoList, //gno array
3973 
3974  sendBuf, //output: sized nLocal, the buffer is filled by the function with gnos.
3975  sendCount, //output: sized nprocs, show the number of send point counts to each proc.
3976 
3977  //TODO futurePartIndex might need to be changed.
3978  newFuturePartitions,//input how many more partitions the part will be partitioned into.
3979  out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
3980  out_part_indices, //output: the part indices which the processor is assigned to.
3981  partIndexBegin, //output: how much the part number should be shifted when setting the solution
3982  doMigrationType,
3983  coordinate_destionations
3984  );
3985 
3986 
3987  /*
3988  lno_t sc = 0;
3989  int partsendCount = 0;
3990  for(int i = 0; i < nprocs; ++i){
3991  if(sendCount[i] > 0){
3992  partsendCount++;
3993  sc += sendCount[i];
3994  }
3995  }
3996 
3997  cout << "me:" << myRank <<
3998  " sending to:" << partsendCount <<
3999  " many processors with assignment-2:" << endl;
4000 
4001  for (int i = 0; i < out_num_part; ++i){
4002  cout << "me:" << myRank << " I am assigned to:" << out_part_indices[i] << endl;
4003  }
4004 
4005 
4006  for(int i = 0; i < num_parts; ++i){
4007  cout << "me:" << myRank <<
4008  " have " << p_gno_np_global_num_coord_each_part_actual[myRank * num_parts + i] <<
4009  " in part:" << i << endl;
4010  }
4011  */
4012  }
4013 
4014  }
4015 }
4016 
4017 
4018 template <typename partId_t, typename lno_t, typename gno_t, typename scalar_t>
4019 void doAll2All(
4020  const RCP<const Environment> &env, //environment
4021  RCP<Comm<int> > &comm, //current communication object.
4022  int doMigrationType,
4023  int all2alloption,
4024  partId_t nprocs,
4025  lno_t nLocal,
4026  lno_t *sendCount,
4027  gno_t *sendBuf,
4028  ArrayRCP<gno_t> &recvBuf,
4029  gno_t &numMyNewGnos,
4030  string iteration,
4031 
4032  int coord_dim, // coordinate dimension
4033  scalar_t **coords, //coordinates.
4034  int weight_dim, //weight dimension
4035  scalar_t **weights, //weights
4036  gno_t *&coordinate_gnos,
4037  int *&coordinate_owners,
4038  int *coordinate_destionations,
4039  partId_t *&assigned_parts,
4040  partId_t num_parts
4041  ){
4042 
4043  //function to obtain recvBuf that holds the new gno's that processor will own.
4044 
4045  if (doMigrationType == 0){
4046  if (all2alloption == 2) {
4047  //cout << "ALL2ALL distribotr" << endl;
4048  //uses distributor object.
4049  partId_t *partIds = allocMemory< partId_t>(nLocal);
4050  partId_t *p = partIds;
4051 
4052  //write which processor each point is going.
4053  for (int i = 0; i < nprocs; ++i){
4054  lno_t sendC = sendCount[i];
4055  for (int ii = 0; ii < sendC; ++ii){
4056  *(p++) = i;
4057  }
4058  }
4059 
4060  env->timerStart(MACRO_TIMERS, "PQJagged - Migration DistPlanCreating-" + iteration);
4061  Tpetra::Distributor distributor(comm);
4062 
4063  ArrayView<const partId_t> pIds( partIds, nLocal);
4064  numMyNewGnos = distributor.createFromSends(pIds);
4065  env->timerStop(MACRO_TIMERS, "PQJagged - Migration DistPlanCreating-" + iteration);
4066 
4067  ArrayRCP<gno_t> recvBuf2(distributor.getTotalReceiveLength());
4068 
4069  env->timerStart(MACRO_TIMERS, "PQJagged - Migration DistPlanCom-" + iteration);
4070  ArrayView<gno_t> s(sendBuf, nLocal);
4071  distributor.doPostsAndWaits<gno_t>(s, 1, recvBuf2());
4072  env->timerStop(MACRO_TIMERS, "PQJagged - Migration DistPlanCom-" + iteration);
4073  recvBuf = recvBuf2;
4074  freeArray<partId_t>(partIds);
4075 
4076  } else if (all2alloption == 1){
4077 
4078 
4079  partId_t *partIds = allocMemory< partId_t>(nLocal);
4080  partId_t *p = partIds;
4081 
4082  //write which processor each point is going.
4083 
4084  for (int i = 0; i < nprocs; ++i){
4085  lno_t sendC = sendCount[i];
4086  //cout << "me:" << comm->getRank() << " to:" << i << " sending:" << sendC << endl;
4087  for (int ii = 0; ii < sendC; ++ii){
4088  *(p++) = i;
4089  }
4090  }
4091 
4092 
4093  ZOLTAN_COMM_OBJ *plan = NULL; /* pointer for communication object */
4094 
4095 
4096  MPI_Comm mpi_comm = Teuchos2MPI (comm);
4097  lno_t incoming = 0;
4098  int message_tag = 7859;
4099 
4100  env->timerStart(MACRO_TIMERS, "PQJagged - Migration Z1PlanCreating-" + iteration);
4101  int ierr = Zoltan_Comm_Create(&plan, nLocal, partIds, mpi_comm, message_tag,
4102  &incoming);
4103  env->timerStop(MACRO_TIMERS, "PQJagged - Migration Z1PlanCreating-" + iteration);
4104 
4105 
4106  ArrayRCP<gno_t> recvBuf2(incoming);
4107  gno_t *recieves = recvBuf2.getRawPtr();
4108 
4109 
4110  message_tag++;
4111  env->timerStart(MACRO_TIMERS, "PQJagged - Migration Z1PlanComm-" + iteration);
4112  ierr = Zoltan_Comm_Do(plan, message_tag, (char *) sendBuf,
4113  sizeof(gno_t),
4114  (char *) recieves);
4115  env->timerStop(MACRO_TIMERS, "PQJagged - Migration Z1PlanComm-" + iteration);
4116 
4117  ierr = Zoltan_Comm_Destroy(&plan);
4118  numMyNewGnos = incoming;
4119  recvBuf = recvBuf2;
4120  freeArray<partId_t>(partIds);
4121 
4122  } else {
4123  ArrayView<gno_t> s (sendBuf, nLocal);
4124  ArrayView<int> sc (sendCount, nprocs);
4125  Array<lno_t> recvCount(nprocs, 0);
4126  try{
4127  AlltoAllv<gno_t>(*comm, *env,
4128  s, sc,
4129  recvBuf, recvCount());
4130  }
4132 
4133  for (int i=0; i < nprocs; i++){
4134  numMyNewGnos += recvCount[i];
4135  }
4136  recvCount.clear();
4137  }
4138  }
4139  else {
4140 /*
4141  int coord_dim, // coordinate dimension
4142  scalar_t **coords, //coordinates.
4143  int weight_dim, //weight dimension
4144  scalar_t **weights, //weights
4145  gno_t * coordinate_gnos,
4146  int * coordinate_owners,
4147  int *coordinate_destionations,
4148  partId_t num_parts
4149 
4150 */
4151  ZOLTAN_COMM_OBJ *plan = NULL;
4152 
4153 
4154  MPI_Comm mpi_comm = Teuchos2MPI (comm);
4155  lno_t incoming = 0;
4156  int message_tag = 7859;
4157 
4158  /*
4159  for (int i = 0; i < nLocal; ++i){
4160  cout << "me:" << comm->getRank() <<
4161  " i:" << i <<
4162  " before coordinate_destionations:" << coordinate_destionations[i] <<
4163  endl;
4164  }
4165  */
4166 
4167 
4168  env->timerStart(MACRO_TIMERS, "PQJagged - Migration Z1PlanCreating-" + iteration);
4169  int ierr = Zoltan_Comm_Create(
4170  &plan, nLocal,
4171  coordinate_destionations, mpi_comm,
4172  message_tag, &incoming);
4173  env->timerStop(MACRO_TIMERS, "PQJagged - Migration Z1PlanCreating-" + iteration);
4174 
4175 
4176 
4177  int toMyself = 0;
4178  for (int i = 0; i < nLocal; ++i){
4179  if (coordinate_destionations[i] == comm->getRank()){
4180  ++toMyself;
4181  }
4182  }
4183  /*
4184  cout << "iteration:" << iteration <<
4185  " me:" << comm->getRank() <<
4186  " mySelf:" << toMyself <<
4187  " nLocal:" << nLocal << endl;
4188  */
4189  /*
4190  cout << "me:" << comm->getRank() << " incoming:" << incoming << endl;
4191  */
4192 
4193  gno_t *incoming_gnos = allocMemory< gno_t>(incoming);
4194 
4195  message_tag++;
4196  env->timerStart(MACRO_TIMERS, "PQJagged - Migration Z1PlanComm-" + iteration);
4197  ierr = Zoltan_Comm_Do(
4198  plan, message_tag,
4199  (char *) coordinate_gnos,
4200  sizeof(gno_t), (char *) incoming_gnos);
4201  env->timerStop(MACRO_TIMERS, "PQJagged - Migration Z1PlanComm-" + iteration);
4202  freeArray<gno_t>(coordinate_gnos);
4203  coordinate_gnos = incoming_gnos;
4204 
4205 
4206 
4207  env->timerStart(MACRO_TIMERS, "PQJagged - Migration Z1Migration-" + iteration);
4208  for (int i = 0; i < coord_dim; ++i){
4209  message_tag++;
4210  scalar_t *coord = coords[i];
4211 
4212  coords[i] = allocMemory<scalar_t>(incoming);
4213  ierr = Zoltan_Comm_Do(
4214  plan, message_tag,
4215  (char *) coord,
4216  sizeof(scalar_t), (char *) coords[i]);
4217  freeArray<scalar_t>(coord);
4218  }
4219 
4220  for (int i = 0; i < weight_dim; ++i){
4221  message_tag++;
4222  scalar_t *weight = weights[i];
4223 
4224  weights[i] = allocMemory<scalar_t>(incoming);
4225  ierr = Zoltan_Comm_Do(
4226  plan, message_tag,
4227  (char *) weight,
4228  sizeof(scalar_t), (char *) weights[i]);
4229  freeArray<scalar_t>(weight);
4230  }
4231 
4232 
4233  int *coord_own = allocMemory<int>(incoming);
4234  message_tag++;
4235  ierr = Zoltan_Comm_Do(
4236  plan, message_tag,
4237  (char *) coordinate_owners,
4238  sizeof(int), (char *) coord_own);
4239  freeArray<int>(coordinate_owners);
4240  coordinate_owners = coord_own;
4241 
4242  /*
4243  for (int i = 0; i < incoming; ++i){
4244  cout << "me:" << comm->getRank() <<
4245  " i:" << i <<
4246  " after move:" << coordinate_owners[i] <<
4247  endl;
4248 
4249 
4250  }
4251  */
4252 
4253 
4254  partId_t *new_parts = allocMemory<int>(incoming);
4255 
4256 
4257  if(nprocs < num_parts){
4258  message_tag++;
4259  ierr = Zoltan_Comm_Do(
4260  plan, message_tag,
4261  (char *) assigned_parts,
4262  sizeof(partId_t), (char *) new_parts);
4263  }
4264 
4265  freeArray<partId_t>(assigned_parts);
4266  assigned_parts = new_parts;
4267  ierr = Zoltan_Comm_Destroy(&plan);
4268  env->timerStop(MACRO_TIMERS, "PQJagged - Migration Z1Migration-" + iteration);
4269  numMyNewGnos = incoming;
4270  }
4271 }
4272 
4273 template <typename mvector_t, typename gno_t>
4274 void doActualMigration(
4275  const RCP<const Environment> &env, //environment
4276  RCP<const mvector_t> &vectors, // on return is the new data,
4277  gno_t numMyNewGnos,
4278  ArrayRCP<gno_t> recvBuf){
4279  try{
4281  vectors, numMyNewGnos, recvBuf.getRawPtr()/*, env*/);
4282  }
4284 }
4285 
4286 template <typename partId_t>
4287 void createSubCommunicator(
4288  RCP<Comm<int> > &comm,
4289  vector<partId_t> &proc_ids
4290  ){
4291 
4292  partId_t groupSize = proc_ids.size();
4293  partId_t *ids = allocMemory<partId_t>(groupSize);
4294  for(partId_t i = 0; i < groupSize; ++i) {
4295  //cout << "ids:" << i << " is:" << proc_ids[i] << endl;
4296  ids[i] = proc_ids[i];
4297  }
4298 
4299  ArrayView<const partId_t> idView(ids, groupSize);
4300  comm = comm->createSubcommunicator(idView);
4301  freeArray<partId_t>(ids);
4302 
4303 }
4304 
4305 template <typename mvector_t, typename lno_t, typename gno_t, typename scalar_t, typename node_t>
4306 void create_new_multi_vector(
4307  const RCP<const Environment> &env,
4308  RCP<Comm<int> > &comm,
4309  RCP <const mvector_t> &mvector,
4310  int multiVectorDim
4311  ){
4312 
4313  typedef ArrayView<const scalar_t> coordList_t;
4314  typedef Tpetra::Map<lno_t, gno_t, node_t> map_t;
4315 
4316  ArrayView<const gno_t> gnoList = mvector->getMap()->getNodeElementList();
4317  size_t localSize = mvector->getLocalLength();
4318 
4319  // Tpetra will calculate the globalSize.
4320  size_t globalSize = Teuchos::OrdinalTraits<size_t>::invalid();
4321 
4322  RCP<map_t> subMap;
4323  try{
4324  subMap= rcp(new map_t(globalSize, gnoList, 0, comm));
4325  }
4327 
4328  coordList_t *avSubList = allocMemory<coordList_t>(multiVectorDim);
4329 
4330  for (int dim=0; dim < multiVectorDim; dim++)
4331  avSubList[dim] = mvector->getData(dim).view(0, localSize);
4332 
4333  ArrayRCP<const ArrayView<const scalar_t> > subVectors =
4334  arcp(avSubList, 0, multiVectorDim);
4335 
4336 
4337  try{
4338  mvector = rcp(new mvector_t(
4339  subMap, subVectors.view(0, multiVectorDim), multiVectorDim));
4340  }
4342 }
4343 
4344 template <typename lno_t, typename partId_t>
4345 void resizeArrays(
4346  lno_t numLocalPoints,
4347  lno_t prev_num_local,
4348  partId_t *& partArray,
4349  partId_t *&permutation,
4350  partId_t *&oldpermutation){
4351 
4352 
4353 
4354  if (prev_num_local != numLocalPoints){
4355  freeArray<partId_t>(partArray);
4356  partArray = allocMemory<partId_t>(numLocalPoints);
4357 
4358  freeArray<lno_t>(permutation);
4359  freeArray<lno_t>(oldpermutation);
4360  oldpermutation = allocMemory<lno_t>(numLocalPoints);
4361  permutation = allocMemory<lno_t>(numLocalPoints);
4362  }
4363 
4364 }
4365 
4366 
4367 template <typename gno_t, typename lno_t,typename scalar_t, typename node_t>
4368 void getNewMultivectorArrays(
4369  RCP<Comm<int> > &comm,
4370  lno_t &numLocalPoints,
4371 
4372  int coord_dim,
4373  scalar_t **coords,
4374  int weight_dim,
4375  scalar_t **weight
4376  ,RCP<const Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> > coordsConst
4377  ,partId_t out_num_parts,
4378  lno_t *&permutations,
4379  lno_t *part_begins
4380  ,partId_t num_parts,
4381  int pqJagged_multiVectorDim
4382 
4383 ){
4384 
4385  for (int i=0; i < coord_dim; i++){
4386  ArrayRCP< const scalar_t > coord = coordsConst->getData(i);
4387  coords[i] =(scalar_t *) coord.getRawPtr();
4388  }
4389 
4390  for (int i=0; i < weight_dim; i++){
4391  if (i + coord_dim >= pqJagged_multiVectorDim) break;
4392  ArrayRCP< const scalar_t > wgts = coordsConst->getData(i+ coord_dim);
4393  weight[i] = (scalar_t *) wgts.getRawPtr();
4394  }
4395  //cout << "me:" << comm->getRank() << " obtained till weights:" << endl;
4396 
4397  if (out_num_parts == 1){
4398  //cout << "me:" << comm->getRank() << " filling permutation:" << endl;
4399  for(lno_t i = 0; i < numLocalPoints; ++i){
4400  permutations[i] = i;
4401  }
4402  part_begins[0] = numLocalPoints;
4403 
4404  //cout << "me:" << comm->getRank() << " filled permutation:" << endl;
4405  }
4406  else {
4407  scalar_t *assigned_parts = (scalar_t *)coordsConst->getData /*getData*/(pqJagged_multiVectorDim).getRawPtr();
4408  lno_t *counts = allocMemory<lno_t>(num_parts);
4409 
4410  partId_t *part_shifts = allocMemory<partId_t>(num_parts);
4411 
4412  memset(counts, 0, sizeof(lno_t) * num_parts);
4413 
4414  for(lno_t i = 0; i < numLocalPoints; ++i){
4415  partId_t ii = assigned_parts[i];
4416  ++counts[ii];
4417  }
4418  partId_t p = 0;
4419  lno_t prev_index = 0;
4420  for(partId_t i = 0; i < num_parts; ++i){
4421  //cout << "me:" << comm->getRank() << " p:" << i << " count:" << counts[i] << " a:" << assigned_parts << endl;
4422  if(counts[i] > 0) {
4423  part_begins[p] = prev_index + counts[i];
4424  prev_index += counts[i];
4425  part_shifts[i] = p++;
4426  }
4427  }
4428  partId_t assigned_count = p - 1;
4429 
4430  for (;p < num_parts; ++p){
4431  part_begins[p] = part_begins[assigned_count];
4432  }
4433  for(partId_t i = 0; i < out_num_parts; ++i){
4434  counts[i] = part_begins[i];
4435  }
4436  for(lno_t i = numLocalPoints - 1; i >= 0; --i){
4437  partId_t part = part_shifts[partId_t(assigned_parts[i])];
4438  permutations[--counts[part]] = i;
4439  }
4440 
4441  freeArray<lno_t>(counts);
4442  freeArray<partId_t>(part_shifts);
4443  }
4444 }
4445 
4446 
4447 
4448 template <typename lno_t, typename partId_t>
4449 void fillPermutationArrays(
4450  RCP<Comm<int> > &comm,
4451  lno_t &numLocalPoints,
4452  partId_t out_num_parts,
4453  lno_t *permutations,
4454  lno_t *part_begins,
4455  partId_t *assigned_parts,
4456  partId_t num_parts
4457 ){
4458  if (out_num_parts == 1){
4459  //cout << "me:" << comm->getRank() << " filling permutation:" << endl;
4460  for(lno_t i = 0; i < numLocalPoints; ++i){
4461  permutations[i] = i;
4462  }
4463  part_begins[0] = numLocalPoints;
4464  }
4465  else {
4466  lno_t *counts = allocMemory<lno_t>(num_parts);
4467 
4468  partId_t *part_shifts = allocMemory<partId_t>(num_parts);
4469 
4470  memset(counts, 0, sizeof(lno_t) * num_parts);
4471 
4472  for(lno_t i = 0; i < numLocalPoints; ++i){
4473  partId_t ii = assigned_parts[i];
4474  ++counts[ii];
4475  }
4476 /*
4477  for(partId_t i = 0; i < num_parts; ++i){
4478  cout << "me:" << comm->getRank() << " i:" << i << " c:" << counts[i] << endl;
4479  }
4480 */
4481  partId_t p = 0;
4482  lno_t prev_index = 0;
4483  for(partId_t i = 0; i < num_parts; ++i){
4484  //cout << "me:" << comm->getRank() << " p:" << i << " count:" << counts[i] << " a:" << assigned_parts << endl;
4485  if(counts[i] > 0) {
4486  part_begins[p] = prev_index + counts[i];
4487  prev_index += counts[i];
4488  part_shifts[i] = p++;
4489  }
4490  }
4491  partId_t assigned_count = p - 1;
4492 
4493  for (;p < num_parts; ++p){
4494  part_begins[p] = part_begins[assigned_count];
4495  }
4496  for(partId_t i = 0; i < out_num_parts; ++i){
4497  counts[i] = part_begins[i];
4498  }
4499  for(lno_t i = numLocalPoints - 1; i >= 0; --i){
4500  partId_t part = part_shifts[partId_t(assigned_parts[i])];
4501  permutations[--counts[part]] = i;
4502  }
4503 
4504  freeArray<lno_t>(counts);
4505  freeArray<partId_t>(part_shifts);
4506  }
4507 }
4508 
4509 
4510 template <typename gno_t,
4511  typename lno_t,
4512  typename scalar_t,
4513  typename node_t,
4514  typename partId_t>
4515 bool migration_refactored(
4516  RCP<Comm<int> > &pcomm, //original communication.
4517  const RCP<const Environment> &env, //environment
4518  RCP<Comm<int> > &comm, //current communication object.
4519 
4520  RCP<const Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> > &vectors, //multivector
4521  int pqJagged_multiVectorDim, //multivector dimension
4522 
4523  gno_t &numGlobalPoints, //numGlobal points, output
4524  lno_t &numLocalPoints, //numLocal points, output
4525 
4526  int coord_dim, // coordinate dimension
4527  scalar_t **coords, //coordinates.
4528  int weight_dim, //weight dimension
4529  scalar_t **weight, //weights
4530 
4531  partId_t * &assigned_parts_, //this should not be necessary anymore.
4532 
4533  partId_t num_parts, //current num parts
4534  partId_t &out_num_part, //output num parts.
4535  vector<partId_t> *newFuturePartitions,
4536 
4537  lno_t *&permutation,
4538  lno_t *&old_permutation,
4539 
4540  lno_t *partBeginArray,
4541  partId_t &partIndexBegin,
4542  //partId_t futurePartIndex,
4543 
4544  int all2alloption,
4545  int assignment_type,
4546  int doMigrationType,
4547  int migration_check_option,
4548  scalar_t migration_imbalance_cut_off,
4549  size_t futureReduceAll,
4550  lno_t numCoordinatesForLastDimPartitioning,
4551 
4552  gno_t *&coordinate_gnos,
4553  int *&actual_gno_owner,
4554  string iteration,
4555  int keep_part_boxes,
4556  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > &inPartBoxes,
4557  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > &outPartBoxes
4558 
4559 ){
4560 /*
4561  if(pcomm->getRank() == 0){
4562  cout << "doMigrationType:" << doMigrationType << endl;
4563  cout << "all2alloption:" << all2alloption << endl;
4564  cout << "assignment_type:" << assignment_type << endl;
4565  cout << "migration_check_option:" << migration_check_option << endl;
4566  }
4567 */
4568  int migration_proc_assignment_type = 1;
4569  partId_t nprocs = comm->getSize();
4570  partId_t myRank = comm->getRank();
4571  int multiVectorDim = pqJagged_multiVectorDim;
4572 
4573 
4574  gno_t *p_gno_np_global_num_coord_each_part_actual = NULL;
4575 
4576  //get the number of coordinates in each part in each processor.
4577  //p_gno_np_global_num_coord_each_part_actual is allocated in this function.
4578  //allocation_size is returned, and this is the size of p_gno_np_global_num_coord_each_part_actual array.
4579  //size_t allocation_size =
4580  getProcessorCoordinatePartCounts <gno_t, lno_t ,partId_t>(
4581  pcomm,
4582  env,
4583  comm,
4584 
4585  migration_proc_assignment_type,
4586  nprocs,
4587  myRank,
4588  num_parts,
4589  partBeginArray,
4590  p_gno_np_global_num_coord_each_part_actual);
4591 
4592 
4593  //check if migration will be performed or not.
4594  if (!checkMigration <gno_t, lno_t ,partId_t>(
4595  pcomm,
4596  env,
4597  comm,
4598 
4599  migration_check_option,
4600  futureReduceAll,
4601  numCoordinatesForLastDimPartitioning,
4602  migration_imbalance_cut_off,
4603 
4604  migration_proc_assignment_type,
4605  nprocs,
4606  myRank,
4607  num_parts,
4608 
4609  p_gno_np_global_num_coord_each_part_actual,
4610  partBeginArray)){
4611 
4612  freeArray<gno_t>(p_gno_np_global_num_coord_each_part_actual);
4613  return false;
4614  }
4615 
4616  //TODO only do it when doMigration is used.
4617  if (nprocs < num_parts) {
4618  if (doMigrationType == 0){
4619  vectors = createNewMultivector(
4620  comm,
4621  numGlobalPoints,
4622  numLocalPoints,
4623 
4624  coord_dim,
4625  coords,
4626 
4627  weight_dim,
4628  weight,
4629 
4630  num_parts,
4631  partBeginArray,
4632  permutation,
4633 
4634  multiVectorDim,
4635  vectors
4636  );
4637  } else {
4638 
4639  for (partId_t i = 0; i < num_parts; ++i){
4640  lno_t pBegin = 0;
4641  if (i > 0) pBegin = partBeginArray[i - 1];
4642  lno_t pEnd = partBeginArray[i];
4643 
4644 
4645 
4646  for (lno_t j = pBegin; j < pEnd; ++j){
4647  lno_t ind = permutation[j];
4648  assigned_parts_[ind] = i;
4649  }
4650  }
4651  }
4652  }
4653 
4654  const gno_t *gnoList = NULL;
4655 
4656 
4657  lno_t *sendCount = NULL;
4658  gno_t *sendBuf = NULL;
4659  int *coordinate_destionations = NULL;
4660  sendCount = allocMemory<lno_t>(nprocs);
4661  for (int i = 0; i < nprocs; ++i) sendCount[i] = 0;
4662 
4663  if (doMigrationType == 0){
4664 
4665  sendBuf = allocMemory<gno_t>(numLocalPoints);
4666 
4667  ArrayView<const gno_t> gno_list = vectors->getMap()->getNodeElementList();
4668  gnoList = gno_list.getRawPtr();
4669  }
4670  else {
4671 
4672  coordinate_destionations = allocMemory<int>(numLocalPoints);
4673  }
4674 
4675  vector<partId_t> ids;
4676  vector<partId_t> out_part_indices;
4677 
4678 
4679  getProcGroups_SendCounts_SendBuff<partId_t, lno_t, gno_t>(
4680  pcomm,
4681  migration_proc_assignment_type,
4682  assignment_type, //either assign to minimize migration, or assign to increase locality.
4683 
4684  p_gno_np_global_num_coord_each_part_actual,
4685  numGlobalPoints,
4686  numLocalPoints,
4687  num_parts,
4688  nprocs,
4689  myRank,
4690 
4691 
4692  partBeginArray, //holds the beginning of each part.
4693  permutation, //the permutation array ordered wrt partBegins array.
4694  gnoList, //gno array
4695 
4696  sendBuf, //output: sized nLocal, the buffer is filled by the function with gnos.
4697  sendCount, //output: sized nprocs, show the number of send point counts to each proc.
4698  ids, //output: this holds the id of the processors for the next subcommunicatior.
4699 
4700  //TODO futurePartIndex might need to be changed.
4701  //futurePartIndex,//input how many more partitions the part will be partitioned into.
4702  newFuturePartitions,
4703  out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
4704  out_part_indices, //output: the part index which the processor is assigned to.
4705  partIndexBegin, //output: how much the part number should be shifted when setting the solution
4706  doMigrationType,
4707  coordinate_destionations
4708  );
4709  vector <partId_t> tmpv;
4710  std::sort (out_part_indices.begin(), out_part_indices.end());
4711  partId_t outP = out_part_indices.size();
4712 
4713  gno_t newGlobalCount = 0;
4714  gno_t *p_gno_np_global_num_coord_each_part = p_gno_np_global_num_coord_each_part_actual + nprocs * num_parts;
4715 
4716 
4717  if (keep_part_boxes){
4718  inPartBoxes->clear();
4719  }
4720 
4721 
4722  for (partId_t i = 0; i < outP; ++i){
4723  partId_t ind = out_part_indices[i];
4724 
4725  newGlobalCount += p_gno_np_global_num_coord_each_part[ind];
4726 
4727  tmpv.push_back((*newFuturePartitions)[ind]);
4728 
4729  if (keep_part_boxes){
4730  //cout << "me:" << pcomm->getRank() << " is assigned to:" << ind << endl;
4731  //(*outPartBoxes)[ind].print();
4732  inPartBoxes->push_back((*outPartBoxes)[ind]);
4733  }
4734  }
4735 
4736 
4737  if (keep_part_boxes){
4738  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > tmpPartBoxes = inPartBoxes;
4739  inPartBoxes = outPartBoxes;
4740  outPartBoxes = tmpPartBoxes;
4741  }
4742 
4743  newFuturePartitions->clear();
4744 
4745  for (partId_t i = 0; i < outP; ++i){
4746  partId_t p = tmpv[i];
4747  newFuturePartitions->push_back(p);
4748  }
4749 
4750  ArrayRCP<gno_t> recvBuf;
4751  gno_t numMyNewGnos = 0;
4752 
4753 
4754  /*
4755  pcomm->barrier();
4756  cout << "it:" << iteration << " in doAll2All:" << endl;
4757  */
4758  env->timerStart(MACRO_TIMERS, "PQJagged - Migration AlltoAll-" + iteration);
4759  doAll2All<partId_t, lno_t, gno_t, scalar_t>(
4760  env, //environment
4761  comm, //current communication object.
4762  doMigrationType,
4763  all2alloption,
4764  nprocs,
4765  numLocalPoints,
4766  sendCount,
4767  sendBuf,
4768  recvBuf,
4769  numMyNewGnos,
4770  iteration,
4771 
4772  coord_dim,
4773  coords,
4774  weight_dim,
4775  weight,
4776  coordinate_gnos,
4777  actual_gno_owner,
4778  coordinate_destionations,
4779  assigned_parts_,
4780  num_parts
4781  );
4782  /*
4783  pcomm->barrier();
4784  cout << "it:" << iteration << " out doAll2All:" << endl;
4785  */
4786 
4787  env->timerStop(MACRO_TIMERS, "PQJagged - Migration AlltoAll-" + iteration);
4788 
4789 
4790  if (doMigrationType == 0){
4791  freeArray<gno_t>(sendBuf);
4792  }
4793  else {
4794  freeArray<int>(coordinate_destionations);
4795 
4796  if(numLocalPoints != numMyNewGnos){
4797  freeArray<lno_t>(permutation);
4798  freeArray<lno_t>(old_permutation);
4799 
4800  permutation = allocMemory<lno_t>(numMyNewGnos);
4801  old_permutation = allocMemory<lno_t>(numMyNewGnos);
4802  }
4803  numLocalPoints = numMyNewGnos;
4804  numGlobalPoints = newGlobalCount;
4805  }
4806  freeArray<lno_t>(sendCount);
4807  freeArray<gno_t>(p_gno_np_global_num_coord_each_part_actual);
4808 
4809  typedef Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> mvector_t;
4810  if(doMigrationType == 0){
4811  env->timerStart(MACRO_TIMERS, "PQJagged - Migration doActualMigration-" + iteration);
4812  doActualMigration<mvector_t, gno_t>(
4813  env, //environment
4814  vectors, // on return is the new data,
4815  numMyNewGnos,
4816  recvBuf);
4817 
4818  env->timerStop(MACRO_TIMERS, "PQJagged - Migration doActualMigration-" + iteration);
4819  }
4820  createSubCommunicator <partId_t>(comm, ids);
4821  ids.clear();
4822 
4823  if(doMigrationType == 0){
4824  create_new_multi_vector<mvector_t, lno_t, gno_t,scalar_t, node_t>(
4825  env, comm,
4826  vectors,
4827  multiVectorDim
4828  );
4829 
4830 
4831 
4832 
4833  lno_t prev_num_local = numLocalPoints;
4834  numLocalPoints = vectors->getLocalLength();
4835  numGlobalPoints = vectors->getGlobalLength();
4836 
4837 
4838 
4839  resizeArrays<lno_t, partId_t>(
4840  numLocalPoints,
4841  prev_num_local,
4842  assigned_parts_,
4843  permutation,
4844  old_permutation
4845  );
4846 
4847 
4848  getNewMultivectorArrays<gno_t, lno_t,scalar_t, node_t>(
4849  comm,
4850  numLocalPoints,
4851  coord_dim,
4852  coords,
4853  weight_dim,
4854  weight,
4855  vectors,
4856  out_num_part,
4857  permutation,
4858  partBeginArray,
4859  num_parts,
4860  pqJagged_multiVectorDim
4861 
4862  );
4863  }
4864  else {
4865  fillPermutationArrays<lno_t,partId_t>(
4866  comm,
4867  numLocalPoints,
4868  out_num_part,
4869  permutation,
4870  partBeginArray,
4871  assigned_parts_,
4872  num_parts
4873  );
4874  }
4875 
4876  return true;
4877 }
4878 
4879 #endif
4880 
4881 template <typename scalar_t, typename partId_t>
4883  const partId_t *partNo,
4884  vector <partId_t> &pAlongI, //assumes this vector is empty.
4885  vector<partId_t> *currentPartitions,
4886  vector<partId_t> *newFuturePartitions, //assumes this vector is empty.
4887  partId_t &futurePartNumbers,
4888 
4889  partId_t currentPartitionCount,
4890  int partArraySize,
4891  int i,
4892  partId_t maxPartNo,
4893  int keep_part_boxes,
4894  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > inPartBoxes,
4895  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > outPartBoxes
4896 ){
4897  partId_t outPartCount = 0;
4898  if(partNo){
4899  //when the partNo array is provided as input,
4900  //each current partition will be partition to the same number of parts.
4901  //we dont need to use the currentPartition vector in this case.
4902 
4903  partId_t p = partNo[i];
4904  if (p < 1){
4905  cout << "i:" << i << " p is given as:" << pAlongI[0] << endl;
4906  exit(1);
4907  }
4908  if (p == 1){
4909  return currentPartitionCount;
4910  }
4911 
4912  for (partId_t ii = 0; ii < currentPartitionCount; ++ii){
4913  pAlongI.push_back(p);
4914 
4915  }
4916 
4917  //TODO this should be removed.
4918  futurePartNumbers /= pAlongI[0];
4919  outPartCount = currentPartitionCount * pAlongI[0];
4920 
4921  if (keep_part_boxes){
4922  for (partId_t k = 0; k < currentPartitionCount; ++k){
4923  for (partId_t j = 0; j < pAlongI[0]; ++j){
4924  outPartBoxes->push_back((*inPartBoxes)[k]);
4925  }
4926  }
4927  }
4928 
4929  //set the how many more parts each part will be divided.
4930  //this is obvious when partNo array is provided as input.
4931  //however, fill this so that weights will be calculated according to this array.
4932  for (partId_t ii = 0; ii < outPartCount; ++ii){
4933  newFuturePartitions->push_back(futurePartNumbers);
4934  }
4935  }
4936  else {
4937  //if partNo array is not provided as input,
4938  //currentPartitions hold how many parts each part should be divided.
4939  //initially it has single number with total number of global parts.
4940 
4941  //calculate the futurePartNumbers from beginning,
4942  //since each part might be divided into different number of parts.
4943  futurePartNumbers = 1; //TODO this should be removed.
4944 
4945  //cout << "i:" << i << endl;
4946  float fEpsilon = numeric_limits<float>::epsilon();
4947  for (partId_t ii = 0; ii < currentPartitionCount; ++ii){
4948  //get how many parts a part should be divided.
4949  partId_t numFuture = (*currentPartitions)[ii];
4950 
4951  //get the ideal number of parts that is close to the
4952  //(partArraySize - i) root of the numFuture.
4953  partId_t numParts = getPartCount<partId_t>( numFuture, 1.0f / (partArraySize - i), fEpsilon);
4954  //partId_t numParts = ceil( pow(numFuture, 1.0f / (partArraySize - i)));// + 0.5f;
4955 
4956  //cout << "\tii:" << ii << " numParts:" << numParts << endl;
4957  //cout << "\tii:" << ii << " numFuture:" << numFuture << endl;
4958  if (numParts > maxPartNo){
4959  cerr << "ERROR: maxPartNo calculation is wrong." << endl;
4960  exit(1);
4961  }
4962  //add this number to pAlongI vector.
4963  pAlongI.push_back(numParts);
4964 
4965 
4966  //increase the output number of parts.
4967  outPartCount += numParts;
4968 
4969  //ideal number of future partitions for each part.
4970  partId_t idealNumFuture = numFuture / numParts;
4971  for (partId_t iii = 0; iii < numParts; ++iii){
4972  partId_t fNofCuts = idealNumFuture;
4973 
4974  if (iii < numFuture % numParts){
4975  //if not uniform, add 1 for the extra parts.
4976  ++fNofCuts;
4977  }
4978  newFuturePartitions->push_back(fNofCuts);
4979 
4980  if (keep_part_boxes){
4981  //for (partId_t j = 0; j < numParts; ++j){
4982  outPartBoxes->push_back((*inPartBoxes)[ii]);
4983  //}
4984  }
4985 
4986 
4987  //TODO this should be removed.
4988  if (fNofCuts > futurePartNumbers) futurePartNumbers = fNofCuts;
4989  }
4990  }
4991 
4992  }
4993  return outPartCount;
4994 }
4995 
5010 template <typename scalar_t, typename lno_t, typename partId_t>
5012  scalar_t &maxCoordinate,
5013  scalar_t &minCoordinate,
5014 
5015  partId_t &currentPart,
5016  lno_t *inTotalCounts,
5017  lno_t *partitionedPointCoordinates,
5018  scalar_t *pqCoord,
5019  partId_t *partIds,
5020 
5021  scalar_t _EPSILON,
5022  partId_t &partition
5023 ){
5024  scalar_t coordinate_range = maxCoordinate - minCoordinate;
5025  //partId_t currentPart = currentWorkPart + kk;
5026  lno_t coordinateEnd= inTotalCounts[currentPart];
5027  lno_t coordinateBegin = currentPart==0 ? 0: inTotalCounts[currentPart -1];
5028 
5029  //if there is single point, or if all points are along a line.
5030  //set initial part to 0 for all.
5031  if(ABS(coordinate_range) < _EPSILON ){
5032 #ifdef HAVE_ZOLTAN2_OMP
5033 #pragma omp parallel for
5034 #endif
5035  for(lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
5036  partIds[partitionedPointCoordinates[ii]] = 0;
5037  }
5038  }
5039  else{
5040 
5041  //otherwise estimate an initial part for each coordinate.
5042  //assuming uniform distribution of points.
5043  scalar_t slice = coordinate_range / partition;
5044 
5045 #ifdef HAVE_ZOLTAN2_OMP
5046 #pragma omp parallel for
5047 #endif
5048  for(lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
5049 
5050  lno_t iii = partitionedPointCoordinates[ii];
5051  partId_t pp = partId_t((pqCoord[iii] - minCoordinate) / slice);
5052  partIds[iii] = 2 * pp;
5053  }
5054  }
5055 }
5056 
5057 
5058 
5059 template <typename partId_t>
5060 void getPartSpecifications(const partId_t *partNo,
5061  int partArraySize,
5062  size_t &numGlobalParts,
5063  partId_t &totalDimensionCut, //how many cuts will be totally
5064  partId_t &totalPartCount , //how many parts will be totally
5065  partId_t &maxPartNo , //maximum cut count along a dimension.
5066  partId_t &reduceAllCount , //estimate on how many reduceAlls will be done.
5067  partId_t &maxTotalCumulativePartCount, //maximum number of parts that might occur
5068  //during the partition before the last partitioning dimension.
5069  partId_t &maxCutNo,
5070  size_t &maxTotalPartCount
5071 ){
5072  if (partNo){
5073  for (int i = 0; i < partArraySize; ++i){
5074  reduceAllCount += totalPartCount;
5075  totalPartCount *= partNo[i];
5076  if(partNo[i] > maxPartNo) maxPartNo = partNo[i];
5077  }
5078  maxTotalCumulativePartCount = totalPartCount / partNo[partArraySize - 1];
5079  numGlobalParts = totalPartCount;
5080  } else {
5081  float fEpsilon = numeric_limits<float>::epsilon();
5082  partId_t futureNumParts = numGlobalParts;
5083 
5084  for (int i = 0; i < partArraySize; ++i){
5085 
5086  partId_t maxNoPartAlongI = getPartCount<partId_t>( futureNumParts, 1.0f / (partArraySize - i), fEpsilon);
5087  //cout << "futureNumParts:" << futureNumParts << "partArraySize:" << partArraySize << " i:" << i << "maxNoPartAlongI:" << maxNoPartAlongI<< endl;
5088  //partId_t maxNoPartAlongI = ceil(pow(futureNumParts, 1.0f / (coordDim - i)));// + 0.5f;
5089  if (maxNoPartAlongI > maxPartNo){
5090  maxPartNo = maxNoPartAlongI;
5091  }
5092  //cout << "i:" << i << "maxPartNo:" << maxPartNo<< endl;
5093 
5094  partId_t nfutureNumParts = futureNumParts / maxNoPartAlongI;
5095  if (futureNumParts % maxNoPartAlongI){
5096  ++nfutureNumParts;
5097  }
5098  futureNumParts = nfutureNumParts;
5099  //cout << "i:" << i << " fp:" << futureNumParts << endl;
5100  }
5101  totalPartCount = numGlobalParts;
5102  //estimate reduceAll Count here.
5103  //we find the upperbound instead.
5104  partId_t p = 1;
5105  for (int i = 0; i < partArraySize; ++i){
5106  reduceAllCount += p;
5107  p *= maxPartNo;
5108  }
5109 
5110  //cout << "maxPartNo:" << maxPartNo << endl;
5111  maxTotalCumulativePartCount = p / maxPartNo;
5112  }
5113 
5114  totalDimensionCut = totalPartCount - 1;
5115  maxCutNo = maxPartNo - 1;
5116  maxTotalPartCount = maxPartNo + size_t(maxCutNo);
5117  //maxPartNo is P, maxCutNo = P-1, matTotalPartcount = 2P-1
5118 }
5119 
5120 
5121 
5152 template <typename lno_t, typename scalar_t>
5154  partId_t partNo,
5155  int noThreads,
5156 
5157  lno_t *partitionedPointPermutations,
5158  scalar_t *pqJagged_coordinates,
5159  bool pqJagged_uniformWeights,
5160  scalar_t *coordWeights,
5161  scalar_t *cutCoordinates,
5162  lno_t coordinateBegin,
5163  lno_t coordinateEnd,
5164 
5165  bool allowNonRectelinearPart,
5166  float *actual_ratios,
5167  scalar_t *localPartWeights,
5168  double **partWeights,
5169  float **nonRectelinearRatios,
5170 
5171  lno_t ** partPointCounts,
5172 
5173  lno_t *newpartitionedPointPermutations,
5174  lno_t *totalCounts,
5175  partId_t *partIds,
5176 
5177  bool isSequentialAndPricise,
5178  scalar_t **pqJaggedAllCoordinates,
5179  int pqCoordDim,
5180  int currentCoord
5181 ){
5182 
5183  //lno_t numCoordsInPart = coordinateEnd - coordinateBegin;
5184  partId_t noCuts = partNo - 1;
5185  //size_t total_part_count = noCuts + partNo;
5186  scalar_t _EPSILON = numeric_limits<scalar_t>::epsilon();
5187 
5188  //if (migration_check == true) allowNonRectelinearPart = false;
5189 #ifdef HAVE_ZOLTAN2_OMP
5190 #pragma omp parallel
5191 #endif
5192  {
5193  int me = 0;
5194 #ifdef HAVE_ZOLTAN2_OMP
5195  me = omp_get_thread_num();
5196 #endif
5197 
5198  lno_t *myPartPointCounts = partPointCounts[me];
5199  float *myRatios = NULL;
5200  if (allowNonRectelinearPart){
5201 
5202 
5203  myRatios = nonRectelinearRatios[me];
5204 #ifdef HAVE_ZOLTAN2_OMP
5205 #pragma omp for
5206 #endif
5207  for (partId_t i = 0; i < noCuts; ++i){
5208  //float r = actual_ratios[i];
5209  //scalar_t leftWeight = r * (localPartWeights[i * 2 + 1] - localPartWeights[i * 2]);
5210  scalar_t leftWeight = actual_ratios[i];
5211  for(int ii = 0; ii < noThreads; ++ii){
5212  if(leftWeight > _EPSILON){
5213 
5214  scalar_t ithWeight = partWeights[ii][i * 2 + 1] - partWeights[ii][i * 2 ];
5215  if(ithWeight < leftWeight){
5216  nonRectelinearRatios[ii][i] = ithWeight;
5217  }
5218  else {
5219  nonRectelinearRatios[ii][i] = leftWeight ;
5220  }
5221  leftWeight -= ithWeight;
5222  }
5223  else {
5224  nonRectelinearRatios[ii][i] = 0;
5225  }
5226  }
5227  }
5228 
5229 /*
5230  for (partId_t i = 0; i < noCuts; ++i){
5231  cout << "myR:" << i << " is:" << myRatios[i] << endl;
5232  }
5233 */
5234  if(noCuts > 0){
5235  for (partId_t i = noCuts - 1; i > 0 ; --i){
5236  if(ABS(cutCoordinates[i] - cutCoordinates[i -1]) < _EPSILON){
5237  myRatios[i] -= myRatios[i - 1] ;
5238  }
5239  myRatios[i] = int ((myRatios[i] + LEAST_SIGNIFICANCE) * SIGNIFICANCE_MUL) / scalar_t(SIGNIFICANCE_MUL);
5240  }
5241  }
5242 /*
5243  for (partId_t i = 0; i < noCuts; ++i){
5244  cout << "myR:" << i << " is:" << myRatios[i] << endl;
5245  }
5246 */
5247 
5248 
5249  }
5250 
5251  for(partId_t ii = 0; ii < partNo; ++ii){
5252  myPartPointCounts[ii] = 0;
5253  }
5254 
5255  if(!allowNonRectelinearPart || !isSequentialAndPricise) {
5256 
5257 #ifdef HAVE_ZOLTAN2_OMP
5258 #pragma omp for
5259 #endif
5260  for (lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
5261 
5262  lno_t i = partitionedPointPermutations[ii];
5263  scalar_t w = pqJagged_uniformWeights? 1:coordWeights[i];
5264  partId_t pp = partIds[i];
5265  partId_t p = pp / 2;
5266  if(pp % 2 == 1){
5267  if(allowNonRectelinearPart && myRatios[p] > _EPSILON * EPS_SCALE){
5268  //cout << "pa:" << p << endl;
5269  myRatios[p] -= w;
5270  if(myRatios[p] < 0 && p < noCuts - 1 && ABS(cutCoordinates[p+1] - cutCoordinates[p]) < _EPSILON){
5271  myRatios[p + 1] += myRatios[p];
5272  }
5273  ++myPartPointCounts[p];
5274  partIds[i] = p;
5275  }
5276  else{
5277  ++p;
5278  //this while loop is necessary when a line is partitioned into
5279  //more than 2 parts.
5280 
5281  while(allowNonRectelinearPart &&
5282  p < noCuts){
5283  //traverse all the cut lines having the same partitiong
5284  if(ABS(cutCoordinates[p] - cutCoordinates[p - 1]) < _EPSILON){
5285  //if line has enough space on left, put it there.
5286  if(myRatios[p] > _EPSILON * EPS_SCALE && myRatios[p] >= ABS(myRatios[p] - w)){
5287  //scalar_t w = pqJagged_uniformWeights? 1:coordWeights[i];
5288  myRatios[p] -= w;
5289  if(myRatios[p] < 0 && p < noCuts - 1 && ABS(cutCoordinates[p+1] - cutCoordinates[p]) < _EPSILON){
5290  myRatios[p + 1] += myRatios[p];
5291  }
5292  break;
5293  }
5294  }
5295  else {
5296  //if cut coordinates are different, put it to next part.
5297  break;
5298  }
5299  ++p;
5300  }
5301 
5302  //scalar_t currentCut = cutCoordinates[p];
5303  //TODO:currently cannot divide 1 line more than 2 parts.
5304  //bug cannot be divided, therefore this part should change.
5305  //cout << "p:" << p+1 << endl;
5306  //++myPartPointCounts[p + 1];
5307  //partIds[i] = p + 1;
5308  ++myPartPointCounts[p];
5309  partIds[i] = p;
5310  }
5311  }
5312  else {
5313  ++myPartPointCounts[p];
5314  partIds[i] = p;
5315  }
5316  }
5317 /*
5318  for (partId_t p = 0; p < noCuts; ++p){
5319 
5320  cout << "p:" << p <<
5321  " myPartPointCounts[p]:" << myPartPointCounts[p] <<
5322  " \t\tcutCoorD:" << cutCoordinates[p] <<
5323  " \tmyRatios[i]:" << myRatios[p] <<
5324  " \tactual_ratios:" << actual_ratios[p] <<
5325  endl;
5326 
5327  }
5328  cout << "p:" << noCuts << " myPartPointCounts[p]:" << myPartPointCounts[noCuts] << endl;
5329 */
5330  } else {
5331  partId_t *cutMap = allocMemory<partId_t> (noCuts);
5332 
5333  typedef uMultiSortItem<lno_t, int, scalar_t> multiSItem;
5334  typedef std::vector< multiSItem > multiSVector;
5335  typedef std::vector<multiSVector> multiS2Vector;
5336 
5337  std::vector<scalar_t *>allocated_memory;
5338  //scalar_t *currentPartWeight = allocMemory<scalar_t> (partNo);
5339  //memset(currentPartWeight, 0, sizeof(scalar_t) * partNo);
5340 
5341  multiS2Vector cutPointSortArrays;
5342 
5343  partId_t differentCutCount = 1;
5344  cutMap[0] = 0;
5345 
5346  multiSVector tmpMultiSVector;
5347  cutPointSortArrays.push_back(tmpMultiSVector);
5348 
5349  for (partId_t i = 1; i < noCuts ; ++i){
5350  if(ABS(cutCoordinates[i] - cutCoordinates[i -1]) < _EPSILON){
5351  cutMap[i] = cutMap[i-1];
5352  }
5353  else {
5354  cutMap[i] = differentCutCount++;
5355  multiSVector tmp2MultiSVector;
5356  cutPointSortArrays.push_back(tmp2MultiSVector);
5357  }
5358  }
5359 
5360 
5361 #ifdef HAVE_ZOLTAN2_OMP
5362 #pragma omp for
5363 #endif
5364  for (lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
5365 
5366  lno_t i = partitionedPointPermutations[ii];
5367  //scalar_t w = pqJagged_uniformWeights? 1:coordWeights[i];
5368 
5369  //cout << "index:" << i << " pqJagged_coordinates:" << pqJagged_coordinates[i] << " p:" << partIds[i] << endl;
5370  partId_t pp = partIds[i];
5371  partId_t p = pp / 2;
5372  if(pp % 2 == 1 /*&& ABS(actual_ratios[p] - 1.0f) < _EPSILON*/){
5373  scalar_t *vals = allocMemory<scalar_t>(pqCoordDim -1);
5374  allocated_memory.push_back(vals);
5375 
5376  int val_ind = 0;
5377  for(int dim = currentCoord + 1; dim < pqCoordDim; ++dim){
5378  vals[val_ind++] = pqJaggedAllCoordinates[dim][i];
5379  }
5380  for(int dim = 0; dim < currentCoord; ++dim){
5381  vals[val_ind++] = pqJaggedAllCoordinates[dim][i];
5382  }
5383  multiSItem tempSortItem(i, pqCoordDim -1, vals);
5384 
5385  partId_t cmap = cutMap[p];
5386  cutPointSortArrays[cmap].push_back(tempSortItem);
5387 
5388  }
5389  else {
5390  ++myPartPointCounts[p];
5391  partIds[i] = p;
5392  //currentPartWeight[p] += w;
5393  }
5394  }
5395 
5396  for (partId_t i = 0; i < differentCutCount; ++i){
5397  std::sort (cutPointSortArrays[i].begin(), cutPointSortArrays[i].end());
5398  }
5399 
5400 
5401  /*
5402  cout << "differentCutCount:" << differentCutCount << endl;
5403 
5404  for (partId_t p = 0; p < noCuts; ++p){
5405 
5406  partId_t mappedCut = cutMap[p];
5407  lno_t cutPointCount = (lno_t)cutPointSortArrays[mappedCut].size();
5408  cout << "p:" << p <<
5409  " mappedCut:" << mappedCut <<
5410  " myPartPointCounts[p]:" << myPartPointCounts[p] <<
5411  " \t\tcutCoorD:" << cutCoordinates[p] <<
5412  " \tcutPointCount[p]:" << cutPointCount <<
5413  " \tmyRatios[i]:" << myRatios[p] <<
5414  " \tactual_ratios:" << actual_ratios[p] <<
5415  endl;
5416 
5417  }
5418  cout << "p:" << noCuts << " myPartPointCounts[p]:" << myPartPointCounts[noCuts] << endl;
5419  */
5420  partId_t prevMap = cutMap[0];
5421  scalar_t leftOver = 0;
5422  for (partId_t p = 0; p < noCuts; ++p){
5423  /*
5424  {
5425  partId_t mappedCut = cutMap[p];
5426  lno_t cutPointCount = (lno_t)cutPointSortArrays[mappedCut].size();
5427 
5428  cout << "p:" << p <<
5429  " mappedCut:" << mappedCut <<
5430  " myPartPointCounts[p]:" << myPartPointCounts[p] <<
5431  " \t\tcutCoorD:" << cutCoordinates[p] <<
5432  " \tcutPointCount[p]:" << cutPointCount <<
5433  " \tmyRatios[i]:" << myRatios[p] <<
5434  " \tactual_ratios:" << actual_ratios[p] <<
5435  endl;
5436 
5437  }
5438  */
5439  //cout << "p:" << p << " leftOVer:" << leftOver << endl;
5440  partId_t mappedCut = cutMap[p];
5441  if (prevMap != mappedCut){
5442  //biggestCutForVector[mappedCut] = p;
5443  lno_t vEnd = (lno_t)cutPointSortArrays[prevMap].size() - 1;
5444  for (; vEnd >= 0; --vEnd){
5445  multiSItem t = cutPointSortArrays[prevMap][vEnd];
5446  lno_t i = t.index;
5447  //scalar_t w = pqJagged_uniformWeights? 1:coordWeights[i];
5448  //cutPointSortArrays[mappedCut].pop_back();
5449  //cout << "putting i : " << i << " on cut:" << prevMap << " to part p:" << p << endl;
5450  ++myPartPointCounts[p];
5451  partIds[i] = p;
5452  }
5453  cutPointSortArrays[prevMap].clear();
5454  }
5455  //biggestCutForVector[mappedCut] = p;
5456  lno_t vEnd = (lno_t)cutPointSortArrays[mappedCut].size() - 1;
5457 
5458  //cout << "c:" << p << " r:" << myRatios[p] << " leftOver:" << leftOver << endl;
5459  //scalar_t leftPartW = currentPartWeight[p];
5460 
5461  for (; vEnd >= 0; --vEnd){
5462  multiSItem t = cutPointSortArrays[mappedCut][vEnd];
5463  lno_t i = t.index;
5464  scalar_t w = pqJagged_uniformWeights? 1:coordWeights[i];
5465 
5466  if(myRatios[p] + leftOver> _EPSILON * EPS_SCALE &&
5467  myRatios[p] + leftOver - ABS(myRatios[p] + leftOver - w) > _EPSILON){
5468 /*
5469  if (p == 4){
5470  cout << "**4***MyRatios:" << myRatios[p] <<
5471  " w:" << w;
5472 
5473  }
5474 */
5475  myRatios[p] -= w;
5476 /*
5477  if (p == 4){
5478  cout << " becomes:" << myRatios[p] << endl;
5479  }
5480 */
5481  cutPointSortArrays[mappedCut].pop_back();
5482  ++myPartPointCounts[p];
5483  //cout << "putting i : " << i << " on cut:" << p << " to part p:" << p << endl;
5484  partIds[i] = p;
5485  if(p < noCuts - 1 && myRatios[p] < _EPSILON){
5486  if(mappedCut == cutMap[p + 1] ){
5487  if (prevMap != mappedCut){
5488  leftOver = myRatios[p];
5489  }
5490  else {
5491  leftOver += myRatios[p];
5492  }
5493  }
5494  else{
5495  leftOver = -myRatios[p];
5496  }
5497  break;
5498  }
5499  } else {
5500  if(p < noCuts - 1 && mappedCut == cutMap[p + 1]){
5501  if (prevMap != mappedCut){
5502  leftOver = myRatios[p];
5503  }
5504  else {
5505  leftOver += myRatios[p];
5506  }
5507  }
5508  else{
5509  leftOver = -myRatios[p];
5510  }
5511  break;
5512  }
5513  }
5514  prevMap = mappedCut;
5515  }
5516  {
5517  lno_t vEnd = (lno_t)cutPointSortArrays[prevMap].size() - 1;
5518  for (; vEnd >= 0; --vEnd){
5519  multiSItem t = cutPointSortArrays[prevMap][vEnd];
5520  lno_t i = t.index;
5521  //scalar_t w = pqJagged_uniformWeights? 1:coordWeights[i];
5522  //cutPointSortArrays[mappedCut].pop_back();
5523  //cout << "putting i : " << i << " on cut:" << prevMap << " to part p:" << noCuts << endl;
5524  ++myPartPointCounts[noCuts];
5525  partIds[i] = noCuts;
5526  }
5527  cutPointSortArrays[prevMap].clear();
5528  }
5529 
5530  freeArray<partId_t> (cutMap);
5531  //freeArray<scalar_t> (currentPartWeight);
5532 
5533  lno_t vSize = (lno_t) allocated_memory.size();
5534  for(lno_t i = 0; i < vSize; ++i){
5535  freeArray<scalar_t> (allocated_memory[i]);
5536  }
5537  }
5538 
5539 
5540 #ifdef HAVE_ZOLTAN2_OMP
5541 #pragma omp for
5542 #endif
5543  for(partId_t j = 0; j < partNo; ++j){
5544  lno_t pwj = 0;
5545  for (int i = 0; i < noThreads; ++i){
5546  lno_t threadPartPointCount = partPointCounts[i][j];
5547  partPointCounts[i][j] = pwj;
5548  pwj += threadPartPointCount;
5549 
5550  }
5551  totalCounts[j] = pwj;// + prev2; //+ coordinateBegin;
5552  }
5553 
5554 #ifdef HAVE_ZOLTAN2_OMP
5555 #pragma omp single
5556 #endif
5557  {
5558  for(partId_t j = 1; j < partNo; ++j){
5559  totalCounts[j] += totalCounts[j - 1];
5560  }
5561  }
5562 
5563  for(partId_t j = 1; j < partNo; ++j){
5564  myPartPointCounts[j] += totalCounts[j - 1] ;
5565  }
5566 
5567 
5568 #ifdef HAVE_ZOLTAN2_OMP
5569 #pragma omp for
5570 #endif
5571  for (lno_t ii = coordinateBegin; ii < coordinateEnd; ++ii){
5572  lno_t i = partitionedPointPermutations[ii];
5573  partId_t p = partIds[i];
5574  newpartitionedPointPermutations[coordinateBegin + myPartPointCounts[p]++] = i;
5575  }
5576  }
5577 }
5578 
5579 
5580 
5581 
5582 template <typename scalar_t, typename lno_t, typename partId_t>
5584  const RCP<const Environment> &env,
5585  lno_t numLocalCoords,
5586  lno_t actualNumCoords,
5587  size_t numGlobalParts,
5588  int coordDim,
5589  scalar_t **pqJagged_coordinates,
5590  lno_t *output_permutation,
5591  lno_t *output_partIndices
5592  //,string partitioningName
5593  ){
5594  //env->timerStart(MACRO_TIMERS, "PQJagged - " +partitioningName+"-Problem_Partitioning");
5595 
5596  const RCP<Comm<int> > commN;
5597  RCP<Comm<int> >comm = Teuchos::rcp_const_cast<Comm<int> >
5598  (Teuchos::DefaultComm<int>::getDefaultSerialComm(commN));
5599 
5600 
5601  const partId_t *partNo = NULL;
5602  int partArraySize = 0;
5603 
5604  //weights are uniform for task mapping
5605  bool pqJagged_uniformWeights[1];
5606  pqJagged_uniformWeights[0] = true;
5607 
5608 
5609  //parts are uniform for task mapping
5610  bool pqJagged_uniformParts[1];
5611  pqJagged_uniformParts[0] = true;
5612  scalar_t *pqJagged_partSizes[1];
5613  pqJagged_partSizes[0] = NULL;
5614  //no weights
5615  //int weightDim = 0;
5616  scalar_t pqJagged_weights[1][1];
5617 
5618 
5619  //as input indices.
5620  lno_t *partitionedPointCoordinates = allocMemory< lno_t>(numLocalCoords);
5621  //initial configuration
5622  //set each pointer-i to i.
5623 #ifdef HAVE_ZOLTAN2_OMP
5624 #pragma omp parallel for
5625 #endif
5626  for(size_t i = 0; i < static_cast<size_t>(numLocalCoords); ++i){
5627  partitionedPointCoordinates[i] = output_permutation[i];
5628  }
5629 
5630  //as output indices
5631  lno_t *newpartitionedPointCoordinates = allocMemory< lno_t>(numLocalCoords);
5632 #ifdef HAVE_ZOLTAN2_OMP
5633 #ifdef FIRST_TOUCH
5634  firstTouch<lno_t>(newpartitionedPointCoordinates, numLocalCoords);
5635 #endif
5636 #endif
5637 
5638 
5639  partId_t *partIds = NULL;
5640  ArrayRCP<partId_t> partId;
5641  if(numLocalCoords > 0){
5642  partIds = allocMemory<partId_t>(numLocalCoords);
5643  }
5644 
5645  //initially there is a single partition
5646  partId_t currentPartitionCount = 1;
5647  //single partition starts at index-0, and ends at numLocalCoords
5648  //inTotalCounts array holds the end points in partitionedPointCoordinates array
5649  //for each partition. Initially sized 1, and single element is set to numLocalCoords.
5650  lno_t *inTotalCounts = allocMemory<lno_t>(1);
5651  inTotalCounts[0] = static_cast<lno_t>(actualNumCoords);//the end of the initial partition is the end of coordinates.
5652  //the ends points of the output.
5653  lno_t *outTotalCounts = NULL;
5654 
5655 
5656 
5657  //get pqJagged specific parameters.
5658  bool allowNonRectelinearPart = true;
5659  int concurrentPartCount = 1; // Set to invalid value
5660 
5661 
5662  int numThreads = 1;
5663 #ifdef HAVE_ZOLTAN2_OMP
5664 #pragma omp parallel shared(numThreads)
5665  {
5666  numThreads = omp_get_num_threads();
5667  }
5668 
5669 #endif
5670 
5671 
5672  partId_t totalDimensionCut = 0; //how many cuts will be totally
5673  partId_t totalPartCount = 1; //how many parts will be totally
5674  partId_t maxPartNo = 0; //maximum cut count along a dimension.
5675  partId_t reduceAllCount = 0; //estimate on how many reduceAlls will be done.
5676  partId_t maxTotalCumulativePartCount = 1; //maximum number of parts that might occur
5677  //during the partition before the last partitioning dimension.
5678  partId_t maxCutNo = 0;
5679  size_t maxTotalPartCount = 0;
5680 
5681  partArraySize = coordDim;
5682  getPartSpecifications <partId_t>(
5683  partNo, //partNoArray Input
5684  partArraySize, //size of the partNoArray --output if partNo is not given.
5685  //coordDim, //coordinate dim
5686  numGlobalParts, //how many global parts will be -- output if partNo is not given.
5687  totalDimensionCut, //how many cuts will be totally
5688  totalPartCount , //how many parts will be totally
5689  maxPartNo , //maximum cut count along a dimension.
5690  reduceAllCount , //estimate on how many reduceAlls will be done.
5691  maxTotalCumulativePartCount, //maximum number of parts that might occur
5692  //during the partition before the last partitioning dimension.
5693  maxCutNo,
5694  maxTotalPartCount
5695  );
5696 
5697 
5698  // coordinates of the cut lines. First one is the min, last one is max coordinate.
5699  // kddnote if (keep_cuts)
5700  // coordinates of the cut lines.
5701  //only store this much if cuts are needed to be stored.
5702  scalar_t *allCutCoordinates = allocMemory< scalar_t>(totalDimensionCut);
5703  // kddnote else
5704  //scalar_t *allCutCoordinates = allocMemory< scalar_t>(maxCutNo * concurrentPartCount);
5705  scalar_t *max_min_array = allocMemory< scalar_t>(numThreads * 2);
5706 
5707  float *nonRectelinearPart = NULL; //how much weight percentage should a MPI put left side of the each cutline
5708  float **nonRectRatios = NULL; //how much weight percentage should each thread in MPI put left side of the each cutline
5709  if(allowNonRectelinearPart){
5710  nonRectelinearPart = allocMemory<float>(maxCutNo * concurrentPartCount);
5711 #ifdef HAVE_ZOLTAN2_OMP
5712 #ifdef FIRST_TOUCH
5713  firstTouch<float>(nonRectelinearPart, maxCutNo);
5714 #endif
5715 #endif
5716  nonRectRatios = allocMemory<float *>(numThreads);
5717  for(int i = 0; i < numThreads; ++i){
5718  nonRectRatios[i] = allocMemory<float>(maxCutNo);
5719  }
5720 #ifdef HAVE_ZOLTAN2_OMP
5721 #ifdef FIRST_TOUCH
5722 #pragma omp parallel
5723  {
5724  int me = omp_get_thread_num();
5725  for(partId_t ii = 0; ii < maxCutNo; ++ii){
5726  nonRectRatios[me][ii] = 0;
5727  }
5728  }
5729 #endif
5730 #endif
5731  }
5732 
5733  // work array to manipulate coordinate of cutlines in different iterations.
5734  //necessary because previous cut line information is used for determining the next cutline information.
5735  //therefore, cannot update the cut work array until all cutlines are determined.
5736  scalar_t *cutCoordinatesWork = allocMemory<scalar_t>(maxCutNo * concurrentPartCount);
5737 
5738 #ifdef HAVE_ZOLTAN2_OMP
5739 #ifdef FIRST_TOUCH
5740  firstTouch<scalar_t>(cutCoordinatesWork, maxCutNo);
5741 #endif
5742 #endif
5743 
5744  //cumulative part weight ratio array.
5745  scalar_t *targetPartWeightRatios = allocMemory<scalar_t>(maxPartNo * concurrentPartCount); // the weight ratios at left side of the cuts. First is 0, last is 1.
5746 #ifdef HAVE_ZOLTAN2_OMP
5747 #ifdef FIRST_TOUCH
5748  firstTouch<scalar_t>(cutPartRatios, maxCutNo);
5749 #endif
5750 #endif
5751 
5752 
5753  scalar_t *cutUpperBounds = allocMemory<scalar_t>(maxCutNo * concurrentPartCount); //upper bound coordinate of a cut line
5754  scalar_t *cutLowerBounds = allocMemory<scalar_t>(maxCutNo* concurrentPartCount); //lower bound coordinate of a cut line
5755  scalar_t *cutLowerWeight = allocMemory<scalar_t>(maxCutNo* concurrentPartCount); //lower bound weight of a cut line
5756  scalar_t *cutUpperWeight = allocMemory<scalar_t>(maxCutNo* concurrentPartCount); //upper bound weight of a cut line
5757 
5758  scalar_t *localMinMaxTotal = allocMemory<scalar_t>(3 * concurrentPartCount); //combined array to exchange the min and max coordinate, and total weight of part.
5759  scalar_t *globalMinMaxTotal = allocMemory<scalar_t>(3 * concurrentPartCount);//global combined array with the results for min, max and total weight.
5760 
5761  //isDone is used to determine if a cutline is determined already.
5762  //If a cut line is already determined, the next iterations will skip this cut line.
5763  bool *isDone = allocMemory<bool>(maxCutNo * concurrentPartCount);
5764  //myNonDoneCount count holds the number of cutlines that have not been finalized for each part
5765  //when concurrentPartCount>1, using this information, if myNonDoneCount[x]==0, then no work is done for this part.
5766  partId_t *myNonDoneCount = allocMemory<partId_t>(concurrentPartCount);
5767  //local part weights of each thread.
5768  double **partWeights = allocMemory<double *>(numThreads);
5769  //the work manupulation array for partweights.
5770  double **pws = allocMemory<double *>(numThreads);
5771 
5772  //leftClosesDistance to hold the min distance of a coordinate to a cutline from left (for each thread).
5773  scalar_t **leftClosestDistance = allocMemory<scalar_t *>(numThreads);
5774  //leftClosesDistance to hold the min distance of a coordinate to a cutline from right (for each thread)
5775  scalar_t **rightClosestDistance = allocMemory<scalar_t *>(numThreads);
5776 
5777  //to store how many points in each part a thread has.
5778  lno_t **partPointCounts = allocMemory<lno_t *>(numThreads);
5779 
5780  for(int i = 0; i < numThreads; ++i){
5781  //partWeights[i] = allocMemory<scalar_t>(maxTotalPartCount);
5782  partWeights[i] = allocMemory < double >(maxTotalPartCount * concurrentPartCount);
5783  rightClosestDistance[i] = allocMemory<scalar_t>(maxCutNo * concurrentPartCount);
5784  leftClosestDistance[i] = allocMemory<scalar_t>(maxCutNo * concurrentPartCount);
5785  partPointCounts[i] = allocMemory<lno_t>(maxPartNo);
5786  }
5787 #ifdef HAVE_ZOLTAN2_OMP
5788 #ifdef FIRST_TOUCH
5789 #pragma omp parallel
5790  {
5791  int me = omp_get_thread_num();
5792  for(partId_t ii = 0; ii < maxPartNo; ++ii){
5793  partPointCounts[me][ii] = 0;
5794  }
5795  for(size_t ii = 0; ii < maxTotalPartCount; ++ii){
5796  partWeights[me][ii] = 0;
5797  }
5798  for(partId_t ii = 0; ii < maxCutNo; ++ii){
5799  rightClosestDistance[me][ii] = 0;
5800  leftClosestDistance[me][ii] = 0;
5801 
5802  }
5803  }
5804 #endif
5805 #endif
5806  // kddnote Needed only when non-rectilinear parts.
5807  scalar_t *cutWeights = allocMemory<scalar_t>(maxCutNo);
5808  scalar_t *globalCutWeights = allocMemory<scalar_t>(maxCutNo);
5809 
5810  //for faster communication, concatanation of
5811  //totalPartWeights sized 2P-1, since there are P parts and P-1 cut lines
5812  //leftClosest distances sized P-1, since P-1 cut lines
5813  //rightClosest distances size P-1, since P-1 cut lines.
5814  scalar_t *totalPartWeights_leftClosests_rightClosests = allocMemory<scalar_t>((maxTotalPartCount + maxCutNo * 2) * concurrentPartCount);
5815  scalar_t *global_totalPartWeights_leftClosests_rightClosests = allocMemory<scalar_t>((maxTotalPartCount + maxCutNo * 2) * concurrentPartCount);
5816 
5817 
5818  scalar_t *cutCoordinates = allCutCoordinates;
5819 
5820  //partId_t leftPartitions = totalPartCount;
5821  scalar_t maxScalar_t = numeric_limits<scalar_t>::max();
5822  scalar_t minScalar_t = -numeric_limits<scalar_t>::max();
5823 
5824 
5825 
5826  scalar_t _EPSILON = numeric_limits<scalar_t>::epsilon();
5827  //partId_t partIndexBegin = 0;
5828  partId_t futurePartNumbers = totalPartCount;
5829 
5830  vector<partId_t> *currentPartitions = new vector<partId_t> ();
5831  vector<partId_t> *newFuturePartitions = new vector<partId_t> ();
5832  newFuturePartitions->push_back(numGlobalParts);
5833  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > t1;
5834  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > t2;
5835 
5836 
5837  for (int i = 0; i < partArraySize; ++i){
5838 
5839  //partitioning array.
5840  //size will be as the number of current partitions
5841  //and this hold how many parts each part will be
5842  //in the current dimension partitioning.
5843  vector <partId_t> pAlongI;
5844 
5845  //number of parts that will be obtained at the end of this partitioning.
5846 
5847 
5848 
5849  //currentPartitions is as the size of current number of parts.
5850  //holds how many more parts each should be divided in the further iterations.
5851  //this will be used to calculate pAlongI,
5852  //as the number of parts that the part will be partitioned
5853  //in the current dimension partitioning.
5854 
5855  //newFuturePartitions will be as the size of outnumParts,
5856  //and this will hold how many more parts that each output part
5857  //should be divided.
5858  //this array will also be used to determine the weight ratios
5859  //of the parts.
5860  //swap the arrays.
5861  vector<partId_t> *tmpPartVect= currentPartitions;
5862  currentPartitions = newFuturePartitions;
5863  newFuturePartitions = tmpPartVect;
5864 
5865 
5866 
5867  //clear newFuturePartitions array as
5868  //getPartitionArrays expects it to be empty.
5869  //it also expects pAlongI to be empty as well.
5870  newFuturePartitions->clear();
5871 
5872  //returns the total number of output parts for this dimension partitioning.
5873  partId_t outPartCount = getPartitionArrays<scalar_t, partId_t>(
5874  partNo,
5875  pAlongI,
5876  currentPartitions,
5877  newFuturePartitions,
5878  futurePartNumbers,
5879  currentPartitionCount,
5880  partArraySize,
5881  i,
5882  maxPartNo,
5883  0,
5884  t1,
5885  t2
5886  );
5887 
5888  if(outPartCount == currentPartitionCount) {
5889  tmpPartVect= currentPartitions;
5890  currentPartitions = newFuturePartitions;
5891  newFuturePartitions = tmpPartVect;
5892  continue;
5893  }
5894 
5895  //get the coordinate axis along which the partitioning will be done.
5896  int coordInd = i % coordDim;
5897  scalar_t * pqCoord = pqJagged_coordinates[coordInd];
5898  //convert i to string to be used for debugging purposes.
5899 
5900  string istring = toString<int>(i);
5901  //env->timerStart(MACRO_TIMERS, "PQJagged - " +partitioningName+"-Problem_Partitioning_" + istring);
5902 
5903  //alloc Memory to point the indices
5904  //of the parts in the permutation array.
5905  outTotalCounts = allocMemory<lno_t>(outPartCount);
5906 
5907  //cout << "outPart:" << outPartCount << " global:" << numGlobalParts << endl;
5908 
5909  //the index where in the outtotalCounts will be written.
5910  partId_t currentOut = 0;
5911  //whatever is written to outTotalCounts will be added with previousEnd so that the points will be shifted.
5912  partId_t previousEnd = 0;
5913 
5914  partId_t currentWorkPart = 0;
5915  partId_t concurrentPart = min(currentPartitionCount - currentWorkPart, concurrentPartCount);
5916 
5917  //always use binary search algorithm.
5918  bool useBinarySearch = true;
5919  partId_t obtainedPartCount = 0;
5920 
5921  //run for all available parts.
5922  for (; currentWorkPart < currentPartitionCount; currentWorkPart += concurrentPart){
5923 
5924  concurrentPart = min(currentPartitionCount - currentWorkPart, concurrentPartCount);
5925 
5926  partId_t workPartCount = 0;
5927  //get the min and max coordinates of each part
5928  //together with the part weights of each part.
5929  for(int kk = 0; kk < concurrentPart; ++kk){
5930  partId_t currentPart = currentWorkPart + kk;
5931 
5932  //if this part wont be partitioned any further
5933  //dont do any work for this part.
5934  if (pAlongI[currentPart] == 1){
5935  continue;
5936  }
5937  ++workPartCount;
5938  lno_t coordinateEnd= inTotalCounts[currentPart];
5939  lno_t coordinateBegin = currentPart==0 ? 0: inTotalCounts[currentPart -1];
5940  //cout << "me:" << problemComm->getRank() << " begin:" << coordinateBegin << " end:" << coordinateEnd << endl;
5941  pqJagged_getLocalMinMaxTotalCoord<scalar_t, lno_t>(
5942  partitionedPointCoordinates,
5943  pqCoord,
5944  pqJagged_uniformWeights[0],
5945  pqJagged_weights[0],
5946  numThreads,
5947  coordinateBegin,
5948  coordinateEnd,
5949  max_min_array,
5950  maxScalar_t,
5951  minScalar_t,
5952  localMinMaxTotal[kk], //min coordinate
5953  localMinMaxTotal[kk + concurrentPart], //max coordinate
5954  localMinMaxTotal[kk + 2*concurrentPart] //total weight);
5955  );
5956 
5957 
5958  }
5959 
5960 
5961  if (workPartCount > 0){
5962  //obtain global Min max of the part.
5963  pqJagged_getGlobalMinMaxTotalCoord<scalar_t>(
5964  comm,
5965  env,
5966  concurrentPart,
5967  localMinMaxTotal,
5968  globalMinMaxTotal);
5969 
5970 
5971  //represents the total number of cutlines
5972  //whose coordinate should be determined.
5973  partId_t allDone = 0;
5974 
5975  //Compute weight ratios for parts & cuts:
5976  //e.g., 0.25 0.25 0.5 0.5 0.75 0.75 1
5977  //part0 cut0 part1 cut1 part2 cut2 part3
5978  partId_t cutShifts = 0;
5979  partId_t partShift = 0;
5980  for(int kk = 0; kk < concurrentPart; ++kk){
5981  scalar_t minCoordinate = globalMinMaxTotal[kk];
5982  scalar_t maxCoordinate = globalMinMaxTotal[kk + concurrentPart];
5983  scalar_t globalTotalWeight = globalMinMaxTotal[kk + 2 * concurrentPart];
5984 
5985  partId_t currentPart = currentWorkPart + kk;
5986 
5987  partId_t partition = pAlongI[currentPart];
5988 
5989  scalar_t *usedCutCoordinate = cutCoordinates + cutShifts;
5990  scalar_t *usedCutPartRatios = targetPartWeightRatios + partShift;
5991  //shift the usedCutCoordinate array as noCuts.
5992  cutShifts += partition - 1;
5993  //shift the partRatio array as noParts.
5994  partShift += partition;
5995 
5996  //cout << "min:" << minCoordinate << " max:" << maxCoordinate << endl;
5997  //calculate only if part is not empty,
5998  //and part will be further partitioend.
5999  if(partition > 1 && minCoordinate <= maxCoordinate){
6000 
6001  //increase allDone by the number of cuts of the current part's cut line number.
6002  allDone += partition - 1;
6003  //set the number of cut lines that should be determined for this part.
6004  myNonDoneCount[kk] = partition - 1;
6005 
6006  //get the target weights of the parts.
6007  pqJagged_getCutCoord_Weights<scalar_t>(
6008  minCoordinate,
6009  maxCoordinate,
6010  pqJagged_uniformParts[0],
6011  pqJagged_uniformWeights[0],
6012  pqJagged_partSizes[0],
6013  partition - 1,
6014  globalTotalWeight,
6015  usedCutCoordinate,
6016  usedCutPartRatios,
6017  numThreads,
6018  currentPartitions,
6019  newFuturePartitions,
6020  currentPart,
6021  obtainedPartCount
6022  );
6023 
6024  //get the initial estimated part assignments of the coordinates.
6025  getInitialPartAssignments<scalar_t, lno_t, partId_t>(
6026  maxCoordinate,
6027  minCoordinate,
6028  currentPart,
6029  inTotalCounts,
6030  partitionedPointCoordinates,
6031  pqCoord,
6032  partIds,
6033  _EPSILON,
6034  partition
6035  );
6036  }
6037  else {
6038  // e.g., if have fewer coordinates than parts, don't need to do next dim.
6039  myNonDoneCount[kk] = 0;
6040  }
6041  obtainedPartCount += partition;
6042  }
6043 
6044  //used imbalance, it is always 0, as it is difficult to estimate a range.
6045  scalar_t used_imbalance = 0;
6046 
6047  // Determine cut lines for k parts here.
6048  pqJagged_1D_Partition<scalar_t, lno_t>(
6049  env,
6050  comm,
6051  partitionedPointCoordinates,
6052  pqCoord,
6053  pqJagged_uniformWeights[0],
6054  pqJagged_weights[0],
6055  targetPartWeightRatios,
6056  globalMinMaxTotal,
6057  localMinMaxTotal,
6058  //pAlongI[0],
6059  numThreads,
6060  //maxScalar_t,
6061  //minScalar_t,
6062  used_imbalance,
6063  currentWorkPart,
6064  concurrentPart,
6065  inTotalCounts,
6066  cutCoordinates,
6067  cutCoordinatesWork,
6068  leftClosestDistance,
6069  rightClosestDistance,
6070  cutUpperBounds,
6071  cutLowerBounds,
6072  cutUpperWeight,
6073  cutLowerWeight,
6074  isDone,
6075  partWeights,
6076  totalPartWeights_leftClosests_rightClosests,
6077  global_totalPartWeights_leftClosests_rightClosests,
6078  allowNonRectelinearPart,
6079  nonRectelinearPart,
6080  cutWeights,
6081  globalCutWeights,
6082  allDone,
6083  myNonDoneCount,
6084  useBinarySearch, // istring,
6085  partIds,
6086  pAlongI
6087  );
6088  }
6089 
6090  //create part chunks
6091  {
6092 
6093  partId_t outShift = 0;
6094  partId_t cutShift = 0;
6095  size_t tlrShift = 0;
6096  size_t pwShift = 0;
6097 
6098  for(int kk = 0; kk < concurrentPart; ++kk){
6099  partId_t curr = currentWorkPart + kk;
6100  partId_t noParts = pAlongI[curr];
6101 
6102  //if the part is empty, skip the part.
6103  if((noParts != 1 )&& globalMinMaxTotal[kk] > globalMinMaxTotal[kk + concurrentPart]) {
6104 
6105  for(partId_t jj = 0; jj < noParts; ++jj){
6106  outTotalCounts[currentOut + outShift + jj] = 0;
6107  }
6108  cutShift += noParts - 1;
6109  tlrShift += (4 *(noParts - 1) + 1);
6110  outShift += noParts;
6111  pwShift += (2 * (noParts - 1) + 1);
6112  continue;
6113  }
6114 
6115  lno_t coordinateEnd= inTotalCounts[curr];
6116  lno_t coordinateBegin = curr==0 ? 0: inTotalCounts[curr -1];
6117  scalar_t *usedCutCoordinate = cutCoordinates + cutShift;
6118  float *usednonRectelinearPart = nonRectelinearPart + cutShift;
6119 
6120  scalar_t *tlr = totalPartWeights_leftClosests_rightClosests + tlrShift;
6121 
6122  for(int ii = 0; ii < numThreads; ++ii){
6123  pws[ii] = partWeights[ii] + pwShift;
6124 
6125  }
6126 
6127  if(noParts > 1){
6128 
6129  // Rewrite the indices based on the computed cuts.
6130  getChunksFromCoordinates<lno_t,scalar_t>(
6131  noParts,
6132  numThreads,
6133  partitionedPointCoordinates,
6134  pqCoord,
6135  pqJagged_uniformWeights[0],
6136  pqJagged_weights[0],
6137 
6138  usedCutCoordinate,
6139  coordinateBegin,
6140  coordinateEnd,
6141 
6142  allowNonRectelinearPart,
6143  usednonRectelinearPart,
6144  tlr,
6145  pws,
6146  nonRectRatios,
6147  //coordinate_linked_list,
6148  //coordinate_starts,
6149  //coordinate_ends,
6150  partPointCounts,
6151 
6152  newpartitionedPointCoordinates,
6153  outTotalCounts + currentOut + outShift,
6154  partIds,
6155  true,
6156 
6157  pqJagged_coordinates,
6158  coordDim,
6159  coordInd
6160 
6161  );
6162 
6163 
6164  }
6165  else {
6166  //if this part is partitioned into 1 then just copy the old values.
6167  lno_t partSize = coordinateEnd - coordinateBegin;
6168  *(outTotalCounts + currentOut + outShift) = partSize;
6169  memcpy(newpartitionedPointCoordinates + coordinateBegin, partitionedPointCoordinates + coordinateBegin, partSize * sizeof(lno_t));
6170  }
6171  cutShift += noParts - 1;
6172  tlrShift += (4 *(noParts - 1) + 1);
6173  outShift += noParts;
6174  pwShift += (2 * (noParts - 1) + 1);
6175  }
6176 
6177  //shift cut coordinates so that all cut coordinates are stored.
6178  cutCoordinates += cutShift;
6179 
6180  //getChunks from coordinates partitioned the parts and
6181  //wrote the indices as if there were a single part.
6182  //now we need to shift the beginning indices.
6183  for(partId_t kk = 0; kk < concurrentPart; ++kk){
6184  partId_t noParts = pAlongI[ currentWorkPart + kk];
6185  for (partId_t ii = 0;ii < noParts ; ++ii){
6186  //shift it by previousCount
6187  outTotalCounts[currentOut+ii] += previousEnd;
6188  }
6189  //increase the previous count by current end.
6190  previousEnd = outTotalCounts[currentOut + noParts - 1];
6191  //increase the current out.
6192  currentOut += noParts ;
6193  }
6194  }
6195  }
6196  // end of this partitioning dimension
6197 
6198  currentPartitionCount = outPartCount;
6199  lno_t * tmp = partitionedPointCoordinates;
6200  partitionedPointCoordinates = newpartitionedPointCoordinates;
6201  newpartitionedPointCoordinates = tmp;
6202  freeArray<lno_t>(inTotalCounts);
6203  inTotalCounts = outTotalCounts;
6204 
6205  //env->timerStop(MACRO_TIMERS, "PQJagged - " +partitioningName+"-Problem_Partitioning_" + istring);
6206  }
6207 
6208 #ifdef HAVE_ZOLTAN2_OMP
6209 #pragma omp parallel for
6210 #endif
6211  for(lno_t i = 0; i < numLocalCoords; ++i){
6212  output_permutation[i] = partitionedPointCoordinates[i];
6213  }
6214 
6215  for(size_t i = 0; i < numGlobalParts ; ++i){
6216  //cout << "i:" << i << endl;
6217  output_partIndices[i] = inTotalCounts[i];
6218  }
6219 
6220 
6221  delete currentPartitions;
6222  delete newFuturePartitions;
6223 
6224  freeArray<lno_t>(partitionedPointCoordinates);
6225  freeArray<lno_t>(newpartitionedPointCoordinates);
6226  freeArray<lno_t>(inTotalCounts);
6227 
6228  freeArray<scalar_t>(allCutCoordinates);
6229  freeArray<scalar_t>(cutCoordinatesWork);
6230  freeArray<scalar_t>(max_min_array);
6231 
6232  if(allowNonRectelinearPart){
6233  freeArray<float>(nonRectelinearPart);
6234  for(int i = 0; i < numThreads; ++i){
6235  freeArray<float>(nonRectRatios[i]);
6236  }
6237  freeArray<float *>(nonRectRatios);
6238  }
6239  freeArray<scalar_t>(targetPartWeightRatios);
6240 
6241  freeArray<scalar_t>(cutUpperBounds);
6242  freeArray<scalar_t>(cutLowerBounds);
6243  freeArray<scalar_t>(cutLowerWeight);
6244  freeArray<scalar_t>(cutUpperWeight);
6245  freeArray<scalar_t> (localMinMaxTotal);
6246  freeArray<scalar_t> (globalMinMaxTotal);
6247  freeArray<bool>(isDone);
6248  freeArray<partId_t>(myNonDoneCount);
6249 
6250  for(int i = 0; i < numThreads; ++i){
6251  freeArray<double>(partWeights[i]);
6252  freeArray<scalar_t>(rightClosestDistance[i]);
6253  freeArray<scalar_t>(leftClosestDistance[i]);
6254  }
6255  freeArray<double *>(partWeights);
6256  freeArray<scalar_t *>(leftClosestDistance);
6257  freeArray<scalar_t *>(rightClosestDistance);
6258 
6259  freeArray<double *> (pws);
6260 
6261  for(int i = 0; i < numThreads; ++i){
6262  freeArray<lno_t>(partPointCounts[i]);
6263  }
6264  freeArray<lno_t *>(partPointCounts);
6265  freeArray<scalar_t>(cutWeights);
6266 
6267  freeArray<scalar_t>(globalCutWeights);
6268  freeArray<scalar_t>(totalPartWeights_leftClosests_rightClosests);
6269  freeArray<scalar_t>(global_totalPartWeights_leftClosests_rightClosests);
6270  //env->timerStop(MACRO_TIMERS, "PQJagged - " +partitioningName+"-Problem_Partitioning");
6271 }
6272 
6282 template <typename Adapter>
6284  const RCP<const Environment> &env,
6285  RCP<Comm<int> > &problemComm,
6286  const RCP<const CoordinateModel<
6287  typename Adapter::base_adapter_t> > &coords,
6288  RCP<PartitioningSolution<Adapter> > &solution
6289 )
6290 {
6291 #ifndef INCLUDE_ZOLTAN2_EXPERIMENTAL
6292 
6293  Z2_THROW_EXPERIMENTAL("Zoltan2 PQJagged is strictly experimental software "
6294  "while it is being developed and tested.")
6295 
6296 #else
6297 
6298  env->timerStart(MACRO_TIMERS, "PQJagged - Total");
6299  env->timerStart(MACRO_TIMERS, "PQJagged - Total2");
6300 
6301  // 0 - for decision
6302  // > 0 - for force migration
6303  // < 0 - for avoid migration
6304 
6305 
6306  typedef typename Adapter::scalar_t scalar_t;
6307  typedef typename Adapter::gno_t gno_t;
6308  typedef typename Adapter::lno_t lno_t;
6309  typedef typename Adapter::node_t node_t;
6310 
6311  /*
6312  if(comm->getRank() == 0){
6313  cout << "size of gno:" << sizeof(gno_t) << endl;
6314  cout << "size of lno:" << sizeof(lno_t) << endl;
6315  cout << "size of scalar_t:" << sizeof(scalar_t) << endl;
6316  }
6317  */
6318  const Teuchos::ParameterList &pl = env->getParameters();
6319 
6320  std::bitset<NUM_RCB_PARAMS> params;
6321  int numTestCuts = 5;
6322 
6323 
6324  scalar_t imbalanceTolerance;
6325 
6326  multiCriteriaNorm mcnorm;
6327  bool ignoreWeights=false;
6328 
6329 
6330  get_partitioning_params<scalar_t>(pl,
6331  imbalanceTolerance,
6332  mcnorm,
6333  params,
6334  numTestCuts,
6335  ignoreWeights);
6336 
6337  const partId_t *partNo = NULL;
6338  int partArraySize = 0;
6339 
6340  if (pl.getPtr<Array <partId_t> >("pqParts")){
6341  partNo = pl.getPtr<Array <partId_t> >("pqParts")->getRawPtr();
6342  partArraySize = pl.getPtr<Array <partId_t> >("pqParts")->size() - 1;
6343  }
6344 
6345  //cout << "partArraySize:" << partArraySize << endl;
6346  int coordDim, weightDim;
6347  size_t nlc;
6348  global_size_t gnc; int criteriaDim;
6349  pqJagged_getCoordinateValues<Adapter>(
6350  coords,
6351  coordDim,
6352  weightDim,
6353  nlc,
6354  gnc,
6355  criteriaDim,
6356  ignoreWeights
6357  );
6358 
6359 
6360  lno_t numLocalCoords = nlc;
6361 #ifdef enable_migration2
6362  gno_t numGlobalCoords = gnc;
6363 #endif
6364 
6365  //allocate only two dimensional pointer.
6366  //raw pointer addresess will be obtained from multivector.
6367  scalar_t **pqJagged_coordinates = allocMemory<scalar_t *>(coordDim);
6368  scalar_t **pqJagged_weights = allocMemory<scalar_t *>(criteriaDim);
6369  bool *pqJagged_uniformParts = allocMemory< bool >(criteriaDim); //if the partitioning results wanted to be uniform.
6370  scalar_t **pqJagged_partSizes = allocMemory<scalar_t *>(criteriaDim); //if in a criteria dimension, uniform part is false this shows ratios of the target part weights.
6371  bool *pqJagged_uniformWeights = allocMemory< bool >(criteriaDim); //if the weights of coordinates are uniform in a criteria dimension.
6372 
6373  ArrayView<const gno_t> pqJagged_gnos;
6374  size_t numGlobalParts;
6375  int pqJagged_multiVectorDim;
6376 
6377  pqJagged_getInputValues<Adapter, scalar_t, gno_t>(
6378  env,
6379  coords,
6380  solution,
6381  params,
6382  coordDim,
6383  weightDim,
6384  numLocalCoords,
6385  numGlobalParts,
6386  pqJagged_multiVectorDim, //output
6387  pqJagged_coordinates, //output
6388  criteriaDim,
6389  pqJagged_weights, //output
6390  pqJagged_gnos, //output
6391  ignoreWeights,
6392  pqJagged_uniformWeights, //output
6393  pqJagged_uniformParts, //output
6394  pqJagged_partSizes //output
6395  );
6396 
6397 
6399 
6400 #ifdef enable_migration2
6401  const gno_t *actual_pqgnos = pqJagged_gnos.getRawPtr();
6402  gno_t *pq_gnos = (gno_t *)actual_pqgnos;
6403  int *actual_owner_of_coordinate = NULL;
6404 #endif
6405 
6406  //as input indices.
6407  lno_t *partitionedPointCoordinates = allocMemory< lno_t>(numLocalCoords);
6408  //initial configuration
6409  //set each pointer-i to i.
6410 #ifdef HAVE_ZOLTAN2_OMP
6411 #pragma omp parallel for
6412 #endif
6413  for(size_t i = 0; i < static_cast<size_t>(numLocalCoords); ++i){
6414  partitionedPointCoordinates[i] = i;
6415  }
6416 
6417  //as output indices
6418  lno_t *newpartitionedPointCoordinates = allocMemory< lno_t>(numLocalCoords);
6419 #ifdef HAVE_ZOLTAN2_OMP
6420 #ifdef FIRST_TOUCH
6421  firstTouch<lno_t>(newpartitionedPointCoordinates, numLocalCoords);
6422 #endif
6423 #endif
6424 
6425 
6426  partId_t *partIds = NULL;
6427  ArrayRCP<partId_t> partId;
6428  if(numLocalCoords > 0){
6429  partIds = allocMemory<partId_t>(numLocalCoords);
6430  }
6431 
6432  //initially there is a single partition
6433  partId_t currentPartitionCount = 1;
6434  //single partition starts at index-0, and ends at numLocalCoords
6435  //inTotalCounts array holds the end points in partitionedPointCoordinates array
6436  //for each partition. Initially sized 1, and single element is set to numLocalCoords.
6437  lno_t *inTotalCounts = allocMemory<lno_t>(1);
6438  inTotalCounts[0] = static_cast<lno_t>(numLocalCoords);//the end of the initial partition is the end of coordinates.
6439  //the ends points of the output.
6440  lno_t *outTotalCounts = NULL;
6441 
6442 
6443 
6444  //get pqJagged specific parameters.
6445  bool allowNonRectelinearPart = false;
6446  int concurrentPartCount = 0; // Set to invalid value
6447  int migration_actualMigration_option = 1;
6448  int migration_check_option = 0;
6449  int migration_all2all_option = 1;
6450  scalar_t migration_imbalance_cut_off = 0.03;
6451  int migration_assignment_type = 0;
6452  int keep_part_boxes = 0;
6453 
6454  int enable_rcb = 0;
6455  int recursion_depth = -1;
6456 
6457  pqJagged_getParameters<scalar_t>(pl,
6458  allowNonRectelinearPart,
6459  concurrentPartCount,
6460  migration_actualMigration_option,
6461  migration_check_option,
6462  migration_all2all_option,
6463  migration_imbalance_cut_off,
6464  migration_assignment_type,
6465  keep_part_boxes,
6466  enable_rcb,
6467  recursion_depth);
6468 
6469  //cout << "enable_rcb:" << enable_rcb << " recursion_depth:" << recursion_depth << endl;
6470  //cout << "partArraySize:" << partArraySize << " recursion_depth:" << recursion_depth << endl;
6471  if (enable_rcb){
6472  recursion_depth = ceil(log ((numGlobalParts)) / log (2.0));
6473  }
6474  if (partArraySize < 1){
6475  if (recursion_depth > 0){
6476  partArraySize = recursion_depth;
6477  }
6478  else {
6479  partArraySize = coordDim;
6480  }
6481  }
6482 
6483  //cout << "partArraySize:" << partArraySize << " recursion_depth:" << recursion_depth << endl;
6484 
6485  int numThreads = 1;
6486 #ifdef HAVE_ZOLTAN2_OMP
6487 #pragma omp parallel shared(numThreads)
6488  {
6489  numThreads = omp_get_num_threads();
6490  }
6491 
6492 #endif
6493 
6494 
6495  partId_t totalDimensionCut = 0; //how many cuts will be totally
6496  partId_t totalPartCount = 1; //how many parts will be totally
6497  partId_t maxPartNo = 0; //maximum cut count along a dimension.
6498  partId_t reduceAllCount = 0; //estimate on how many reduceAlls will be done.
6499  partId_t maxTotalCumulativePartCount = 1; //maximum number of parts that might occur
6500  //during the partition before the last partitioning dimension.
6501  partId_t maxCutNo = 0;
6502  size_t maxTotalPartCount = 0;
6503 
6504  getPartSpecifications <partId_t>(
6505  partNo, //partNoArray Input
6506  partArraySize, //size of the partNoArray --output if partNo is not given.
6507  //coordDim, //coordinate dim
6508  numGlobalParts, //how many global parts will be -- output if partNo is not given.
6509  totalDimensionCut, //how many cuts will be totally
6510  totalPartCount , //how many parts will be totally
6511  maxPartNo , //maximum cut count along a dimension.
6512  reduceAllCount , //estimate on how many reduceAlls will be done.
6513  maxTotalCumulativePartCount, //maximum number of parts that might occur
6514  //during the partition before the last partitioning dimension.
6515  maxCutNo,
6516  maxTotalPartCount
6517  );
6518 
6519  if (concurrentPartCount == 0)
6520  {
6521  // User did not specify concurrentPartCount parameter, Pick a default.
6522  // Still a conservative default. We could go as big as
6523  // maxTotalCumulativePartCount, but trying not to use too much memory.
6524  // Another assumption the total #parts will be large-very large
6525  if (coordDim == partArraySize)
6526  {
6527  // partitioning each dimension only once, pick the default as
6528  // maxPartNo >> default
6529  concurrentPartCount = min(Z2_DEFAULT_CON_PART_COUNT, maxPartNo);
6530  }
6531  else
6532  {
6533  // partitioning each dimension more than once, pick the max
6534  concurrentPartCount = max(Z2_DEFAULT_CON_PART_COUNT, maxPartNo);
6535  }
6536  }
6537 
6538  if(concurrentPartCount > maxTotalCumulativePartCount){
6539  if(problemComm->getRank() == 0){
6540  cerr << "Warning: Concurrent part calculation count ("<< concurrentPartCount << ") has been set bigger than maximum amount that can be used." << " Setting to:" << maxTotalCumulativePartCount << "." << endl;
6541  }
6542  concurrentPartCount = maxTotalCumulativePartCount;
6543  }
6544  RCP<Comm<int> > comm = problemComm->duplicate();
6545 
6546  // coordinates of the cut lines. First one is the min, last one is max coordinate.
6547  // kddnote if (keep_cuts)
6548  // coordinates of the cut lines.
6549  //only store this much if cuts are needed to be stored.
6550  scalar_t *allCutCoordinates = allocMemory< scalar_t>(totalDimensionCut);
6551  // kddnote else
6552  //scalar_t *allCutCoordinates = allocMemory< scalar_t>(maxCutNo * concurrentPartCount);
6553  scalar_t *max_min_array = allocMemory< scalar_t>(numThreads * 2);
6554 
6555  float *nonRectelinearPart = NULL; //how much weight percentage should a MPI put left side of the each cutline
6556  float **nonRectRatios = NULL; //how much weight percentage should each thread in MPI put left side of the each cutline
6557  if(allowNonRectelinearPart){
6558  nonRectelinearPart = allocMemory<float>(maxCutNo * concurrentPartCount);
6559 #ifdef HAVE_ZOLTAN2_OMP
6560 #ifdef FIRST_TOUCH
6561  firstTouch<float>(nonRectelinearPart, maxCutNo);
6562 #endif
6563 #endif
6564  nonRectRatios = allocMemory<float *>(numThreads);
6565  for(int i = 0; i < numThreads; ++i){
6566  nonRectRatios[i] = allocMemory<float>(maxCutNo);
6567  }
6568 #ifdef HAVE_ZOLTAN2_OMP
6569 #ifdef FIRST_TOUCH
6570 #pragma omp parallel
6571  {
6572  int me = omp_get_thread_num();
6573  for(partId_t ii = 0; ii < maxCutNo; ++ii){
6574  nonRectRatios[me][ii] = 0;
6575  }
6576  }
6577 #endif
6578 #endif
6579  }
6580 
6581  // work array to manipulate coordinate of cutlines in different iterations.
6582  //necessary because previous cut line information is used for determining the next cutline information.
6583  //therefore, cannot update the cut work array until all cutlines are determined.
6584  scalar_t *cutCoordinatesWork = allocMemory<scalar_t>(maxCutNo * concurrentPartCount);
6585 
6586 #ifdef HAVE_ZOLTAN2_OMP
6587 #ifdef FIRST_TOUCH
6588  firstTouch<scalar_t>(cutCoordinatesWork, maxCutNo);
6589 #endif
6590 #endif
6591 
6592  //cumulative part weight ratio array.
6593  scalar_t *targetPartWeightRatios = allocMemory<scalar_t>(maxPartNo * concurrentPartCount); // the weight ratios at left side of the cuts. First is 0, last is 1.
6594 #ifdef HAVE_ZOLTAN2_OMP
6595 #ifdef FIRST_TOUCH
6596  firstTouch<scalar_t>(cutPartRatios, maxCutNo);
6597 #endif
6598 #endif
6599 
6600 
6601  scalar_t *cutUpperBounds = allocMemory<scalar_t>(maxCutNo * concurrentPartCount); //upper bound coordinate of a cut line
6602  scalar_t *cutLowerBounds = allocMemory<scalar_t>(maxCutNo* concurrentPartCount); //lower bound coordinate of a cut line
6603  scalar_t *cutLowerWeight = allocMemory<scalar_t>(maxCutNo* concurrentPartCount); //lower bound weight of a cut line
6604  scalar_t *cutUpperWeight = allocMemory<scalar_t>(maxCutNo* concurrentPartCount); //upper bound weight of a cut line
6605 
6606  scalar_t *localMinMaxTotal = allocMemory<scalar_t>(3 * concurrentPartCount); //combined array to exchange the min and max coordinate, and total weight of part.
6607  scalar_t *globalMinMaxTotal = allocMemory<scalar_t>(3 * concurrentPartCount);//global combined array with the results for min, max and total weight.
6608 
6609  //isDone is used to determine if a cutline is determined already.
6610  //If a cut line is already determined, the next iterations will skip this cut line.
6611  bool *isDone = allocMemory<bool>(maxCutNo * concurrentPartCount);
6612  //myNonDoneCount count holds the number of cutlines that have not been finalized for each part
6613  //when concurrentPartCount>1, using this information, if myNonDoneCount[x]==0, then no work is done for this part.
6614  partId_t *myNonDoneCount = allocMemory<partId_t>(concurrentPartCount);
6615  //local part weights of each thread.
6616  double **partWeights = allocMemory<double *>(numThreads);
6617  //the work manupulation array for partweights.
6618  double **pws = allocMemory<double *>(numThreads);
6619 
6620  //leftClosesDistance to hold the min distance of a coordinate to a cutline from left (for each thread).
6621  scalar_t **leftClosestDistance = allocMemory<scalar_t *>(numThreads);
6622  //leftClosesDistance to hold the min distance of a coordinate to a cutline from right (for each thread)
6623  scalar_t **rightClosestDistance = allocMemory<scalar_t *>(numThreads);
6624 
6625  //to store how many points in each part a thread has.
6626  lno_t **partPointCounts = allocMemory<lno_t *>(numThreads);
6627 
6628  for(int i = 0; i < numThreads; ++i){
6629  //partWeights[i] = allocMemory<scalar_t>(maxTotalPartCount);
6630  partWeights[i] = allocMemory < double >(maxTotalPartCount * concurrentPartCount);
6631  rightClosestDistance[i] = allocMemory<scalar_t>(maxCutNo * concurrentPartCount);
6632  leftClosestDistance[i] = allocMemory<scalar_t>(maxCutNo * concurrentPartCount);
6633  partPointCounts[i] = allocMemory<lno_t>(maxPartNo);
6634  }
6635 #ifdef HAVE_ZOLTAN2_OMP
6636 #ifdef FIRST_TOUCH
6637 #pragma omp parallel
6638  {
6639  int me = omp_get_thread_num();
6640  for(partId_t ii = 0; ii < maxPartNo; ++ii){
6641  partPointCounts[me][ii] = 0;
6642  }
6643  for(size_t ii = 0; ii < maxTotalPartCount; ++ii){
6644  partWeights[me][ii] = 0;
6645  }
6646  for(partId_t ii = 0; ii < maxCutNo; ++ii){
6647  rightClosestDistance[me][ii] = 0;
6648  leftClosestDistance[me][ii] = 0;
6649 
6650  }
6651  }
6652 #endif
6653 #endif
6654  // kddnote Needed only when non-rectilinear parts.
6655  scalar_t *cutWeights = allocMemory<scalar_t>(maxCutNo);
6656  scalar_t *globalCutWeights = allocMemory<scalar_t>(maxCutNo);
6657 
6658  //for faster communication, concatanation of
6659  //totalPartWeights sized 2P-1, since there are P parts and P-1 cut lines
6660  //leftClosest distances sized P-1, since P-1 cut lines
6661  //rightClosest distances size P-1, since P-1 cut lines.
6662  scalar_t *totalPartWeights_leftClosests_rightClosests = allocMemory<scalar_t>((maxTotalPartCount + maxCutNo * 2) * concurrentPartCount);
6663  scalar_t *global_totalPartWeights_leftClosests_rightClosests = allocMemory<scalar_t>((maxTotalPartCount + maxCutNo * 2) * concurrentPartCount);
6664 
6665 
6666  scalar_t *cutCoordinates = allCutCoordinates;
6667 
6668  //partId_t leftPartitions = totalPartCount;
6669  scalar_t maxScalar_t = numeric_limits<scalar_t>::max();
6670  scalar_t minScalar_t = -numeric_limits<scalar_t>::max();
6671 
6672 
6673  env->timerStart(MACRO_TIMERS, "PQJagged - Problem_Partitioning");
6674 
6675  //create multivector based on the coordinates, weights, and multivectordim
6676 #ifdef enable_migration2
6677  typedef Tpetra::MultiVector<scalar_t, lno_t, gno_t, node_t> mvector_t;
6678  RCP<const mvector_t> mvector;
6679  if(migration_actualMigration_option == 0){
6680 
6681  mvector = create_initial_multi_vector <gno_t,lno_t,scalar_t,node_t>(
6682  env,
6683  comm,
6684  numGlobalCoords,
6685  numLocalCoords,
6686  coordDim,// coord_dim,
6687  pqJagged_coordinates,//coords,
6688  weightDim, //weight_dim,
6689  pqJagged_weights, //weight,
6690  pqJagged_multiVectorDim// multiVectorDim
6691  );
6692 
6693  }
6694  else {
6695  for (int i=0; i < coordDim; i++){
6696  scalar_t *coord = allocMemory<scalar_t>(numLocalCoords);
6697 #ifdef HAVE_ZOLTAN2_OMP
6698 #pragma omp parallel for
6699 #endif
6700  for (lno_t j=0; j < numLocalCoords; j++) coord[j] = pqJagged_coordinates[i][j];
6701 
6702  pqJagged_coordinates[i] = coord;
6703  }
6704  for (int i=0; i < weightDim; i++){
6705  scalar_t *w = allocMemory<scalar_t>(numLocalCoords);
6706 #ifdef HAVE_ZOLTAN2_OMP
6707 #pragma omp parallel for
6708 #endif
6709  for (lno_t j=0; j < numLocalCoords; j++) w[j] = pqJagged_weights[i][j];
6710 
6711  pqJagged_weights[i] = w;
6712  }
6713  pq_gnos = allocMemory<gno_t>(numLocalCoords);
6714 #ifdef HAVE_ZOLTAN2_OMP
6715 #pragma omp parallel for
6716 #endif
6717  for (lno_t j=0; j < numLocalCoords; j++) pq_gnos[j] = actual_pqgnos[j];
6718 
6719  actual_owner_of_coordinate = allocMemory<int>(numLocalCoords);
6720  int me = comm->getRank();
6721 #ifdef HAVE_ZOLTAN2_OMP
6722 #pragma omp parallel for
6723 #endif
6724  for (lno_t j=0; j < numLocalCoords; j++) actual_owner_of_coordinate[j] = me;
6725  }
6726 
6727 #endif
6728 
6729 
6730  scalar_t _EPSILON = numeric_limits<scalar_t>::epsilon();
6731  partId_t partIndexBegin = 0;
6732  partId_t futurePartNumbers = totalPartCount;
6733  bool is_data_ever_migrated = false;
6734 
6735  vector<partId_t> *currentPartitions = new vector<partId_t> ();
6736  vector<partId_t> *newFuturePartitions = new vector<partId_t> ();
6737  newFuturePartitions->push_back(numGlobalParts);
6738 
6739  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > inPartBoxes(new vector <coordinateModelPartBox <scalar_t, partId_t> > (), true) ;
6740  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > outPartBoxes(new vector <coordinateModelPartBox <scalar_t, partId_t> > (), true);
6741 
6742 
6743  if(keep_part_boxes){
6744 
6745  scalar_t *mins = allocMemory<scalar_t>(coordDim);
6746  scalar_t *gmins = allocMemory<scalar_t>(coordDim);
6747  scalar_t *maxs = allocMemory<scalar_t>(coordDim);
6748  scalar_t *gmaxs = allocMemory<scalar_t>(coordDim);
6749  for (int i = 0; i < coordDim; ++i){
6750  //cout << " pqJagged_coordinates[i][0]:" << pqJagged_coordinates[i][0] << endl;
6751  scalar_t localMin = pqJagged_coordinates[i][0];
6752  scalar_t localMax = pqJagged_coordinates[i][0];
6753  for (lno_t j = 1; j < numLocalCoords; ++j){
6754  //cout << " pqJagged_coordinates[i][i]:" << pqJagged_coordinates[i][j] << endl;
6755  if (pqJagged_coordinates[i][j] < localMin){
6756  localMin = pqJagged_coordinates[i][j];
6757  }
6758  if (pqJagged_coordinates[i][j] > localMax){
6759  localMax = pqJagged_coordinates[i][j];
6760  }
6761  }
6762  //cout << " localMin:" << localMin << endl;
6763  //cout << " localMax:" << localMax << endl;
6764  mins[i] = localMin;
6765  maxs[i] = localMax;
6766  }
6767  reduceAll<int, scalar_t>(*comm, Teuchos::REDUCE_MIN,
6768  coordDim, mins, gmins
6769  );
6770 
6771  reduceAll<int, scalar_t>(*comm, Teuchos::REDUCE_MAX,
6772  coordDim, maxs, gmaxs
6773  );
6774  coordinateModelPartBox <scalar_t, partId_t> tmpBox (0, coordDim, gmins, gmaxs);
6775  //coordinateModelPartBox <scalar_t, partId_t> tmpBox (0, coordDim);
6776  freeArray<scalar_t>(mins);
6777  freeArray<scalar_t>(gmins);
6778  freeArray<scalar_t>(maxs);
6779  freeArray<scalar_t>(gmaxs);
6780  outPartBoxes->push_back(tmpBox);
6781  }
6782 
6783  //cout << "partArraySize:" << partArraySize << endl;
6784  for (int i = 0; i < partArraySize; ++i){
6785 
6786  //partitioning array.
6787  //size will be as the number of current partitions
6788  //and this hold how many parts each part will be
6789  //in the current dimension partitioning.
6790  vector <partId_t> pAlongI;
6791 
6792  //number of parts that will be obtained at the end of this partitioning.
6793 
6794 
6795 
6796  //currentPartitions is as the size of current number of parts.
6797  //holds how many more parts each should be divided in the further iterations.
6798  //this will be used to calculate pAlongI,
6799  //as the number of parts that the part will be partitioned
6800  //in the current dimension partitioning.
6801 
6802  //newFuturePartitions will be as the size of outnumParts,
6803  //and this will hold how many more parts that each output part
6804  //should be divided.
6805  //this array will also be used to determine the weight ratios
6806  //of the parts.
6807  //swap the arrays.
6808  vector<partId_t> *tmpPartVect= currentPartitions;
6809  currentPartitions = newFuturePartitions;
6810  newFuturePartitions = tmpPartVect;
6811 
6812  //clear newFuturePartitions array as
6813  //getPartitionArrays expects it to be empty.
6814  //it also expects pAlongI to be empty as well.
6815  newFuturePartitions->clear();
6816 
6817  if(keep_part_boxes){
6818  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > tmpPartBoxes = inPartBoxes;
6819  inPartBoxes = outPartBoxes;
6820  outPartBoxes = tmpPartBoxes;
6821  outPartBoxes->clear();
6822 
6823 /*
6824  for (partId_t j = 0; j < inPartBoxes->size(); ++j){
6825 
6826  cout << "me:" << j << endl;
6827  (*inPartBoxes)[j].print();
6828  }
6829  */
6830  }
6831 
6832 
6833  //returns the total number of output parts for this dimension partitioning.
6834  partId_t outPartCount = getPartitionArrays<scalar_t, partId_t>(
6835  partNo,
6836  pAlongI,
6837  currentPartitions,
6838  newFuturePartitions,
6839  futurePartNumbers,
6840  currentPartitionCount,
6841  partArraySize,
6842  i,
6843  maxPartNo,
6844  keep_part_boxes,
6845  inPartBoxes,
6846  outPartBoxes
6847  );
6848 
6849 
6850 
6851  if(outPartCount == currentPartitionCount) {
6852  tmpPartVect= currentPartitions;
6853  currentPartitions = newFuturePartitions;
6854  newFuturePartitions = tmpPartVect;
6855 
6856  if(keep_part_boxes){
6857  RCP < vector <coordinateModelPartBox <scalar_t, partId_t> > > tmpPartBoxes = inPartBoxes;
6858  inPartBoxes = outPartBoxes;
6859  outPartBoxes = tmpPartBoxes;
6860  }
6861  continue;
6862  }
6863 
6864 #ifdef enable_migration2
6865  int worldSize = comm->getSize();
6866  long migration_reduceAllPop = reduceAllCount * worldSize;
6867 #endif
6868 
6869 
6870  //get the coordinate axis along which the partitioning will be done.
6871  int coordInd = i % coordDim;
6872  scalar_t * pqCoord = pqJagged_coordinates[coordInd];
6873  //convert i to string to be used for debugging purposes.
6874  string istring = toString<int>(i);
6875 
6876 
6877  env->timerStart(MACRO_TIMERS, "PQJagged - Problem_Partitioning_" + istring);
6878 
6879  //alloc Memory to point the indices
6880  //of the parts in the permutation array.
6881  outTotalCounts = allocMemory<lno_t>(outPartCount);
6882 
6883  //the index where in the outtotalCounts will be written.
6884  partId_t currentOut = 0;
6885  //whatever is written to outTotalCounts will be added with previousEnd so that the points will be shifted.
6886  partId_t previousEnd = 0;
6887 
6888  partId_t currentWorkPart = 0;
6889  partId_t concurrentPart = min(currentPartitionCount - currentWorkPart, concurrentPartCount);
6890 
6891  //always use binary search algorithm.
6892  bool useBinarySearch = true;
6893  partId_t obtainedPartCount = 0;
6894 
6895  //run for all available parts.
6896  for (; currentWorkPart < currentPartitionCount; currentWorkPart += concurrentPart){
6897 
6898  concurrentPart = min(currentPartitionCount - currentWorkPart, concurrentPartCount);
6899 #ifdef mpi_communication
6900  concurrent = concurrentPart;
6901 #endif
6902 
6903 
6904  partId_t workPartCount = 0;
6905  //get the min and max coordinates of each part
6906  //together with the part weights of each part.
6907  for(int kk = 0; kk < concurrentPart; ++kk){
6908  partId_t currentPart = currentWorkPart + kk;
6909 
6910  //if this part wont be partitioned any further
6911  //dont do any work for this part.
6912  if (pAlongI[currentPart] == 1){
6913  continue;
6914  }
6915  ++workPartCount;
6916  lno_t coordinateEnd= inTotalCounts[currentPart];
6917  lno_t coordinateBegin = currentPart==0 ? 0: inTotalCounts[currentPart -1];
6918  //cout << "me:" << problemComm->getRank() << " begin:" << coordinateBegin << " end:" << coordinateEnd << endl;
6919  pqJagged_getLocalMinMaxTotalCoord<scalar_t, lno_t>(
6920  partitionedPointCoordinates,
6921  pqCoord,
6922  pqJagged_uniformWeights[0],
6923  pqJagged_weights[0],
6924  numThreads,
6925  coordinateBegin,
6926  coordinateEnd,
6927  max_min_array,
6928  maxScalar_t,
6929  minScalar_t,
6930  localMinMaxTotal[kk], //min coordinate
6931  localMinMaxTotal[kk + concurrentPart], //max coordinate
6932  localMinMaxTotal[kk + 2*concurrentPart] //total weight);
6933  );
6934 
6935 
6936  }
6937 
6938 
6939  if (workPartCount > 0){
6940  //obtain global Min max of the part.
6941  pqJagged_getGlobalMinMaxTotalCoord<scalar_t>(
6942  comm,
6943  env,
6944  concurrentPart,
6945  localMinMaxTotal,
6946  globalMinMaxTotal);
6947 
6948 
6949  //represents the total number of cutlines
6950  //whose coordinate should be determined.
6951  partId_t allDone = 0;
6952 
6953  //Compute weight ratios for parts & cuts:
6954  //e.g., 0.25 0.25 0.5 0.5 0.75 0.75 1
6955  //part0 cut0 part1 cut1 part2 cut2 part3
6956  partId_t cutShifts = 0;
6957  partId_t partShift = 0;
6958  for(int kk = 0; kk < concurrentPart; ++kk){
6959  scalar_t minCoordinate = globalMinMaxTotal[kk];
6960  scalar_t maxCoordinate = globalMinMaxTotal[kk + concurrentPart];
6961 
6962  scalar_t globalTotalWeight = globalMinMaxTotal[kk + 2 * concurrentPart];
6963 
6964  partId_t currentPart = currentWorkPart + kk;
6965 
6966  partId_t partition = pAlongI[currentPart];
6967 
6968  scalar_t *usedCutCoordinate = cutCoordinates + cutShifts;
6969  scalar_t *usedCutPartRatios = targetPartWeightRatios + partShift;
6970  //shift the usedCutCoordinate array as noCuts.
6971  cutShifts += partition - 1;
6972  //shift the partRatio array as noParts.
6973  partShift += partition;
6974 
6975  //cout << "min:" << minCoordinate << " max:" << maxCoordinate << endl;
6976  //calculate only if part is not empty,
6977  //and part will be further partitioend.
6978  if(partition > 1 && minCoordinate <= maxCoordinate){
6979 
6980  //increase allDone by the number of cuts of the current part's cut line number.
6981  allDone += partition - 1;
6982  //set the number of cut lines that should be determined for this part.
6983  myNonDoneCount[kk] = partition - 1;
6984 
6985  //get the target weights of the parts.
6986  pqJagged_getCutCoord_Weights<scalar_t>(
6987  minCoordinate,
6988  maxCoordinate,
6989  pqJagged_uniformParts[0],
6990  pqJagged_uniformWeights[0],
6991  pqJagged_partSizes[0],
6992  partition - 1,
6993  globalTotalWeight,
6994  usedCutCoordinate,
6995  usedCutPartRatios,
6996  numThreads,
6997  currentPartitions,
6998  newFuturePartitions,
6999  currentPart,
7000  obtainedPartCount
7001  );
7002 
7003  //get the initial estimated part assignments of the coordinates.
7004  getInitialPartAssignments<scalar_t, lno_t, partId_t>(
7005  maxCoordinate,
7006  minCoordinate,
7007  currentPart,
7008  inTotalCounts,
7009  partitionedPointCoordinates,
7010  pqCoord,
7011  partIds,
7012  _EPSILON,
7013  partition
7014  );
7015  }
7016  else {
7017  // e.g., if have fewer coordinates than parts, don't need to do next dim.
7018  myNonDoneCount[kk] = 0;
7019  }
7020  obtainedPartCount += partition;
7021  }
7022 
7023 
7024 
7025  //used imbalance, it is always 0, as it is difficult to estimate a range.
7026  scalar_t used_imbalance = 0;
7027 
7028 
7029  // Determine cut lines for k parts here.
7030  pqJagged_1D_Partition<scalar_t, lno_t>(
7031  env,
7032  comm,
7033  partitionedPointCoordinates,
7034  pqCoord,
7035  pqJagged_uniformWeights[0],
7036  pqJagged_weights[0],
7037  targetPartWeightRatios,
7038  globalMinMaxTotal,
7039  localMinMaxTotal,
7040  //pAlongI[0],
7041  numThreads,
7042  //maxScalar_t,
7043  //minScalar_t,
7044  used_imbalance,
7045  currentWorkPart,
7046  concurrentPart,
7047  inTotalCounts,
7048  cutCoordinates,
7049  cutCoordinatesWork,
7050  leftClosestDistance,
7051  rightClosestDistance,
7052  cutUpperBounds,
7053  cutLowerBounds,
7054  cutUpperWeight,
7055  cutLowerWeight,
7056  isDone,
7057  partWeights,
7058  totalPartWeights_leftClosests_rightClosests,
7059  global_totalPartWeights_leftClosests_rightClosests,
7060  allowNonRectelinearPart,
7061  nonRectelinearPart,
7062  cutWeights,
7063  globalCutWeights,
7064  allDone,
7065  myNonDoneCount,
7066  useBinarySearch, // istring,
7067  partIds,
7068  pAlongI
7069  );
7070 
7071 
7072 
7073  }
7074 
7075 
7076  //create part chunks
7077  {
7078 
7079  partId_t outShift = 0;
7080  partId_t cutShift = 0;
7081  size_t tlrShift = 0;
7082  size_t pwShift = 0;
7083 
7084  for(int kk = 0; kk < concurrentPart; ++kk){
7085  partId_t curr = currentWorkPart + kk;
7086  partId_t noParts = pAlongI[curr];
7087 
7088  //if the part is empty, skip the part.
7089  if((noParts != 1 )&& globalMinMaxTotal[kk] > globalMinMaxTotal[kk + concurrentPart]) {
7090 
7091  for(partId_t jj = 0; jj < noParts; ++jj){
7092  outTotalCounts[currentOut + outShift + jj] = 0;
7093  }
7094  cutShift += noParts - 1;
7095  tlrShift += (4 *(noParts - 1) + 1);
7096  outShift += noParts;
7097  pwShift += (2 * (noParts - 1) + 1);
7098  continue;
7099  }
7100 
7101  lno_t coordinateEnd= inTotalCounts[curr];
7102  lno_t coordinateBegin = curr==0 ? 0: inTotalCounts[curr -1];
7103  scalar_t *usedCutCoordinate = cutCoordinates + cutShift;
7104  float *usednonRectelinearPart = nonRectelinearPart + cutShift;
7105 
7106  scalar_t *tlr = totalPartWeights_leftClosests_rightClosests + tlrShift;
7107 
7108  for(int ii = 0; ii < numThreads; ++ii){
7109  pws[ii] = partWeights[ii] + pwShift;
7110 
7111  }
7112 /*
7113  cout << endl;
7114  scalar_t prev = 0;
7115  for (int i = 0; i < noParts * 2 - 1 ; ++i){
7116  scalar_t w = 0;
7117  for(int ii = 0; ii < numThreads; ++ii){
7118  w += pws[ii][i];
7119  }
7120 
7121  cout << "\ti:" << i << " w:" << w - prev << endl;
7122  prev = w;
7123  }
7124 
7125 */
7126  if(noParts > 1){
7127  if(keep_part_boxes){
7128  for (partId_t j = 0; j < noParts - 1; ++j){
7129 /*
7130  cout << " outShift + currentOut + j: " << outShift + currentOut + j << endl;
7131  cout << " coordInd:" << coordInd << " cut:" << "usedCutCoordinate["<< j<< "]" << usedCutCoordinate[j] << endl;
7132 
7133  cout << "me:" << problemComm->getRank() << " before update:" << endl;
7134 
7135  (*outPartBoxes)[outShift + currentOut + j].print();
7136 */
7137  (*outPartBoxes)[outShift + currentOut + j].updateMinMax(usedCutCoordinate[j], 1 /*update max*/, coordInd);
7138 /*
7139  cout << "me:" << problemComm->getRank() << " after update:"<< endl;
7140  (*outPartBoxes)[outShift + currentOut + j].print();
7141 
7142  cout << "me:" << problemComm->getRank() << " before update:"<< endl;
7143 
7144  (*outPartBoxes)[outShift + currentOut + j + 1].print();
7145 */
7146  (*outPartBoxes)[outShift + currentOut + j + 1].updateMinMax(usedCutCoordinate[j], 0 /*update min*/, coordInd);
7147 /*
7148  cout << "me:" << problemComm->getRank() << " after update:"<< endl;
7149  (*outPartBoxes)[outShift + currentOut + j + 1].print();
7150 */
7151 
7152  }
7153  }
7154 
7155  // Rewrite the indices based on the computed cuts.
7156  getChunksFromCoordinates<lno_t,scalar_t>(
7157  noParts,
7158  numThreads,
7159  partitionedPointCoordinates,
7160  pqCoord,
7161  pqJagged_uniformWeights[0],
7162  pqJagged_weights[0],
7163 
7164  usedCutCoordinate,
7165  coordinateBegin,
7166  coordinateEnd,
7167 
7168  allowNonRectelinearPart,
7169  usednonRectelinearPart,
7170  tlr,
7171  pws,
7172  nonRectRatios,
7173  //coordinate_linked_list,
7174  //coordinate_starts,
7175  //coordinate_ends,
7176  partPointCounts,
7177 
7178  newpartitionedPointCoordinates,
7179  outTotalCounts + currentOut + outShift,
7180  partIds,
7181  //true, //should be false!!!
7182  false,
7183  pqJagged_coordinates,
7184  coordDim,
7185  coordInd
7186 
7187  );
7188  /*
7189  lno_t *mm = outTotalCounts + currentOut + outShift;
7190  for (int i = 0; i < noParts; ++i){
7191  lno_t pbeg = 0;
7192  lno_t pend = mm[i];
7193  if (i > 0) pbeg = mm[i - 1];
7194 
7195 
7196  cout << "\ti:" << i << " w:" << pend - pbeg << endl;
7197  }
7198  */
7199 
7200 
7201  }
7202  else {
7203  //if this part is partitioned into 1 then just copy the old values.
7204  lno_t partSize = coordinateEnd - coordinateBegin;
7205  *(outTotalCounts + currentOut + outShift) = partSize;
7206  memcpy(newpartitionedPointCoordinates + coordinateBegin, partitionedPointCoordinates + coordinateBegin, partSize * sizeof(lno_t));
7207  }
7208  cutShift += noParts - 1;
7209  tlrShift += (4 *(noParts - 1) + 1);
7210  outShift += noParts;
7211  pwShift += (2 * (noParts - 1) + 1);
7212  }
7213 
7214  //shift cut coordinates so that all cut coordinates are stored.
7215  cutCoordinates += cutShift;
7216 
7217  //getChunks from coordinates partitioned the parts and
7218  //wrote the indices as if there were a single part.
7219  //now we need to shift the beginning indices.
7220  for(partId_t kk = 0; kk < concurrentPart; ++kk){
7221  partId_t noParts = pAlongI[ currentWorkPart + kk];
7222  for (partId_t ii = 0;ii < noParts ; ++ii){
7223  //shift it by previousCount
7224  outTotalCounts[currentOut+ii] += previousEnd;
7225  }
7226  //increase the previous count by current end.
7227  previousEnd = outTotalCounts[currentOut + noParts - 1];
7228  //increase the current out.
7229  currentOut += noParts ;
7230  }
7231  }
7232  }
7233  // end of this partitioning dimension
7234 
7235 
7236  bool is_migrated_in_current = false;
7237  /*
7238  //now check for the migration.
7239  cout << "futurePartNumbers :" << futurePartNumbers <<
7240  " migration_check_option:" << migration_check_option <<
7241  " worldSize:" << worldSize << endl;
7242 
7243  */
7244 
7245 #ifdef enable_migration2
7246  if (
7247  futurePartNumbers > 1 &&
7248  migration_check_option >= 0 &&
7249  worldSize > 1){
7250  env->timerStart(MACRO_TIMERS, "PQJagged - Problem_Migration-" + istring);
7251 
7252 
7253  partId_t num_parts = outPartCount;
7254  if (
7255  migration_refactored<gno_t, lno_t, scalar_t, node_t, partId_t>(
7256  problemComm,
7257  env, comm,
7258  mvector,
7259  pqJagged_multiVectorDim,
7260  numGlobalCoords,//numGlobalPoints,
7261  numLocalCoords,
7262  coordDim,
7263  pqJagged_coordinates, //outout will be modified.
7264  weightDim,
7265  pqJagged_weights,// output will be modified.
7266 
7267  partIds,
7268  num_parts,
7269  currentPartitionCount, //output
7270  newFuturePartitions, //output
7271  newpartitionedPointCoordinates, //output
7272  partitionedPointCoordinates,
7273  outTotalCounts //output
7274  ,partIndexBegin,
7275  //futurePartNumbers,
7276 
7277  migration_all2all_option,
7278  migration_assignment_type,
7279  migration_actualMigration_option, //migration_proc_assignment_type
7280  migration_check_option,
7281  migration_imbalance_cut_off,
7282  migration_reduceAllPop,
7283  numLocalCoords / (futurePartNumbers * currentPartitionCount) ,
7284 
7285  //used when z1 migration is used.
7286  pq_gnos,
7287  actual_owner_of_coordinate,
7288  istring,
7289 
7290  keep_part_boxes,
7291  inPartBoxes,
7292  outPartBoxes
7293  )
7294  )
7295  {
7296  is_migrated_in_current = true;
7297  is_data_ever_migrated = true;
7298  env->timerStop(MACRO_TIMERS, "PQJagged - Problem_Migration-" + istring);
7299  reduceAllCount /= num_parts;
7300 
7301  }
7302  }
7303 #endif
7304 
7305  lno_t * tmp = partitionedPointCoordinates;
7306  partitionedPointCoordinates = newpartitionedPointCoordinates;
7307  newpartitionedPointCoordinates = tmp;
7308 
7309  if(!is_migrated_in_current){
7310  reduceAllCount -= currentPartitionCount;
7311  currentPartitionCount = outPartCount;
7312  }
7313  freeArray<lno_t>(inTotalCounts);
7314  inTotalCounts = outTotalCounts;
7315 
7316  env->timerStop(MACRO_TIMERS, "PQJagged - Problem_Partitioning_" + istring);
7317  }
7318 
7319  //cout << "me:" << problemComm->getRank() << " done:" << endl;
7320 
7321  // Partitioning is done
7322  delete currentPartitions;
7323  delete newFuturePartitions;
7324 
7325  env->timerStop(MACRO_TIMERS, "PQJagged - Problem_Partitioning");
7327 
7328  env->timerStart(MACRO_TIMERS, "PQJagged - Part_Assignment");
7329 
7330 #ifdef debug_setparts
7331  string fname = toString<int>(problemComm->getRank());
7332  fname = fname + ".print";
7333  FILE *f = fopen(fname.c_str(), "w");
7334 #endif
7335 /*
7336  problemComm->barrier();
7337 
7338 
7339  cout << "me:" << problemComm->getRank()
7340  << " partIndexBegin:" << partIndexBegin
7341  << " currentPartitionCount:" << currentPartitionCount
7342  << endl;
7343 
7344  problemComm->barrier();
7345  */
7346 
7347 #ifdef HAVE_ZOLTAN2_OMP
7348 #pragma omp parallel for
7349 #endif
7350  for(partId_t i = 0; i < currentPartitionCount;++i){
7351 
7352  lno_t begin = 0;
7353  lno_t end = inTotalCounts[i];
7354 
7355  if(i > 0) begin = inTotalCounts[i -1];
7356  partId_t pToSet = i + partIndexBegin;
7357  if (keep_part_boxes){
7358  (*outPartBoxes)[i].setpId(pToSet);
7359  }
7360  /*
7361 #ifdef HAVE_ZOLTAN2_OMP
7362 #pragma omp for
7363 #endif
7364  */
7365  //cout <<"me:" << problemComm->getRank()<< " p:" << i + partIndexBegin << " count:" << end - begin << endl;
7366  for (lno_t ii = begin; ii < end; ++ii){
7367  lno_t k = partitionedPointCoordinates[ii];
7368  partIds[k] = pToSet;
7369 
7370 #ifdef debug_setparts
7371  fprintf(f, "setting %d with coords: %lf %lf %lf to part %d\n", k, pqJagged_coordinates[0][k], pqJagged_coordinates[1][k], pqJagged_coordinates[
7372  ][k], partIds[k]);
7373 #endif
7374 
7375  }
7376  }
7377  //cout << "me:" << problemComm->getRank() << " currentPartitionCount:" << currentPartitionCount << endl;
7378 
7379 #ifdef debug_setparts
7380  fclose(f);
7381 #endif
7382  env->timerStop(MACRO_TIMERS, "PQJagged - Part_Assignment");
7383  ArrayRCP<const gno_t> gnoList;
7384  if(!is_data_ever_migrated){
7385 
7386  if(numLocalCoords > 0){
7387  gnoList = arcpFromArrayView(pqJagged_gnos);
7388  }
7389  }
7390 #ifdef enable_migration2
7391  else {
7392  if(migration_actualMigration_option == 0){
7393  gnoList = arcpFromArrayView(mvector->getMap()->getNodeElementList());
7394  }
7395  else {
7396 
7397  ZOLTAN_COMM_OBJ *plan = NULL;
7398  MPI_Comm mpi_comm = Teuchos2MPI (problemComm);
7399 
7400  lno_t incoming = 0;
7401  int message_tag = 7856;
7402 
7403 
7404  env->timerStart(MACRO_TIMERS, "PQJagged - Final Z1PlanCreating");
7405  int ierr = Zoltan_Comm_Create(
7406  &plan, numLocalCoords,
7407  actual_owner_of_coordinate, mpi_comm,
7408  message_tag, &incoming);
7409  env->timerStop(MACRO_TIMERS, "PQJagged - Final Z1PlanCreating" );
7410 
7411 
7412  gno_t *incoming_gnos = allocMemory< gno_t>(incoming);
7413 
7414  message_tag++;
7415  env->timerStart(MACRO_TIMERS, "PQJagged - Final Z1PlanComm");
7416  ierr = Zoltan_Comm_Do(
7417  plan, message_tag,
7418  (char *) pq_gnos,
7419  sizeof(gno_t),
7420  (char *) incoming_gnos);
7421 
7422  freeArray<gno_t>(pq_gnos);
7423  pq_gnos = incoming_gnos;
7424 
7425  partId_t *incoming_partIds = allocMemory< partId_t>(incoming);
7426 
7427  message_tag++;
7428  ierr = Zoltan_Comm_Do(
7429  plan, message_tag,
7430  (char *) partIds,
7431  sizeof(partId_t),
7432  (char *) incoming_partIds);
7433  freeArray<partId_t>(partIds);
7434  partIds = incoming_partIds;
7435 
7436  env->timerStop(MACRO_TIMERS, "PQJagged - Final Z1PlanComm");
7437  ierr = Zoltan_Comm_Destroy(&plan);
7438 
7439  numLocalCoords = incoming;
7440  is_data_ever_migrated = false;
7441 
7442 
7443  ArrayView<const gno_t> avpqgnos(pq_gnos, numLocalCoords);
7444  gnoList = arcpFromArrayView(avpqgnos);
7445  //cout << " me:" << problemComm->getRank() << " gnoList:" << gnoList() << endl;
7446  }
7447 
7448  }
7449 #endif
7450  env->timerStop(MACRO_TIMERS, "PQJagged - Total2");
7451 
7452  env->timerStart(MACRO_TIMERS, "PQJagged - Solution_Part_Assignment");
7453  partId = arcp(partIds, 0, numLocalCoords, true);
7454 
7455 #ifdef migrate_gid
7456  solution->setParts(gnoList, partId,true);
7457 #endif
7458 
7459  if (keep_part_boxes){
7460  solution->setPartBoxes(outPartBoxes);
7461  }
7462 #ifndef migrate_gid
7463  solution->setParts(gnoList, partId,!is_data_ever_migrated);
7464 #endif
7465  env->timerStop(MACRO_TIMERS, "PQJagged - Solution_Part_Assignment");
7466 
7467  env->timerStart(MACRO_TIMERS, "PQJagged - Problem_Free");
7468  /*
7469  if(comm->getRank() == 0){
7470  for(partId_t i = 0; i < totalPartCount - 1;++i){
7471  cout << "i:"<< i<<" cut coordinate:" << allCutCoordinates[i] << endl;
7472  }
7473  }
7474  */
7475 
7476 
7477 #ifdef enable_migration2
7478  if (migration_actualMigration_option != 0){
7479 
7480  for (int i=0; i < coordDim; i++){
7481 
7482  freeArray<scalar_t>(pqJagged_coordinates[i]);
7483  }
7484  for (int i=0; i < weightDim; i++){
7485 
7486  freeArray<scalar_t>(pqJagged_weights[i]);
7487  }
7488 
7489  //freeArray<gno_t>(pq_gnos);
7490  freeArray<int>(actual_owner_of_coordinate);
7491  }
7492 #endif
7493 
7494  for(int i = 0; i < numThreads; ++i){
7495  freeArray<lno_t>(partPointCounts[i]);
7496  }
7497 
7498  freeArray<lno_t *>(partPointCounts);
7499  freeArray<double *> (pws);
7500 
7501  if(allowNonRectelinearPart){
7502  freeArray<float>(nonRectelinearPart);
7503  for(int i = 0; i < numThreads; ++i){
7504  freeArray<float>(nonRectRatios[i]);
7505  }
7506  freeArray<float *>(nonRectRatios);
7507  }
7508 
7509  freeArray<partId_t>(myNonDoneCount);
7510 
7511  freeArray<scalar_t>(cutWeights);
7512 
7513  freeArray<scalar_t>(globalCutWeights);
7514 
7515  freeArray<scalar_t>(max_min_array);
7516 
7517  freeArray<lno_t>(outTotalCounts);
7518 
7519  freeArray<lno_t>(partitionedPointCoordinates);
7520 
7521  freeArray<lno_t>(newpartitionedPointCoordinates);
7522 
7523  freeArray<scalar_t>(allCutCoordinates);
7524 
7525  freeArray<scalar_t *>(pqJagged_coordinates);
7526 
7527  freeArray<scalar_t *>(pqJagged_weights);
7528 
7529  freeArray<bool>(pqJagged_uniformParts);
7530 
7531  freeArray<scalar_t> (localMinMaxTotal);
7532 
7533  freeArray<scalar_t> (globalMinMaxTotal);
7534 
7535  freeArray<scalar_t *>(pqJagged_partSizes);
7536 
7537  freeArray<bool>(pqJagged_uniformWeights);
7538 
7539  freeArray<scalar_t>(cutCoordinatesWork);
7540 
7541  freeArray<scalar_t>(targetPartWeightRatios);
7542 
7543  freeArray<scalar_t>(cutUpperBounds);
7544 
7545  freeArray<scalar_t>(cutLowerBounds);
7546 
7547 
7548  freeArray<scalar_t>(cutLowerWeight);
7549  freeArray<scalar_t>(cutUpperWeight);
7550  freeArray<bool>(isDone);
7551  freeArray<scalar_t>(totalPartWeights_leftClosests_rightClosests);
7552  freeArray<scalar_t>(global_totalPartWeights_leftClosests_rightClosests);
7553 
7554  for(int i = 0; i < numThreads; ++i){
7555  freeArray<double>(partWeights[i]);
7556  freeArray<scalar_t>(rightClosestDistance[i]);
7557  freeArray<scalar_t>(leftClosestDistance[i]);
7558  }
7559 
7560  freeArray<double *>(partWeights);
7561  freeArray<scalar_t *>(leftClosestDistance);
7562  freeArray<scalar_t *>(rightClosestDistance);
7563 
7564 
7565  env->timerStop(MACRO_TIMERS, "PQJagged - Problem_Free");
7566  env->timerStop(MACRO_TIMERS, "PQJagged - Total");
7567 
7568 
7569 
7570 #endif // INCLUDE_ZOLTAN2_EXPERIMENTAL
7571 }
7572 
7573 
7574 
7575 } // namespace Zoltan2
7576 
7577 
7578 
7579 
7580 
7581 #endif
7582 
void AlgPQJagged(const RCP< const Environment > &env, RCP< Comm< int > > &problemComm, const RCP< const CoordinateModel< typename Adapter::base_adapter_t > > &coords, RCP< PartitioningSolution< Adapter > > &solution)
PQJagged coordinate partitioning algorithm.
#define SWAP(a, b, temp)
Time an algorithm (or other entity) as a whole.
void pqJagged_getLocalMinMaxTotalCoord(lno_t *partitionedPointPermutations, scalar_t *pqJagged_coordinates, bool pqJagged_uniformWeights, scalar_t *pqJagged_weights, int numThreads, lno_t coordinateBegin, lno_t coordinateEnd, scalar_t *max_min_array, scalar_t maxScalar, scalar_t minScalar, scalar_t &minCoordinate, scalar_t &maxCoordinate, scalar_t &totalWeight)
Function to determine the local minimum and maximum coordinate, and local total weight in the given s...
void pqJagged_getCutCoord_Weights(scalar_t minCoordinate, scalar_t maxCoordinate, bool pqJagged_uniformParts, bool pqJagged_uniformWeights, scalar_t *pqJagged_partSizes, partId_t noCuts, scalar_t globalTotalWeight, scalar_t *cutCoordinates, scalar_t *cutPartRatios, int numThreads, vector< partId_t > *currentPartitions, vector< partId_t > *futurePartitions, partId_t partIndex, partId_t futureArrayIndex)
Function that calculates the new coordinates for the cut lines. Function is called inside the paralle...
void pqJagged_getGlobalMinMaxTotalCoord(RCP< Comm< int > > &comm, const RCP< const Environment > &env, partId_t concurrentPartCount, scalar_t *localMinMaxTotal, scalar_t *globalMinMaxTotal)
Function that reduces global minimum and maximum coordinates with global total weight from given loca...
#define MIN_WORK_LAST_DIM
void set(IT index_, CT count_, WT *vals_)
#define FUTURE_REDUCEALL_CUTOFF
PQJaggedCombinedReductionOp(std::vector< Ordinal > *pVector, Ordinal vBegin, Ordinal k_)
#define Z2_FORWARD_EXCEPTIONS
Forward an exception back through call stack.
Metric class and namespace methods to compute quality metrics.
Zoltan2::StridedData< lno_t, scalar_t > input_t
Definition: GraphModel.cpp:80
size_t global_size_t
scalar_t pivotPos(scalar_t *cutUpperBounds, scalar_t *cutLowerBounds, size_t currentCutIndex, scalar_t *cutUpperWeight, scalar_t *cutLowerWeight, scalar_t ew, scalar_t _EPSILON)
Function that calculates the next pivot position, according to given coordinates of upper bound and l...
void getChunksFromCoordinates(partId_t partNo, int noThreads, lno_t *partitionedPointPermutations, scalar_t *pqJagged_coordinates, bool pqJagged_uniformWeights, scalar_t *coordWeights, scalar_t *cutCoordinates, lno_t coordinateBegin, lno_t coordinateEnd, bool allowNonRectelinearPart, float *actual_ratios, scalar_t *localPartWeights, double **partWeights, float **nonRectelinearRatios, lno_t **partPointCounts, lno_t *newpartitionedPointPermutations, lno_t *totalCounts, partId_t *partIds, bool isSequentialAndPricise, scalar_t **pqJaggedAllCoordinates, int pqCoordDim, int currentCoord)
Function that determines the permutation indices of the coordinates.
#define EPS_SCALE
partId_t getPartCount(partId_t numFuture, float root, float fEpsilon)
void freeArray(T *&array)
void getNewCoordinates(const RCP< const Environment > &env, RCP< Comm< int > > &comm, const size_t &total_part_count, const partId_t &noCuts, const scalar_t &maxCoordinate, const scalar_t &minCoordinate, const scalar_t &globalTotalWeight, const scalar_t &imbalanceTolerance, scalar_t *globalPartWeights, const scalar_t *localPartWeights, const scalar_t *targetPartWeightRatios, bool *isDone, scalar_t *cutCoordinates, scalar_t *cutUpperBounds, scalar_t *cutLowerBounds, scalar_t *leftClosestDistance, scalar_t *rightClosestDistance, scalar_t *cutLowerWeight, scalar_t *cutUpperWeight, scalar_t *newCutCoordinates, bool allowNonRectelinearPart, float *nonRectelinearPartRatios, partId_t *rectilinearCutCount, scalar_t *localCutWeights, scalar_t *globalCutWeights, partId_t &myNoneDoneCount)
Function that calculates the new coordinates for the cut lines. Function is called inside the paralle...
zoltan2_partId_t partId_t
zoltan2_partId_t partId_t
void get_partitioning_params(const Teuchos::ParameterList &pl, T &imbalanceTolerance, multiCriteriaNorm &mcnorm, std::bitset< NUM_RCB_PARAMS > &params, int &numTestCuts, bool &ignoreWeights)
coordinateModelPartBox Class, represents the boundaries of the box which is a result of a geometric p...
void getInitialPartAssignments(scalar_t &maxCoordinate, scalar_t &minCoordinate, partId_t &currentPart, lno_t *inTotalCounts, lno_t *partitionedPointCoordinates, scalar_t *pqCoord, partId_t *partIds, scalar_t _EPSILON, partId_t &partition)
Function that calculates the new coordinates for the cut lines. Function is called inside the paralle...
void pqJagged_printInput(int coordDim, int weightDim, size_t numLocalCoords, global_size_t numGlobalCoords, int criteriaDim, scalar_t **pqJagged_values, scalar_t **pqJagged_weights, bool *pqJagged_uniformParts, bool *pqJagged_uniformWeights, gno_t *pqJagged_gnos, bool ignoreWeights, size_t numGlobalParts, scalar_t **pqJagged_partSizes)
Printing the input values, to check configuration.
This class provides geometric coordinates with optional weights to the Zoltan2 algorithm.
void reduce(const Ordinal count, const T inBuffer[], T inoutBuffer[]) const
Implement Teuchos::ValueTypeReductionOp interface.
T * allocMemory(size_t size)
void pqJagged_getInputValues(const RCP< const Environment > &env, const RCP< const CoordinateModel< typename Adapter::base_adapter_t > > &coords, RCP< PartitioningSolution< Adapter > > &solution, std::bitset< NUM_RCB_PARAMS > &params, const int &coordDim, const int &weightDim, const size_t &numLocalCoords, size_t &numGlobalParts, int &pqJagged_multiVectorDim, scalar_t **pqJagged_values, const int &criteriaDim, scalar_t **pqJagged_weights, ArrayView< const gno_t > &pqJagged_gnos, bool &ignoreWeights, bool *pqJagged_uniformWeights, bool *pqJagged_uniformParts, scalar_t **pqJagged_partSizes)
Function returning the input values for the problem such as the coordinates, weights and desiredPartS...
void inserToPart(partId_t partNo, lno_t coordinateIndex)
Inserting a coordinate to a particular part. Since, class does not have the size information, it is user&#39;s responsibility to provide indices for partNo and coordinateIndex that are in the range.
void firstTouch(T *arrayName, size_t arraySize)
dictionary vals
Definition: xml2dox.py:186
lno_t * getPartBegins()
partBegins getter function.
uMultiSortItem< IT, CT, WT > operator=(const uMultiSortItem< IT, CT, WT > &other)
void pqJagged_getCoordinateValues(const RCP< const CoordinateModel< typename Adapter::base_adapter_t > > &coords, int &coordDim, int &weightDim, size_t &numLocalCoords, global_size_t &numGlobalCoords, int &criteriaDim, const bool &ignoreWeights)
Returns the input coordinate value parameters.
A PartitioningSolution is a solution to a partitioning problem.
tuple root
Definition: xml2dox.py:168
uMultiSortItem(const uMultiSortItem< IT, CT, WT > &other)
void getPartSpecifications(const partId_t *partNo, int partArraySize, size_t &numGlobalParts, partId_t &totalDimensionCut, partId_t &totalPartCount, partId_t &maxPartNo, partId_t &reduceAllCount, partId_t &maxTotalCumulativePartCount, partId_t &maxCutNo, size_t &maxTotalPartCount)
lno_t * getLinkedList()
linkedList getter function.
PQJaggedCombinedReductionOp()
Default Constructor.
The StridedData class manages lists of weights or coordinates.
PQJaggedCombinedMinMaxTotalReductionOp(Ordinal nmin, Ordinal nmax, Ordinal nTotal)
Constructor.
static RCP< const User > doMigration(const RCP< const User > &from, lno_t numLocalRows, const gno_t *myNewRows)
Migrate the object Given a user object and a new row distribution, create and return a new user objec...
void pqJagged_1DPart_getPartWeights(size_t total_part_count, partId_t noCuts, scalar_t maxCoordinate, scalar_t minCoordinate, scalar_t _EPSILON, int numThreads, lno_t coordinateBegin, lno_t coordinateEnd, lno_t *partitionedPointPermutations, scalar_t *pqJagged_coordinates, bool pqJagged_uniformWeights, scalar_t *pqJagged_weights, scalar_t *cutCoordinates_tmp, bool *isDone, double *myPartWeights, scalar_t *myLeftClosest, scalar_t *myRightClosest, bool useBinarySearch, partId_t *partIds)
Function that calculates the new coordinates for the cut lines. Function is called inside the paralle...
void pqJagged_1D_Partition(const RCP< const Environment > &env, RCP< Comm< int > > &comm, lno_t *partitionedPointPermutations, scalar_t *pqJagged_coordinates, bool pqJagged_uniformWeights, scalar_t *pqJagged_weights, scalar_t *targetPartWeightRatios, scalar_t *globalMinMaxTotal, scalar_t *localMinMaxTotal, int numThreads, scalar_t imbalanceTolerance, partId_t currentPartBeginIndex, partId_t concurrentPartCount, lno_t *inTotalCounts, scalar_t *cutCoordinates, scalar_t *cutCoordinatesWork, scalar_t **leftClosestDistance, scalar_t **rightClosestDistance, scalar_t *cutUpperBounds, scalar_t *cutLowerBounds, scalar_t *cutUpperWeight, scalar_t *cutLowerWeight, bool *isDone, double **partWeights, scalar_t *local_totalPartWeights_leftClosest_rightCloset, scalar_t *global_totalPartWeights_leftClosest_rightCloset, bool allowNonRectelinearPart, float *nonRectelinearPartRatios, scalar_t *localCutWeights, scalar_t *globalCutWeights, partId_t allDone, partId_t *myNonDoneCounts, bool useBinarySearch, partId_t *partIds, vector< partId_t > &pVector)
Function that is responsible from 1D partitioning of the given range of coordinates.
partId_t getPartitionArrays(const partId_t *partNo, vector< partId_t > &pAlongI, vector< partId_t > *currentPartitions, vector< partId_t > *newFuturePartitions, partId_t &futurePartNumbers, partId_t currentPartitionCount, int partArraySize, int i, partId_t maxPartNo, int keep_part_boxes, RCP< vector< coordinateModelPartBox< scalar_t, partId_t > > > inPartBoxes, RCP< vector< coordinateModelPartBox< scalar_t, partId_t > > > outPartBoxes)
uMultiSortItem(IT index_, CT count_, WT *vals_)
double scalar_t
std::string toString(tt obj)
PQJaggedCombinedReductionOp(Ordinal nsum, Ordinal nmin1, Ordinal nmin2, Ordinal k_)
Constructor.
void set(lno_t *linkedList_, lno_t *partBegins_, lno_t *partEnds_)
The memory is provided to class via set function.
#define imbalanceOf2(Wachieved, wExpected)
#define Z2_THROW_EXPERIMENTAL(mystr)
Throw an error when experimental code is requested but not compiled.
void sequentialTaskPartitioning(const RCP< const Environment > &env, lno_t numLocalCoords, lno_t actualNumCoords, size_t numGlobalParts, int coordDim, scalar_t **pqJagged_coordinates, lno_t *output_permutation, lno_t *output_partIndices)
#define ABS(x)
Defines the CoordinateModel classes.
lno_t * getPartEnds()
partEnds getter function.
#define LEAST_SIGNIFICANCE
multiCriteriaNorm
Enumerator used in code for multicriteria norm choice.
void accumulateThreadResults(const vector< partId_t > &pVector, partId_t vBegin, partId_t concurrentPartCount, int numThreads, bool *isDone, scalar_t **leftClosestPoints, scalar_t **rightClosestPoints, double **partWeights, scalar_t *totalPartWeights_leftClosest_rightCloset)
Function that reduces the result of multiple threads for left and right closest points and part weigh...
bool operator>(const uMultiSortItem< IT, CT, WT > &other) const
#define Z2_THROW_OUTSIDE_ERROR(env)
Throw an error returned from outside the Zoltan2 library.
void uqsort(IT n, uSortItem< IT, WT > *arr)
#define Z2_DEFAULT_CON_PART_COUNT
void reduce(const Ordinal count, const T inBuffer[], T inoutBuffer[]) const
Implement Teuchos::ValueTypeReductionOp interface.
void pqJagged_getParameters(const Teuchos::ParameterList &pl, bool &allowNonrectilinear, partId_t &concurrentPartCount, int &migration_actualMigration_option, int &migration_check_option, int &migration_all2all_option, T &migration_imbalance_cut_off, int &migration_assignment_type, int &keep_part_boxes, int &enable_rcb, int &recursion_depth)
Returns the parameters such as: Partitioning problem parameters of interest: Partitioning objective i...
Methods written for the RCB algorithm.
#define SIGNIFICANCE_MUL
A helper class containing array representation of coordinate linked lists.
Kokkos::DefaultNode::DefaultNodeType node_t