mpi_tree.txx 72 KB

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