mpi_tree.txx 76 KB

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