mpi_tree.txx 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  1. /**
  2. * \file mpi_tree.txx
  3. * \author Dhairya Malhotra, dhairya.malhotra@gmail.com
  4. * \date 12-11-2010
  5. * \brief This file contains the implementation of the class MPI_Tree.
  6. */
  7. #include <assert.h>
  8. #include <cstring>
  9. #include <fstream>
  10. #include <list>
  11. #include <set>
  12. #include <parUtils.h>
  13. #include <ompUtils.h>
  14. #include <profile.hpp>
  15. namespace pvfmm{
  16. /**
  17. * @author Dhairya Malhotra, dhairya.malhotra@gmail.com
  18. * @date 08 Feb 2011
  19. */
  20. inline int p2oLocal(Vector<MortonId> & nodes, Vector<MortonId>& leaves,
  21. unsigned int maxNumPts, unsigned int maxDepth, bool complete) {
  22. assert(maxDepth<=MAX_DEPTH);
  23. std::vector<MortonId> leaves_lst;
  24. unsigned int init_size=leaves.Dim();
  25. unsigned int num_pts=nodes.Dim();
  26. MortonId curr_node=leaves[0];
  27. MortonId last_node=leaves[init_size-1].NextId();
  28. MortonId next_node;
  29. unsigned int curr_pt=0;
  30. unsigned int next_pt=curr_pt+maxNumPts;
  31. while(next_pt <= num_pts){
  32. next_node = curr_node.NextId();
  33. while( next_pt < num_pts && next_node > nodes[next_pt] && curr_node.GetDepth() < maxDepth-1 ){
  34. curr_node = curr_node.getDFD(curr_node.GetDepth()+1);
  35. next_node = curr_node.NextId();
  36. }
  37. leaves_lst.push_back(curr_node);
  38. curr_node = next_node;
  39. unsigned int inc=maxNumPts;
  40. while(next_pt < num_pts && curr_node > nodes[next_pt]){
  41. // We have more than maxNumPts points per octant because the node can
  42. // not be refined any further.
  43. inc=inc<<1;
  44. next_pt+=inc;
  45. if(next_pt > num_pts){
  46. next_pt = num_pts;
  47. break;
  48. }
  49. }
  50. curr_pt = std::lower_bound(&nodes[0]+curr_pt,&nodes[0]+next_pt,curr_node,std::less<MortonId>())-&nodes[0];
  51. if(curr_pt >= num_pts) break;
  52. next_pt = curr_pt + maxNumPts;
  53. if(next_pt > num_pts) next_pt = num_pts;
  54. }
  55. #ifndef NDEBUG
  56. for(size_t i=0;i<leaves_lst.size();i++){
  57. size_t a=std::lower_bound(&nodes[0],&nodes[0]+nodes.Dim(),leaves_lst[i],std::less<MortonId>())-&nodes[0];
  58. size_t b=std::lower_bound(&nodes[0],&nodes[0]+nodes.Dim(),leaves_lst[i].NextId(),std::less<MortonId>())-&nodes[0];
  59. assert(b-a<=maxNumPts || leaves_lst[i].GetDepth()==maxDepth-1);
  60. if(i==leaves_lst.size()-1) assert(b==nodes.Dim() && a<nodes.Dim());
  61. if(i==0) assert(a==0);
  62. }
  63. #endif
  64. if(complete)
  65. while(curr_node<last_node){
  66. while( curr_node.NextId() > last_node && curr_node.GetDepth() < maxDepth-1 )
  67. curr_node = curr_node.getDFD(curr_node.GetDepth()+1);
  68. leaves_lst.push_back(curr_node);
  69. curr_node = curr_node.NextId();
  70. }
  71. leaves=leaves_lst;
  72. return 0;
  73. }
  74. inline int points2Octree(const Vector<MortonId>& pt_mid, Vector<MortonId>& nodes,
  75. unsigned int maxDepth, unsigned int maxNumPts, const MPI_Comm& comm ) {
  76. int myrank, np;
  77. MPI_Comm_rank(comm, &myrank);
  78. MPI_Comm_size(comm, &np);
  79. // Sort morton id of points.
  80. Profile::Tic("SortMortonId", &comm, true, 5);
  81. Vector<MortonId> pt_sorted;
  82. //par::partitionW<MortonId>(pt_mid, NULL, comm);
  83. par::HyperQuickSort(pt_mid, pt_sorted, comm);
  84. size_t pt_cnt=pt_sorted.Dim();
  85. Profile::Toc();
  86. // Add last few points from next process, to get the boundary octant right.
  87. Profile::Tic("Comm", &comm, true, 5);
  88. {
  89. { // Adjust maxNumPts
  90. size_t glb_pt_cnt=0;
  91. MPI_Allreduce(&pt_cnt, &glb_pt_cnt, 1, par::Mpi_datatype<size_t>::value(), par::Mpi_datatype<size_t>::sum(), comm);
  92. if(glb_pt_cnt<maxNumPts*np) maxNumPts=glb_pt_cnt/np;
  93. }
  94. size_t recv_size=0;
  95. size_t send_size=(2*maxNumPts<pt_cnt?2*maxNumPts:pt_cnt);
  96. {
  97. MPI_Request recvRequest;
  98. MPI_Request sendRequest;
  99. MPI_Status statusWait;
  100. if(myrank < (np-1)) MPI_Irecv (&recv_size, 1, par::Mpi_datatype<size_t>::value(), myrank+1, 1, comm, &recvRequest);
  101. if(myrank > 0 ) MPI_Issend(&send_size, 1, par::Mpi_datatype<size_t>::value(), myrank-1, 1, comm, &sendRequest);
  102. if(myrank < (np-1)) MPI_Wait(&recvRequest, &statusWait);
  103. if(myrank > 0 ) MPI_Wait(&sendRequest, &statusWait); //This can be done later.
  104. }
  105. if(recv_size>0){// Resize pt_sorted.
  106. Vector<MortonId> pt_sorted_(pt_cnt+recv_size);
  107. mem::memcopy(&pt_sorted_[0], &pt_sorted[0], pt_cnt*sizeof(MortonId));
  108. pt_sorted.Swap(pt_sorted_);
  109. }
  110. {// Exchange data.
  111. MPI_Request recvRequest;
  112. MPI_Request sendRequest;
  113. MPI_Status statusWait;
  114. if(myrank < (np-1)) MPI_Irecv (&pt_sorted[0]+pt_cnt, recv_size, par::Mpi_datatype<MortonId>::value(), myrank+1, 1, comm, &recvRequest);
  115. if(myrank > 0 ) MPI_Issend(&pt_sorted[0] , send_size, par::Mpi_datatype<MortonId>::value(), myrank-1, 1, comm, &sendRequest);
  116. if(myrank < (np-1)) MPI_Wait(&recvRequest, &statusWait);
  117. if(myrank > 0 ) MPI_Wait(&sendRequest, &statusWait); //This can be done later.
  118. }
  119. }
  120. Profile::Toc();
  121. // Construct local octree.
  122. Profile::Tic("p2o_local", &comm, false, 5);
  123. Vector<MortonId> nodes_local(1); nodes_local[0]=MortonId();
  124. p2oLocal(pt_sorted, nodes_local, maxNumPts, maxDepth, myrank==np-1);
  125. Profile::Toc();
  126. // Remove duplicate nodes on adjacent processors.
  127. Profile::Tic("RemoveDuplicates", &comm, true, 5);
  128. {
  129. size_t node_cnt=nodes_local.Dim();
  130. MortonId first_node;
  131. MortonId last_node=nodes_local[node_cnt-1];
  132. { // Send last_node to next process and get first_node from previous process.
  133. MPI_Request recvRequest;
  134. MPI_Request sendRequest;
  135. MPI_Status statusWait;
  136. if(myrank < (np-1)) MPI_Issend(& last_node, 1, par::Mpi_datatype<MortonId>::value(), myrank+1, 1, comm, &recvRequest);
  137. if(myrank > 0 ) MPI_Irecv (&first_node, 1, par::Mpi_datatype<MortonId>::value(), myrank-1, 1, comm, &sendRequest);
  138. if(myrank < (np-1)) MPI_Wait(&recvRequest, &statusWait);
  139. if(myrank > 0 ) MPI_Wait(&sendRequest, &statusWait); //This can be done later.
  140. }
  141. size_t i=0;
  142. std::vector<MortonId> node_lst;
  143. if(myrank){
  144. while(i<node_cnt && nodes_local[i].getDFD(maxDepth)<first_node) i++; assert(i);
  145. last_node=nodes_local[i>0?i-1:0].NextId(); // Next MortonId in the tree after first_node.
  146. while(first_node<last_node){ // Complete nodes between first_node and last_node.
  147. while(first_node.isAncestor(last_node))
  148. first_node=first_node.getDFD(first_node.GetDepth()+1);
  149. if(first_node==last_node) break;
  150. node_lst.push_back(first_node);
  151. first_node=first_node.NextId();
  152. }
  153. }
  154. for(;i<node_cnt-(myrank==np-1?0:1);i++) node_lst.push_back(nodes_local[i]);
  155. nodes=node_lst;
  156. }
  157. Profile::Toc();
  158. // Repartition nodes.
  159. Profile::Tic("partitionW", &comm, false, 5);
  160. par::partitionW<MortonId>(nodes, NULL , comm);
  161. Profile::Toc();
  162. return 0;
  163. }
  164. template <class TreeNode>
  165. void MPI_Tree<TreeNode>::Initialize(typename Node_t::NodeData* init_data){
  166. //Initialize root node.
  167. Profile::Tic("InitRoot",Comm(),false,3);
  168. Tree<TreeNode>::Initialize(init_data);
  169. TreeNode* rnode=this->RootNode();
  170. assert(this->dim==COORD_DIM);
  171. Profile::Toc();
  172. Profile::Tic("Points2Octee",Comm(),true,3);
  173. Vector<MortonId> lin_oct;
  174. { //Get the linear tree.
  175. // Compute MortonId from pt_coord.
  176. Vector<MortonId> pt_mid;
  177. Vector<Real_t>& pt_coord=rnode->pt_coord;
  178. size_t pt_cnt=pt_coord.Dim()/this->dim;
  179. pt_mid.Resize(pt_cnt);
  180. #pragma omp parallel for
  181. for(size_t i=0;i<pt_cnt;i++){
  182. pt_mid[i]=MortonId(pt_coord[i*COORD_DIM+0],pt_coord[i*COORD_DIM+1],pt_coord[i*COORD_DIM+2],this->max_depth);
  183. }
  184. //Get the linear tree.
  185. points2Octree(pt_mid,lin_oct,this->max_depth,init_data->max_pts,*Comm());
  186. }
  187. Profile::Toc();
  188. Profile::Tic("ScatterPoints",Comm(),true,3);
  189. { // Sort and partition point coordinates and values.
  190. std::vector<Vector<Real_t>*> coord_lst;
  191. std::vector<Vector<Real_t>*> value_lst;
  192. std::vector<Vector<size_t>*> scatter_lst;
  193. rnode->NodeDataVec(coord_lst, value_lst, scatter_lst);
  194. assert(coord_lst.size()==value_lst.size());
  195. assert(coord_lst.size()==scatter_lst.size());
  196. Vector<MortonId> pt_mid;
  197. Vector<size_t> scatter_index;
  198. for(size_t i=0;i<coord_lst.size();i++){
  199. if(!coord_lst[i]) continue;
  200. Vector<Real_t>& pt_coord=*coord_lst[i];
  201. { // Compute MortonId from pt_coord.
  202. size_t pt_cnt=pt_coord.Dim()/this->dim;
  203. pt_mid.Resize(pt_cnt);
  204. #pragma omp parallel for
  205. for(size_t i=0;i<pt_cnt;i++){
  206. pt_mid[i]=MortonId(pt_coord[i*COORD_DIM+0],pt_coord[i*COORD_DIM+1],pt_coord[i*COORD_DIM+2],this->max_depth);
  207. }
  208. }
  209. par::SortScatterIndex(pt_mid , scatter_index, comm, &lin_oct[0]);
  210. par::ScatterForward (pt_coord, scatter_index, comm);
  211. if(value_lst[i]!=NULL){
  212. Vector<Real_t>& pt_value=*value_lst[i];
  213. par::ScatterForward(pt_value, scatter_index, comm);
  214. }
  215. if(scatter_lst[i]!=NULL){
  216. Vector<size_t>& pt_scatter=*scatter_lst[i];
  217. pt_scatter=scatter_index;
  218. }
  219. }
  220. }
  221. Profile::Toc();
  222. //Initialize the pointer based tree from the linear tree.
  223. Profile::Tic("PointerTree",Comm(),false,3);
  224. { // Construct the pointer tree from lin_oct
  225. int omp_p=omp_get_max_threads();
  226. // Partition nodes between threads
  227. rnode->SetGhost(false);
  228. for(int i=0;i<omp_p;i++){
  229. size_t idx=(lin_oct.Dim()*i)/omp_p;
  230. Node_t* n=FindNode(lin_oct[idx], true);
  231. assert(n->GetMortonId()==lin_oct[idx]);
  232. UNUSED(n);
  233. }
  234. #pragma omp parallel for
  235. for(int i=0;i<omp_p;i++){
  236. size_t a=(lin_oct.Dim()* i )/omp_p;
  237. size_t b=(lin_oct.Dim()*(i+1))/omp_p;
  238. size_t idx=a;
  239. Node_t* n=FindNode(lin_oct[idx], false);
  240. if(a==0) n=rnode;
  241. while(n!=NULL && (idx<b || i==omp_p-1)){
  242. n->SetGhost(false);
  243. MortonId dn=n->GetMortonId();
  244. if(idx<b && dn.isAncestor(lin_oct[idx])){
  245. if(n->IsLeaf()) n->Subdivide();
  246. }else if(idx<b && dn==lin_oct[idx]){
  247. if(!n->IsLeaf()) n->Truncate();
  248. assert(n->IsLeaf());
  249. idx++;
  250. }else{
  251. n->Truncate();
  252. n->SetGhost(true);
  253. }
  254. n=this->PreorderNxt(n);
  255. }
  256. assert(idx==b);
  257. }
  258. }
  259. Profile::Toc();
  260. #ifndef NDEBUG
  261. CheckTree();
  262. #endif
  263. }
  264. template <class TreeNode>
  265. void MPI_Tree<TreeNode>::CoarsenTree(){
  266. int myrank;
  267. MPI_Comm_rank(*Comm(),&myrank);
  268. //Redistribute.
  269. {
  270. Node_t* n=this->PostorderFirst();
  271. while(n){
  272. if(n->IsLeaf() && !n->IsGhost()) break;
  273. n=this->PostorderNxt(n);
  274. }
  275. while(myrank){
  276. Node_t* n_parent=(Node_t*)n->Parent();
  277. Node_t* n_ = n_parent;
  278. while(n_ && !n_->IsLeaf()){
  279. n_=this->PostorderNxt(n_);
  280. if(!n_) break;
  281. }
  282. if(!n_ || n_->IsGhost()) break;
  283. if(n->Depth()<=n_->Depth()) break;
  284. if(n_->Depth()<=1) break;
  285. n=n_;
  286. }
  287. MortonId loc_min=n->GetMortonId();
  288. RedistNodes(&loc_min);
  289. }
  290. //Truncate ghost nodes and build node list
  291. std::vector<Node_t*> leaf_nodes;
  292. {
  293. Node_t* n=this->PostorderFirst();
  294. while(n!=NULL){
  295. if(n->IsLeaf() && !n->IsGhost()) break;
  296. n->Truncate();
  297. n->SetGhost(true);
  298. n->ClearData();
  299. n=this->PostorderNxt(n);
  300. }
  301. while(n!=NULL){
  302. if(n->IsLeaf() && n->IsGhost()) break;
  303. if(n->IsLeaf()) leaf_nodes.push_back(n);
  304. n=this->PreorderNxt(n);
  305. }
  306. while(n!=NULL){
  307. n->Truncate();
  308. n->SetGhost(true);
  309. n->ClearData();
  310. n=this->PreorderNxt(n);
  311. }
  312. }
  313. size_t node_cnt=leaf_nodes.size();
  314. //Partition nodes between OpenMP threads.
  315. int omp_p=omp_get_max_threads();
  316. std::vector<MortonId> mid(omp_p);
  317. std::vector<MortonId> split_key(omp_p);
  318. #pragma omp parallel for
  319. for(int i=0;i<omp_p;i++){
  320. mid[i]=leaf_nodes[(i*node_cnt)/omp_p]->GetMortonId();
  321. }
  322. //Coarsen Tree.
  323. #pragma omp parallel for
  324. for(int i=0;i<omp_p;i++){
  325. Node_t* n_=leaf_nodes[i*node_cnt/omp_p];
  326. if(i*node_cnt/omp_p<(i+1)*node_cnt/omp_p)
  327. while(n_!=NULL){
  328. MortonId n_mid=n_->GetMortonId();
  329. if(!n_->IsLeaf() && !n_mid.isAncestor(mid[i].getDFD()))
  330. if(i<omp_p-1? !n_mid.isAncestor(mid[i+1].getDFD()):true)
  331. if(!n_->SubdivCond()) n_->Truncate();
  332. if(i<omp_p-1? n_mid==mid[i+1]: false) break;
  333. n_=this->PostorderNxt(n_);
  334. }
  335. }
  336. //Truncate nodes along ancestors of splitters.
  337. for(int i=0;i<omp_p;i++){
  338. Node_t* n_=FindNode(mid[i], false, this->RootNode());
  339. while(n_->Depth()>0){
  340. n_=(Node_t*)n_->Parent();
  341. if(!n_->SubdivCond()) n_->Truncate();
  342. else break;
  343. }
  344. }
  345. }
  346. template <class TreeNode>
  347. void MPI_Tree<TreeNode>::RefineTree(){
  348. int np, myrank;
  349. MPI_Comm_size(*Comm(),&np);
  350. MPI_Comm_rank(*Comm(),&myrank);
  351. int omp_p=omp_get_max_threads();
  352. int n_child=1UL<<this->Dim();
  353. //Coarsen tree.
  354. MPI_Tree<TreeNode>::CoarsenTree();
  355. //Build node list.
  356. std::vector<Node_t*> leaf_nodes;
  357. {
  358. Node_t* n=this->PostorderFirst();
  359. while(n!=NULL){
  360. if(n->IsLeaf() && !n->IsGhost())
  361. leaf_nodes.push_back(n);
  362. n=this->PostorderNxt(n);
  363. }
  364. }
  365. size_t tree_node_cnt=leaf_nodes.size();
  366. //Adaptive subdivision of leaf nodes with load balancing.
  367. for(int l=0;l<this->max_depth;l++){
  368. //Subdivide nodes.
  369. std::vector<std::vector<Node_t*> > leaf_nodes_(omp_p);
  370. #pragma omp parallel for
  371. for(int i=0;i<omp_p;i++){
  372. size_t a=(leaf_nodes.size()* i )/omp_p;
  373. size_t b=(leaf_nodes.size()*(i+1))/omp_p;
  374. for(size_t j=a;j<b;j++){
  375. if(leaf_nodes[j]->IsLeaf() && !leaf_nodes[j]->IsGhost()){
  376. if(leaf_nodes[j]->SubdivCond()) leaf_nodes[j]->Subdivide();
  377. if(!leaf_nodes[j]->IsLeaf())
  378. for(int k=0;k<n_child;k++)
  379. leaf_nodes_[i].push_back((Node_t*)leaf_nodes[j]->Child(k));
  380. }
  381. }
  382. }
  383. for(int i=0;i<omp_p;i++)
  384. tree_node_cnt+=(leaf_nodes_[i].size()/n_child)*(n_child-1);
  385. //Determine load imbalance.
  386. size_t global_max, global_sum;
  387. MPI_Allreduce(&tree_node_cnt, &global_max, 1, par::Mpi_datatype<size_t>::value(), par::Mpi_datatype<size_t>::max(), *Comm());
  388. MPI_Allreduce(&tree_node_cnt, &global_sum, 1, par::Mpi_datatype<size_t>::value(), par::Mpi_datatype<size_t>::sum(), *Comm());
  389. //RedistNodes if needed.
  390. if(global_max*np>4*global_sum){
  391. #ifndef NDEBUG
  392. Profile::Tic("RedistNodes",Comm(),true,4);
  393. #endif
  394. RedistNodes();
  395. #ifndef NDEBUG
  396. Profile::Toc();
  397. #endif
  398. //Rebuild node list.
  399. leaf_nodes.clear();
  400. Node_t* n=this->PostorderFirst();
  401. while(n!=NULL){
  402. if(n->IsLeaf() && !n->IsGhost())
  403. leaf_nodes.push_back(n);
  404. n=this->PostorderNxt(n);
  405. }
  406. tree_node_cnt=leaf_nodes.size();
  407. }else{
  408. //Combine partial list of nodes.
  409. int node_cnt=0;
  410. for(int j=0;j<omp_p;j++)
  411. node_cnt+=leaf_nodes_[j].size();
  412. leaf_nodes.resize(node_cnt);
  413. #pragma omp parallel for
  414. for(int i=0;i<omp_p;i++){
  415. int offset=0;
  416. for(int j=0;j<i;j++)
  417. offset+=leaf_nodes_[j].size();
  418. for(size_t j=0;j<leaf_nodes_[i].size();j++)
  419. leaf_nodes[offset+j]=leaf_nodes_[i][j];
  420. }
  421. }
  422. }
  423. RedistNodes();
  424. MPI_Tree<TreeNode>::CoarsenTree();
  425. RedistNodes();
  426. MPI_Tree<TreeNode>::CoarsenTree();
  427. RedistNodes();
  428. }
  429. template <class TreeNode>
  430. void MPI_Tree<TreeNode>::RedistNodes(MortonId* loc_min) {
  431. int np, myrank;
  432. MPI_Comm_size(*Comm(),&np);
  433. MPI_Comm_rank(*Comm(),&myrank);
  434. if(np==1)return;
  435. //Create a linear tree in dendro format.
  436. Node_t* curr_node=this->PreorderFirst();
  437. std::vector<MortonId> in;
  438. std::vector<Node_t*> node_lst;
  439. while(curr_node!=NULL){
  440. if(curr_node->IsLeaf() && !curr_node->IsGhost()){
  441. node_lst.push_back(curr_node);
  442. in.push_back(curr_node->GetMortonId());
  443. }
  444. curr_node=this->PreorderNxt(curr_node);
  445. }
  446. size_t leaf_cnt=in.size();
  447. //Get new mins.
  448. std::vector<MortonId> new_mins(np);
  449. if(loc_min==NULL){
  450. //Partition vector of MortonIds using par::partitionW
  451. std::vector<MortonId> in_=in;
  452. std::vector<long long> wts(in_.size());
  453. #pragma omp parallel for
  454. for(size_t i=0;i<wts.size();i++){
  455. wts[i]=node_lst[i]->NodeCost();
  456. }
  457. par::partitionW<MortonId>(in_,&wts[0],*Comm());
  458. MPI_Allgather(&in_[0] , 1, par::Mpi_datatype<MortonId>::value(),
  459. &new_mins[0], 1, par::Mpi_datatype<MortonId>::value(), *Comm());
  460. }else{
  461. MPI_Allgather(loc_min , 1, par::Mpi_datatype<MortonId>::value(),
  462. &new_mins[0], 1, par::Mpi_datatype<MortonId>::value(), *Comm());
  463. }
  464. //Now exchange nodes according to new mins
  465. std::vector<PackedData> data(leaf_cnt);
  466. std::vector<int> send_cnts; send_cnts.assign(np,0);
  467. std::vector<int> send_size; send_size.assign(np,0);
  468. size_t sbuff_size=0;
  469. int omp_p=omp_get_max_threads();
  470. #pragma omp parallel for reduction(+:sbuff_size)
  471. for(int i=0;i<omp_p;i++){
  472. size_t a=( i *np)/omp_p;
  473. size_t b=((i+1)*np)/omp_p;
  474. if(b>a){
  475. size_t p_iter=a;
  476. size_t node_iter=std::lower_bound(&in[0], &in[in.size()], new_mins[a])-&in[0];
  477. for( ;node_iter<node_lst.size();node_iter++){
  478. while(p_iter+1u<(size_t)np? in[node_iter]>=new_mins[p_iter+1]: false) p_iter++;
  479. if(p_iter>=b) break;
  480. send_cnts[p_iter]++;
  481. data[node_iter]=node_lst[node_iter]->Pack();
  482. send_size[p_iter]+=data[node_iter].length+sizeof(size_t)+sizeof(MortonId);
  483. sbuff_size +=data[node_iter].length+sizeof(size_t)+sizeof(MortonId);
  484. }
  485. }
  486. }
  487. std::vector<int> recv_cnts(np);
  488. std::vector<int> recv_size(np);
  489. MPI_Alltoall(&send_cnts[0], 1, par::Mpi_datatype<int>::value(),
  490. &recv_cnts[0], 1, par::Mpi_datatype<int>::value(), *Comm());
  491. MPI_Alltoall(&send_size[0], 1, par::Mpi_datatype<int>::value(),
  492. &recv_size[0], 1, par::Mpi_datatype<int>::value(), *Comm());
  493. size_t recv_cnt=0;
  494. #pragma omp parallel for reduction(+:recv_cnt)
  495. for(int i=0;i<np;i++) recv_cnt+=recv_cnts[i];
  496. std::vector<MortonId> out(recv_cnt);
  497. std::vector<int> sdisp; sdisp.assign(np,0);
  498. std::vector<int> rdisp; rdisp.assign(np,0);
  499. omp_par::scan(&send_size[0],&sdisp[0],np); //TODO Don't need to do a full scan
  500. omp_par::scan(&recv_size[0],&rdisp[0],np); // as most entries will be 0.
  501. size_t rbuff_size=rdisp[np-1]+recv_size[np-1];
  502. char* send_buff=new char[sbuff_size];
  503. char* recv_buff=new char[rbuff_size];
  504. std::vector<char*> data_ptr(leaf_cnt);
  505. char* s_ptr=send_buff;
  506. for(size_t i=0;i<leaf_cnt;i++){
  507. *((MortonId*)s_ptr)=in [i] ; s_ptr+=sizeof(MortonId);
  508. *(( size_t*)s_ptr)=data[i].length; s_ptr+=sizeof(size_t);
  509. data_ptr[i]=s_ptr ; s_ptr+=data[i].length;
  510. }
  511. #pragma omp parallel for
  512. for(int p=0;p<omp_p;p++){
  513. size_t a=( p *leaf_cnt)/omp_p;
  514. size_t b=((p+1)*leaf_cnt)/omp_p;
  515. for(size_t i=a;i<b;i++)
  516. mem::memcopy(data_ptr[i], data[i].data, data[i].length);
  517. }
  518. par::Mpi_Alltoallv_sparse<char>(&send_buff[0], &send_size[0], &sdisp[0],
  519. &recv_buff[0], &recv_size[0], &rdisp[0], *Comm());
  520. char* r_ptr=recv_buff;
  521. std::vector<PackedData> r_data(recv_cnt);
  522. for(size_t i=0;i<recv_cnt;i++){
  523. out [i] =*(MortonId*)r_ptr; r_ptr+=sizeof(MortonId);
  524. r_data[i].length=*( size_t*)r_ptr; r_ptr+=sizeof(size_t);
  525. r_data[i].data = r_ptr; r_ptr+=r_data[i].length;
  526. }
  527. //Initialize all new nodes.
  528. int nchld=1UL<<this->Dim();
  529. size_t node_iter=0;
  530. MortonId dn;
  531. node_lst.resize(recv_cnt);
  532. Node_t* n=this->PreorderFirst();
  533. while(n!=NULL && node_iter<recv_cnt){
  534. n->SetGhost(false);
  535. dn=n->GetMortonId();
  536. if(dn.isAncestor(out[node_iter]) && dn!=out[node_iter]){
  537. if(n->IsLeaf()){
  538. {
  539. n->SetGhost(true);
  540. n->Subdivide();
  541. n->SetGhost(false);
  542. for(int j=0;j<nchld;j++){
  543. Node_t* ch_node=(Node_t*)n->Child(j);
  544. ch_node->SetGhost(false);
  545. }
  546. }
  547. }
  548. }else if(dn==out[node_iter]){
  549. if(!n->IsLeaf()){
  550. n->Truncate();
  551. n->SetGhost(false);
  552. }
  553. node_lst[node_iter]=n;
  554. node_iter++;
  555. }else{
  556. n->Truncate(); //This node does not belong to this process.
  557. n->SetGhost(true);
  558. }
  559. n=this->PreorderNxt(n);
  560. }
  561. while(n!=NULL){
  562. n->Truncate();
  563. n->SetGhost(true);
  564. n=this->PreorderNxt(n);
  565. }
  566. #pragma omp parallel for
  567. for(int p=0;p<omp_p;p++){
  568. size_t a=( p *recv_cnt)/omp_p;
  569. size_t b=((p+1)*recv_cnt)/omp_p;
  570. for(size_t i=a;i<b;i++)
  571. node_lst[i]->Unpack(r_data[i]);
  572. }
  573. //Free memory buffers.
  574. delete[] recv_buff;
  575. delete[] send_buff;
  576. }
  577. template <class TreeNode>
  578. TreeNode* MPI_Tree<TreeNode>::FindNode(MortonId& key, bool subdiv, TreeNode* start){
  579. int num_child=1UL<<this->Dim();
  580. Node_t* n=start;
  581. if(n==NULL) n=this->RootNode();
  582. while(n->GetMortonId()<key && (!n->IsLeaf()||subdiv)){
  583. if(n->IsLeaf() && !n->IsGhost()) n->Subdivide();
  584. if(n->IsLeaf()) break;
  585. for(int j=0;j<num_child;j++){
  586. if(((Node_t*)n->Child(j))->GetMortonId().NextId()>key){
  587. n=(Node_t*)n->Child(j);
  588. break;
  589. }
  590. }
  591. }
  592. assert(!subdiv || n->IsGhost() || n->GetMortonId()==key);
  593. return n;
  594. }
  595. //list must be sorted.
  596. inline int lineariseList(std::vector<MortonId> & list, MPI_Comm comm) {
  597. int rank,size;
  598. MPI_Comm_rank(comm,&rank);
  599. MPI_Comm_size(comm,&size);
  600. //Remove empty processors...
  601. int new_rank, new_size;
  602. MPI_Comm new_comm;
  603. MPI_Comm_split(comm, (list.empty()?0:1), rank, &new_comm);
  604. MPI_Comm_rank (new_comm, &new_rank);
  605. MPI_Comm_size (new_comm, &new_size);
  606. if(!list.empty()) {
  607. //Send the last octant to the next processor.
  608. MortonId lastOctant = list[list.size()-1];
  609. MortonId lastOnPrev;
  610. MPI_Request recvRequest;
  611. MPI_Request sendRequest;
  612. if(new_rank > 0) {
  613. MPI_Irecv(&lastOnPrev, 1, par::Mpi_datatype<MortonId>::value(), new_rank-1, 1, new_comm, &recvRequest);
  614. }
  615. if(new_rank < (new_size-1)) {
  616. MPI_Issend( &lastOctant, 1, par::Mpi_datatype<MortonId>::value(), new_rank+1, 1, new_comm, &sendRequest);
  617. }
  618. if(new_rank > 0) {
  619. std::vector<MortonId> tmp(list.size()+1);
  620. for(size_t i = 0; i < list.size(); i++) {
  621. tmp[i+1] = list[i];
  622. }
  623. MPI_Status statusWait;
  624. MPI_Wait(&recvRequest, &statusWait);
  625. tmp[0] = lastOnPrev;
  626. list.swap(tmp);
  627. }
  628. {// Remove duplicates and ancestors.
  629. std::vector<MortonId> tmp;
  630. if(!(list.empty())) {
  631. for(unsigned int i = 0; i < (list.size()-1); i++) {
  632. if( (!(list[i].isAncestor(list[i+1]))) && (list[i] != list[i+1]) ) {
  633. tmp.push_back(list[i]);
  634. }
  635. }
  636. if(new_rank == (new_size-1)) {
  637. tmp.push_back(list[list.size()-1]);
  638. }
  639. }
  640. list.swap(tmp);
  641. }
  642. if(new_rank < (new_size-1)) {
  643. MPI_Status statusWait;
  644. MPI_Wait(&sendRequest, &statusWait);
  645. }
  646. }//not empty procs only
  647. return 1;
  648. }//end fn.
  649. inline int balanceOctree (std::vector<MortonId > &in, std::vector<MortonId > &out,
  650. unsigned int dim, unsigned int maxDepth, bool periodic, MPI_Comm comm) {
  651. int omp_p=omp_get_max_threads();
  652. int rank, size;
  653. MPI_Comm_size(comm,&size);
  654. MPI_Comm_rank(comm,&rank);
  655. if(size==1 && in.size()==1){
  656. out=in;
  657. return 0;
  658. }
  659. #ifdef __VERBOSE__
  660. long long locInSize = in.size();
  661. #endif
  662. //////////////////////////////////////////////////////////////////////////////////////////////////
  663. { //Redistribute.
  664. //Vector<long long> balance_wt(size);
  665. //#pragma omp parallel for
  666. //for(size_t i=0;i<size;i++){
  667. // balance_wt[i]=in[i].GetDepth();
  668. //}
  669. //par::partitionW<MortonId>(in, &balance_wt[0], comm);
  670. par::partitionW<MortonId>(in, NULL, comm);
  671. }
  672. //Build level-by-level set of nodes.
  673. std::vector<std::set<MortonId> > nodes((maxDepth+1)*omp_p);
  674. #pragma omp parallel for
  675. for(int p=0;p<omp_p;p++){
  676. size_t a=( p *in.size())/omp_p;
  677. size_t b=((p+1)*in.size())/omp_p;
  678. for(size_t i=a;i<b;){
  679. size_t d=in[i].GetDepth();
  680. if(d==0){i++; continue;}
  681. MortonId pnode=in[i].getAncestor(d-1);
  682. nodes[d-1+(maxDepth+1)*p].insert(pnode);
  683. while(i<b && d==in[i].GetDepth() && pnode==in[i].getAncestor(d-1)) i++;
  684. }
  685. //Add new nodes level-by-level.
  686. std::vector<MortonId> nbrs;
  687. unsigned int num_chld=1UL<<dim;
  688. for(unsigned int l=maxDepth;l>=1;l--){
  689. //Build set of parents of balancing nodes.
  690. std::set<MortonId> nbrs_parent;
  691. std::set<MortonId>::iterator start=nodes[l+(maxDepth+1)*p].begin();
  692. std::set<MortonId>::iterator end =nodes[l+(maxDepth+1)*p].end();
  693. for(std::set<MortonId>::iterator node=start; node != end;){
  694. node->NbrList(nbrs, l, periodic);
  695. int nbr_cnt=nbrs.size();
  696. for(int i=0;i<nbr_cnt;i++)
  697. nbrs_parent.insert(nbrs[i].getAncestor(l-1));
  698. node++;
  699. }
  700. //Get the balancing nodes.
  701. std::set<MortonId>& ancestor_nodes=nodes[l-1+(maxDepth+1)*p];
  702. start=nbrs_parent.begin();
  703. end =nbrs_parent.end();
  704. ancestor_nodes.insert(start,end);
  705. }
  706. //Remove non-leaf nodes. (optional)
  707. for(unsigned int l=1;l<=maxDepth;l++){
  708. std::set<MortonId>::iterator start=nodes[l +(maxDepth+1)*p].begin();
  709. std::set<MortonId>::iterator end =nodes[l +(maxDepth+1)*p].end();
  710. std::set<MortonId>& ancestor_nodes=nodes[l-1+(maxDepth+1)*p];
  711. for(std::set<MortonId>::iterator node=start; node != end; node++){
  712. MortonId parent=node->getAncestor(node->GetDepth()-1);
  713. ancestor_nodes.erase(parent);
  714. }
  715. }
  716. }
  717. //Resize in.
  718. std::vector<size_t> node_cnt(omp_p,0);
  719. std::vector<size_t> node_dsp(omp_p,0);
  720. #pragma omp parallel for
  721. for(int i=0;i<omp_p;i++){
  722. for(unsigned int j=0;j<=maxDepth;j++)
  723. node_cnt[i]+=nodes[j+i*(maxDepth+1)].size();
  724. }
  725. omp_par::scan(&node_cnt[0],&node_dsp[0], omp_p);
  726. in.resize(node_cnt[omp_p-1]+node_dsp[omp_p-1]);
  727. //Copy leaf nodes to in.
  728. #pragma omp parallel for
  729. for(int p=0;p<omp_p;p++){
  730. size_t node_iter=node_dsp[p];
  731. for(unsigned int l=0;l<=maxDepth;l++){
  732. std::set<MortonId>::iterator start=nodes[l +(maxDepth+1)*p].begin();
  733. std::set<MortonId>::iterator end =nodes[l +(maxDepth+1)*p].end();
  734. for(std::set<MortonId>::iterator node=start; node != end; node++)
  735. in[node_iter++]=*node;
  736. }
  737. }
  738. #ifdef __VERBOSE__
  739. //Local size before removing duplicates and ancestors (linearise).
  740. long long locTmpSize = in.size();
  741. #endif
  742. //Sort, Linearise, Redistribute.
  743. //TODO The following might work better as it reduces the comm bandwidth:
  744. //Split comm into sqrt(np) processes and sort, linearise for each comm group.
  745. //Then do the global sort, linearise with the original comm.
  746. par::HyperQuickSort(in, out, comm);
  747. lineariseList(out, comm);
  748. par::partitionW<MortonId>(out, NULL , comm);
  749. { // Add children
  750. //Remove empty processors...
  751. int new_rank, new_size;
  752. MPI_Comm new_comm;
  753. MPI_Comm_split(comm, (out.empty()?0:1), rank, &new_comm);
  754. MPI_Comm_rank (new_comm, &new_rank);
  755. MPI_Comm_size (new_comm, &new_size);
  756. if(!out.empty()) {
  757. MortonId nxt_mid(0,0,0,0);
  758. { // Get last octant from previous process.
  759. assert(out.size());
  760. //Send the last octant to the next processor.
  761. MortonId lastOctant = out.back();
  762. MortonId lastOnPrev;
  763. MPI_Request recvRequest;
  764. MPI_Request sendRequest;
  765. if(rank > 0) {
  766. MPI_Irecv(&lastOnPrev, 1, par::Mpi_datatype<MortonId>::value(), rank-1, 1, comm, &recvRequest);
  767. }
  768. if(rank < (size-1)) {
  769. MPI_Issend( &lastOctant, 1, par::Mpi_datatype<MortonId>::value(), rank+1, 1, comm, &sendRequest);
  770. }
  771. if(rank > 0) {
  772. MPI_Status statusWait;
  773. MPI_Wait(&recvRequest, &statusWait);
  774. nxt_mid = lastOnPrev.NextId();
  775. }
  776. if(rank < (size-1)) {
  777. MPI_Status statusWait;
  778. MPI_Wait(&sendRequest, &statusWait);
  779. }
  780. }
  781. std::vector<MortonId> out1;
  782. std::vector<MortonId> children;
  783. for(size_t i=0;i<out.size();i++){
  784. while(nxt_mid.getDFD()<out[i]){
  785. while(nxt_mid.isAncestor(out[i])){
  786. nxt_mid=nxt_mid.getAncestor(nxt_mid.GetDepth()+1);
  787. }
  788. out1.push_back(nxt_mid);
  789. nxt_mid=nxt_mid.NextId();
  790. }
  791. children=out[i].Children();
  792. for(size_t j=0;j<8;j++){
  793. out1.push_back(children[j]);
  794. }
  795. nxt_mid=out[i].NextId();
  796. }
  797. if(rank==size-1){
  798. while(nxt_mid.GetDepth()>0){
  799. out1.push_back(nxt_mid);
  800. nxt_mid=nxt_mid.NextId();
  801. }
  802. }
  803. out.swap(out1);
  804. }
  805. }
  806. //////////////////////////////////////////////////////////////////////////////////////////////////
  807. #ifdef __VERBOSE__
  808. long long locOutSize = out.size();
  809. long long globInSize, globTmpSize, globOutSize;
  810. MPI_Allreduce(&locInSize , &globInSize , 1, par::Mpi_datatype<long long>::value(), par::Mpi_datatype<long long>::sum(), comm);
  811. MPI_Allreduce(&locTmpSize, &globTmpSize, 1, par::Mpi_datatype<long long>::value(), par::Mpi_datatype<long long>::sum(), comm);
  812. MPI_Allreduce(&locOutSize, &globOutSize, 1, par::Mpi_datatype<long long>::value(), par::Mpi_datatype<long long>::sum(), comm);
  813. if(!rank) std::cout<<"Balance Octree. inpSize: "<<globInSize
  814. <<" tmpSize: "<<globTmpSize
  815. <<" outSize: "<<globOutSize
  816. <<" activeNpes: "<<size<<std::endl;
  817. #endif
  818. return 0;
  819. }//end function
  820. template <class TreeNode>
  821. void MPI_Tree<TreeNode>::Balance21(BoundaryType bndry) {
  822. int num_proc,myrank;
  823. MPI_Comm_rank(*Comm(),&myrank);
  824. MPI_Comm_size(*Comm(),&num_proc);
  825. //Using Dendro for balancing
  826. //Create a linear tree in dendro format.
  827. Node_t* curr_node=this->PreorderFirst();
  828. std::vector<MortonId> in;
  829. while(curr_node!=NULL){
  830. if(curr_node->IsLeaf() && !curr_node->IsGhost()){
  831. in.push_back(curr_node->GetMortonId());
  832. }
  833. curr_node=this->PreorderNxt(curr_node);
  834. }
  835. //2:1 balance
  836. Profile::Tic("ot::balanceOctree",Comm(),true,3);
  837. std::vector<MortonId> out;
  838. balanceOctree(in, out, this->Dim(), this->max_depth, (bndry==Periodic), *Comm());
  839. Profile::Toc();
  840. //Get new_mins.
  841. std::vector<MortonId> new_mins(num_proc);
  842. MPI_Allgather(&out[0] , 1, par::Mpi_datatype<MortonId>::value(),
  843. &new_mins[0], 1, par::Mpi_datatype<MortonId>::value(), *Comm());
  844. // Refine to new_mins in my range of octants
  845. // or else RedistNodes(...) will not work correctly.
  846. {
  847. int i=0;
  848. std::vector<MortonId> mins=GetMins();
  849. while(new_mins[i]<mins[myrank] && i<num_proc) i++; //TODO: Use binary search.
  850. for(;i<num_proc;i++){
  851. Node_t* n=FindNode(new_mins[i], true);
  852. if(n->IsGhost()) break;
  853. else assert(n->GetMortonId()==new_mins[i]);
  854. }
  855. }
  856. //Redist nodes using new_mins.
  857. Profile::Tic("RedistNodes",Comm(),true,3);
  858. RedistNodes(&out[0]);
  859. #ifndef NDEBUG
  860. std::vector<MortonId> mins=GetMins();
  861. assert(mins[myrank].getDFD()==out[0].getDFD());
  862. #endif
  863. Profile::Toc();
  864. //Now subdivide the current tree as necessary to make it balanced.
  865. Profile::Tic("LocalSubdivide",Comm(),false,3);
  866. int omp_p=omp_get_max_threads();
  867. for(int i=0;i<omp_p;i++){
  868. size_t a=(out.size()*i)/omp_p;
  869. Node_t* n=FindNode(out[a], true);
  870. assert(n->GetMortonId()==out[a]);
  871. UNUSED(n);
  872. }
  873. #pragma omp parallel for
  874. for(int i=0;i<omp_p;i++){
  875. size_t a=(out.size()* i )/omp_p;
  876. size_t b=(out.size()*(i+1))/omp_p;
  877. MortonId dn;
  878. size_t node_iter=a;
  879. Node_t* n=FindNode(out[node_iter], false);
  880. while(n!=NULL && node_iter<b){
  881. n->SetGhost(false);
  882. dn=n->GetMortonId();
  883. if(dn.isAncestor(out[node_iter]) && dn!=out[node_iter]){
  884. if(n->IsLeaf()) n->Subdivide();
  885. }else if(dn==out[node_iter]){
  886. assert(n->IsLeaf());
  887. //if(!n->IsLeaf()){ //This should never happen
  888. // n->Truncate();
  889. // n->SetGhost(false);
  890. //}
  891. assert(n->IsLeaf());
  892. node_iter++;
  893. }else{
  894. n->Truncate(); //This node does not belong to this process.
  895. n->SetGhost(true);
  896. }
  897. n=this->PreorderNxt(n);
  898. }
  899. if(i==omp_p-1){
  900. while(n!=NULL){
  901. n->Truncate();
  902. n->SetGhost(true);
  903. n=this->PreorderNxt(n);
  904. }
  905. }
  906. }
  907. Profile::Toc();
  908. }
  909. template <class TreeNode>
  910. void MPI_Tree<TreeNode>::Balance21_local(BoundaryType bndry){
  911. //SetColleagues(bndry);
  912. std::vector<std::vector<Node_t*> > node_lst(this->max_depth+1);
  913. Node_t* curr_node=this->PreorderFirst();
  914. while(curr_node!=NULL){
  915. node_lst[curr_node->Depth()].push_back(curr_node);
  916. curr_node=this->PreorderNxt(curr_node);
  917. }
  918. int n1=pow(3.0,this->Dim());
  919. int n2=pow(2.0,this->Dim());
  920. for(int i=this->max_depth;i>0;i--){
  921. Real_t s=pow(0.5,i);
  922. for(size_t j=0;j<node_lst[i].size();j++){
  923. curr_node=node_lst[i][j];
  924. Real_t* coord=curr_node->Coord();
  925. if(!curr_node->IsLeaf()) for(int k=0;k<n1;k++){
  926. if(curr_node->Colleague(k)==NULL){
  927. Real_t c0[3]={coord[0]+((k/1)%3-1)*s+s*0.5,
  928. coord[1]+((k/3)%3-1)*s+s*0.5,
  929. coord[2]+((k/9)%3-1)*s+s*0.5};
  930. if(bndry==Periodic){
  931. c0[0]=c0[0]-floor(c0[0]);
  932. c0[1]=c0[1]-floor(c0[1]);
  933. c0[2]=c0[2]-floor(c0[2]);
  934. }
  935. if(c0[0]>0 && c0[0]<1)
  936. if(c0[1]>0 && c0[1]<1)
  937. if(c0[2]>0 && c0[2]<1){
  938. Node_t* node=this->RootNode();
  939. while(node->Depth()<i){
  940. if(node->IsLeaf()){
  941. node->Subdivide();
  942. for(int l=0;l<n2;l++){
  943. node_lst[node->Depth()+1].push_back((Node_t*)node->Child(l));
  944. /*
  945. SetColleagues(bndry,(Node_t*)node->Child(l));
  946. for(int i_=0;i_<n1;i_++){
  947. Node_t* coll=(Node_t*)((Node_t*)node->Child(l))->Colleague(i_);
  948. if(coll!=NULL) SetColleagues(bndry,coll);
  949. }// */
  950. }
  951. }
  952. Real_t s1=pow(0.5,node->Depth()+1);
  953. Real_t* c1=node->Coord();
  954. int c_id=((c0[0]-c1[0])>s1?1:0)+
  955. ((c0[1]-c1[1])>s1?2:0)+
  956. ((c0[2]-c1[2])>s1?4:0);
  957. node=(Node_t*)node->Child(c_id);
  958. /*if(node->Depth()==i){
  959. c1=node->Coord();
  960. std::cout<<(c0[0]-c1[0])-s1/2<<' '
  961. std::cout<<(c0[1]-c1[1])-s1/2<<' '
  962. std::cout<<(c0[2]-c1[2])-s1/2<<'\n';
  963. }// */
  964. }
  965. }
  966. }
  967. }
  968. }
  969. }
  970. }
  971. template <class TreeNode>
  972. void MPI_Tree<TreeNode>::SetColleagues(BoundaryType bndry, Node_t* node){
  973. int n1=(int)pow(3.0,this->Dim());
  974. int n2=(int)pow(2.0,this->Dim());
  975. if(node==NULL){
  976. Node_t* curr_node=this->PreorderFirst();
  977. if(curr_node!=NULL){
  978. if(bndry==Periodic){
  979. for(int i=0;i<n1;i++)
  980. curr_node->SetColleague(curr_node,i);
  981. }else{
  982. curr_node->SetColleague(curr_node,(n1-1)/2);
  983. }
  984. curr_node=this->PreorderNxt(curr_node);
  985. }
  986. Vector<std::vector<Node_t*> > nodes(MAX_DEPTH);
  987. while(curr_node!=NULL){
  988. nodes[curr_node->Depth()].push_back(curr_node);
  989. curr_node=this->PreorderNxt(curr_node);
  990. }
  991. for(size_t i=0;i<MAX_DEPTH;i++){
  992. size_t j0=nodes[i].size();
  993. Node_t** nodes_=&nodes[i][0];
  994. #pragma omp parallel for
  995. for(size_t j=0;j<j0;j++){
  996. SetColleagues(bndry, nodes_[j]);
  997. }
  998. }
  999. }else{
  1000. /* //This is slower
  1001. Node_t* root_node=this->RootNode();
  1002. int d=node->Depth();
  1003. Real_t* c0=node->Coord();
  1004. Real_t s=pow(0.5,d);
  1005. Real_t c[COORD_DIM];
  1006. int idx=0;
  1007. for(int i=-1;i<=1;i++)
  1008. for(int j=-1;j<=1;j++)
  1009. for(int k=-1;k<=1;k++){
  1010. c[0]=c0[0]+s*0.5+s*k;
  1011. c[1]=c0[1]+s*0.5+s*j;
  1012. c[2]=c0[2]+s*0.5+s*i;
  1013. if(bndry==Periodic){
  1014. if(c[0]<0.0) c[0]+=1.0;
  1015. if(c[0]>1.0) c[0]-=1.0;
  1016. if(c[1]<1.0) c[1]+=1.0;
  1017. if(c[1]>1.0) c[1]-=1.0;
  1018. if(c[2]<1.0) c[2]+=1.0;
  1019. if(c[2]>1.0) c[2]-=1.0;
  1020. }
  1021. node->SetColleague(NULL,idx);
  1022. if(c[0]<1.0 && c[0]>0.0)
  1023. if(c[1]<1.0 && c[1]>0.0)
  1024. if(c[2]<1.0 && c[2]>0.0){
  1025. MortonId m(c,d);
  1026. Node_t* nbr=FindNode(m,false,root_node);
  1027. while(nbr->Depth()>d) nbr=(Node_t*)nbr->Parent();
  1028. if(nbr->Depth()==d) node->SetColleague(nbr,idx);
  1029. }
  1030. idx++;
  1031. }
  1032. /*/
  1033. Node_t* parent_node;
  1034. Node_t* tmp_node1;
  1035. Node_t* tmp_node2;
  1036. for(int i=0;i<n1;i++)node->SetColleague(NULL,i);
  1037. parent_node=(Node_t*)node->Parent();
  1038. if(parent_node==NULL) return;
  1039. int l=node->Path2Node();
  1040. for(int i=0;i<n1;i++){ //For each coll of the parent
  1041. tmp_node1=(Node_t*)parent_node->Colleague(i);
  1042. if(tmp_node1!=NULL)
  1043. if(!tmp_node1->IsLeaf()){
  1044. for(int j=0;j<n2;j++){ //For each child
  1045. tmp_node2=(Node_t*)tmp_node1->Child(j);
  1046. if(tmp_node2!=NULL){
  1047. bool flag=true;
  1048. int a=1,b=1,new_indx=0;
  1049. for(int k=0;k<this->Dim();k++){
  1050. int indx_diff=(((i/b)%3)-1)*2+((j/a)%2)-((l/a)%2);
  1051. if(-1>indx_diff || indx_diff>1) flag=false;
  1052. new_indx+=(indx_diff+1)*b;
  1053. a*=2;b*=3;
  1054. }
  1055. if(flag){
  1056. node->SetColleague(tmp_node2,new_indx);
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }// */
  1062. }
  1063. }
  1064. template <class TreeNode>
  1065. bool MPI_Tree<TreeNode>::CheckTree(){
  1066. int myrank,np;
  1067. MPI_Comm_rank(*Comm(),&myrank);
  1068. MPI_Comm_size(*Comm(),&np);
  1069. std::vector<MortonId> mins=GetMins();
  1070. std::stringstream st;
  1071. st<<"PID_"<<myrank<<" : ";
  1072. std::string str;
  1073. Node_t* n=this->PostorderFirst();
  1074. while(n!=NULL){
  1075. if(myrank<np-1) if(n->GetMortonId().getDFD()>=mins[myrank+1])break;
  1076. if(n->GetMortonId()>=mins[myrank] && n->IsLeaf() && n->IsGhost()){
  1077. std::cout<<n->GetMortonId()<<'\n';
  1078. std::cout<<mins[myrank]<<'\n';
  1079. if(myrank+1<np) std::cout<<mins[myrank+1]<<'\n';
  1080. std::cout<<myrank<<'\n';
  1081. assert(false);
  1082. }
  1083. if(n->GetMortonId()<mins[myrank] && n->IsLeaf() && !n->IsGhost()){
  1084. assert(false);
  1085. }
  1086. if(!n->IsGhost() && n->Depth()>0)
  1087. assert(!((Node_t*)n->Parent())->IsGhost());
  1088. n=this->PostorderNxt(n);
  1089. }
  1090. while(n!=NULL){
  1091. if(n->IsLeaf() && !n->IsGhost()){
  1092. st<<"non-ghost leaf node "<<n->GetMortonId()<<"; after last node.";
  1093. str=st.str(); ASSERT_WITH_MSG(false,str.c_str());
  1094. }
  1095. n=this->PostorderNxt(n);
  1096. }
  1097. return true;
  1098. };
  1099. /**
  1100. * \brief Determines if node is used in the region between Morton Ids m1 and m2
  1101. * ( m1 <= m2 ).
  1102. */
  1103. template <class TreeNode>
  1104. void IsShared(std::vector<TreeNode*>& nodes, MortonId* m1, MortonId* m2, BoundaryType bndry, std::vector<char>& shared_flag){
  1105. MortonId mm1, mm2;
  1106. if(m1!=NULL) mm1=m1->getDFD();
  1107. if(m2!=NULL) mm2=m2->getDFD();
  1108. shared_flag.resize(nodes.size());
  1109. int omp_p=omp_get_max_threads();
  1110. #pragma omp parallel for
  1111. for(int j=0;j<omp_p;j++){
  1112. size_t a=((j )*nodes.size())/omp_p;
  1113. size_t b=((j+1)*nodes.size())/omp_p;
  1114. std::vector<MortonId> nbr_lst;
  1115. for(size_t i=a;i<b;i++){
  1116. shared_flag[i]=false;
  1117. TreeNode* node=nodes[i];
  1118. assert(node!=NULL);
  1119. if(node->Depth()<2){
  1120. shared_flag[i]=true;
  1121. continue;
  1122. }
  1123. node->GetMortonId().NbrList(nbr_lst, node->Depth()-1, bndry==Periodic);
  1124. for(size_t k=0;k<nbr_lst.size();k++){
  1125. MortonId n1=nbr_lst[k] .getDFD();
  1126. MortonId n2=nbr_lst[k].NextId().getDFD();
  1127. if(m1==NULL || n2>mm1)
  1128. if(m2==NULL || n1<mm2){
  1129. shared_flag[i]=true;
  1130. break;
  1131. }
  1132. }
  1133. }
  1134. }
  1135. }
  1136. inline void IsShared(std::vector<PackedData>& nodes, MortonId* m1, MortonId* m2, BoundaryType bndry, std::vector<char>& shared_flag){
  1137. MortonId mm1, mm2;
  1138. if(m1!=NULL) mm1=m1->getDFD();
  1139. if(m2!=NULL) mm2=m2->getDFD();
  1140. shared_flag.resize(nodes.size());
  1141. int omp_p=omp_get_max_threads();
  1142. #pragma omp parallel for
  1143. for(int j=0;j<omp_p;j++){
  1144. size_t a=((j )*nodes.size())/omp_p;
  1145. size_t b=((j+1)*nodes.size())/omp_p;
  1146. std::vector<MortonId> nbr_lst;
  1147. for(size_t i=a;i<b;i++){
  1148. shared_flag[i]=false;
  1149. MortonId* node=(MortonId*)nodes[i].data;
  1150. assert(node!=NULL);
  1151. if(node->GetDepth()<2){
  1152. shared_flag[i]=true;
  1153. continue;
  1154. }
  1155. node->NbrList(nbr_lst, node->GetDepth()-1, bndry==Periodic);
  1156. for(size_t k=0;k<nbr_lst.size();k++){
  1157. MortonId n1=nbr_lst[k] .getDFD();
  1158. MortonId n2=nbr_lst[k].NextId().getDFD();
  1159. if(m1==NULL || n2>mm1)
  1160. if(m2==NULL || n1<mm2){
  1161. shared_flag[i]=true;
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. }
  1167. }
  1168. /**
  1169. * \brief Construct Locally Essential Tree by exchanging Ghost octants.
  1170. */
  1171. template <class TreeNode>
  1172. void MPI_Tree<TreeNode>::ConstructLET(BoundaryType bndry){
  1173. //Profile::Tic("LET_Hypercube", &comm, true, 5);
  1174. //ConstructLET_Hypercube(bndry);
  1175. //Profile::Toc();
  1176. //Profile::Tic("LET_Sparse", &comm, true, 5);
  1177. ConstructLET_Sparse(bndry);
  1178. //Profile::Toc();
  1179. #ifndef NDEBUG
  1180. CheckTree();
  1181. #endif
  1182. }
  1183. /**
  1184. * \brief Hypercube based scheme to exchange Ghost octants.
  1185. */
  1186. //#define PREFETCH_T0(addr,nrOfBytesAhead) _mm_prefetch(((char *)(addr))+nrOfBytesAhead,_MM_HINT_T0)
  1187. template <class TreeNode>
  1188. void MPI_Tree<TreeNode>::ConstructLET_Hypercube(BoundaryType bndry){
  1189. int num_p,rank;
  1190. MPI_Comm_size(*Comm(),&num_p);
  1191. MPI_Comm_rank(*Comm(),&rank );
  1192. if(num_p==1) return;
  1193. int omp_p=omp_get_max_threads();
  1194. std::vector<MortonId> mins=GetMins();
  1195. // Build list of shared nodes.
  1196. std::vector<Node_t*> shared_nodes; shared_nodes.clear();
  1197. std::vector<Node_t*> node_lst; node_lst.clear();
  1198. Node_t* curr_node=this->PreorderFirst();
  1199. while(curr_node!=NULL){
  1200. if(curr_node->GetMortonId().getDFD()>=mins[rank]) break;
  1201. curr_node=this->PreorderNxt(curr_node);
  1202. }
  1203. while(curr_node!=NULL){
  1204. if(curr_node->IsGhost()) break;
  1205. node_lst.push_back(curr_node);
  1206. curr_node=this->PreorderNxt(curr_node);
  1207. }
  1208. std::vector<char> node_flag0; node_flag0.clear();
  1209. std::vector<char> node_flag1; node_flag1.clear();
  1210. IsShared(node_lst,&mins[0],&mins[rank],bndry,node_flag0);
  1211. if(rank<num_p-1) IsShared(node_lst,&mins[rank+1],NULL,bndry,node_flag1);
  1212. for(size_t i=0;i<node_lst.size();i++){
  1213. if(node_flag0[i] || (rank<num_p-1 && node_flag1[i]))
  1214. shared_nodes.push_back(node_lst[i]);
  1215. }
  1216. //std::cout<<"Shared = "<<shared_nodes.size()<<'\n';
  1217. // Pack shared nodes.
  1218. static std::vector<char> shrd_buff_vec0(omp_p*64l*1024l*1024l);
  1219. static std::vector<char> shrd_buff_vec1(omp_p*128l*1024l*1024l);
  1220. static std::vector<char> send_buff_vec(omp_p*64l*1024l*1024l); char* send_buff;
  1221. static std::vector<char> recv_buff_vec(omp_p*64l*1024l*1024l); char* recv_buff;
  1222. std::vector<PackedData> shrd_data;
  1223. size_t max_data_size=0;
  1224. {
  1225. long max_data_size_lcl=0;
  1226. long max_data_size_glb=0;
  1227. char* data_ptr=&shrd_buff_vec0[0];
  1228. for(size_t i=0;i<shared_nodes.size();i++){
  1229. PackedData p=shared_nodes[i]->Pack(true,data_ptr,sizeof(MortonId));
  1230. ((MortonId*)data_ptr)[0]=shared_nodes[i]->GetMortonId();
  1231. p.length+=sizeof(MortonId);
  1232. shrd_data.push_back(p);
  1233. data_ptr+=p.length;
  1234. if(max_data_size_lcl<(long)p.length) max_data_size_lcl=p.length;
  1235. assert(data_ptr<=&(*shrd_buff_vec0.end())); //TODO: resize if needed.
  1236. }
  1237. MPI_Allreduce(&max_data_size_lcl, &max_data_size_glb, 1, MPI_LONG, MPI_MAX, *Comm());
  1238. max_data_size=max_data_size_glb;
  1239. }
  1240. // Memory slots for storing node data.
  1241. std::set<void*> mem_set;
  1242. size_t mem_set_size=0;
  1243. size_t range[2]={0,(size_t)num_p-1};
  1244. while(range[1]-range[0]>0){
  1245. size_t split_p=(range[0]+range[1])/2;
  1246. size_t new_range[2]={(size_t)rank<=split_p?range[0]:split_p+1,(size_t)rank<=split_p?split_p:range[1]};
  1247. size_t com_range[2]={(size_t)rank> split_p?range[0]:split_p+1,(size_t)rank> split_p?split_p:range[1]};
  1248. size_t partner=rank-new_range[0]+com_range[0];
  1249. if(partner>range[1]) partner--;
  1250. bool extra_partner=((size_t)rank==range[1] && ((range[1]-range[0])%2)==0);
  1251. int send_length=0;
  1252. std::vector<PackedData> shrd_data_new;
  1253. IsShared(shrd_data, &mins[com_range[0]], (com_range[1]==(size_t)num_p-1?NULL:&mins[com_range[1]+1]),bndry, node_flag0);
  1254. IsShared(shrd_data, &mins[new_range[0]], (new_range[1]==(size_t)num_p-1?NULL:&mins[new_range[1]+1]),bndry, node_flag1);
  1255. {
  1256. std::vector<void*> srctrg_ptr;
  1257. std::vector<size_t> mem_size;
  1258. for(size_t i=0;i<shrd_data.size();i++){
  1259. PackedData& p=shrd_data[i];
  1260. if( node_flag0[i]){ // Copy data to send buffer.
  1261. char* data_ptr=(char*)&send_buff_vec[send_length];
  1262. ((size_t*)data_ptr)[0]=p.length; data_ptr+=sizeof(size_t);
  1263. //mem::memcopy(data_ptr,p.data,p.length);
  1264. mem_size.push_back(p.length);
  1265. srctrg_ptr.push_back(p.data);
  1266. srctrg_ptr.push_back(data_ptr);
  1267. send_length+=p.length+sizeof(size_t);
  1268. assert((size_t)send_length<=send_buff_vec.size()); //TODO: resize if needed.
  1269. }
  1270. if(!node_flag1[i]){ // Free memory slot.
  1271. //assert(node_flag0[0]);
  1272. if(p.data>=&shrd_buff_vec1[0] && p.data<&shrd_buff_vec1[0]+shrd_buff_vec1.size())
  1273. mem_set.insert(p.data);
  1274. } else shrd_data_new.push_back(p);
  1275. }
  1276. shrd_data=shrd_data_new;
  1277. #pragma omp parallel for
  1278. for(int k=0;k<omp_p;k++){
  1279. size_t i0=((k+0)*mem_size.size())/omp_p;
  1280. size_t i1=((k+1)*mem_size.size())/omp_p;
  1281. for(size_t i=i0;i<i1;i++){
  1282. mem::memcopy(srctrg_ptr[2*i+1],srctrg_ptr[2*i+0],mem_size[i]);
  1283. }
  1284. }
  1285. }
  1286. //Exchange send size.
  1287. int recv_length=0;
  1288. int extra_recv_length=0;
  1289. int extra_send_length=0;
  1290. MPI_Status status;
  1291. MPI_Sendrecv (& send_length,1,MPI_INT,partner,0, &recv_length,1,MPI_INT,partner,0,*Comm(),&status);
  1292. if(extra_partner) MPI_Sendrecv(&extra_send_length,1,MPI_INT,split_p,0,&extra_recv_length,1,MPI_INT,split_p,0,*Comm(),&status);
  1293. //SendRecv data.
  1294. assert((size_t)send_length <=send_buff_vec.size()); send_buff=&send_buff_vec[0];
  1295. assert((size_t)recv_length+extra_recv_length<=recv_buff_vec.size()); recv_buff=&recv_buff_vec[0];
  1296. MPI_Sendrecv (send_buff,send_length,MPI_BYTE,partner,0, recv_buff , recv_length,MPI_BYTE,partner,0,*Comm(),&status);
  1297. if(extra_partner) MPI_Sendrecv( NULL, 0,MPI_BYTE,split_p,0,&recv_buff[recv_length],extra_recv_length,MPI_BYTE,split_p,0,*Comm(),&status);
  1298. //Get nodes from received data.
  1299. {
  1300. std::vector<void*> srctrg_ptr;
  1301. std::vector<size_t> mem_size;
  1302. int buff_length=0;
  1303. while(buff_length<recv_length+extra_recv_length){
  1304. PackedData p0,p1;
  1305. p0.length=((size_t*)&recv_buff_vec[buff_length])[0];
  1306. p0.data=(char*)&recv_buff_vec[buff_length]+sizeof(size_t);
  1307. buff_length+=p0.length+sizeof(size_t);
  1308. p1.length=p0.length;
  1309. if(mem_set.size()==0){
  1310. assert(mem_set_size*max_data_size<shrd_buff_vec1.size());
  1311. p1.data=&shrd_buff_vec1[mem_set_size*max_data_size];
  1312. mem_set_size++;
  1313. }else{
  1314. p1.data=*mem_set.begin();
  1315. mem_set.erase(mem_set.begin());
  1316. }
  1317. //mem::memcopy(p1.data,p0.data,p0.length);
  1318. mem_size.push_back(p0.length);
  1319. srctrg_ptr.push_back(p0.data);
  1320. srctrg_ptr.push_back(p1.data);
  1321. shrd_data.push_back(p1);
  1322. }
  1323. #pragma omp parallel for
  1324. for(int k=0;k<omp_p;k++){
  1325. size_t i0=((k+0)*mem_size.size())/omp_p;
  1326. size_t i1=((k+1)*mem_size.size())/omp_p;
  1327. for(size_t i=i0;i<i1;i++){
  1328. mem::memcopy(srctrg_ptr[2*i+1],srctrg_ptr[2*i+0],mem_size[i]);
  1329. }
  1330. }
  1331. }
  1332. range[0]=new_range[0];
  1333. range[1]=new_range[1];
  1334. }
  1335. //Add shared_nodes to the tree.
  1336. //std::cout<<"Number of Ghost Nodes = "<<shrd_data.size()<<'\n';
  1337. int nchld=(1UL<<this->Dim()); // Number of children.
  1338. std::vector<Node_t*> shrd_nodes(shrd_data.size());
  1339. for(size_t i=0;i<shrd_data.size();i++){ // Find shared nodes.
  1340. MortonId& mid=*(MortonId*)shrd_data[i].data;
  1341. Node_t* srch_node=this->RootNode();
  1342. while(srch_node->GetMortonId()!=mid){
  1343. Node_t* ch_node;
  1344. if(srch_node->IsLeaf()){
  1345. srch_node->SetGhost(true);
  1346. srch_node->Subdivide();
  1347. }
  1348. for(int j=nchld-1;j>=0;j--){
  1349. ch_node=(Node_t*)srch_node->Child(j);
  1350. if(ch_node->GetMortonId()<=mid){
  1351. srch_node=ch_node;
  1352. break;
  1353. }
  1354. }
  1355. }
  1356. shrd_nodes[i]=srch_node;
  1357. }
  1358. #pragma omp parallel for
  1359. for(size_t i=0;i<shrd_data.size();i++){
  1360. if(shrd_nodes[i]->IsGhost()) { // Initialize ghost node.
  1361. PackedData p=shrd_data[i];
  1362. p.data=((char*)p.data)+sizeof(MortonId);
  1363. p.length-=sizeof(MortonId);
  1364. shrd_nodes[i]->Unpack(p);
  1365. }
  1366. }
  1367. //Now LET is complete.
  1368. }
  1369. /**
  1370. * \brief Sparse communication scheme to exchange Ghost octants.
  1371. */
  1372. template <class TreeNode>
  1373. void MPI_Tree<TreeNode>::ConstructLET_Sparse(BoundaryType bndry){
  1374. typedef int MPI_size_t;
  1375. struct CommData{
  1376. MortonId mid;
  1377. TreeNode* node;
  1378. size_t pkd_length;
  1379. size_t usr_cnt;
  1380. MortonId usr_mid[COLLEAGUE_COUNT];
  1381. size_t usr_pid[COLLEAGUE_COUNT];
  1382. };
  1383. int num_p,rank;
  1384. MPI_Comm_size(*Comm(),&num_p);
  1385. MPI_Comm_rank(*Comm(),&rank );
  1386. if(num_p==1) return;
  1387. int omp_p=omp_get_max_threads();
  1388. std::vector<MortonId> mins=GetMins();
  1389. // Allocate Memory.
  1390. static std::vector<char> send_buff;
  1391. static std::vector<char> recv_buff;
  1392. //Profile::Tic("SharedNodes", &comm, false, 5);
  1393. CommData* node_comm_data=NULL; // CommData for all nodes.
  1394. std::vector<void*> shared_data; // CommData for shared nodes.
  1395. std::vector<par::SortPair<size_t,size_t> > pid_node_pair; // <pid, shared_data index> list
  1396. { // Set node_comm_data
  1397. MortonId mins_r0=mins[ rank+0 ].getDFD();
  1398. MortonId mins_r1=mins[std::min(rank+1,num_p-1)].getDFD();
  1399. std::vector<TreeNode*> nodes=this->GetNodeList();
  1400. node_comm_data=(CommData*)this->memgr.malloc(sizeof(CommData)*nodes.size());
  1401. #pragma omp parallel for
  1402. for(size_t tid=0;tid<omp_p;tid++){
  1403. std::vector<MortonId> nbr_lst;
  1404. size_t a=(nodes.size()* tid )/omp_p;
  1405. size_t b=(nodes.size()*(tid+1))/omp_p;
  1406. for(size_t i=a;i<b;i++){
  1407. bool shared=false;
  1408. CommData& comm_data=node_comm_data[i];
  1409. comm_data.node=nodes[i];
  1410. comm_data.mid=comm_data.node->GetMortonId();
  1411. comm_data.usr_cnt=0;
  1412. if(comm_data.node->IsGhost()) continue;
  1413. if(comm_data.node->Depth()==0) continue;
  1414. if(comm_data.mid.getDFD()<mins_r0) continue;
  1415. MortonId mid0=comm_data.mid. getDFD();
  1416. MortonId mid1=comm_data.mid.NextId().getDFD();
  1417. comm_data.mid.NbrList(nbr_lst,comm_data.node->Depth()-1, bndry==Periodic);
  1418. comm_data.usr_cnt=nbr_lst.size();
  1419. for(size_t j=0;j<nbr_lst.size();j++){
  1420. MortonId usr_mid=nbr_lst[j];
  1421. MortonId usr_mid_dfd=usr_mid.getDFD();
  1422. comm_data.usr_mid[j]=usr_mid;
  1423. comm_data.usr_pid[j]=std::upper_bound(&mins[0],&mins[num_p],usr_mid_dfd)-&mins[0]-1;
  1424. // if(usr_mid_dfd<mins_r0 || (rank+1<num_p && usr_mid_dfd>=mins_r1)){ // Find the user pid.
  1425. // size_t usr_pid=std::upper_bound(&mins[0],&mins[num_p],usr_mid_dfd)-&mins[0]-1;
  1426. // comm_data.usr_pid[j]=usr_pid;
  1427. // }else comm_data.usr_pid[j]=rank;
  1428. if(!shared){ // Check if this node needs to be transferred during broadcast.
  1429. if(comm_data.usr_pid[j]!=rank || (rank+1<num_p && usr_mid.NextId()>mins_r1) ){
  1430. shared=true;
  1431. }
  1432. }
  1433. }
  1434. #pragma omp critical (ADD_SHARED)
  1435. if(shared){
  1436. for(size_t j=0;j<comm_data.usr_cnt;j++)
  1437. if(comm_data.usr_pid[j]!=rank){
  1438. bool unique_pid=true;
  1439. for(size_t k=0;k<j;k++){
  1440. if(comm_data.usr_pid[j]==comm_data.usr_pid[k]){
  1441. unique_pid=false;
  1442. break;
  1443. }
  1444. }
  1445. if(unique_pid){
  1446. par::SortPair<size_t,size_t> p;
  1447. p.key=comm_data.usr_pid[j];
  1448. p.data=shared_data.size();
  1449. pid_node_pair.push_back(p);
  1450. }
  1451. }
  1452. shared_data.push_back(&comm_data);
  1453. }
  1454. }
  1455. }
  1456. omp_par::merge_sort(&pid_node_pair[0], &pid_node_pair[pid_node_pair.size()]);
  1457. //std::cout<<rank<<' '<<shared_data.size()<<' '<<pid_node_pair.size()<<'\n';
  1458. }
  1459. //Profile::Toc();
  1460. //Profile::Tic("PackNodes", &comm, false, 5);
  1461. { // Pack shared nodes.
  1462. #pragma omp parallel for
  1463. for(size_t tid=0;tid<omp_p;tid++){
  1464. size_t buff_length=10l*1024l*1024l; // 10MB buffer per thread.
  1465. char* buff=(char*)this->memgr.malloc(buff_length);
  1466. size_t a=( tid *shared_data.size())/omp_p;
  1467. size_t b=((tid+1)*shared_data.size())/omp_p;
  1468. for(size_t i=a;i<b;i++){
  1469. CommData& comm_data=*(CommData*)shared_data[i];
  1470. PackedData p0=comm_data.node->Pack(true,buff);
  1471. assert(p0.length<buff_length);
  1472. shared_data[i]=this->memgr.malloc(sizeof(CommData)+p0.length);
  1473. CommData& new_comm_data=*(CommData*)shared_data[i];
  1474. new_comm_data=comm_data;
  1475. new_comm_data.pkd_length=sizeof(CommData)+p0.length;
  1476. mem::memcopy(((char*)shared_data[i])+sizeof(CommData),buff,p0.length);
  1477. }
  1478. this->memgr.free(buff);
  1479. }
  1480. // now CommData is stored in shared_data
  1481. this->memgr.free(node_comm_data);
  1482. node_comm_data=NULL;
  1483. }
  1484. //Profile::Toc();
  1485. //Profile::Tic("SendBuff", &comm, false, 5);
  1486. std::vector<MPI_size_t> send_size(num_p,0);
  1487. std::vector<MPI_size_t> send_disp(num_p,0);
  1488. if(pid_node_pair.size()){ // Build send_buff.
  1489. std::vector<size_t> size(pid_node_pair.size(),0);
  1490. std::vector<size_t> disp(pid_node_pair.size(),0);
  1491. #pragma omp parallel for
  1492. for(size_t i=0;i<pid_node_pair.size();i++){
  1493. size[i]=((CommData*)shared_data[pid_node_pair[i].data])->pkd_length;
  1494. }
  1495. omp_par::scan(&size[0],&disp[0],pid_node_pair.size());
  1496. // Resize send_buff.
  1497. if(send_buff.size()<size[pid_node_pair.size()-1]+disp[pid_node_pair.size()-1]){
  1498. send_buff.resize(size[pid_node_pair.size()-1]+disp[pid_node_pair.size()-1]);
  1499. }
  1500. // Copy data to send_buff.
  1501. #pragma omp parallel for
  1502. for(size_t i=0;i<pid_node_pair.size();i++){
  1503. size_t shrd_idx=pid_node_pair[i].data;
  1504. mem::memcopy(&send_buff[disp[i]], shared_data[shrd_idx], size[i]);
  1505. }
  1506. // Compute send_size, send_disp.
  1507. {
  1508. // Compute send_size.
  1509. #pragma omp parallel for
  1510. for(size_t tid=0;tid<omp_p;tid++){
  1511. size_t a=(pid_node_pair.size()* tid )/omp_p;
  1512. size_t b=(pid_node_pair.size()*(tid+1))/omp_p;
  1513. if(a>0 && a<pid_node_pair.size()){
  1514. size_t p0=pid_node_pair[a].key;
  1515. while(a<pid_node_pair.size() && p0==pid_node_pair[a].key) a++;
  1516. }
  1517. if(b>0 && b<pid_node_pair.size()){
  1518. size_t p1=pid_node_pair[b].key;
  1519. while(b<pid_node_pair.size() && p1==pid_node_pair[b].key) b++;
  1520. }
  1521. for(size_t i=a;i<b;i++){
  1522. send_size[pid_node_pair[i].key]+=size[i];
  1523. }
  1524. }
  1525. // Compute send_disp.
  1526. omp_par::scan(&send_size[0],&send_disp[0],num_p);
  1527. }
  1528. }
  1529. //Profile::Toc();
  1530. //Profile::Tic("A2A_Sparse", &comm, true, 5);
  1531. size_t recv_length=0;
  1532. { // Allocate recv_buff.
  1533. std::vector<MPI_size_t> recv_size(num_p,0);
  1534. std::vector<MPI_size_t> recv_disp(num_p,0);
  1535. MPI_Alltoall(&send_size[0], 1, par::Mpi_datatype<MPI_size_t>::value(),
  1536. &recv_size[0], 1, par::Mpi_datatype<MPI_size_t>::value(), *Comm());
  1537. omp_par::scan(&recv_size[0],&recv_disp[0],num_p);
  1538. recv_length=recv_size[num_p-1]+recv_disp[num_p-1];
  1539. if(recv_buff.size()<recv_length){
  1540. recv_buff.resize(recv_length);
  1541. }
  1542. par::Mpi_Alltoallv_sparse(&send_buff[0], &send_size[0], &send_disp[0],
  1543. &recv_buff[0], &recv_size[0], &recv_disp[0], *Comm());
  1544. }
  1545. //Profile::Toc();
  1546. //Profile::Tic("Unpack", &comm, false, 5);
  1547. std::vector<void*> recv_data; // CommData for received nodes.
  1548. { // Unpack received octants.
  1549. std::vector<par::SortPair<MortonId,size_t> > mid_indx_pair;
  1550. for(size_t i=0; i<recv_length;){
  1551. CommData& comm_data=*(CommData*)&recv_buff[i];
  1552. recv_data.push_back(&comm_data);
  1553. { // Add mid_indx_pair
  1554. par::SortPair<MortonId,size_t> p;
  1555. p.key=comm_data.mid;
  1556. p.data=mid_indx_pair.size();
  1557. mid_indx_pair.push_back(p);
  1558. }
  1559. i+=comm_data.pkd_length;
  1560. assert(comm_data.pkd_length>0);
  1561. }
  1562. std::vector<Node_t*> recv_nodes(recv_data.size());
  1563. { // Find received octants in tree.
  1564. omp_par::merge_sort(&mid_indx_pair[0], &mid_indx_pair[0]+mid_indx_pair.size());
  1565. std::vector<size_t> indx(omp_p+1);
  1566. for(size_t i=0;i<=omp_p;i++){
  1567. size_t j=(mid_indx_pair.size()*i)/omp_p;
  1568. if(j>0) while(j<mid_indx_pair.size()-1){
  1569. if(mid_indx_pair[j+1].key.GetDepth()<=
  1570. mid_indx_pair[j].key.GetDepth()) break;
  1571. j++;
  1572. }
  1573. indx[i]=j;
  1574. }
  1575. int nchld=(1UL<<this->Dim()); // Number of children.
  1576. if(mid_indx_pair.size()>0)
  1577. for(size_t tid=1;tid<omp_p;tid++){
  1578. size_t j=indx[tid];
  1579. MortonId& mid=mid_indx_pair[j].key;
  1580. Node_t* srch_node=this->RootNode();
  1581. while(srch_node->GetMortonId()!=mid){
  1582. Node_t* ch_node;
  1583. if(srch_node->IsLeaf()){
  1584. srch_node->SetGhost(true);
  1585. srch_node->Subdivide();
  1586. }
  1587. for(int j=nchld-1;j>=0;j--){
  1588. ch_node=(Node_t*)srch_node->Child(j);
  1589. if(ch_node->GetMortonId()<=mid){
  1590. srch_node=ch_node;
  1591. break;
  1592. }
  1593. }
  1594. }
  1595. }
  1596. #pragma omp parallel for
  1597. for(size_t tid=0;tid<omp_p;tid++){
  1598. size_t a=indx[tid ];
  1599. size_t b=indx[tid+1];
  1600. for(size_t j=a;j<b;j++){ // Find shared nodes.
  1601. size_t i=mid_indx_pair[j].data;
  1602. MortonId& mid=mid_indx_pair[j].key;
  1603. Node_t* srch_node=this->RootNode();
  1604. while(srch_node->GetMortonId()!=mid){
  1605. Node_t* ch_node;
  1606. if(srch_node->IsLeaf()){
  1607. srch_node->SetGhost(true);
  1608. srch_node->Subdivide();
  1609. }
  1610. for(int j=nchld-1;j>=0;j--){
  1611. ch_node=(Node_t*)srch_node->Child(j);
  1612. if(ch_node->GetMortonId()<=mid){
  1613. srch_node=ch_node;
  1614. break;
  1615. }
  1616. }
  1617. }
  1618. recv_nodes[i]=srch_node;
  1619. }
  1620. }
  1621. }
  1622. #pragma omp parallel for
  1623. for(size_t i=0;i<recv_data.size();i++){ // Unpack
  1624. if(!recv_nodes[i]->IsGhost()) continue;
  1625. assert(recv_nodes[i]->IsGhost());
  1626. CommData& comm_data=*(CommData*)recv_data[i];
  1627. PackedData p;
  1628. p.data=((char*)recv_data[i])+sizeof(CommData);
  1629. p.length=comm_data.pkd_length-sizeof(CommData);
  1630. recv_nodes[i]->Unpack(p);
  1631. }
  1632. }
  1633. //Profile::Toc();
  1634. //Profile::Tic("Broadcast", &comm, true, 5);
  1635. { // Broadcast octants.
  1636. std::vector<MortonId> shrd_mid;
  1637. if(rank+1<num_p){ // Set shrd_mid.
  1638. MortonId m=mins[rank+1];
  1639. while(m.GetDepth()>0 && m.getDFD()>=mins[rank+1]){
  1640. m=m.getAncestor(m.GetDepth()-1);
  1641. }
  1642. size_t d=m.GetDepth()+1;
  1643. shrd_mid.resize(d);
  1644. for(size_t i=0;i<d;i++){
  1645. shrd_mid[i]=m.getAncestor(i);
  1646. }
  1647. }
  1648. std::vector<void*> shrd_data; // CommData for shared nodes.
  1649. { // Set shrd_data
  1650. for(size_t i=0;i<shared_data.size();i++){
  1651. CommData& comm_data=*(CommData*)shared_data[i];
  1652. assert(comm_data.mid.GetDepth()>0);
  1653. size_t d=comm_data.mid.GetDepth()-1;
  1654. if(d<shrd_mid.size() && shrd_mid[d].getDFD()>=mins[rank])
  1655. for(size_t j=0;j<comm_data.usr_cnt;j++){
  1656. if(comm_data.usr_mid[j]==shrd_mid[d]){
  1657. shrd_data.push_back(&comm_data);
  1658. break;
  1659. }
  1660. }
  1661. if(shrd_data.size()==0 || shrd_data.back()!=&comm_data) this->memgr.free(&comm_data);
  1662. }
  1663. for(size_t i=0;i<recv_data.size();i++){
  1664. CommData& comm_data=*(CommData*)recv_data[i];
  1665. assert(comm_data.mid.GetDepth()>0);
  1666. size_t d=comm_data.mid.GetDepth()-1;
  1667. if(d<shrd_mid.size() && shrd_mid[d].getDFD()>=mins[rank])
  1668. for(size_t j=0;j<comm_data.usr_cnt;j++){
  1669. if(comm_data.usr_mid[j]==shrd_mid[d]){
  1670. char* data_ptr=(char*)this->memgr.malloc(comm_data.pkd_length);
  1671. mem::memcopy(data_ptr, &comm_data, comm_data.pkd_length);
  1672. shrd_data.push_back(data_ptr);
  1673. break;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. size_t pid_shift=1;
  1679. while(pid_shift<num_p){
  1680. MPI_size_t recv_pid=(rank>=pid_shift?rank-pid_shift:rank);
  1681. MPI_size_t send_pid=(rank+pid_shift<num_p?rank+pid_shift:rank);
  1682. MPI_size_t send_length=0;
  1683. if(send_pid!=rank){ // Send data for send_pid
  1684. std::vector<void*> send_data;
  1685. std::vector<size_t> send_size;
  1686. for(size_t i=0; i<shrd_data.size();i++){
  1687. CommData& comm_data=*(CommData*)shrd_data[i];
  1688. size_t d=comm_data.mid.GetDepth()-1;
  1689. bool shared=(d<shrd_mid.size() && shrd_mid[d].NextId().getDFD()>mins[send_pid].getDFD());
  1690. if(shared) for(size_t j=0;j<comm_data.usr_cnt;j++){ // if send_pid already has this node then skip
  1691. if(comm_data.usr_pid[j]==send_pid){
  1692. shared=false;
  1693. break;
  1694. }
  1695. }
  1696. if(!shared) continue;
  1697. send_data.push_back(&comm_data);
  1698. send_size.push_back(comm_data.pkd_length);
  1699. }
  1700. std::vector<size_t> send_disp(send_data.size(),0);
  1701. omp_par::scan(&send_size[0],&send_disp[0],send_data.size());
  1702. if(send_data.size()>0) send_length=send_size.back()+send_disp.back();
  1703. // Resize send_buff.
  1704. if(send_buff.size()<send_length){
  1705. send_buff.resize(send_length);
  1706. }
  1707. // Copy data to send_buff.
  1708. #pragma omp parallel for
  1709. for(size_t i=0;i<send_data.size();i++){
  1710. CommData& comm_data=*(CommData*)send_data[i];
  1711. mem::memcopy(&send_buff[send_disp[i]], &comm_data, comm_data.pkd_length);
  1712. }
  1713. }
  1714. MPI_size_t recv_length=0;
  1715. { // Send-Recv data
  1716. MPI_Request request;
  1717. MPI_Status status;
  1718. if(recv_pid!=rank) MPI_Irecv(&recv_length, 1, par::Mpi_datatype<MPI_size_t>::value(),recv_pid, 1, *Comm(), &request);
  1719. if(send_pid!=rank) MPI_Send (&send_length, 1, par::Mpi_datatype<MPI_size_t>::value(),send_pid, 1, *Comm());
  1720. if(recv_pid!=rank) MPI_Wait(&request, &status);
  1721. // Resize recv_buff
  1722. if(recv_buff.size()<recv_length){
  1723. recv_buff.resize(recv_length);
  1724. }
  1725. if(recv_length>0) MPI_Irecv(&recv_buff[0], recv_length, par::Mpi_datatype<char>::value(),recv_pid, 1, *Comm(), &request);
  1726. if(send_length>0) MPI_Send (&send_buff[0], send_length, par::Mpi_datatype<char>::value(),send_pid, 1, *Comm());
  1727. if(recv_length>0) MPI_Wait(&request, &status);
  1728. }
  1729. std::vector<void*> recv_data; // CommData for received nodes.
  1730. { // Unpack received octants.
  1731. std::vector<par::SortPair<MortonId,size_t> > mid_indx_pair;
  1732. for(size_t i=0; i<recv_length;){
  1733. CommData& comm_data=*(CommData*)&recv_buff[i];
  1734. recv_data.push_back(&comm_data);
  1735. { // Add mid_indx_pair
  1736. par::SortPair<MortonId,size_t> p;
  1737. p.key=comm_data.mid;
  1738. p.data=mid_indx_pair.size();
  1739. mid_indx_pair.push_back(p);
  1740. }
  1741. i+=comm_data.pkd_length;
  1742. assert(comm_data.pkd_length>0);
  1743. }
  1744. std::vector<Node_t*> recv_nodes(recv_data.size());
  1745. int nchld=(1UL<<this->Dim()); // Number of children.
  1746. // for(size_t i=0;i<recv_data.size();i++){ // Find received octants in tree.
  1747. // CommData& comm_data=*(CommData*)recv_data[i];
  1748. // MortonId& mid=comm_data.mid;
  1749. // Node_t* srch_node=this->RootNode();
  1750. // while(srch_node->GetMortonId()!=mid){
  1751. // Node_t* ch_node;
  1752. // if(srch_node->IsLeaf()){
  1753. // srch_node->SetGhost(true);
  1754. // srch_node->Subdivide();
  1755. // }
  1756. // for(int j=nchld-1;j>=0;j--){
  1757. // ch_node=(Node_t*)srch_node->Child(j);
  1758. // if(ch_node->GetMortonId()<=mid){
  1759. // srch_node=ch_node;
  1760. // break;
  1761. // }
  1762. // }
  1763. // }
  1764. // recv_nodes[i]=srch_node;
  1765. // }
  1766. { // Find received octants in tree.
  1767. omp_par::merge_sort(&mid_indx_pair[0], &mid_indx_pair[0]+mid_indx_pair.size());
  1768. std::vector<size_t> indx(omp_p+1);
  1769. for(size_t i=0;i<=omp_p;i++){
  1770. size_t j=(mid_indx_pair.size()*i)/omp_p;
  1771. if(j>0) while(j<mid_indx_pair.size()-1){
  1772. if(mid_indx_pair[j+1].key.GetDepth()<=
  1773. mid_indx_pair[j].key.GetDepth()) break;
  1774. j++;
  1775. }
  1776. indx[i]=j;
  1777. }
  1778. int nchld=(1UL<<this->Dim()); // Number of children.
  1779. if(mid_indx_pair.size()>0)
  1780. for(size_t tid=1;tid<omp_p;tid++){
  1781. size_t j=indx[tid];
  1782. MortonId& mid=mid_indx_pair[j].key;
  1783. Node_t* srch_node=this->RootNode();
  1784. while(srch_node->GetMortonId()!=mid){
  1785. Node_t* ch_node;
  1786. if(srch_node->IsLeaf()){
  1787. srch_node->SetGhost(true);
  1788. srch_node->Subdivide();
  1789. }
  1790. for(int j=nchld-1;j>=0;j--){
  1791. ch_node=(Node_t*)srch_node->Child(j);
  1792. if(ch_node->GetMortonId()<=mid){
  1793. srch_node=ch_node;
  1794. break;
  1795. }
  1796. }
  1797. }
  1798. }
  1799. #pragma omp parallel for
  1800. for(size_t tid=0;tid<omp_p;tid++){
  1801. size_t a=indx[tid ];
  1802. size_t b=indx[tid+1];
  1803. for(size_t j=a;j<b;j++){ // Find shared nodes.
  1804. size_t i=mid_indx_pair[j].data;
  1805. MortonId& mid=mid_indx_pair[j].key;
  1806. Node_t* srch_node=this->RootNode();
  1807. while(srch_node->GetMortonId()!=mid){
  1808. Node_t* ch_node;
  1809. if(srch_node->IsLeaf()){
  1810. srch_node->SetGhost(true);
  1811. srch_node->Subdivide();
  1812. }
  1813. for(int j=nchld-1;j>=0;j--){
  1814. ch_node=(Node_t*)srch_node->Child(j);
  1815. if(ch_node->GetMortonId()<=mid){
  1816. srch_node=ch_node;
  1817. break;
  1818. }
  1819. }
  1820. }
  1821. recv_nodes[i]=srch_node;
  1822. }
  1823. }
  1824. }
  1825. #pragma omp parallel for
  1826. for(size_t i=0;i<recv_data.size();i++){
  1827. if(!recv_nodes[i]->IsGhost()) continue;
  1828. assert(recv_nodes[i]->IsGhost());
  1829. CommData& comm_data=*(CommData*)recv_data[i];
  1830. PackedData p;
  1831. p.data=((char*)recv_data[i])+sizeof(CommData);
  1832. p.length=comm_data.pkd_length-sizeof(CommData);
  1833. recv_nodes[i]->Unpack(p);
  1834. }
  1835. }
  1836. pid_shift<<=1;
  1837. send_pid=(rank+pid_shift<num_p?rank+pid_shift:rank);
  1838. if(send_pid!=rank){ // Set shrd_data
  1839. for(size_t i=0;i<recv_data.size();i++){
  1840. CommData& comm_data=*(CommData*)recv_data[i];
  1841. //{ // Skip if this node already exists.
  1842. // bool skip=false;
  1843. // for(size_t k=0;k<shrd_data.size();k++){
  1844. // CommData& comm_data_=*(CommData*)shrd_data[k];
  1845. // if(comm_data_.mid==comm_data.mid){
  1846. // assert(false);
  1847. // skip=true;
  1848. // break;
  1849. // }
  1850. // }
  1851. // if(skip) continue;
  1852. //}
  1853. assert(comm_data.mid.GetDepth()>0);
  1854. size_t d=comm_data.mid.GetDepth()-1;
  1855. if(d<shrd_mid.size() && shrd_mid[d].isAncestor(mins[rank]) && shrd_mid[d].NextId().getDFD()>mins[send_pid].getDFD())
  1856. for(size_t j=0;j<comm_data.usr_cnt;j++){
  1857. if(comm_data.usr_mid[j]==shrd_mid[d]){
  1858. char* data_ptr=(char*)this->memgr.malloc(comm_data.pkd_length);
  1859. mem::memcopy(data_ptr, &comm_data, comm_data.pkd_length);
  1860. shrd_data.push_back(data_ptr);
  1861. break;
  1862. }
  1863. }
  1864. }
  1865. }
  1866. }
  1867. // Free data
  1868. //Profile::Tic("Free", &comm, false, 5);
  1869. for(size_t i=0;i<shrd_data.size();i++) this->memgr.free(shrd_data[i]);
  1870. //Profile::Toc();
  1871. }
  1872. //Profile::Toc();
  1873. }
  1874. inline bool isLittleEndian(){
  1875. uint16_t number = 0x1;
  1876. uint8_t *numPtr = (uint8_t*)&number;
  1877. return (numPtr[0] == 1);
  1878. }
  1879. template <class TreeNode>
  1880. void MPI_Tree<TreeNode>::Write2File(const char* fname, int lod){
  1881. typedef double VTKData_t;
  1882. int myrank, np;
  1883. MPI_Comm_size(*Comm(),&np);
  1884. MPI_Comm_rank(*Comm(),&myrank);
  1885. std::vector<Real_t> coord_; //Coordinates of octant corners.
  1886. std::vector<Real_t> value_; //Data value at points.
  1887. std::vector<VTKData_t> coord; //Coordinates of octant corners.
  1888. std::vector<VTKData_t> value; //Data value at points.
  1889. std::vector<int32_t> mpi_rank; //MPI_Rank at points.
  1890. std::vector<int32_t> connect; //Cell connectivity.
  1891. std::vector<int32_t> offset ; //Cell offset.
  1892. std::vector<uint8_t> types ; //Cell types.
  1893. //Build list of octant corner points.
  1894. Node_t* n=this->PreorderFirst();
  1895. while(n!=NULL){
  1896. if(!n->IsGhost() && n->IsLeaf())
  1897. n->VTU_Data(coord_, value_, connect, offset, types, lod);
  1898. n=this->PreorderNxt(n);
  1899. }
  1900. for(size_t i=0;i<coord_.size();i++) coord.push_back(coord_[i]);
  1901. for(size_t i=0;i<value_.size();i++) value.push_back(value_[i]);
  1902. int pt_cnt=coord.size()/COORD_DIM;
  1903. int dof=(pt_cnt?value.size()/pt_cnt:0);
  1904. assert(value.size()==(size_t)pt_cnt*dof);
  1905. int cell_cnt=types.size();
  1906. mpi_rank.resize(pt_cnt);
  1907. int new_myrank=myrank;//rand();
  1908. for(int i=0;i<pt_cnt;i++) mpi_rank[i]=new_myrank;
  1909. //Open file for writing.
  1910. std::stringstream vtufname;
  1911. vtufname<<fname<<std::setfill('0')<<std::setw(6)<<myrank<<".vtu";
  1912. std::ofstream vtufile;
  1913. vtufile.open(vtufname.str().c_str());
  1914. if(vtufile.fail()) return;
  1915. //Proceed to write to file.
  1916. size_t data_size=0;
  1917. vtufile<<"<?xml version=\"1.0\"?>\n";
  1918. if(isLittleEndian()) vtufile<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n";
  1919. else vtufile<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"BigEndian\">\n";
  1920. //===========================================================================
  1921. vtufile<<" <UnstructuredGrid>\n";
  1922. vtufile<<" <Piece NumberOfPoints=\""<<pt_cnt<<"\" NumberOfCells=\""<<cell_cnt<<"\">\n";
  1923. //---------------------------------------------------------------------------
  1924. vtufile<<" <Points>\n";
  1925. vtufile<<" <DataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<COORD_DIM<<"\" Name=\"Position\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1926. data_size+=sizeof(uint32_t)+coord.size()*sizeof(VTKData_t);
  1927. vtufile<<" </Points>\n";
  1928. //---------------------------------------------------------------------------
  1929. vtufile<<" <PointData>\n";
  1930. vtufile<<" <DataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<dof<<"\" Name=\"value\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1931. data_size+=sizeof(uint32_t)+value.size()*sizeof(VTKData_t);
  1932. vtufile<<" <DataArray type=\"Int32\" NumberOfComponents=\"1\" Name=\"mpi_rank\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1933. data_size+=sizeof(uint32_t)+mpi_rank.size()*sizeof(int32_t);
  1934. vtufile<<" </PointData>\n";
  1935. //---------------------------------------------------------------------------
  1936. //---------------------------------------------------------------------------
  1937. vtufile<<" <Cells>\n";
  1938. vtufile<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1939. data_size+=sizeof(uint32_t)+connect.size()*sizeof(int32_t);
  1940. vtufile<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1941. data_size+=sizeof(uint32_t)+offset.size() *sizeof(int32_t);
  1942. vtufile<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1943. data_size+=sizeof(uint32_t)+types.size() *sizeof(uint8_t);
  1944. vtufile<<" </Cells>\n";
  1945. //---------------------------------------------------------------------------
  1946. //vtufile<<" <CellData>\n";
  1947. //vtufile<<" <DataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" Name=\"Velocity\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1948. //vtufile<<" </CellData>\n";
  1949. //---------------------------------------------------------------------------
  1950. vtufile<<" </Piece>\n";
  1951. vtufile<<" </UnstructuredGrid>\n";
  1952. //===========================================================================
  1953. vtufile<<" <AppendedData encoding=\"raw\">\n";
  1954. vtufile<<" _";
  1955. int32_t block_size;
  1956. block_size=coord .size()*sizeof(VTKData_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&coord [0], coord .size()*sizeof(VTKData_t));
  1957. block_size=value .size()*sizeof(VTKData_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&value [0], value .size()*sizeof(VTKData_t));
  1958. block_size=mpi_rank.size()*sizeof( int32_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&mpi_rank[0], mpi_rank.size()*sizeof( int32_t));
  1959. block_size=connect.size()*sizeof(int32_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&connect[0], connect.size()*sizeof(int32_t));
  1960. block_size=offset .size()*sizeof(int32_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&offset [0], offset .size()*sizeof(int32_t));
  1961. block_size=types .size()*sizeof(uint8_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&types [0], types .size()*sizeof(uint8_t));
  1962. vtufile<<"\n";
  1963. vtufile<<" </AppendedData>\n";
  1964. //===========================================================================
  1965. vtufile<<"</VTKFile>\n";
  1966. vtufile.close();
  1967. if(myrank) return;
  1968. std::stringstream pvtufname;
  1969. pvtufname<<fname<<".pvtu";
  1970. std::ofstream pvtufile;
  1971. pvtufile.open(pvtufname.str().c_str());
  1972. if(pvtufile.fail()) return;
  1973. pvtufile<<"<?xml version=\"1.0\"?>\n";
  1974. pvtufile<<"<VTKFile type=\"PUnstructuredGrid\">\n";
  1975. pvtufile<<" <PUnstructuredGrid GhostLevel=\"0\">\n";
  1976. pvtufile<<" <PPoints>\n";
  1977. pvtufile<<" <PDataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<COORD_DIM<<"\" Name=\"Position\"/>\n";
  1978. pvtufile<<" </PPoints>\n";
  1979. pvtufile<<" <PPointData>\n";
  1980. pvtufile<<" <PDataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<dof<<"\" Name=\"value\"/>\n";
  1981. pvtufile<<" <PDataArray type=\"Int32\" NumberOfComponents=\"1\" Name=\"mpi_rank\"/>\n";
  1982. pvtufile<<" </PPointData>\n";
  1983. {
  1984. // Extract filename from path.
  1985. std::stringstream vtupath;
  1986. vtupath<<'/'<<fname<<'\0';
  1987. char *fname_ = (char*)strrchr(vtupath.str().c_str(), '/') + 1;
  1988. //std::string fname_ = boost::filesystem::path(fname).filename().string().
  1989. for(int i=0;i<np;i++) pvtufile<<" <Piece Source=\""<<fname_<<std::setfill('0')<<std::setw(6)<<i<<".vtu\"/>\n";
  1990. }
  1991. pvtufile<<" </PUnstructuredGrid>\n";
  1992. pvtufile<<"</VTKFile>\n";
  1993. pvtufile.close();
  1994. }
  1995. template <class TreeNode>
  1996. const std::vector<MortonId>& MPI_Tree<TreeNode>::GetMins(){
  1997. Node_t* n=this->PreorderFirst();
  1998. while(n!=NULL){
  1999. if(!n->IsGhost() && n->IsLeaf()) break;
  2000. n=this->PreorderNxt(n);
  2001. }
  2002. ASSERT_WITH_MSG(n!=NULL,"No non-ghost nodes found on this process.");
  2003. MortonId my_min;
  2004. my_min=n->GetMortonId();
  2005. int np;
  2006. MPI_Comm_size(*Comm(),&np);
  2007. mins.resize(np);
  2008. MPI_Allgather(&my_min , 1, par::Mpi_datatype<MortonId>::value(),
  2009. &mins[0], 1, par::Mpi_datatype<MortonId>::value(), *Comm());
  2010. return mins;
  2011. }
  2012. }//end namespace